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.

1244 lines
53 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. # -*- coding: 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.get_company_currency(
  154. form['company_id'] and
  155. type(form['company_id']) in (list, tuple) and
  156. form['company_id'][0] or form['company_id'])
  157. if not form['currency_id']:
  158. self.to_currency_id = self.from_currency_id
  159. else:
  160. self.to_currency_id = (
  161. form['currency_id'] and
  162. type(form['currency_id']) in (list, tuple) and
  163. form['currency_id'][0] or form['currency_id'])
  164. return self.pool.get('res.currency').browse(
  165. self.cr, self.uid, 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'] and
  505. type(form['company_id']) in (list, tuple) and
  506. form['company_id'][0] or
  507. 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'] and
  521. type(form['company_id']) in (list, tuple) and
  522. form['company_id'][0] or
  523. form['company_id'], 'credit')
  524. debit_account_ids = self.\
  525. get_company_accounts(form['company_id'] and
  526. type(form['company_id']) in (list, tuple) and
  527. form['company_id'][0] or
  528. 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'] and
  543. form['display_account_level'] or
  544. 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]) and
  768. 'TOTAL %s' % (aa_id[3].name.upper()) or
  769. 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': (
  775. credit_account_ids and
  776. (id in credit_account_ids and -1 or 1) or 1),
  777. }
  778. if form['columns'] == 'qtr':
  779. for pn in range(1, 5):
  780. if form['inf_type'] == 'IS':
  781. d, c, b = map(z, [
  782. all_account_period.get(pn - 1).
  783. get(id).get('debit', 0.0),
  784. all_account_period.get(pn - 1).
  785. get(id).get('credit', 0.0),
  786. all_account_period.get(pn - 1).
  787. get(id).get('balance', 0.0)])
  788. res.update({
  789. 'dbr%s' % pn: self.exchange(d),
  790. 'cdr%s' % pn: self.exchange(c),
  791. 'bal%s' % pn: self.exchange(b),
  792. })
  793. else:
  794. i, d, c = map(z, [
  795. all_account_period.get(pn - 1).
  796. get(id).get('balanceinit', 0.0),
  797. all_account_period.get(pn - 1).
  798. get(id).get('debit', 0.0),
  799. all_account_period.get(pn - 1).
  800. get(id).get('credit', 0.0)])
  801. b = z(i + d - c)
  802. res.update({
  803. 'dbr%s' % pn: self.exchange(d),
  804. 'cdr%s' % pn: self.exchange(c),
  805. 'bal%s' % pn: self.exchange(b),
  806. })
  807. if form['inf_type'] == 'IS':
  808. d, c, b = map(z, [
  809. all_account_period.get('all').get(id).
  810. get('debit', 0.0),
  811. all_account_period.get('all').get(id).
  812. get('credit', 0.0),
  813. all_account_period.get('all').get(id).
  814. get('balance')])
  815. res.update({
  816. 'dbr5': self.exchange(d),
  817. 'cdr5': self.exchange(c),
  818. 'bal5': self.exchange(b),
  819. })
  820. else:
  821. i, d, c = map(z, [
  822. all_account_period.get('all').get(id).
  823. get('balanceinit', 0.0),
  824. all_account_period.get('all').get(id).
  825. get('debit', 0.0),
  826. all_account_period.get('all').get(id).
  827. get('credit', 0.0)])
  828. b = z(i + d - c)
  829. res.update({
  830. 'dbr5': self.exchange(d),
  831. 'cdr5': self.exchange(c),
  832. 'bal5': self.exchange(b),
  833. })
  834. elif form['columns'] == 'thirteen':
  835. pn = 1
  836. for p_num in range(12):
  837. if form['inf_type'] == 'IS':
  838. d, c, b = map(z, [
  839. all_account_period.get(p_num).
  840. get(id).get('debit', 0.0),
  841. all_account_period.get(p_num).
  842. get(id).get('credit', 0.0),
  843. all_account_period.get(p_num).
  844. get(id).get('balance', 0.0)])
  845. res.update({
  846. 'dbr%s' % pn: self.exchange(d),
  847. 'cdr%s' % pn: self.exchange(c),
  848. 'bal%s' % pn: self.exchange(b),
  849. })
  850. else:
  851. i, d, c = map(z, [
  852. all_account_period.get(p_num).
  853. get(id).get('balanceinit', 0.0),
  854. all_account_period.get(p_num).
  855. get(id).get('debit', 0.0),
  856. all_account_period.get(p_num).
  857. get(id).get('credit', 0.0)])
  858. b = z(i + d - c)
  859. res.update({
  860. 'dbr%s' % pn: self.exchange(d),
  861. 'cdr%s' % pn: self.exchange(c),
  862. 'bal%s' % pn: self.exchange(b),
  863. })
  864. pn += 1
  865. if form['inf_type'] == 'IS':
  866. d, c, b = map(z, [
  867. all_account_period.get('all').get(id).
  868. get('debit', 0.0),
  869. all_account_period.get('all').get(id).
  870. get('credit', 0.0),
  871. all_account_period.get('all').get(id).
  872. get('balance', 0.0)])
  873. res.update({
  874. 'dbr13': self.exchange(d),
  875. 'cdr13': self.exchange(c),
  876. 'bal13': self.exchange(b),
  877. })
  878. else:
  879. i, d, c = map(z, [
  880. all_account_period.get('all').get(id).
  881. get('balanceinit', 0.0),
  882. all_account_period.get('all').get(id).
  883. get('debit', 0.0),
  884. all_account_period.get('all').get(id).
  885. get('credit', 0.0)])
  886. b = z(i + d - c)
  887. res.update({
  888. 'dbr13': self.exchange(d),
  889. 'cdr13': self.exchange(c),
  890. 'bal13': self.exchange(b),
  891. })
  892. else:
  893. i, d, c = map(z, [
  894. all_account_period.get('all').get(id).
  895. get('balanceinit', 0.0),
  896. all_account_period.get('all').get(id).
  897. get('debit', 0.0),
  898. all_account_period.get('all').get(id).
  899. get('credit', 0.0)])
  900. b = z(i + d - c)
  901. res.update({
  902. 'balanceinit': self.exchange(i),
  903. 'debit': self.exchange(d),
  904. 'credit': self.exchange(c),
  905. 'ytd': self.exchange(d - c),
  906. })
  907. if form['inf_type'] == 'IS' and form['columns'] == 'one':
  908. res.update({
  909. 'balance': self.exchange(d - c),
  910. })
  911. else:
  912. res.update({
  913. 'balance': self.exchange(b),
  914. })
  915. #
  916. # Check whether we must include this line in the report or not
  917. #
  918. to_include = False
  919. if form['columns'] in ('thirteen', 'qtr'):
  920. to_test = [False]
  921. if form['display_account'] == 'mov' and aa_id[3].parent_id:
  922. # Include accounts with movements
  923. for x in range(pn - 1):
  924. to_test.append(res.get(
  925. 'dbr%s' % x, 0.0) >= 0.005 and True or False)
  926. to_test.append(res.get(
  927. 'cdr%s' % x, 0.0) >= 0.005 and True or False)
  928. if any(to_test):
  929. to_include = True
  930. elif form['display_account'] == 'bal' and aa_id[3].\
  931. parent_id:
  932. # Include accounts with balance
  933. for x in range(pn - 1):
  934. to_test.append(res.get(
  935. 'bal%s' % x, 0.0) >= 0.005 and True or False)
  936. if any(to_test):
  937. to_include = True
  938. elif form['display_account'] == 'bal_mov' and aa_id[3].\
  939. parent_id:
  940. # Include accounts with balance or movements
  941. for x in range(pn - 1):
  942. to_test.append(res.get(
  943. 'bal%s' % x, 0.0) >= 0.005 and True or False)
  944. to_test.append(res.get(
  945. 'dbr%s' % x, 0.0) >= 0.005 and True or False)
  946. to_test.append(res.get(
  947. 'cdr%s' % x, 0.0) >= 0.005 and True or False)
  948. if any(to_test):
  949. to_include = True
  950. else:
  951. # Include all accounts
  952. to_include = True
  953. else:
  954. if form['display_account'] == 'mov' and aa_id[3].parent_id:
  955. # Include accounts with movements
  956. if abs(d) >= 0.005 or abs(c) >= 0.005:
  957. to_include = True
  958. elif form['display_account'] == 'bal' and aa_id[3].\
  959. parent_id:
  960. # Include accounts with balance
  961. if abs(b) >= 0.005:
  962. to_include = True
  963. elif form['display_account'] == 'bal_mov' and aa_id[3].\
  964. parent_id:
  965. # Include accounts with balance or movements
  966. if abs(b) >= 0.005 \
  967. or abs(d) >= 0.005 \
  968. or abs(c) >= 0.005:
  969. to_include = True
  970. else:
  971. # Include all accounts
  972. to_include = True
  973. # ~ ANALYTIC LEDGER
  974. if to_include and form['analytic_ledger'] \
  975. and form['columns'] == 'four' \
  976. and form['inf_type'] == 'BS' \
  977. and res['type'] in ('other', 'liquidity',
  978. 'receivable', 'payable'):
  979. res['mayor'] = self._get_analytic_ledger(res, ctx=ctx_end)
  980. elif to_include and form['journal_ledger'] \
  981. and form['columns'] == 'four' \
  982. and form['inf_type'] == 'BS' \
  983. and res['type'] in ('other', 'liquidity',
  984. 'receivable', 'payable'):
  985. res['journal'] = self._get_journal_ledger(res, ctx=ctx_end)
  986. elif to_include and form['partner_balance'] \
  987. and form['columns'] == 'four' \
  988. and form['inf_type'] == 'BS' \
  989. and res['type'] in ('other', 'liquidity',
  990. 'receivable', 'payable'):
  991. res['partner'] = self._get_partner_balance(
  992. res, ctx_i['periods'], ctx=ctx_end)
  993. else:
  994. res['mayor'] = []
  995. if to_include:
  996. result_acc.append(res)
  997. #
  998. # Check whether we must sumarize this line in the report
  999. # or not
  1000. #
  1001. if form['tot_check'] and (res['id'] in account_list) \
  1002. and (res['id'] not in tot):
  1003. if form['columns'] == 'qtr':
  1004. tot_check = True
  1005. tot[res['id']] = True
  1006. tot_bal1 += res.get('bal1', 0.0)
  1007. tot_bal2 += res.get('bal2', 0.0)
  1008. tot_bal3 += res.get('bal3', 0.0)
  1009. tot_bal4 += res.get('bal4', 0.0)
  1010. tot_bal5 += res.get('bal5', 0.0)
  1011. elif form['columns'] == 'thirteen':
  1012. tot_check = True
  1013. tot[res['id']] = True
  1014. tot_bal1 += res.get('bal1', 0.0)
  1015. tot_bal2 += res.get('bal2', 0.0)
  1016. tot_bal3 += res.get('bal3', 0.0)
  1017. tot_bal4 += res.get('bal4', 0.0)
  1018. tot_bal5 += res.get('bal5', 0.0)
  1019. tot_bal6 += res.get('bal6', 0.0)
  1020. tot_bal7 += res.get('bal7', 0.0)
  1021. tot_bal8 += res.get('bal8', 0.0)
  1022. tot_bal9 += res.get('bal9', 0.0)
  1023. tot_bal10 += res.get('bal10', 0.0)
  1024. tot_bal11 += res.get('bal11', 0.0)
  1025. tot_bal12 += res.get('bal12', 0.0)
  1026. tot_bal13 += res.get('bal13', 0.0)
  1027. else:
  1028. tot_check = True
  1029. tot[res['id']] = True
  1030. tot_bin += res['balanceinit']
  1031. tot_deb += res['debit']
  1032. tot_crd += res['credit']
  1033. tot_ytd += res['ytd']
  1034. tot_eje += res['balance']
  1035. if tot_check:
  1036. str_label = form['lab_str']
  1037. res2 = {
  1038. 'type': 'view',
  1039. 'name': 'TOTAL %s' % (str_label),
  1040. 'label': False,
  1041. 'total': True,
  1042. }
  1043. if form['columns'] == 'qtr':
  1044. res2.update(dict(
  1045. bal1=z(tot_bal1),
  1046. bal2=z(tot_bal2),
  1047. bal3=z(tot_bal3),
  1048. bal4=z(tot_bal4),
  1049. bal5=z(tot_bal5),))
  1050. elif form['columns'] == 'thirteen':
  1051. res2.update(dict(
  1052. bal1=z(tot_bal1),
  1053. bal2=z(tot_bal2),
  1054. bal3=z(tot_bal3),
  1055. bal4=z(tot_bal4),
  1056. bal5=z(tot_bal5),
  1057. bal6=z(tot_bal6),
  1058. bal7=z(tot_bal7),
  1059. bal8=z(tot_bal8),
  1060. bal9=z(tot_bal9),
  1061. bal10=z(tot_bal10),
  1062. bal11=z(tot_bal11),
  1063. bal12=z(tot_bal12),
  1064. bal13=z(tot_bal13),))
  1065. else:
  1066. res2.update({
  1067. 'balanceinit': tot_bin,
  1068. 'debit': tot_deb,
  1069. 'credit': tot_crd,
  1070. 'ytd': tot_ytd,
  1071. 'balance': tot_eje,
  1072. })
  1073. result_acc.append(res2)
  1074. return result_acc
  1075. report_sxw.report_sxw(
  1076. 'report.afr.1cols',
  1077. 'wizard.report',
  1078. 'account_financial_report/report/balance_full.rml',
  1079. parser=account_balance,
  1080. header=False)
  1081. report_sxw.report_sxw(
  1082. 'report.afr.2cols',
  1083. 'wizard.report',
  1084. 'account_financial_report/report/balance_full_2_cols.rml',
  1085. parser=account_balance,
  1086. header=False)
  1087. report_sxw.report_sxw(
  1088. 'report.afr.4cols',
  1089. 'wizard.report',
  1090. 'account_financial_report/report/balance_full_4_cols.rml',
  1091. parser=account_balance,
  1092. header=False)
  1093. report_sxw.report_sxw(
  1094. 'report.afr.analytic.ledger',
  1095. 'wizard.report',
  1096. 'account_financial_report/report/balance_full_4_cols_analytic_ledger.rml',
  1097. parser=account_balance,
  1098. header=False)
  1099. report_sxw.report_sxw(
  1100. 'report.afr.partner.balance',
  1101. 'wizard.report',
  1102. 'account_financial_report/report/balance_full_4_cols_partner_balance.rml',
  1103. parser=account_balance,
  1104. header=False)
  1105. report_sxw.report_sxw(
  1106. 'report.afr.journal.ledger',
  1107. 'wizard.report',
  1108. 'account_financial_report/report/balance_full_4_cols_journal_ledger.rml',
  1109. parser=account_balance,
  1110. header=False)
  1111. report_sxw.report_sxw(
  1112. 'report.afr.5cols',
  1113. 'wizard.report',
  1114. 'account_financial_report/report/balance_full_5_cols.rml',
  1115. parser=account_balance,
  1116. header=False)
  1117. report_sxw.report_sxw(
  1118. 'report.afr.qtrcols',
  1119. 'wizard.report',
  1120. 'account_financial_report/report/balance_full_qtr_cols.rml',
  1121. parser=account_balance,
  1122. header=False)
  1123. report_sxw.report_sxw(
  1124. 'report.afr.13cols',
  1125. 'wizard.report',
  1126. 'account_financial_report/report/balance_full_13_cols.rml',
  1127. parser=account_balance,
  1128. header=False)