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.

1243 lines
53 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
  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 time
  29. from openerp.report import report_sxw
  30. from openerp.tools.translate import _
  31. from openerp.osv import osv
  32. class account_balance(report_sxw.rml_parse):
  33. def __init__(self, cr, uid, name, context):
  34. super(account_balance, self).__init__(cr, uid, name, context)
  35. self.sum_debit = 0.00
  36. self.sum_credit = 0.00
  37. self.sum_balance = 0.00
  38. self.sum_debit_fy = 0.00
  39. self.sum_credit_fy = 0.00
  40. self.sum_balance_fy = 0.00
  41. self.date_lst = []
  42. self.date_lst_string = ''
  43. self.localcontext.update({
  44. 'time': time,
  45. 'lines': self.lines,
  46. 'get_fiscalyear_text': self.get_fiscalyear_text,
  47. 'get_periods_and_date_text': self.get_periods_and_date_text,
  48. 'get_informe_text': self.get_informe_text,
  49. 'get_month': self.get_month,
  50. 'exchange_name': self.exchange_name,
  51. 'get_vat_by_country': self.get_vat_by_country,
  52. })
  53. self.context = context
  54. def get_vat_by_country(self, form):
  55. """
  56. Return the vat of the partner by country
  57. """
  58. rc_obj = self.pool.get('res.company')
  59. country_code = rc_obj.browse(self.cr, self.uid,
  60. form['company_id'][0]).partner_id.\
  61. country_id.code or ''
  62. string_vat = rc_obj.browse(self.cr, self.uid,
  63. form['company_id'][0]).partner_id.vat or ''
  64. if string_vat:
  65. if country_code == 'MX':
  66. return '%s' % (string_vat[2:])
  67. elif country_code == 'VE':
  68. return '- %s-%s-%s' % (string_vat[2:3],
  69. string_vat[3:11],
  70. string_vat[11:12])
  71. else:
  72. return string_vat
  73. else:
  74. return _('\nVAT OF COMPANY NOT AVAILABLE')
  75. def get_fiscalyear_text(self, form):
  76. """
  77. Returns the fiscal year text used on the report.
  78. """
  79. fiscalyear_obj = self.pool['account.fiscalyear']
  80. fiscalyear = None
  81. if form.get('fiscalyear'):
  82. fiscalyear = fiscalyear_obj.browse(
  83. self.cr, self.uid, form['fiscalyear'])
  84. return fiscalyear.name or fiscalyear.code
  85. else:
  86. fiscalyear = fiscalyear_obj.browse(
  87. self.cr, self.uid, fiscalyear_obj.find(self.cr, self.uid))
  88. return "%s*" % (fiscalyear.name or fiscalyear.code)
  89. def get_informe_text(self, form):
  90. """
  91. Returns the header text used on the report.
  92. """
  93. afr_id = form['afr_id'] and type(form['afr_id']) in (
  94. list, tuple) and form['afr_id'][0] or form['afr_id']
  95. if afr_id:
  96. name = self.pool.get('afr').browse(self.cr, self.uid, afr_id).name
  97. elif form['analytic_ledger'] and form['columns'] == 'four' \
  98. 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. return _('From ') + self.formatLang(form['date_from'], date=True) \
  111. + _(' to ') + self.formatLang(form['date_to'], date=True)
  112. elif form['filter'] in ['byperiod', 'all']:
  113. aux = []
  114. period_obj = self.pool.get('account.period')
  115. for period in period_obj.browse(self.cr, self.uid,
  116. form['periods']):
  117. aux.append(period.date_start)
  118. aux.append(period.date_stop)
  119. sorted(aux)
  120. return _('From ') + self.formatLang(aux[0], date=True) + \
  121. _(' to ') + self.formatLang(aux[-1], date=True)
  122. def get_periods_and_date_text(self, form):
  123. """
  124. Returns the text with the periods/dates used on the report.
  125. """
  126. period_obj = self.pool['account.period']
  127. fiscalyear_obj = self.pool['account.fiscalyear']
  128. fiscalyear_id = form[
  129. 'fiscalyear'] or fiscalyear_obj.find(self.cr, self.uid)
  130. period_ids = period_obj.search(self.cr, self.uid, [(
  131. 'fiscalyear_id', '=', fiscalyear_id), ('special', '=', False)])
  132. if form['filter'] in ['byperiod', 'all']:
  133. period_ids = form['periods']
  134. periods_str = ', '.join([period.name or period.code
  135. for period in period_obj.browse(self.cr,
  136. self.uid,
  137. period_ids)])
  138. dates_str = None
  139. if form['filter'] in ['bydate', 'all']:
  140. dates_str = self.formatLang(form[
  141. 'date_from'], date=True) + ' - ' + \
  142. self.formatLang(form['date_to'],
  143. date=True) + ' '
  144. return {'periods': periods_str, 'date': dates_str}
  145. def special_period(self, periods):
  146. period_obj = self.pool.get('account.period')
  147. period_brw = period_obj.browse(self.cr, self.uid, periods)
  148. period_counter = [True for i in period_brw if not i.special]
  149. if not period_counter:
  150. return True
  151. return False
  152. def exchange_name(self, form):
  153. self.from_currency_id = self.\
  154. get_company_currency(form['company_id']
  155. and type(form['company_id']) in (list, tuple)
  156. and form['company_id'][0]
  157. or form['company_id'])
  158. if not form['currency_id']:
  159. self.to_currency_id = self.from_currency_id
  160. else:
  161. self.to_currency_id = form['currency_id'] \
  162. and type(form['currency_id']) in (list, tuple) \
  163. and form['currency_id'][0] or form['currency_id']
  164. return self.pool.get('res.currency').browse(self.cr, self.uid,
  165. self.to_currency_id).name
  166. def exchange(self, from_amount):
  167. if self.from_currency_id == self.to_currency_id:
  168. return from_amount
  169. curr_obj = self.pool.get('res.currency')
  170. return curr_obj.compute(self.cr, self.uid, self.from_currency_id,
  171. self.to_currency_id, from_amount)
  172. def get_company_currency(self, company_id):
  173. rc_obj = self.pool.get('res.company')
  174. return rc_obj.browse(self.cr, self.uid, company_id).currency_id.id
  175. def get_company_accounts(self, company_id, acc='credit'):
  176. rc_obj = self.pool.get('res.company')
  177. if acc == 'credit':
  178. return [brw.id for brw in rc_obj.browse(
  179. self.cr, self.uid,
  180. company_id).credit_account_ids]
  181. else:
  182. return [brw.id for brw in rc_obj.browse(
  183. self.cr, self.uid,
  184. company_id).debit_account_ids]
  185. def _get_partner_balance(self, account, init_period, ctx=None):
  186. res = []
  187. ctx = ctx or {}
  188. if account['type'] in ('other', 'liquidity', 'receivable', 'payable'):
  189. sql_query = """
  190. SELECT
  191. CASE
  192. WHEN aml.partner_id IS NOT NULL
  193. THEN (SELECT name
  194. FROM res_partner
  195. WHERE aml.partner_id = id)
  196. ELSE 'UNKNOWN'
  197. END AS partner_name,
  198. CASE
  199. WHEN aml.partner_id IS NOT NULL
  200. THEN aml.partner_id
  201. ELSE 0
  202. END AS p_idx,
  203. %s,
  204. %s,
  205. %s,
  206. %s
  207. FROM account_move_line AS aml
  208. INNER JOIN account_account aa ON aa.id = aml.account_id
  209. INNER JOIN account_move am ON am.id = aml.move_id
  210. %s
  211. GROUP BY p_idx, partner_name
  212. """
  213. WHERE_POSTED = ''
  214. if ctx.get('state', 'posted') == 'posted':
  215. WHERE_POSTED = "AND am.state = 'posted'"
  216. cur_periods = ', '.join([str(i) for i in ctx['periods']])
  217. init_periods = ', '.join([str(i) for i in init_period])
  218. WHERE = """
  219. WHERE aml.period_id IN (%s)
  220. AND aa.id = %s
  221. AND aml.state <> 'draft'
  222. """ % (init_periods, account['id'])
  223. query_init = sql_query % ('SUM(aml.debit) AS init_dr',
  224. 'SUM(aml.credit) AS init_cr',
  225. '0.0 AS bal_dr',
  226. '0.0 AS bal_cr',
  227. WHERE + WHERE_POSTED)
  228. WHERE = """
  229. WHERE aml.period_id IN (%s)
  230. AND aa.id = %s
  231. AND aml.state <> 'draft'
  232. """ % (cur_periods, account['id'])
  233. query_bal = sql_query % ('0.0 AS init_dr',
  234. '0.0 AS init_cr',
  235. 'SUM(aml.debit) AS bal_dr',
  236. 'SUM(aml.credit) AS bal_cr',
  237. WHERE + WHERE_POSTED)
  238. query = '''
  239. SELECT
  240. partner_name,
  241. p_idx,
  242. SUM(init_dr)-SUM(init_cr) AS balanceinit,
  243. SUM(bal_dr) AS debit,
  244. SUM(bal_cr) AS credit,
  245. SUM(init_dr) - SUM(init_cr)
  246. + SUM(bal_dr) - SUM(bal_cr) AS balance
  247. FROM (
  248. SELECT
  249. *
  250. FROM (%s) vinit
  251. UNION ALL (%s)
  252. ) v
  253. GROUP BY p_idx, partner_name
  254. ORDER BY partner_name
  255. ''' % (query_init, query_bal)
  256. self.cr.execute(query)
  257. res_dict = self.cr.dictfetchall()
  258. unknown = False
  259. for det in res_dict:
  260. i, d, c, b = det['balanceinit'], det[
  261. 'debit'], det['credit'], det['balance'],
  262. if not any([i, d, c, b]):
  263. continue
  264. data = {
  265. 'partner_name': det['partner_name'],
  266. 'balanceinit': i,
  267. 'debit': d,
  268. 'credit': c,
  269. 'balance': b,
  270. }
  271. if not det['p_idx']:
  272. unknown = data
  273. continue
  274. res.append(data)
  275. unknown and res.append(unknown)
  276. return res
  277. def _get_analytic_ledger(self, account, ctx=None):
  278. if ctx is None:
  279. ctx = {}
  280. res = []
  281. if account['type'] in ('other', 'liquidity', 'receivable', 'payable'):
  282. # ~ TODO: CUANDO EL PERIODO ESTE VACIO LLENARLO CON LOS PERIODOS
  283. # DEL EJERCICIO
  284. # ~ FISCAL, SIN LOS PERIODOS ESPECIALES
  285. periods = ', '.join([str(i) for i in ctx['periods']])
  286. # ~ periods = str(tuple(ctx['periods']))
  287. where = """where aml.period_id in (%s)
  288. and aa.id = %s
  289. and aml.state <> 'draft'""" % (periods, account['id'])
  290. if ctx.get('state', 'posted') == 'posted':
  291. where += "AND am.state = 'posted'"
  292. sql_detalle = """select aml.id as id,
  293. aj.name as diario,
  294. aa.name as descripcion,
  295. (select name
  296. from res_partner
  297. where aml.partner_id = id) as partner,
  298. aa.code as cuenta,
  299. aml.name as name,
  300. aml.ref as ref,
  301. case when aml.debit is null
  302. then 0.00
  303. else aml.debit
  304. end as debit,
  305. case when aml.credit is null
  306. then 0.00
  307. else aml.credit
  308. end as credit,
  309. (select code
  310. from account_analytic_account
  311. where aml.analytic_account_id = id)
  312. as analitica,
  313. aml.date as date,
  314. ap.name as periodo,
  315. am.name as asiento
  316. from account_move_line aml
  317. inner join account_journal aj
  318. on aj.id = aml.journal_id
  319. inner join account_account aa
  320. on aa.id = aml.account_id
  321. inner join account_period ap
  322. on ap.id = aml.period_id
  323. inner join account_move am
  324. on am.id = aml.move_id """ \
  325. + where + """ order by date, am.name"""
  326. self.cr.execute(sql_detalle)
  327. resultat = self.cr.dictfetchall()
  328. balance = account['balanceinit']
  329. for det in resultat:
  330. balance += det['debit'] - det['credit']
  331. res.append({
  332. 'id': det['id'],
  333. 'date': det['date'],
  334. 'journal': det['diario'],
  335. 'partner': det['partner'],
  336. 'name': det['name'],
  337. 'entry': det['asiento'],
  338. 'ref': det['ref'],
  339. 'debit': det['debit'],
  340. 'credit': det['credit'],
  341. 'analytic': det['analitica'],
  342. 'period': det['periodo'],
  343. 'balance': balance,
  344. })
  345. return res
  346. def _get_journal_ledger(self, account, ctx=None):
  347. if ctx is None:
  348. ctx = {}
  349. res = []
  350. am_obj = self.pool.get('account.move')
  351. if account['type'] in ('other', 'liquidity', 'receivable', 'payable'):
  352. # ~ TODO: CUANDO EL PERIODO ESTE VACIO LLENARLO CON LOS PERIODOS
  353. # DEL EJERCICIO
  354. # ~ FISCAL, SIN LOS PERIODOS ESPECIALES
  355. periods = ', '.join([str(i) for i in ctx['periods']])
  356. # ~ periods = str(tuple(ctx['periods']))
  357. where = """where aml.period_id in (%s)
  358. and aa.id = %s
  359. and aml.state <> 'draft'""" % (periods, account['id'])
  360. if ctx.get('state', 'posted') == 'posted':
  361. where += "AND am.state = 'posted'"
  362. sql_detalle = """SELECT
  363. DISTINCT am.id as am_id,
  364. aj.name as diario,
  365. am.name as name,
  366. am.date as date,
  367. ap.name as periodo
  368. from account_move_line aml
  369. inner join account_journal aj on aj.id = aml.journal_id
  370. inner join account_account aa on aa.id = aml.account_id
  371. inner join account_period ap on ap.id = aml.period_id
  372. inner join account_move am on am.id = aml.move_id """ \
  373. + where + """ order by date, am.name"""
  374. self.cr.execute(sql_detalle)
  375. resultat = self.cr.dictfetchall()
  376. for det in resultat:
  377. res.append({
  378. 'am_id': det['am_id'],
  379. 'journal': det['diario'],
  380. 'name': det['name'],
  381. 'date': det['date'],
  382. 'period': det['periodo'],
  383. 'obj': am_obj.browse(self.cr, self.uid, det['am_id'])
  384. })
  385. return res
  386. def lines(self, form, level=0):
  387. """
  388. Returns all the data needed for the report lines
  389. (account info plus debit/credit/balance in the selected period
  390. and the full year)
  391. """
  392. account_obj = self.pool.get('account.account')
  393. period_obj = self.pool.get('account.period')
  394. fiscalyear_obj = self.pool.get('account.fiscalyear')
  395. def _get_children_and_consol(cr, uid, ids, level, context=None,
  396. change_sign=False):
  397. if context is None:
  398. context = {}
  399. aa_obj = self.pool.get('account.account')
  400. ids2 = []
  401. for aa_brw in aa_obj.browse(cr, uid, ids, context):
  402. if aa_brw.child_id and aa_brw.level < level \
  403. and aa_brw.type != 'consolidation':
  404. if not change_sign:
  405. ids2.append([aa_brw.id, True, False, aa_brw])
  406. ids2 += _get_children_and_consol(
  407. cr, uid, [x.id for x in aa_brw.child_id], level,
  408. context, change_sign=change_sign)
  409. if change_sign:
  410. ids2.append(aa_brw.id)
  411. else:
  412. ids2.append([aa_brw.id, False, True, aa_brw])
  413. else:
  414. if change_sign:
  415. ids2.append(aa_brw.id)
  416. else:
  417. ids2.append([aa_brw.id, True, True, aa_brw])
  418. return ids2
  419. #######################################################################
  420. # CONTEXT FOR ENDIND BALANCE #
  421. #######################################################################
  422. def _ctx_end(ctx):
  423. ctx_end = ctx
  424. ctx_end['filter'] = form.get('filter', 'all')
  425. ctx_end['fiscalyear'] = fiscalyear.id
  426. # ~ ctx_end['periods'] = period_obj.\
  427. # search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),
  428. # ('special','=',False)])
  429. if ctx_end['filter'] not in ['bydate', 'none']:
  430. special = self.special_period(form['periods'])
  431. else:
  432. special = False
  433. if form['filter'] in ['byperiod', 'all']:
  434. if special:
  435. ctx_end['periods'] = period_obj.search(
  436. self.cr, self.uid,
  437. [('id', 'in', form['periods'] or ctx_end.get('periods',
  438. False))])
  439. else:
  440. ctx_end['periods'] = period_obj.search(
  441. self.cr, self.uid,
  442. [('id', 'in', form['periods'] or ctx_end.get('periods',
  443. False)),
  444. ('special', '=', False)])
  445. if form['filter'] in ['bydate', 'all', 'none']:
  446. ctx_end['date_from'] = form['date_from']
  447. ctx_end['date_to'] = form['date_to']
  448. return ctx_end.copy()
  449. def missing_period(ctx_init):
  450. ctx_init['fiscalyear'] = \
  451. fiscalyear_obj.search(self.cr, self.uid,
  452. [('date_stop', '<',
  453. fiscalyear.date_start)],
  454. order='date_stop') \
  455. and fiscalyear_obj.search(self.cr, self.uid,
  456. [('date_stop', '<',
  457. fiscalyear.date_start)],
  458. order='date_stop')[-1] or []
  459. ctx_init['periods'] = period_obj.search(
  460. self.cr, self.uid,
  461. [('fiscalyear_id', '=', ctx_init['fiscalyear']),
  462. ('date_stop', '<', fiscalyear.date_start)])
  463. return ctx_init
  464. #######################################################################
  465. # CONTEXT FOR INITIAL BALANCE #
  466. #######################################################################
  467. def _ctx_init(ctx):
  468. ctx_init = self.context.copy()
  469. ctx_init['filter'] = form.get('filter', 'all')
  470. ctx_init['fiscalyear'] = fiscalyear.id
  471. if form['filter'] in ['byperiod', 'all']:
  472. ctx_init['periods'] = form['periods']
  473. if not ctx_init['periods']:
  474. ctx_init = missing_period(ctx_init.copy())
  475. date_start = min([period.date_start for period in period_obj.
  476. browse(self.cr, self.uid,
  477. ctx_init['periods'])])
  478. ctx_init['periods'] = period_obj.search(
  479. self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
  480. ('date_stop', '<=', date_start)])
  481. elif form['filter'] in ['bydate']:
  482. ctx_init['date_from'] = fiscalyear.date_start
  483. ctx_init['date_to'] = form['date_from']
  484. ctx_init['periods'] = period_obj.search(
  485. self.cr, self.uid,
  486. [('fiscalyear_id', '=', fiscalyear.id),
  487. ('date_stop', '<=', ctx_init['date_to'])])
  488. elif form['filter'] == 'none':
  489. ctx_init['periods'] = period_obj.search(
  490. self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
  491. ('special', '=', True)])
  492. date_start = min([period.date_start for period in period_obj.
  493. browse(self.cr, self.uid,
  494. ctx_init['periods'])])
  495. ctx_init['periods'] = period_obj.search(
  496. self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
  497. ('date_start', '<=', date_start),
  498. ('special', '=', True)])
  499. return ctx_init.copy()
  500. def z(n):
  501. return abs(n) < 0.005 and 0.0 or n
  502. self.context['state'] = form['target_move'] or 'posted'
  503. self.from_currency_id = self.\
  504. get_company_currency(form['company_id']
  505. and type(form['company_id']) in (list, tuple)
  506. and form['company_id'][0]
  507. or form['company_id'])
  508. if not form['currency_id']:
  509. self.to_currency_id = self.from_currency_id
  510. else:
  511. self.to_currency_id = form['currency_id'] \
  512. and type(form['currency_id']) in (list, tuple) \
  513. and form['currency_id'][0] \
  514. or form['currency_id']
  515. if 'account_list' in form and form['account_list']:
  516. account_ids = form['account_list']
  517. account_list = form['account_list']
  518. del form['account_list']
  519. credit_account_ids = self.\
  520. get_company_accounts(form['company_id']
  521. and type(form['company_id']) in (list, tuple)
  522. and form['company_id'][0]
  523. or form['company_id'], 'credit')
  524. debit_account_ids = self.\
  525. get_company_accounts(form['company_id']
  526. and type(form['company_id']) in (list, tuple)
  527. and form['company_id'][0]
  528. or form['company_id'], 'debit')
  529. if form.get('fiscalyear'):
  530. if type(form.get('fiscalyear')) in (list, tuple):
  531. fiscalyear = form['fiscalyear'] and form['fiscalyear'][0]
  532. elif type(form.get('fiscalyear')) in (int,):
  533. fiscalyear = form['fiscalyear']
  534. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, fiscalyear)
  535. ################################################################
  536. # Get the accounts #
  537. ################################################################
  538. all_account_ids = _get_children_and_consol(
  539. self.cr, self.uid, account_ids, 100, self.context)
  540. account_ids = _get_children_and_consol(
  541. self.cr, self.uid, account_ids,
  542. form['display_account_level']
  543. and form['display_account_level']
  544. or 100, self.context)
  545. credit_account_ids = _get_children_and_consol(
  546. self.cr, self.uid, credit_account_ids, 100, self.context,
  547. change_sign=True)
  548. debit_account_ids = _get_children_and_consol(
  549. self.cr, self.uid, debit_account_ids, 100, self.context,
  550. change_sign=True)
  551. credit_account_ids = list(set(
  552. credit_account_ids) - set(debit_account_ids))
  553. #
  554. # Generate the report lines (checking each account)
  555. #
  556. tot_check = False
  557. if not form['periods']:
  558. form['periods'] = period_obj.search(
  559. self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
  560. ('special', '=', False)],
  561. order='date_start asc')
  562. if not form['periods']:
  563. raise osv.except_osv(_('UserError'), _(
  564. 'The Selected Fiscal Year Does not have Regular Periods'))
  565. if form['columns'] == 'qtr':
  566. period_ids = period_obj.search(
  567. self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
  568. ('special', '=', False)],
  569. order='date_start asc')
  570. a = 0
  571. l = []
  572. p = []
  573. for x in period_ids:
  574. a += 1
  575. if a < 3:
  576. l.append(x)
  577. else:
  578. l.append(x)
  579. p.append(l)
  580. l = []
  581. a = 0
  582. tot_bal1 = 0.0
  583. tot_bal2 = 0.0
  584. tot_bal3 = 0.0
  585. tot_bal4 = 0.0
  586. tot_bal5 = 0.0
  587. elif form['columns'] == 'thirteen':
  588. period_ids = period_obj.search(
  589. self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
  590. ('special', '=', False)],
  591. order='date_start asc')
  592. tot_bal1 = 0.0
  593. tot_bal1 = 0.0
  594. tot_bal2 = 0.0
  595. tot_bal3 = 0.0
  596. tot_bal4 = 0.0
  597. tot_bal5 = 0.0
  598. tot_bal6 = 0.0
  599. tot_bal7 = 0.0
  600. tot_bal8 = 0.0
  601. tot_bal9 = 0.0
  602. tot_bal10 = 0.0
  603. tot_bal11 = 0.0
  604. tot_bal12 = 0.0
  605. tot_bal13 = 0.0
  606. else:
  607. ctx_end = _ctx_end(self.context.copy())
  608. tot_bin = 0.0
  609. tot_deb = 0.0
  610. tot_crd = 0.0
  611. tot_ytd = 0.0
  612. tot_eje = 0.0
  613. res = {}
  614. result_acc = []
  615. tot = {}
  616. ###############################################################
  617. # Calculations of credit, debit and balance,
  618. # without repeating operations.
  619. ###############################################################
  620. account_black_ids = account_obj.search(
  621. self.cr, self.uid, (
  622. [('id', 'in', [i[0] for i in all_account_ids]),
  623. ('type', 'not in', ('view', 'consolidation'))]))
  624. account_not_black_ids = account_obj.search(
  625. self.cr, self.uid, ([('id', 'in', [i[0] for i in all_account_ids]),
  626. ('type', '=', 'view')]))
  627. acc_cons_ids = account_obj.search(
  628. self.cr, self.uid, ([('id', 'in', [i[0] for i in all_account_ids]),
  629. ('type', 'in', ('consolidation',))]))
  630. account_consol_ids = acc_cons_ids and account_obj.\
  631. _get_children_and_consol(self.cr, self.uid, acc_cons_ids) or []
  632. account_black_ids += account_obj.search(self.cr, self.uid, (
  633. [('id', 'in', account_consol_ids),
  634. ('type', 'not in',
  635. ('view', 'consolidation'))]))
  636. account_black_ids = list(set(account_black_ids))
  637. c_account_not_black_ids = account_obj.search(self.cr, self.uid, ([
  638. ('id', 'in', account_consol_ids),
  639. ('type', '=', 'view')]))
  640. delete_cons = False
  641. if c_account_not_black_ids:
  642. delete_cons = set(account_not_black_ids) & set(
  643. c_account_not_black_ids) and True or False
  644. account_not_black_ids = list(
  645. set(account_not_black_ids) - set(c_account_not_black_ids))
  646. # This could be done quickly with a sql sentence
  647. account_not_black = account_obj.browse(
  648. self.cr, self.uid, account_not_black_ids)
  649. account_not_black.sort(key=lambda x: x.level)
  650. account_not_black.reverse()
  651. account_not_black_ids = [i.id for i in account_not_black]
  652. c_account_not_black = account_obj.browse(
  653. self.cr, self.uid, c_account_not_black_ids)
  654. c_account_not_black.sort(key=lambda x: x.level)
  655. c_account_not_black.reverse()
  656. c_account_not_black_ids = [i.id for i in c_account_not_black]
  657. if delete_cons:
  658. account_not_black_ids = c_account_not_black_ids + \
  659. account_not_black_ids
  660. account_not_black = c_account_not_black + account_not_black
  661. else:
  662. acc_cons_brw = account_obj.browse(
  663. self.cr, self.uid, acc_cons_ids)
  664. acc_cons_brw.sort(key=lambda x: x.level)
  665. acc_cons_brw.reverse()
  666. acc_cons_ids = [i.id for i in acc_cons_brw]
  667. account_not_black_ids = c_account_not_black_ids + \
  668. acc_cons_ids + account_not_black_ids
  669. account_not_black = c_account_not_black + \
  670. acc_cons_brw + account_not_black
  671. all_account_period = {} # All accounts per period
  672. # Iteration limit depending on the number of columns
  673. if form['columns'] == 'thirteen':
  674. limit = 13
  675. elif form['columns'] == 'qtr':
  676. limit = 5
  677. else:
  678. limit = 1
  679. for p_act in range(limit):
  680. if limit != 1:
  681. if p_act == limit - 1:
  682. form['periods'] = period_ids
  683. else:
  684. if form['columns'] == 'thirteen':
  685. form['periods'] = [period_ids[p_act]]
  686. elif form['columns'] == 'qtr':
  687. form['periods'] = p[p_act]
  688. if form['inf_type'] == 'IS':
  689. ctx_to_use = _ctx_end(self.context.copy())
  690. else:
  691. ctx_i = _ctx_init(self.context.copy())
  692. ctx_to_use = _ctx_end(self.context.copy())
  693. account_black = account_obj.browse(
  694. self.cr, self.uid, account_black_ids, ctx_to_use)
  695. if form['inf_type'] == 'BS':
  696. account_black_init = account_obj.browse(
  697. self.cr, self.uid, account_black_ids, ctx_i)
  698. # ~ Black
  699. dict_black = {}
  700. for i in account_black:
  701. d = i.debit
  702. c = i.credit
  703. dict_black[i.id] = {
  704. 'obj': i,
  705. 'debit': d,
  706. 'credit': c,
  707. 'balance': d - c
  708. }
  709. if form['inf_type'] == 'BS':
  710. dict_black.get(i.id)['balanceinit'] = 0.0
  711. # If the report is a balance sheet
  712. # Balanceinit values are added to the dictionary
  713. if form['inf_type'] == 'BS':
  714. for i in account_black_init:
  715. dict_black.get(i.id)['balanceinit'] = i.balance
  716. # ~ Not black
  717. dict_not_black = {}
  718. for i in account_not_black:
  719. dict_not_black[i.id] = {
  720. 'obj': i, 'debit': 0.0, 'credit': 0.0, 'balance': 0.0}
  721. if form['inf_type'] == 'BS':
  722. dict_not_black.get(i.id)['balanceinit'] = 0.0
  723. all_account = dict_black.copy(
  724. ) # It makes a copy because they modify
  725. for acc_id in account_not_black_ids:
  726. acc_childs = dict_not_black.get(acc_id).get('obj').\
  727. type == 'view' \
  728. and dict_not_black.get(acc_id).get('obj').child_id \
  729. or dict_not_black.get(acc_id).get('obj').child_consol_ids
  730. for child_id in acc_childs:
  731. if child_id.type == 'consolidation' and delete_cons:
  732. continue
  733. dict_not_black.get(acc_id)['debit'] += all_account.get(
  734. child_id.id).get('debit')
  735. dict_not_black.get(acc_id)['credit'] += all_account.get(
  736. child_id.id).get('credit')
  737. dict_not_black.get(acc_id)['balance'] += all_account.get(
  738. child_id.id).get('balance')
  739. if form['inf_type'] == 'BS':
  740. dict_not_black.get(acc_id)['balanceinit'] += \
  741. all_account.get(child_id.id).get('balanceinit')
  742. all_account[acc_id] = dict_not_black[acc_id]
  743. if p_act == limit - 1:
  744. all_account_period['all'] = all_account
  745. else:
  746. if form['columns'] == 'thirteen':
  747. all_account_period[p_act] = all_account
  748. elif form['columns'] == 'qtr':
  749. all_account_period[p_act] = all_account
  750. ###############################################################
  751. # End of the calculations of credit, debit and balance
  752. #
  753. ###############################################################
  754. for aa_id in account_ids:
  755. id = aa_id[0]
  756. if aa_id[3].type == 'consolidation' and delete_cons:
  757. continue
  758. #
  759. # Check if we need to include this level
  760. #
  761. if not form['display_account_level'] \
  762. or aa_id[3].level <= form['display_account_level']:
  763. res = {
  764. 'id': id,
  765. 'type': aa_id[3].type,
  766. 'code': aa_id[3].code,
  767. 'name': (aa_id[2] and not aa_id[1])
  768. and 'TOTAL %s' % (aa_id[3].name.upper())
  769. or aa_id[3].name,
  770. 'parent_id': aa_id[3].parent_id and aa_id[3].parent_id.id,
  771. 'level': aa_id[3].level,
  772. 'label': aa_id[1],
  773. 'total': aa_id[2],
  774. 'change_sign': credit_account_ids
  775. and (id in credit_account_ids and -1 or 1) or 1
  776. }
  777. if form['columns'] == 'qtr':
  778. for pn in range(1, 5):
  779. if form['inf_type'] == 'IS':
  780. d, c, b = map(z, [
  781. all_account_period.get(pn - 1).
  782. get(id).get('debit', 0.0),
  783. all_account_period.get(pn - 1).
  784. get(id).get('credit', 0.0),
  785. all_account_period.get(pn - 1).
  786. get(id).get('balance', 0.0)])
  787. res.update({
  788. 'dbr%s' % pn: self.exchange(d),
  789. 'cdr%s' % pn: self.exchange(c),
  790. 'bal%s' % pn: self.exchange(b),
  791. })
  792. else:
  793. i, d, c = map(z, [
  794. all_account_period.get(pn - 1).
  795. get(id).get('balanceinit', 0.0),
  796. all_account_period.get(pn - 1).
  797. get(id).get('debit', 0.0),
  798. all_account_period.get(pn - 1).
  799. get(id).get('credit', 0.0)])
  800. b = z(i + d - c)
  801. res.update({
  802. 'dbr%s' % pn: self.exchange(d),
  803. 'cdr%s' % pn: self.exchange(c),
  804. 'bal%s' % pn: self.exchange(b),
  805. })
  806. if form['inf_type'] == 'IS':
  807. d, c, b = map(z, [
  808. all_account_period.get('all').get(id).
  809. get('debit', 0.0),
  810. all_account_period.get('all').get(id).
  811. get('credit', 0.0),
  812. all_account_period.get('all').get(id).
  813. get('balance')])
  814. res.update({
  815. 'dbr5': self.exchange(d),
  816. 'cdr5': self.exchange(c),
  817. 'bal5': self.exchange(b),
  818. })
  819. else:
  820. i, d, c = map(z, [
  821. all_account_period.get('all').get(id).
  822. get('balanceinit', 0.0),
  823. all_account_period.get('all').get(id).
  824. get('debit', 0.0),
  825. all_account_period.get('all').get(id).
  826. get('credit', 0.0)])
  827. b = z(i + d - c)
  828. res.update({
  829. 'dbr5': self.exchange(d),
  830. 'cdr5': self.exchange(c),
  831. 'bal5': self.exchange(b),
  832. })
  833. elif form['columns'] == 'thirteen':
  834. pn = 1
  835. for p_num in range(12):
  836. if form['inf_type'] == 'IS':
  837. d, c, b = map(z, [
  838. all_account_period.get(p_num).
  839. get(id).get('debit', 0.0),
  840. all_account_period.get(p_num).
  841. get(id).get('credit', 0.0),
  842. all_account_period.get(p_num).
  843. get(id).get('balance', 0.0)])
  844. res.update({
  845. 'dbr%s' % pn: self.exchange(d),
  846. 'cdr%s' % pn: self.exchange(c),
  847. 'bal%s' % pn: self.exchange(b),
  848. })
  849. else:
  850. i, d, c = map(z, [
  851. all_account_period.get(p_num).
  852. get(id).get('balanceinit', 0.0),
  853. all_account_period.get(p_num).
  854. get(id).get('debit', 0.0),
  855. all_account_period.get(p_num).
  856. get(id).get('credit', 0.0)])
  857. b = z(i + d - c)
  858. res.update({
  859. 'dbr%s' % pn: self.exchange(d),
  860. 'cdr%s' % pn: self.exchange(c),
  861. 'bal%s' % pn: self.exchange(b),
  862. })
  863. pn += 1
  864. if form['inf_type'] == 'IS':
  865. d, c, b = map(z, [
  866. all_account_period.get('all').get(id).
  867. get('debit', 0.0),
  868. all_account_period.get('all').get(id).
  869. get('credit', 0.0),
  870. all_account_period.get('all').get(id).
  871. get('balance', 0.0)])
  872. res.update({
  873. 'dbr13': self.exchange(d),
  874. 'cdr13': self.exchange(c),
  875. 'bal13': self.exchange(b),
  876. })
  877. else:
  878. i, d, c = map(z, [
  879. all_account_period.get('all').get(id).
  880. get('balanceinit', 0.0),
  881. all_account_period.get('all').get(id).
  882. get('debit', 0.0),
  883. all_account_period.get('all').get(id).
  884. get('credit', 0.0)])
  885. b = z(i + d - c)
  886. res.update({
  887. 'dbr13': self.exchange(d),
  888. 'cdr13': self.exchange(c),
  889. 'bal13': self.exchange(b),
  890. })
  891. else:
  892. i, d, c = map(z, [
  893. all_account_period.get('all').get(id).
  894. get('balanceinit', 0.0),
  895. all_account_period.get('all').get(id).
  896. get('debit', 0.0),
  897. all_account_period.get('all').get(id).
  898. get('credit', 0.0)])
  899. b = z(i + d - c)
  900. res.update({
  901. 'balanceinit': self.exchange(i),
  902. 'debit': self.exchange(d),
  903. 'credit': self.exchange(c),
  904. 'ytd': self.exchange(d - c),
  905. })
  906. if form['inf_type'] == 'IS' and form['columns'] == 'one':
  907. res.update({
  908. 'balance': self.exchange(d - c),
  909. })
  910. else:
  911. res.update({
  912. 'balance': self.exchange(b),
  913. })
  914. #
  915. # Check whether we must include this line in the report or not
  916. #
  917. to_include = False
  918. if form['columns'] in ('thirteen', 'qtr'):
  919. to_test = [False]
  920. if form['display_account'] == 'mov' and aa_id[3].parent_id:
  921. # Include accounts with movements
  922. for x in range(pn - 1):
  923. to_test.append(res.get(
  924. 'dbr%s' % x, 0.0) >= 0.005 and True or False)
  925. to_test.append(res.get(
  926. 'cdr%s' % x, 0.0) >= 0.005 and True or False)
  927. if any(to_test):
  928. to_include = True
  929. elif form['display_account'] == 'bal' and aa_id[3].\
  930. parent_id:
  931. # Include accounts with balance
  932. for x in range(pn - 1):
  933. to_test.append(res.get(
  934. 'bal%s' % x, 0.0) >= 0.005 and True or False)
  935. if any(to_test):
  936. to_include = True
  937. elif form['display_account'] == 'bal_mov' and aa_id[3].\
  938. parent_id:
  939. # Include accounts with balance or movements
  940. for x in range(pn - 1):
  941. to_test.append(res.get(
  942. 'bal%s' % x, 0.0) >= 0.005 and True or False)
  943. to_test.append(res.get(
  944. 'dbr%s' % x, 0.0) >= 0.005 and True or False)
  945. to_test.append(res.get(
  946. 'cdr%s' % x, 0.0) >= 0.005 and True or False)
  947. if any(to_test):
  948. to_include = True
  949. else:
  950. # Include all accounts
  951. to_include = True
  952. else:
  953. if form['display_account'] == 'mov' and aa_id[3].parent_id:
  954. # Include accounts with movements
  955. if abs(d) >= 0.005 or abs(c) >= 0.005:
  956. to_include = True
  957. elif form['display_account'] == 'bal' and aa_id[3].\
  958. parent_id:
  959. # Include accounts with balance
  960. if abs(b) >= 0.005:
  961. to_include = True
  962. elif form['display_account'] == 'bal_mov' and aa_id[3].\
  963. parent_id:
  964. # Include accounts with balance or movements
  965. if abs(b) >= 0.005 \
  966. or abs(d) >= 0.005 \
  967. or abs(c) >= 0.005:
  968. to_include = True
  969. else:
  970. # Include all accounts
  971. to_include = True
  972. # ~ ANALYTIC LEDGER
  973. if to_include and form['analytic_ledger'] \
  974. and form['columns'] == 'four' \
  975. and form['inf_type'] == 'BS' \
  976. and res['type'] in ('other', 'liquidity',
  977. 'receivable', 'payable'):
  978. res['mayor'] = self._get_analytic_ledger(res, ctx=ctx_end)
  979. elif to_include and form['journal_ledger'] \
  980. and form['columns'] == 'four' \
  981. and form['inf_type'] == 'BS' \
  982. and res['type'] in ('other', 'liquidity',
  983. 'receivable', 'payable'):
  984. res['journal'] = self._get_journal_ledger(res, ctx=ctx_end)
  985. elif to_include and form['partner_balance'] \
  986. and form['columns'] == 'four' \
  987. and form['inf_type'] == 'BS' \
  988. and res['type'] in ('other', 'liquidity',
  989. 'receivable', 'payable'):
  990. res['partner'] = self._get_partner_balance(
  991. res, ctx_i['periods'], ctx=ctx_end)
  992. else:
  993. res['mayor'] = []
  994. if to_include:
  995. result_acc.append(res)
  996. #
  997. # Check whether we must sumarize this line in the report
  998. # or not
  999. #
  1000. if form['tot_check'] and (res['id'] in account_list) \
  1001. and (res['id'] not in tot):
  1002. if form['columns'] == 'qtr':
  1003. tot_check = True
  1004. tot[res['id']] = True
  1005. tot_bal1 += res.get('bal1', 0.0)
  1006. tot_bal2 += res.get('bal2', 0.0)
  1007. tot_bal3 += res.get('bal3', 0.0)
  1008. tot_bal4 += res.get('bal4', 0.0)
  1009. tot_bal5 += res.get('bal5', 0.0)
  1010. elif form['columns'] == 'thirteen':
  1011. tot_check = True
  1012. tot[res['id']] = True
  1013. tot_bal1 += res.get('bal1', 0.0)
  1014. tot_bal2 += res.get('bal2', 0.0)
  1015. tot_bal3 += res.get('bal3', 0.0)
  1016. tot_bal4 += res.get('bal4', 0.0)
  1017. tot_bal5 += res.get('bal5', 0.0)
  1018. tot_bal6 += res.get('bal6', 0.0)
  1019. tot_bal7 += res.get('bal7', 0.0)
  1020. tot_bal8 += res.get('bal8', 0.0)
  1021. tot_bal9 += res.get('bal9', 0.0)
  1022. tot_bal10 += res.get('bal10', 0.0)
  1023. tot_bal11 += res.get('bal11', 0.0)
  1024. tot_bal12 += res.get('bal12', 0.0)
  1025. tot_bal13 += res.get('bal13', 0.0)
  1026. else:
  1027. tot_check = True
  1028. tot[res['id']] = True
  1029. tot_bin += res['balanceinit']
  1030. tot_deb += res['debit']
  1031. tot_crd += res['credit']
  1032. tot_ytd += res['ytd']
  1033. tot_eje += res['balance']
  1034. if tot_check:
  1035. str_label = form['lab_str']
  1036. res2 = {
  1037. 'type': 'view',
  1038. 'name': 'TOTAL %s' % (str_label),
  1039. 'label': False,
  1040. 'total': True,
  1041. }
  1042. if form['columns'] == 'qtr':
  1043. res2.update(dict(
  1044. bal1=z(tot_bal1),
  1045. bal2=z(tot_bal2),
  1046. bal3=z(tot_bal3),
  1047. bal4=z(tot_bal4),
  1048. bal5=z(tot_bal5),))
  1049. elif form['columns'] == 'thirteen':
  1050. res2.update(dict(
  1051. bal1=z(tot_bal1),
  1052. bal2=z(tot_bal2),
  1053. bal3=z(tot_bal3),
  1054. bal4=z(tot_bal4),
  1055. bal5=z(tot_bal5),
  1056. bal6=z(tot_bal6),
  1057. bal7=z(tot_bal7),
  1058. bal8=z(tot_bal8),
  1059. bal9=z(tot_bal9),
  1060. bal10=z(tot_bal10),
  1061. bal11=z(tot_bal11),
  1062. bal12=z(tot_bal12),
  1063. bal13=z(tot_bal13),))
  1064. else:
  1065. res2.update({
  1066. 'balanceinit': tot_bin,
  1067. 'debit': tot_deb,
  1068. 'credit': tot_crd,
  1069. 'ytd': tot_ytd,
  1070. 'balance': tot_eje,
  1071. })
  1072. result_acc.append(res2)
  1073. return result_acc
  1074. report_sxw.report_sxw(
  1075. 'report.afr.1cols',
  1076. 'wizard.report',
  1077. 'account_financial_report/report/balance_full.rml',
  1078. parser=account_balance,
  1079. header=False)
  1080. report_sxw.report_sxw(
  1081. 'report.afr.2cols',
  1082. 'wizard.report',
  1083. 'account_financial_report/report/balance_full_2_cols.rml',
  1084. parser=account_balance,
  1085. header=False)
  1086. report_sxw.report_sxw(
  1087. 'report.afr.4cols',
  1088. 'wizard.report',
  1089. 'account_financial_report/report/balance_full_4_cols.rml',
  1090. parser=account_balance,
  1091. header=False)
  1092. report_sxw.report_sxw(
  1093. 'report.afr.analytic.ledger',
  1094. 'wizard.report',
  1095. 'account_financial_report/report/balance_full_4_cols_analytic_ledger.rml',
  1096. parser=account_balance,
  1097. header=False)
  1098. report_sxw.report_sxw(
  1099. 'report.afr.partner.balance',
  1100. 'wizard.report',
  1101. 'account_financial_report/report/balance_full_4_cols_partner_balance.rml',
  1102. parser=account_balance,
  1103. header=False)
  1104. report_sxw.report_sxw(
  1105. 'report.afr.journal.ledger',
  1106. 'wizard.report',
  1107. 'account_financial_report/report/balance_full_4_cols_journal_ledger.rml',
  1108. parser=account_balance,
  1109. header=False)
  1110. report_sxw.report_sxw(
  1111. 'report.afr.5cols',
  1112. 'wizard.report',
  1113. 'account_financial_report/report/balance_full_5_cols.rml',
  1114. parser=account_balance,
  1115. header=False)
  1116. report_sxw.report_sxw(
  1117. 'report.afr.qtrcols',
  1118. 'wizard.report',
  1119. 'account_financial_report/report/balance_full_qtr_cols.rml',
  1120. parser=account_balance,
  1121. header=False)
  1122. report_sxw.report_sxw(
  1123. 'report.afr.13cols',
  1124. 'wizard.report',
  1125. 'account_financial_report/report/balance_full_13_cols.rml',
  1126. parser=account_balance,
  1127. header=False)