You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1060 lines
49 KiB

12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
  1. # -*- encoding: utf-8 -*-
  2. ###########################################################################
  3. # Module Writen to OpenERP, Open Source Management Solution
  4. # Copyright (C) OpenERP Venezuela (<http://openerp.com.ve>).
  5. # All Rights Reserved
  6. # Credits######################################################
  7. # Coded by: Humberto Arocha humberto@openerp.com.ve
  8. # Angelica Barrios angelicaisabelb@gmail.com
  9. # Jordi Esteve <jesteve@zikzakmedia.com>
  10. # Javier Duran <javieredm@gmail.com>
  11. # Planified by: Humberto Arocha
  12. # Finance by: LUBCAN COL S.A.S http://www.lubcancol.com
  13. # Audited by: Humberto Arocha humberto@openerp.com.ve
  14. #############################################################################
  15. # This program is free software: you can redistribute it and/or modify
  16. # it under the terms of the GNU General Public License as published by
  17. # the Free Software Foundation, either version 3 of the License, or
  18. # (at your option) any later version.
  19. #
  20. # This program is distributed in the hope that it will be useful,
  21. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. # GNU General Public License for more details.
  24. #
  25. # You should have received a copy of the GNU General Public License
  26. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  27. ##############################################################################
  28. import xml
  29. import copy
  30. from operator import itemgetter
  31. import time
  32. import datetime
  33. from report import report_sxw
  34. from tools import config
  35. from tools.translate import _
  36. from osv import osv
  37. from openerp.tools.safe_eval import safe_eval as eval
  38. class account_balance(report_sxw.rml_parse):
  39. def __init__(self, cr, uid, name, context):
  40. super(account_balance, self).__init__(cr, uid, name, context)
  41. self.sum_debit = 0.00
  42. self.sum_credit = 0.00
  43. self.sum_balance = 0.00
  44. self.sum_debit_fy = 0.00
  45. self.sum_credit_fy = 0.00
  46. self.sum_balance_fy = 0.00
  47. self.date_lst = []
  48. self.date_lst_string = ''
  49. self.localcontext.update({
  50. 'time': time,
  51. 'lines': self.lines,
  52. 'get_fiscalyear_text': self.get_fiscalyear_text,
  53. 'get_periods_and_date_text': self.get_periods_and_date_text,
  54. 'get_informe_text': self.get_informe_text,
  55. 'get_month': self.get_month,
  56. 'exchange_name': self.exchange_name,
  57. 'get_vat_by_country': self.get_vat_by_country,
  58. })
  59. self.context = context
  60. def get_vat_by_country(self, form):
  61. """
  62. Return the vat of the partner by country
  63. """
  64. rc_obj = self.pool.get('res.company')
  65. country_code=rc_obj.browse(self.cr, self.uid, form['company_id'][0]).partner_id.country_id.code or ''
  66. string_vat= rc_obj.browse(self.cr, self.uid, form['company_id'][0]).partner_id.vat or ''
  67. if string_vat:
  68. if country_code=='MX':
  69. return '%s' % (string_vat[2:])
  70. elif country_code=='VE':
  71. return '- %s-%s-%s'%(string_vat[2:3],string_vat[3:11],string_vat[11:12])
  72. else:
  73. return string_vat
  74. else:
  75. return _('\nVAT OF COMPANY NOT AVAILABLE')
  76. def get_fiscalyear_text(self, form):
  77. """
  78. Returns the fiscal year text used on the report.
  79. """
  80. fiscalyear_obj = self.pool.get('account.fiscalyear')
  81. fiscalyear = None
  82. if form.get('fiscalyear'):
  83. fiscalyear = fiscalyear_obj.browse(
  84. self.cr, self.uid, form['fiscalyear'])
  85. return fiscalyear.name or fiscalyear.code
  86. else:
  87. fiscalyear = fiscalyear_obj.browse(
  88. self.cr, self.uid, fiscalyear_obj.find(self.cr, self.uid))
  89. return "%s*" % (fiscalyear.name or fiscalyear.code)
  90. def get_informe_text(self, form):
  91. """
  92. Returns the header text used on the report.
  93. """
  94. afr_id = form['afr_id'] and type(form['afr_id']) in (
  95. list, tuple) and form['afr_id'][0] or form['afr_id']
  96. if afr_id:
  97. name = self.pool.get('afr').browse(self.cr, self.uid, afr_id).name
  98. elif form['analytic_ledger'] and form['columns'] == 'four' and form['inf_type'] == 'BS':
  99. name = _('Analytic Ledger')
  100. elif form['inf_type'] == 'BS':
  101. name = _('Balance Sheet')
  102. elif form['inf_type'] == 'IS':
  103. name = _('Income Statement')
  104. return name
  105. def get_month(self, form):
  106. '''
  107. return day, year and month
  108. '''
  109. if form['filter'] in ['bydate', 'all']:
  110. months = ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio",
  111. "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"]
  112. mes = months[time.strptime(form['date_to'], "%Y-%m-%d")[1]-1]
  113. ano = time.strptime(form['date_to'], "%Y-%m-%d")[0]
  114. dia = time.strptime(form['date_to'], "%Y-%m-%d")[2]
  115. return _('From ')+self.formatLang(form['date_from'], date=True) + _(' to ')+self.formatLang(form['date_to'], date=True)
  116. elif form['filter'] in ['byperiod', 'all']:
  117. aux = []
  118. period_obj = self.pool.get('account.period')
  119. for period in period_obj.browse(self.cr, self.uid, form['periods']):
  120. aux.append(period.date_start)
  121. aux.append(period.date_stop)
  122. sorted(aux)
  123. return _('From ')+self.formatLang(aux[0], date=True)+_(' to ')+self.formatLang(aux[-1], date=True)
  124. def get_periods_and_date_text(self, form):
  125. """
  126. Returns the text with the periods/dates used on the report.
  127. """
  128. period_obj = self.pool.get('account.period')
  129. periods_str = None
  130. fiscalyear_id = form[
  131. 'fiscalyear'] or fiscalyear_obj.find(self.cr, self.uid)
  132. period_ids = period_obj.search(self.cr, self.uid, [(
  133. 'fiscalyear_id', '=', fiscalyear_id), ('special', '=', False)])
  134. if form['filter'] in ['byperiod', 'all']:
  135. period_ids = form['periods']
  136. periods_str = ', '.join([period.name or period.code for period in period_obj.browse(
  137. self.cr, self.uid, period_ids)])
  138. dates_str = None
  139. if form['filter'] in ['bydate', 'all']:
  140. dates_str = self.formatLang(form[
  141. 'date_from'], date=True) + ' - ' + self.formatLang(form['date_to'], date=True) + ' '
  142. return {'periods': periods_str, 'date': dates_str}
  143. def special_period(self, periods):
  144. period_obj = self.pool.get('account.period')
  145. period_brw = period_obj.browse(self.cr, self.uid, periods)
  146. period_counter = [True for i in period_brw if not i.special]
  147. if not period_counter:
  148. return True
  149. return False
  150. def exchange_name(self, form):
  151. self.from_currency_id = self.get_company_currency(form['company_id'] and type(form[
  152. 'company_id']) in (list, tuple) and form['company_id'][0] or form['company_id'])
  153. if not form['currency_id']:
  154. self.to_currency_id = self.from_currency_id
  155. else:
  156. self.to_currency_id = form['currency_id'] and type(form['currency_id']) in (
  157. list, tuple) and form['currency_id'][0] or form['currency_id']
  158. return self.pool.get('res.currency').browse(self.cr, self.uid, self.to_currency_id).name
  159. def exchange(self, from_amount):
  160. if self.from_currency_id == self.to_currency_id:
  161. return from_amount
  162. curr_obj = self.pool.get('res.currency')
  163. return curr_obj.compute(self.cr, self.uid, self.from_currency_id, self.to_currency_id, from_amount)
  164. def get_company_currency(self, company_id):
  165. rc_obj = self.pool.get('res.company')
  166. return rc_obj.browse(self.cr, self.uid, company_id).currency_id.id
  167. def get_company_accounts(self, company_id, acc='credit'):
  168. rc_obj = self.pool.get('res.company')
  169. if acc == 'credit':
  170. return [brw.id for brw in rc_obj.browse(self.cr, self.uid, company_id).credit_account_ids]
  171. else:
  172. return [brw.id for brw in rc_obj.browse(self.cr, self.uid, company_id).debit_account_ids]
  173. def _get_partner_balance(self, account, init_period, ctx=None):
  174. rp_obj = self.pool.get('res.partner')
  175. res = []
  176. ctx = ctx or {}
  177. if account['type'] in ('other', 'liquidity', 'receivable', 'payable'):
  178. sql_query = """
  179. SELECT
  180. CASE
  181. WHEN aml.partner_id IS NOT NULL
  182. THEN (SELECT name FROM res_partner WHERE aml.partner_id = id)
  183. ELSE 'UNKNOWN'
  184. END AS partner_name,
  185. CASE
  186. WHEN aml.partner_id IS NOT NULL
  187. THEN aml.partner_id
  188. ELSE 0
  189. END AS p_idx,
  190. %s,
  191. %s,
  192. %s,
  193. %s
  194. FROM account_move_line AS aml
  195. INNER JOIN account_account aa ON aa.id = aml.account_id
  196. INNER JOIN account_move am ON am.id = aml.move_id
  197. %s
  198. GROUP BY p_idx, partner_name
  199. """
  200. WHERE_POSTED = ''
  201. if ctx.get('state','posted')=='posted':
  202. WHERE_POSTED = "AND am.state = 'posted'"
  203. cur_periods = ', '.join([str(i) for i in ctx['periods']])
  204. init_periods = ', '.join([str(i) for i in init_period])
  205. WHERE = """
  206. WHERE aml.period_id IN (%s)
  207. AND aa.id = %s
  208. AND aml.state <> 'draft'
  209. """ % (init_periods, account['id'])
  210. query_init = sql_query%('SUM(aml.debit) AS init_dr',
  211. 'SUM(aml.credit) AS init_cr',
  212. '0.0 AS bal_dr',
  213. '0.0 AS bal_cr',
  214. WHERE+WHERE_POSTED)
  215. WHERE = """
  216. WHERE aml.period_id IN (%s)
  217. AND aa.id = %s
  218. AND aml.state <> 'draft'
  219. """ % (cur_periods, account['id'])
  220. query_bal = sql_query%('0.0 AS init_dr',
  221. '0.0 AS init_cr',
  222. 'SUM(aml.debit) AS bal_dr',
  223. 'SUM(aml.credit) AS bal_cr',
  224. WHERE+WHERE_POSTED)
  225. query = '''
  226. SELECT
  227. partner_name,
  228. p_idx,
  229. SUM(init_dr)-SUM(init_cr) AS balanceinit,
  230. SUM(bal_dr) AS debit,
  231. SUM(bal_cr) AS credit,
  232. SUM(init_dr) - SUM(init_cr) + SUM(bal_dr) - SUM(bal_cr) AS balance
  233. FROM (
  234. SELECT
  235. *
  236. FROM (%s) vinit
  237. UNION ALL (%s)
  238. ) v
  239. GROUP BY p_idx, partner_name
  240. ORDER BY partner_name
  241. '''%(query_init,query_bal)
  242. self.cr.execute(query)
  243. res_dict = self.cr.dictfetchall()
  244. for det in res_dict:
  245. i,d,c,b = det['balanceinit'], det['debit'], det['credit'], det['balance'],
  246. any([bool(i),bool(d),bool(c),bool(b)]) and res.append({
  247. 'partner_name': det['partner_name'],
  248. 'balanceinit': i,
  249. 'debit': d,
  250. 'credit': c,
  251. 'balance': b,
  252. })
  253. return res
  254. def _get_analytic_ledger(self, account, ctx={}):
  255. res = []
  256. if account['type'] in ('other', 'liquidity', 'receivable', 'payable'):
  257. #~ TODO: CUANDO EL PERIODO ESTE VACIO LLENARLO CON LOS PERIODOS DEL EJERCICIO
  258. #~ FISCAL, SIN LOS PERIODOS ESPECIALES
  259. periods = ', '.join([str(i) for i in ctx['periods']])
  260. #~ periods = str(tuple(ctx['periods']))
  261. where = """where aml.period_id in (%s) and aa.id = %s and aml.state <> 'draft'""" % (
  262. periods, account['id'])
  263. if ctx.get('state','posted')=='posted':
  264. where += "AND am.state = 'posted'"
  265. sql_detalle = """select aml.id as id, aj.name as diario, aa.name as descripcion,
  266. (select name from res_partner where aml.partner_id = id) as partner,
  267. aa.code as cuenta, aml.name as name,
  268. aml.ref as ref,
  269. case when aml.debit is null then 0.00 else aml.debit end as debit,
  270. case when aml.credit is null then 0.00 else aml.credit end as credit,
  271. (select code from account_analytic_account where aml.analytic_account_id = id) as analitica,
  272. aml.date as date, ap.name as periodo,
  273. am.name as asiento
  274. from account_move_line aml
  275. inner join account_journal aj on aj.id = aml.journal_id
  276. inner join account_account aa on aa.id = aml.account_id
  277. inner join account_period ap on ap.id = aml.period_id
  278. inner join account_move am on am.id = aml.move_id """ + where +\
  279. """ order by date, am.name"""
  280. self.cr.execute(sql_detalle)
  281. resultat = self.cr.dictfetchall()
  282. balance = account['balanceinit']
  283. for det in resultat:
  284. balance += det['debit'] - det['credit']
  285. res.append({
  286. 'id': det['id'],
  287. 'date': det['date'],
  288. 'journal': det['diario'],
  289. 'partner': det['partner'],
  290. 'name': det['name'],
  291. 'entry': det['asiento'],
  292. 'ref': det['ref'],
  293. 'debit': det['debit'],
  294. 'credit': det['credit'],
  295. 'analytic': det['analitica'],
  296. 'period': det['periodo'],
  297. 'balance': balance,
  298. })
  299. return res
  300. def _get_journal_ledger(self, account, ctx={}):
  301. res = []
  302. am_obj = self.pool.get('account.move')
  303. print 'AM OBJ ', am_obj
  304. if account['type'] in ('other', 'liquidity', 'receivable', 'payable'):
  305. #~ TODO: CUANDO EL PERIODO ESTE VACIO LLENARLO CON LOS PERIODOS DEL EJERCICIO
  306. #~ FISCAL, SIN LOS PERIODOS ESPECIALES
  307. periods = ', '.join([str(i) for i in ctx['periods']])
  308. #~ periods = str(tuple(ctx['periods']))
  309. where = """where aml.period_id in (%s) and aa.id = %s and aml.state <> 'draft'""" % (
  310. periods, account['id'])
  311. if ctx.get('state','posted')=='posted':
  312. where += "AND am.state = 'posted'"
  313. sql_detalle = """SELECT
  314. DISTINCT am.id as am_id,
  315. aj.name as diario,
  316. am.name as name,
  317. am.date as date,
  318. ap.name as periodo
  319. from account_move_line aml
  320. inner join account_journal aj on aj.id = aml.journal_id
  321. inner join account_account aa on aa.id = aml.account_id
  322. inner join account_period ap on ap.id = aml.period_id
  323. inner join account_move am on am.id = aml.move_id """ + where +\
  324. """ order by date, am.name"""
  325. self.cr.execute(sql_detalle)
  326. resultat = self.cr.dictfetchall()
  327. for det in resultat:
  328. res.append({
  329. 'am_id': det['am_id'],
  330. 'journal': det['diario'],
  331. 'name': det['name'],
  332. 'date': det['date'],
  333. 'period': det['periodo'],
  334. 'obj': am_obj.browse(self.cr,self.uid,det['am_id'])
  335. })
  336. print 'ACCOUNT NAME', am_obj.browse(self.cr,self.uid,det['am_id']).name
  337. return res
  338. def lines(self, form, level=0):
  339. """
  340. Returns all the data needed for the report lines
  341. (account info plus debit/credit/balance in the selected period
  342. and the full year)
  343. """
  344. account_obj = self.pool.get('account.account')
  345. period_obj = self.pool.get('account.period')
  346. fiscalyear_obj = self.pool.get('account.fiscalyear')
  347. def _get_children_and_consol(cr, uid, ids, level, context={}, change_sign=False):
  348. aa_obj = self.pool.get('account.account')
  349. ids2 = []
  350. for aa_brw in aa_obj.browse(cr, uid, ids, context):
  351. if aa_brw.child_id and aa_brw.level < level and aa_brw.type != 'consolidation':
  352. if not change_sign:
  353. ids2.append([aa_brw.id, True, False, aa_brw])
  354. ids2 += _get_children_and_consol(cr, uid, [
  355. x.id for x in aa_brw.child_id], level, context, change_sign=change_sign)
  356. if change_sign:
  357. ids2.append(aa_brw.id)
  358. else:
  359. ids2.append([aa_brw.id, False, True, aa_brw])
  360. else:
  361. if change_sign:
  362. ids2.append(aa_brw.id)
  363. else:
  364. ids2.append([aa_brw.id, True, True, aa_brw])
  365. return ids2
  366. #############################################################################
  367. # CONTEXT FOR ENDIND BALANCE #
  368. #######################################################################
  369. def _ctx_end(ctx):
  370. ctx_end = ctx
  371. ctx_end['filter'] = form.get('filter', 'all')
  372. ctx_end['fiscalyear'] = fiscalyear.id
  373. #~ ctx_end['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('special','=',False)])
  374. if ctx_end['filter'] not in ['bydate', 'none']:
  375. special = self.special_period(form['periods'])
  376. else:
  377. special = False
  378. if form['filter'] in ['byperiod', 'all']:
  379. if special:
  380. ctx_end['periods'] = period_obj.search(self.cr, self.uid, [(
  381. 'id', 'in', form['periods'] or ctx_end.get('periods', False))])
  382. else:
  383. ctx_end['periods'] = period_obj.search(self.cr, self.uid, [('id', 'in', form[
  384. 'periods'] or ctx_end.get('periods', False)), ('special', '=', False)])
  385. if form['filter'] in ['bydate', 'all', 'none']:
  386. ctx_end['date_from'] = form['date_from']
  387. ctx_end['date_to'] = form['date_to']
  388. return ctx_end.copy()
  389. def missing_period(ctx_init):
  390. ctx_init['fiscalyear'] = fiscalyear_obj.search(self.cr, self.uid, [('date_stop', '<', fiscalyear.date_start)], order='date_stop') and \
  391. fiscalyear_obj.search(self.cr, self.uid, [(
  392. 'date_stop', '<', fiscalyear.date_start)], order='date_stop')[-1] or []
  393. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [(
  394. 'fiscalyear_id', '=', ctx_init['fiscalyear']), ('date_stop', '<', fiscalyear.date_start)])
  395. return ctx_init
  396. #############################################################################
  397. # CONTEXT FOR INITIAL BALANCE #
  398. #######################################################################
  399. def _ctx_init(ctx):
  400. ctx_init = self.context.copy()
  401. ctx_init['filter'] = form.get('filter', 'all')
  402. ctx_init['fiscalyear'] = fiscalyear.id
  403. if form['filter'] in ['byperiod', 'all']:
  404. ctx_init['periods'] = form['periods']
  405. if not ctx_init['periods']:
  406. ctx_init = missing_period(ctx_init.copy())
  407. date_start = min([period.date_start for period in period_obj.browse(
  408. self.cr, self.uid, ctx_init['periods'])])
  409. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [(
  410. 'fiscalyear_id', '=', fiscalyear.id), ('date_stop', '<=', date_start)])
  411. elif form['filter'] in ['bydate']:
  412. ctx_init['date_from'] = fiscalyear.date_start
  413. ctx_init['date_to'] = form['date_from']
  414. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [(
  415. 'fiscalyear_id', '=', fiscalyear.id), ('date_stop', '<=', ctx_init['date_to'])])
  416. elif form['filter'] == 'none':
  417. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [(
  418. 'fiscalyear_id', '=', fiscalyear.id), ('special', '=', True)])
  419. date_start = min([period.date_start for period in period_obj.browse(
  420. self.cr, self.uid, ctx_init['periods'])])
  421. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [(
  422. 'fiscalyear_id', '=', fiscalyear.id), ('date_start', '<=', date_start), ('special', '=', True)])
  423. return ctx_init.copy()
  424. def z(n):
  425. return abs(n) < 0.005 and 0.0 or n
  426. self.context['state'] = form['target_move'] or 'posted'
  427. self.from_currency_id = self.get_company_currency(form['company_id'] and type(form[
  428. 'company_id']) in (list, tuple) and form['company_id'][0] or form['company_id'])
  429. if not form['currency_id']:
  430. self.to_currency_id = self.from_currency_id
  431. else:
  432. self.to_currency_id = form['currency_id'] and type(form['currency_id']) in (
  433. list, tuple) and form['currency_id'][0] or form['currency_id']
  434. if 'account_list' in form and form['account_list']:
  435. account_ids = form['account_list']
  436. account_list= form['account_list']
  437. del form['account_list']
  438. credit_account_ids = self.get_company_accounts(form['company_id'] and type(form[
  439. 'company_id']) in (list, tuple) and form['company_id'][0] or form['company_id'], 'credit')
  440. debit_account_ids = self.get_company_accounts(form['company_id'] and type(form[
  441. 'company_id']) in (list, tuple) and form['company_id'][0] or form['company_id'], 'debit')
  442. if form.get('fiscalyear'):
  443. if type(form.get('fiscalyear')) in (list, tuple):
  444. fiscalyear = form['fiscalyear'] and form['fiscalyear'][0]
  445. elif type(form.get('fiscalyear')) in (int,):
  446. fiscalyear = form['fiscalyear']
  447. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, fiscalyear)
  448. ################################################################
  449. # Get the accounts #
  450. ################################################################
  451. all_account_ids = _get_children_and_consol(
  452. self.cr, self.uid, account_ids, 100, self.context)
  453. account_ids = _get_children_and_consol(self.cr, self.uid, account_ids, form[
  454. 'display_account_level'] and form['display_account_level'] or 100, self.context)
  455. credit_account_ids = _get_children_and_consol(
  456. self.cr, self.uid, credit_account_ids, 100, self.context, change_sign=True)
  457. debit_account_ids = _get_children_and_consol(
  458. self.cr, self.uid, debit_account_ids, 100, self.context, change_sign=True)
  459. credit_account_ids = list(set(
  460. credit_account_ids) - set(debit_account_ids))
  461. #
  462. # Generate the report lines (checking each account)
  463. #
  464. tot_check = False
  465. if not form['periods']:
  466. form['periods'] = period_obj.search(self.cr, self.uid, [(
  467. 'fiscalyear_id', '=', fiscalyear.id), ('special', '=', False)], order='date_start asc')
  468. if not form['periods']:
  469. raise osv.except_osv(_('UserError'), _(
  470. 'The Selected Fiscal Year Does not have Regular Periods'))
  471. if form['columns'] == 'qtr':
  472. period_ids = period_obj.search(self.cr, self.uid, [(
  473. 'fiscalyear_id', '=', fiscalyear.id), ('special', '=', False)], order='date_start asc')
  474. a = 0
  475. l = []
  476. p = []
  477. for x in period_ids:
  478. a += 1
  479. if a < 3:
  480. l.append(x)
  481. else:
  482. l.append(x)
  483. p.append(l)
  484. l = []
  485. a = 0
  486. tot_bal1 = 0.0
  487. tot_bal2 = 0.0
  488. tot_bal3 = 0.0
  489. tot_bal4 = 0.0
  490. tot_bal5 = 0.0
  491. elif form['columns'] == 'thirteen':
  492. period_ids = period_obj.search(self.cr, self.uid, [(
  493. 'fiscalyear_id', '=', fiscalyear.id), ('special', '=', False)], order='date_start asc')
  494. tot_bal1 = 0.0
  495. tot_bal1 = 0.0
  496. tot_bal2 = 0.0
  497. tot_bal3 = 0.0
  498. tot_bal4 = 0.0
  499. tot_bal5 = 0.0
  500. tot_bal6 = 0.0
  501. tot_bal7 = 0.0
  502. tot_bal8 = 0.0
  503. tot_bal9 = 0.0
  504. tot_bal10 = 0.0
  505. tot_bal11 = 0.0
  506. tot_bal12 = 0.0
  507. tot_bal13 = 0.0
  508. else:
  509. ctx_end = _ctx_end(self.context.copy())
  510. tot_bin = 0.0
  511. tot_deb = 0.0
  512. tot_crd = 0.0
  513. tot_ytd = 0.0
  514. tot_eje = 0.0
  515. res = {}
  516. result_acc = []
  517. tot = {}
  518. ###############################################################
  519. # Calculations of credit, debit and balance,
  520. # without repeating operations.
  521. ###############################################################
  522. account_black_ids = account_obj.search(self.cr, self.uid, (
  523. [('id', 'in', [i[0] for i in all_account_ids]),
  524. ('type', 'not in',
  525. ('view', 'consolidation'))]))
  526. account_not_black_ids = account_obj.search(self.cr, self.uid, ([('id', 'in', [
  527. i[0] for i in all_account_ids]),('type', '=', 'view')]))
  528. acc_cons_ids = account_obj.search(self.cr, self.uid, ([('id', 'in', [
  529. i[0] for i in all_account_ids]), ('type', 'in', ('consolidation',))]))
  530. account_consol_ids = acc_cons_ids and account_obj._get_children_and_consol(
  531. self.cr, self.uid, acc_cons_ids) or []
  532. account_black_ids += account_obj.search(self.cr, self.uid, (
  533. [('id', 'in', account_consol_ids ),
  534. ('type', 'not in',
  535. ('view', 'consolidation'))]))
  536. account_black_ids = list(set(account_black_ids))
  537. c_account_not_black_ids = account_obj.search(self.cr, self.uid, ([
  538. ('id', 'in', account_consol_ids),
  539. ('type', '=', 'view')]))
  540. delete_cons = False
  541. if c_account_not_black_ids:
  542. delete_cons = set(account_not_black_ids) & set(c_account_not_black_ids) and True or False
  543. account_not_black_ids = list(set(account_not_black_ids) - set(c_account_not_black_ids))
  544. # This could be done quickly with a sql sentence
  545. account_not_black = account_obj.browse(
  546. self.cr, self.uid, account_not_black_ids)
  547. account_not_black.sort(key=lambda x: x.level)
  548. account_not_black.reverse()
  549. account_not_black_ids = [i.id for i in account_not_black]
  550. c_account_not_black = account_obj.browse(
  551. self.cr, self.uid, c_account_not_black_ids)
  552. c_account_not_black.sort(key=lambda x: x.level)
  553. c_account_not_black.reverse()
  554. c_account_not_black_ids = [i.id for i in c_account_not_black]
  555. if delete_cons:
  556. account_not_black_ids = c_account_not_black_ids + account_not_black_ids
  557. account_not_black = c_account_not_black + account_not_black
  558. else:
  559. acc_cons_brw = account_obj.browse(
  560. self.cr, self.uid, acc_cons_ids)
  561. acc_cons_brw.sort(key=lambda x: x.level)
  562. acc_cons_brw.reverse()
  563. acc_cons_ids = [i.id for i in acc_cons_brw]
  564. account_not_black_ids = c_account_not_black_ids + acc_cons_ids + account_not_black_ids
  565. account_not_black = c_account_not_black + acc_cons_brw + account_not_black
  566. all_account_period = {} # All accounts per period
  567. # Iteration limit depending on the number of columns
  568. if form['columns'] == 'thirteen':
  569. limit = 13
  570. elif form['columns'] == 'qtr':
  571. limit = 5
  572. else:
  573. limit = 1
  574. for p_act in range(limit):
  575. if limit != 1:
  576. if p_act == limit-1:
  577. form['periods'] = period_ids
  578. else:
  579. if form['columns'] == 'thirteen':
  580. form['periods'] = [period_ids[p_act]]
  581. elif form['columns'] == 'qtr':
  582. form['periods'] = p[p_act]
  583. if form['inf_type'] == 'IS':
  584. ctx_to_use = _ctx_end(self.context.copy())
  585. else:
  586. ctx_i = _ctx_init(self.context.copy())
  587. ctx_to_use = _ctx_end(self.context.copy())
  588. account_black = account_obj.browse(
  589. self.cr, self.uid, account_black_ids, ctx_to_use)
  590. if form['inf_type'] == 'BS':
  591. account_black_init = account_obj.browse(
  592. self.cr, self.uid, account_black_ids, ctx_i)
  593. #~ Black
  594. dict_black = {}
  595. for i in account_black:
  596. d = i.debit
  597. c = i.credit
  598. dict_black[i.id] = {
  599. 'obj': i,
  600. 'debit': d,
  601. 'credit': c,
  602. 'balance': d-c
  603. }
  604. if form['inf_type'] == 'BS':
  605. dict_black.get(i.id)['balanceinit'] = 0.0
  606. # If the report is a balance sheet
  607. # Balanceinit values are added to the dictionary
  608. if form['inf_type'] == 'BS':
  609. for i in account_black_init:
  610. dict_black.get(i.id)['balanceinit'] = i.balance
  611. #~ Not black
  612. dict_not_black = {}
  613. for i in account_not_black:
  614. dict_not_black[i.id] = {
  615. 'obj': i, 'debit': 0.0, 'credit': 0.0, 'balance': 0.0}
  616. if form['inf_type'] == 'BS':
  617. dict_not_black.get(i.id)['balanceinit'] = 0.0
  618. all_account = dict_black.copy(
  619. ) #It makes a copy because they modify
  620. for acc_id in account_not_black_ids:
  621. acc_childs = dict_not_black.get(acc_id).get('obj').type=='view' \
  622. and dict_not_black.get(acc_id).get('obj').child_id \
  623. or dict_not_black.get(acc_id).get('obj').child_consol_ids
  624. for child_id in acc_childs:
  625. if child_id.type == 'consolidation' and delete_cons:
  626. continue
  627. dict_not_black.get(acc_id)['debit'] += all_account.get(
  628. child_id.id).get('debit')
  629. dict_not_black.get(acc_id)['credit'] += all_account.get(
  630. child_id.id).get('credit')
  631. dict_not_black.get(acc_id)['balance'] += all_account.get(
  632. child_id.id).get('balance')
  633. if form['inf_type'] == 'BS':
  634. dict_not_black.get(acc_id)['balanceinit'] += all_account.get(
  635. child_id.id).get('balanceinit')
  636. all_account[acc_id] = dict_not_black[acc_id]
  637. if p_act == limit-1:
  638. all_account_period['all'] = all_account
  639. else:
  640. if form['columns'] == 'thirteen':
  641. all_account_period[p_act] = all_account
  642. elif form['columns'] == 'qtr':
  643. all_account_period[p_act] = all_account
  644. ###############################################################
  645. # End of the calculations of credit, debit and balance
  646. #
  647. ###############################################################
  648. for aa_id in account_ids:
  649. id = aa_id[0]
  650. if aa_id[3].type == 'consolidation' and delete_cons:
  651. continue
  652. #
  653. # Check if we need to include this level
  654. #
  655. if not form['display_account_level'] or aa_id[3].level <= form['display_account_level']:
  656. res = {
  657. 'id': id,
  658. 'type': aa_id[3].type,
  659. 'code': aa_id[3].code,
  660. 'name': (aa_id[2] and not aa_id[1]) and 'TOTAL %s' % (aa_id[3].name.upper()) or aa_id[3].name,
  661. 'parent_id': aa_id[3].parent_id and aa_id[3].parent_id.id,
  662. 'level': aa_id[3].level,
  663. 'label': aa_id[1],
  664. 'total': aa_id[2],
  665. 'change_sign': credit_account_ids and (id in credit_account_ids and -1 or 1) or 1
  666. }
  667. if form['columns'] == 'qtr':
  668. for pn in range(1, 5):
  669. if form['inf_type'] == 'IS':
  670. d, c, b = map(z, [
  671. all_account_period.get(pn-1).get(id).get('debit', 0.0), all_account_period.get(pn-1).get(id).get('credit', 0.0), all_account_period.get(pn-1).get(id).get('balance', 0.0)])
  672. res.update({
  673. 'dbr%s' % pn: self.exchange(d),
  674. 'cdr%s' % pn: self.exchange(c),
  675. 'bal%s' % pn: self.exchange(b),
  676. })
  677. else:
  678. i, d, c = map(z, [
  679. all_account_period.get(pn-1).get(id).get('balanceinit', 0.0), all_account_period.get(pn-1).get(id).get('debit', 0.0), all_account_period.get(pn-1).get(id).get('credit', 0.0)])
  680. b = z(i+d-c)
  681. res.update({
  682. 'dbr%s' % pn: self.exchange(d),
  683. 'cdr%s' % pn: self.exchange(c),
  684. 'bal%s' % pn: self.exchange(b),
  685. })
  686. if form['inf_type'] == 'IS':
  687. d, c, b = map(z, [
  688. all_account_period.get('all').get(id).get('debit', 0.0), all_account_period.get('all').get(id).get('credit',0.0), all_account_period.get('all').get(id).get('balance')])
  689. res.update({
  690. 'dbr5': self.exchange(d),
  691. 'cdr5': self.exchange(c),
  692. 'bal5': self.exchange(b),
  693. })
  694. else:
  695. i, d, c = map(z, [
  696. all_account_period.get('all').get(id).get('balanceinit', 0.0), all_account_period.get('all').get(id).get('debit', 0.0), all_account_period.get('all').get(id).get('credit',0.0)])
  697. b = z(i+d-c)
  698. res.update({
  699. 'dbr5': self.exchange(d),
  700. 'cdr5': self.exchange(c),
  701. 'bal5': self.exchange(b),
  702. })
  703. elif form['columns'] == 'thirteen':
  704. pn = 1
  705. for p_num in range(12):
  706. if form['inf_type'] == 'IS':
  707. d, c, b = map(z, [
  708. all_account_period.get(p_num).get(id).get('debit', 0.0), all_account_period.get(p_num).get(id).get('credit', 0.0), all_account_period.get(p_num).get(id).get('balance', 0.0)])
  709. res.update({
  710. 'dbr%s' % pn: self.exchange(d),
  711. 'cdr%s' % pn: self.exchange(c),
  712. 'bal%s' % pn: self.exchange(b),
  713. })
  714. else:
  715. i, d, c = map(z, [
  716. all_account_period.get(p_num).get(id).get('balanceinit', 0.0), all_account_period.get(p_num).get(id).get('debit', 0.0), all_account_period.get(p_num).get(id).get('credit', 0.0)])
  717. b = z(i+d-c)
  718. res.update({
  719. 'dbr%s' % pn: self.exchange(d),
  720. 'cdr%s' % pn: self.exchange(c),
  721. 'bal%s' % pn: self.exchange(b),
  722. })
  723. pn += 1
  724. if form['inf_type'] == 'IS':
  725. d, c, b = map(z, [
  726. all_account_period.get('all').get(id).get('debit', 0.0), all_account_period.get('all').get(id).get('credit', 0.0), all_account_period.get('all').get(id).get('balance', 0.0)])
  727. res.update({
  728. 'dbr13': self.exchange(d),
  729. 'cdr13': self.exchange(c),
  730. 'bal13': self.exchange(b),
  731. })
  732. else:
  733. i, d, c = map(z, [
  734. all_account_period.get('all').get(id).get('balanceinit', 0.0), all_account_period.get('all').get(id).get('debit', 0.0), all_account_period.get('all').get(id).get('credit', 0.0)])
  735. b = z(i+d-c)
  736. res.update({
  737. 'dbr13': self.exchange(d),
  738. 'cdr13': self.exchange(c),
  739. 'bal13': self.exchange(b),
  740. })
  741. else:
  742. i, d, c = map(z, [
  743. all_account_period.get('all').get(id).get('balanceinit', 0.0), all_account_period.get('all').get(id).get('debit', 0.0), all_account_period.get('all').get(id).get('credit', 0.0)])
  744. b = z(i+d-c)
  745. res.update({
  746. 'balanceinit': self.exchange(i),
  747. 'debit': self.exchange(d),
  748. 'credit': self.exchange(c),
  749. 'ytd': self.exchange(d-c),
  750. })
  751. if form['inf_type'] == 'IS' and form['columns'] == 'one':
  752. res.update({
  753. 'balance': self.exchange(d-c),
  754. })
  755. else:
  756. res.update({
  757. 'balance': self.exchange(b),
  758. })
  759. #
  760. # Check whether we must include this line in the report or not
  761. #
  762. to_include = False
  763. if form['columns'] in ('thirteen', 'qtr'):
  764. to_test = [False]
  765. if form['display_account'] == 'mov' and aa_id[3].parent_id:
  766. # Include accounts with movements
  767. for x in range(pn-1):
  768. to_test.append(res.get(
  769. 'dbr%s' % x, 0.0) >= 0.005 and True or False)
  770. to_test.append(res.get(
  771. 'cdr%s' % x, 0.0) >= 0.005 and True or False)
  772. if any(to_test):
  773. to_include = True
  774. elif form['display_account'] == 'bal' and aa_id[3].parent_id:
  775. # Include accounts with balance
  776. for x in range(pn-1):
  777. to_test.append(res.get(
  778. 'bal%s' % x, 0.0) >= 0.005 and True or False)
  779. if any(to_test):
  780. to_include = True
  781. elif form['display_account'] == 'bal_mov' and aa_id[3].parent_id:
  782. # Include accounts with balance or movements
  783. for x in range(pn-1):
  784. to_test.append(res.get(
  785. 'bal%s' % x, 0.0) >= 0.005 and True or False)
  786. to_test.append(res.get(
  787. 'dbr%s' % x, 0.0) >= 0.005 and True or False)
  788. to_test.append(res.get(
  789. 'cdr%s' % x, 0.0) >= 0.005 and True or False)
  790. if any(to_test):
  791. to_include = True
  792. else:
  793. # Include all accounts
  794. to_include = True
  795. else:
  796. if form['display_account'] == 'mov' and aa_id[3].parent_id:
  797. # Include accounts with movements
  798. if abs(d) >= 0.005 or abs(c) >= 0.005:
  799. to_include = True
  800. elif form['display_account'] == 'bal' and aa_id[3].parent_id:
  801. # Include accounts with balance
  802. if abs(b) >= 0.005:
  803. to_include = True
  804. elif form['display_account'] == 'bal_mov' and aa_id[3].parent_id:
  805. # Include accounts with balance or movements
  806. if abs(b) >= 0.005 or abs(d) >= 0.005 or abs(c) >= 0.005:
  807. to_include = True
  808. else:
  809. # Include all accounts
  810. to_include = True
  811. #~ ANALYTIC LEDGER
  812. if to_include and form['analytic_ledger'] and form['columns'] == 'four' and form['inf_type'] == 'BS' and res['type'] in ('other', 'liquidity', 'receivable', 'payable'):
  813. res['mayor'] = self._get_analytic_ledger(res, ctx=ctx_end)
  814. elif to_include and form['journal_ledger'] and form['columns'] == 'four' and form['inf_type'] == 'BS' and res['type'] in ('other', 'liquidity', 'receivable', 'payable'):
  815. res['journal'] = self._get_journal_ledger(res, ctx=ctx_end)
  816. elif to_include and form['partner_balance'] and form['columns'] == 'four' and form['inf_type'] == 'BS' and res['type'] in ('other', 'liquidity', 'receivable', 'payable'):
  817. res['partner'] = self._get_partner_balance(res, ctx_i['periods'], ctx=ctx_end)
  818. else:
  819. res['mayor'] = []
  820. if to_include:
  821. result_acc.append(res)
  822. #
  823. # Check whether we must sumarize this line in the report or not
  824. #
  825. if form['tot_check'] and (res['id'] in account_list) and (res['id'] not in tot):
  826. if form['columns'] == 'qtr':
  827. tot_check = True
  828. tot[res['id']] = True
  829. tot_bal1 += res.get('bal1', 0.0)
  830. tot_bal2 += res.get('bal2', 0.0)
  831. tot_bal3 += res.get('bal3', 0.0)
  832. tot_bal4 += res.get('bal4', 0.0)
  833. tot_bal5 += res.get('bal5', 0.0)
  834. elif form['columns'] == 'thirteen':
  835. tot_check = True
  836. tot[res['id']] = True
  837. tot_bal1 += res.get('bal1', 0.0)
  838. tot_bal2 += res.get('bal2', 0.0)
  839. tot_bal3 += res.get('bal3', 0.0)
  840. tot_bal4 += res.get('bal4', 0.0)
  841. tot_bal5 += res.get('bal5', 0.0)
  842. tot_bal6 += res.get('bal6', 0.0)
  843. tot_bal7 += res.get('bal7', 0.0)
  844. tot_bal8 += res.get('bal8', 0.0)
  845. tot_bal9 += res.get('bal9', 0.0)
  846. tot_bal10 += res.get('bal10', 0.0)
  847. tot_bal11 += res.get('bal11', 0.0)
  848. tot_bal12 += res.get('bal12', 0.0)
  849. tot_bal13 += res.get('bal13', 0.0)
  850. else:
  851. tot_check = True
  852. tot[res['id']] = True
  853. tot_bin += res['balanceinit']
  854. tot_deb += res['debit']
  855. tot_crd += res['credit']
  856. tot_ytd += res['ytd']
  857. tot_eje += res['balance']
  858. if tot_check:
  859. str_label = form['lab_str']
  860. res2 = {
  861. 'type': 'view',
  862. 'name': 'TOTAL %s' % (str_label),
  863. 'label': False,
  864. 'total': True,
  865. }
  866. if form['columns'] == 'qtr':
  867. res2.update(dict(
  868. bal1=z(tot_bal1),
  869. bal2=z(tot_bal2),
  870. bal3=z(tot_bal3),
  871. bal4=z(tot_bal4),
  872. bal5=z(tot_bal5),))
  873. elif form['columns'] == 'thirteen':
  874. res2.update(dict(
  875. bal1=z(tot_bal1),
  876. bal2=z(tot_bal2),
  877. bal3=z(tot_bal3),
  878. bal4=z(tot_bal4),
  879. bal5=z(tot_bal5),
  880. bal6=z(tot_bal6),
  881. bal7=z(tot_bal7),
  882. bal8=z(tot_bal8),
  883. bal9=z(tot_bal9),
  884. bal10=z(tot_bal10),
  885. bal11=z(tot_bal11),
  886. bal12=z(tot_bal12),
  887. bal13=z(tot_bal13),))
  888. else:
  889. res2.update({
  890. 'balanceinit': tot_bin,
  891. 'debit': tot_deb,
  892. 'credit': tot_crd,
  893. 'ytd': tot_ytd,
  894. 'balance': tot_eje,
  895. })
  896. result_acc.append(res2)
  897. return result_acc
  898. report_sxw.report_sxw('report.afr.1cols',
  899. 'wizard.report',
  900. 'account_financial_report/report/balance_full.rml',
  901. parser=account_balance,
  902. header=False)
  903. report_sxw.report_sxw('report.afr.2cols',
  904. 'wizard.report',
  905. 'account_financial_report/report/balance_full_2_cols.rml',
  906. parser=account_balance,
  907. header=False)
  908. report_sxw.report_sxw('report.afr.4cols',
  909. 'wizard.report',
  910. 'account_financial_report/report/balance_full_4_cols.rml',
  911. parser=account_balance,
  912. header=False)
  913. report_sxw.report_sxw('report.afr.analytic.ledger',
  914. 'wizard.report',
  915. 'account_financial_report/report/balance_full_4_cols_analytic_ledger.rml',
  916. parser=account_balance,
  917. header=False)
  918. report_sxw.report_sxw('report.afr.partner.balance',
  919. 'wizard.report',
  920. 'account_financial_report/report/balance_full_4_cols_partner_balance.rml',
  921. parser=account_balance,
  922. header=False)
  923. report_sxw.report_sxw('report.afr.journal.ledger',
  924. 'wizard.report',
  925. 'account_financial_report/report/balance_full_4_cols_journal_ledger.rml',
  926. parser=account_balance,
  927. header=False)
  928. report_sxw.report_sxw('report.afr.5cols',
  929. 'wizard.report',
  930. 'account_financial_report/report/balance_full_5_cols.rml',
  931. parser=account_balance,
  932. header=False)
  933. report_sxw.report_sxw('report.afr.qtrcols',
  934. 'wizard.report',
  935. 'account_financial_report/report/balance_full_qtr_cols.rml',
  936. parser=account_balance,
  937. header=False)
  938. report_sxw.report_sxw('report.afr.13cols',
  939. 'wizard.report',
  940. 'account_financial_report/report/balance_full_13_cols.rml',
  941. parser=account_balance,
  942. header=False)