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.

1238 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={}):
  278. res = []
  279. if account['type'] in ('other', 'liquidity', 'receivable', 'payable'):
  280. # ~ TODO: CUANDO EL PERIODO ESTE VACIO LLENARLO CON LOS PERIODOS
  281. # DEL EJERCICIO
  282. # ~ FISCAL, SIN LOS PERIODOS ESPECIALES
  283. periods = ', '.join([str(i) for i in ctx['periods']])
  284. # ~ periods = str(tuple(ctx['periods']))
  285. where = """where aml.period_id in (%s)
  286. and aa.id = %s
  287. and aml.state <> 'draft'""" % (periods, account['id'])
  288. if ctx.get('state', 'posted') == 'posted':
  289. where += "AND am.state = 'posted'"
  290. sql_detalle = """select aml.id as id,
  291. aj.name as diario,
  292. aa.name as descripcion,
  293. (select name
  294. from res_partner
  295. where aml.partner_id = id) as partner,
  296. aa.code as cuenta,
  297. aml.name as name,
  298. aml.ref as ref,
  299. case when aml.debit is null
  300. then 0.00
  301. else aml.debit
  302. end as debit,
  303. case when aml.credit is null
  304. then 0.00
  305. else aml.credit
  306. end as credit,
  307. (select code
  308. from account_analytic_account
  309. where aml.analytic_account_id = id)
  310. as analitica,
  311. aml.date as date,
  312. ap.name as periodo,
  313. am.name as asiento
  314. from account_move_line aml
  315. inner join account_journal aj
  316. on aj.id = aml.journal_id
  317. inner join account_account aa
  318. on aa.id = aml.account_id
  319. inner join account_period ap
  320. on ap.id = aml.period_id
  321. inner join account_move am
  322. on am.id = aml.move_id """ \
  323. + where + """ order by date, am.name"""
  324. self.cr.execute(sql_detalle)
  325. resultat = self.cr.dictfetchall()
  326. balance = account['balanceinit']
  327. for det in resultat:
  328. balance += det['debit'] - det['credit']
  329. res.append({
  330. 'id': det['id'],
  331. 'date': det['date'],
  332. 'journal': det['diario'],
  333. 'partner': det['partner'],
  334. 'name': det['name'],
  335. 'entry': det['asiento'],
  336. 'ref': det['ref'],
  337. 'debit': det['debit'],
  338. 'credit': det['credit'],
  339. 'analytic': det['analitica'],
  340. 'period': det['periodo'],
  341. 'balance': balance,
  342. })
  343. return res
  344. def _get_journal_ledger(self, account, ctx={}):
  345. res = []
  346. am_obj = self.pool.get('account.move')
  347. print 'AM OBJ ', am_obj
  348. if account['type'] in ('other', 'liquidity', 'receivable', 'payable'):
  349. # ~ TODO: CUANDO EL PERIODO ESTE VACIO LLENARLO CON LOS PERIODOS
  350. # DEL EJERCICIO
  351. # ~ FISCAL, SIN LOS PERIODOS ESPECIALES
  352. periods = ', '.join([str(i) for i in ctx['periods']])
  353. # ~ periods = str(tuple(ctx['periods']))
  354. where = """where aml.period_id in (%s)
  355. and aa.id = %s
  356. and aml.state <> 'draft'""" % (periods, account['id'])
  357. if ctx.get('state', 'posted') == 'posted':
  358. where += "AND am.state = 'posted'"
  359. sql_detalle = """SELECT
  360. DISTINCT am.id as am_id,
  361. aj.name as diario,
  362. am.name as name,
  363. am.date as date,
  364. ap.name as periodo
  365. from account_move_line aml
  366. inner join account_journal aj on aj.id = aml.journal_id
  367. inner join account_account aa on aa.id = aml.account_id
  368. inner join account_period ap on ap.id = aml.period_id
  369. inner join account_move am on am.id = aml.move_id """ \
  370. + where + """ order by date, am.name"""
  371. self.cr.execute(sql_detalle)
  372. resultat = self.cr.dictfetchall()
  373. for det in resultat:
  374. res.append({
  375. 'am_id': det['am_id'],
  376. 'journal': det['diario'],
  377. 'name': det['name'],
  378. 'date': det['date'],
  379. 'period': det['periodo'],
  380. 'obj': am_obj.browse(self.cr, self.uid, det['am_id'])
  381. })
  382. print 'ACCOUNT NAME', am_obj.browse(self.cr, self.uid,
  383. det['am_id']).name
  384. return res
  385. def lines(self, form, level=0):
  386. """
  387. Returns all the data needed for the report lines
  388. (account info plus debit/credit/balance in the selected period
  389. and the full year)
  390. """
  391. account_obj = self.pool.get('account.account')
  392. period_obj = self.pool.get('account.period')
  393. fiscalyear_obj = self.pool.get('account.fiscalyear')
  394. def _get_children_and_consol(cr, uid, ids, level, context={},
  395. change_sign=False):
  396. aa_obj = self.pool.get('account.account')
  397. ids2 = []
  398. for aa_brw in aa_obj.browse(cr, uid, ids, context):
  399. if aa_brw.child_id and aa_brw.level < level \
  400. and aa_brw.type != 'consolidation':
  401. if not change_sign:
  402. ids2.append([aa_brw.id, True, False, aa_brw])
  403. ids2 += _get_children_and_consol(
  404. cr, uid, [x.id for x in aa_brw.child_id], level,
  405. context, change_sign=change_sign)
  406. if change_sign:
  407. ids2.append(aa_brw.id)
  408. else:
  409. ids2.append([aa_brw.id, False, True, aa_brw])
  410. else:
  411. if change_sign:
  412. ids2.append(aa_brw.id)
  413. else:
  414. ids2.append([aa_brw.id, True, True, aa_brw])
  415. return ids2
  416. #######################################################################
  417. # CONTEXT FOR ENDIND BALANCE #
  418. #######################################################################
  419. def _ctx_end(ctx):
  420. ctx_end = ctx
  421. ctx_end['filter'] = form.get('filter', 'all')
  422. ctx_end['fiscalyear'] = fiscalyear.id
  423. # ~ ctx_end['periods'] = period_obj.\
  424. # search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),
  425. # ('special','=',False)])
  426. if ctx_end['filter'] not in ['bydate', 'none']:
  427. special = self.special_period(form['periods'])
  428. else:
  429. special = False
  430. if form['filter'] in ['byperiod', 'all']:
  431. if special:
  432. ctx_end['periods'] = period_obj.search(
  433. self.cr, self.uid,
  434. [('id', 'in', form['periods'] or ctx_end.get('periods',
  435. False))])
  436. else:
  437. ctx_end['periods'] = period_obj.search(
  438. self.cr, self.uid,
  439. [('id', 'in', form['periods'] or ctx_end.get('periods',
  440. False)),
  441. ('special', '=', False)])
  442. if form['filter'] in ['bydate', 'all', 'none']:
  443. ctx_end['date_from'] = form['date_from']
  444. ctx_end['date_to'] = form['date_to']
  445. return ctx_end.copy()
  446. def missing_period(ctx_init):
  447. ctx_init['fiscalyear'] = \
  448. fiscalyear_obj.search(self.cr, self.uid,
  449. [('date_stop', '<',
  450. fiscalyear.date_start)],
  451. order='date_stop') \
  452. and fiscalyear_obj.search(self.cr, self.uid,
  453. [('date_stop', '<',
  454. fiscalyear.date_start)],
  455. order='date_stop')[-1] or []
  456. ctx_init['periods'] = period_obj.search(
  457. self.cr, self.uid,
  458. [('fiscalyear_id', '=', ctx_init['fiscalyear']),
  459. ('date_stop', '<', fiscalyear.date_start)])
  460. return ctx_init
  461. #######################################################################
  462. # CONTEXT FOR INITIAL BALANCE #
  463. #######################################################################
  464. def _ctx_init(ctx):
  465. ctx_init = self.context.copy()
  466. ctx_init['filter'] = form.get('filter', 'all')
  467. ctx_init['fiscalyear'] = fiscalyear.id
  468. if form['filter'] in ['byperiod', 'all']:
  469. ctx_init['periods'] = form['periods']
  470. if not ctx_init['periods']:
  471. ctx_init = missing_period(ctx_init.copy())
  472. date_start = min([period.date_start for period in period_obj.
  473. browse(self.cr, self.uid,
  474. ctx_init['periods'])])
  475. ctx_init['periods'] = period_obj.search(
  476. self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
  477. ('date_stop', '<=', date_start)])
  478. elif form['filter'] in ['bydate']:
  479. ctx_init['date_from'] = fiscalyear.date_start
  480. ctx_init['date_to'] = form['date_from']
  481. ctx_init['periods'] = period_obj.search(
  482. self.cr, self.uid,
  483. [('fiscalyear_id', '=', fiscalyear.id),
  484. ('date_stop', '<=', ctx_init['date_to'])])
  485. elif form['filter'] == 'none':
  486. ctx_init['periods'] = period_obj.search(
  487. self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
  488. ('special', '=', True)])
  489. date_start = min([period.date_start for period in period_obj.
  490. browse(self.cr, self.uid,
  491. ctx_init['periods'])])
  492. ctx_init['periods'] = period_obj.search(
  493. self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
  494. ('date_start', '<=', date_start),
  495. ('special', '=', True)])
  496. return ctx_init.copy()
  497. def z(n):
  498. return abs(n) < 0.005 and 0.0 or n
  499. self.context['state'] = form['target_move'] or 'posted'
  500. self.from_currency_id = self.\
  501. get_company_currency(form['company_id']
  502. and type(form['company_id']) in (list, tuple)
  503. and form['company_id'][0]
  504. or form['company_id'])
  505. if not form['currency_id']:
  506. self.to_currency_id = self.from_currency_id
  507. else:
  508. self.to_currency_id = form['currency_id'] \
  509. and type(form['currency_id']) in (list, tuple) \
  510. and form['currency_id'][0] \
  511. or form['currency_id']
  512. if 'account_list' in form and form['account_list']:
  513. account_ids = form['account_list']
  514. account_list = form['account_list']
  515. del form['account_list']
  516. credit_account_ids = self.\
  517. get_company_accounts(form['company_id']
  518. and type(form['company_id']) in (list, tuple)
  519. and form['company_id'][0]
  520. or form['company_id'], 'credit')
  521. debit_account_ids = self.\
  522. get_company_accounts(form['company_id']
  523. and type(form['company_id']) in (list, tuple)
  524. and form['company_id'][0]
  525. or form['company_id'], 'debit')
  526. if form.get('fiscalyear'):
  527. if type(form.get('fiscalyear')) in (list, tuple):
  528. fiscalyear = form['fiscalyear'] and form['fiscalyear'][0]
  529. elif type(form.get('fiscalyear')) in (int,):
  530. fiscalyear = form['fiscalyear']
  531. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, fiscalyear)
  532. ################################################################
  533. # Get the accounts #
  534. ################################################################
  535. all_account_ids = _get_children_and_consol(
  536. self.cr, self.uid, account_ids, 100, self.context)
  537. account_ids = _get_children_and_consol(
  538. self.cr, self.uid, account_ids,
  539. form['display_account_level']
  540. and form['display_account_level']
  541. or 100, self.context)
  542. credit_account_ids = _get_children_and_consol(
  543. self.cr, self.uid, credit_account_ids, 100, self.context,
  544. change_sign=True)
  545. debit_account_ids = _get_children_and_consol(
  546. self.cr, self.uid, debit_account_ids, 100, self.context,
  547. change_sign=True)
  548. credit_account_ids = list(set(
  549. credit_account_ids) - set(debit_account_ids))
  550. #
  551. # Generate the report lines (checking each account)
  552. #
  553. tot_check = False
  554. if not form['periods']:
  555. form['periods'] = period_obj.search(
  556. self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
  557. ('special', '=', False)],
  558. order='date_start asc')
  559. if not form['periods']:
  560. raise osv.except_osv(_('UserError'), _(
  561. 'The Selected Fiscal Year Does not have Regular Periods'))
  562. if form['columns'] == 'qtr':
  563. period_ids = period_obj.search(
  564. self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
  565. ('special', '=', False)],
  566. order='date_start asc')
  567. a = 0
  568. l = []
  569. p = []
  570. for x in period_ids:
  571. a += 1
  572. if a < 3:
  573. l.append(x)
  574. else:
  575. l.append(x)
  576. p.append(l)
  577. l = []
  578. a = 0
  579. tot_bal1 = 0.0
  580. tot_bal2 = 0.0
  581. tot_bal3 = 0.0
  582. tot_bal4 = 0.0
  583. tot_bal5 = 0.0
  584. elif form['columns'] == 'thirteen':
  585. period_ids = period_obj.search(
  586. self.cr, self.uid, [('fiscalyear_id', '=', fiscalyear.id),
  587. ('special', '=', False)],
  588. order='date_start asc')
  589. tot_bal1 = 0.0
  590. tot_bal1 = 0.0
  591. tot_bal2 = 0.0
  592. tot_bal3 = 0.0
  593. tot_bal4 = 0.0
  594. tot_bal5 = 0.0
  595. tot_bal6 = 0.0
  596. tot_bal7 = 0.0
  597. tot_bal8 = 0.0
  598. tot_bal9 = 0.0
  599. tot_bal10 = 0.0
  600. tot_bal11 = 0.0
  601. tot_bal12 = 0.0
  602. tot_bal13 = 0.0
  603. else:
  604. ctx_end = _ctx_end(self.context.copy())
  605. tot_bin = 0.0
  606. tot_deb = 0.0
  607. tot_crd = 0.0
  608. tot_ytd = 0.0
  609. tot_eje = 0.0
  610. res = {}
  611. result_acc = []
  612. tot = {}
  613. ###############################################################
  614. # Calculations of credit, debit and balance,
  615. # without repeating operations.
  616. ###############################################################
  617. account_black_ids = account_obj.search(
  618. self.cr, self.uid, (
  619. [('id', 'in', [i[0] for i in all_account_ids]),
  620. ('type', 'not in', ('view', 'consolidation'))]))
  621. account_not_black_ids = account_obj.search(
  622. self.cr, self.uid, ([('id', 'in', [i[0] for i in all_account_ids]),
  623. ('type', '=', 'view')]))
  624. acc_cons_ids = account_obj.search(
  625. self.cr, self.uid, ([('id', 'in', [i[0] for i in all_account_ids]),
  626. ('type', 'in', ('consolidation',))]))
  627. account_consol_ids = acc_cons_ids and account_obj.\
  628. _get_children_and_consol(self.cr, self.uid, acc_cons_ids) or []
  629. account_black_ids += account_obj.search(self.cr, self.uid, (
  630. [('id', 'in', account_consol_ids),
  631. ('type', 'not in',
  632. ('view', 'consolidation'))]))
  633. account_black_ids = list(set(account_black_ids))
  634. c_account_not_black_ids = account_obj.search(self.cr, self.uid, ([
  635. ('id', 'in', account_consol_ids),
  636. ('type', '=', 'view')]))
  637. delete_cons = False
  638. if c_account_not_black_ids:
  639. delete_cons = set(account_not_black_ids) & set(
  640. c_account_not_black_ids) and True or False
  641. account_not_black_ids = list(
  642. set(account_not_black_ids) - set(c_account_not_black_ids))
  643. # This could be done quickly with a sql sentence
  644. account_not_black = account_obj.browse(
  645. self.cr, self.uid, account_not_black_ids)
  646. account_not_black.sort(key=lambda x: x.level)
  647. account_not_black.reverse()
  648. account_not_black_ids = [i.id for i in account_not_black]
  649. c_account_not_black = account_obj.browse(
  650. self.cr, self.uid, c_account_not_black_ids)
  651. c_account_not_black.sort(key=lambda x: x.level)
  652. c_account_not_black.reverse()
  653. c_account_not_black_ids = [i.id for i in c_account_not_black]
  654. if delete_cons:
  655. account_not_black_ids = c_account_not_black_ids + \
  656. account_not_black_ids
  657. account_not_black = c_account_not_black + account_not_black
  658. else:
  659. acc_cons_brw = account_obj.browse(
  660. self.cr, self.uid, acc_cons_ids)
  661. acc_cons_brw.sort(key=lambda x: x.level)
  662. acc_cons_brw.reverse()
  663. acc_cons_ids = [i.id for i in acc_cons_brw]
  664. account_not_black_ids = c_account_not_black_ids + \
  665. acc_cons_ids + account_not_black_ids
  666. account_not_black = c_account_not_black + \
  667. acc_cons_brw + account_not_black
  668. all_account_period = {} # All accounts per period
  669. # Iteration limit depending on the number of columns
  670. if form['columns'] == 'thirteen':
  671. limit = 13
  672. elif form['columns'] == 'qtr':
  673. limit = 5
  674. else:
  675. limit = 1
  676. for p_act in range(limit):
  677. if limit != 1:
  678. if p_act == limit - 1:
  679. form['periods'] = period_ids
  680. else:
  681. if form['columns'] == 'thirteen':
  682. form['periods'] = [period_ids[p_act]]
  683. elif form['columns'] == 'qtr':
  684. form['periods'] = p[p_act]
  685. if form['inf_type'] == 'IS':
  686. ctx_to_use = _ctx_end(self.context.copy())
  687. else:
  688. ctx_i = _ctx_init(self.context.copy())
  689. ctx_to_use = _ctx_end(self.context.copy())
  690. account_black = account_obj.browse(
  691. self.cr, self.uid, account_black_ids, ctx_to_use)
  692. if form['inf_type'] == 'BS':
  693. account_black_init = account_obj.browse(
  694. self.cr, self.uid, account_black_ids, ctx_i)
  695. # ~ Black
  696. dict_black = {}
  697. for i in account_black:
  698. d = i.debit
  699. c = i.credit
  700. dict_black[i.id] = {
  701. 'obj': i,
  702. 'debit': d,
  703. 'credit': c,
  704. 'balance': d - c
  705. }
  706. if form['inf_type'] == 'BS':
  707. dict_black.get(i.id)['balanceinit'] = 0.0
  708. # If the report is a balance sheet
  709. # Balanceinit values are added to the dictionary
  710. if form['inf_type'] == 'BS':
  711. for i in account_black_init:
  712. dict_black.get(i.id)['balanceinit'] = i.balance
  713. # ~ Not black
  714. dict_not_black = {}
  715. for i in account_not_black:
  716. dict_not_black[i.id] = {
  717. 'obj': i, 'debit': 0.0, 'credit': 0.0, 'balance': 0.0}
  718. if form['inf_type'] == 'BS':
  719. dict_not_black.get(i.id)['balanceinit'] = 0.0
  720. all_account = dict_black.copy(
  721. ) # It makes a copy because they modify
  722. for acc_id in account_not_black_ids:
  723. acc_childs = dict_not_black.get(acc_id).get('obj').\
  724. type == 'view' \
  725. and dict_not_black.get(acc_id).get('obj').child_id \
  726. or dict_not_black.get(acc_id).get('obj').child_consol_ids
  727. for child_id in acc_childs:
  728. if child_id.type == 'consolidation' and delete_cons:
  729. continue
  730. dict_not_black.get(acc_id)['debit'] += all_account.get(
  731. child_id.id).get('debit')
  732. dict_not_black.get(acc_id)['credit'] += all_account.get(
  733. child_id.id).get('credit')
  734. dict_not_black.get(acc_id)['balance'] += all_account.get(
  735. child_id.id).get('balance')
  736. if form['inf_type'] == 'BS':
  737. dict_not_black.get(acc_id)['balanceinit'] += \
  738. all_account.get(child_id.id).get('balanceinit')
  739. all_account[acc_id] = dict_not_black[acc_id]
  740. if p_act == limit - 1:
  741. all_account_period['all'] = all_account
  742. else:
  743. if form['columns'] == 'thirteen':
  744. all_account_period[p_act] = all_account
  745. elif form['columns'] == 'qtr':
  746. all_account_period[p_act] = all_account
  747. ###############################################################
  748. # End of the calculations of credit, debit and balance
  749. #
  750. ###############################################################
  751. for aa_id in account_ids:
  752. id = aa_id[0]
  753. if aa_id[3].type == 'consolidation' and delete_cons:
  754. continue
  755. #
  756. # Check if we need to include this level
  757. #
  758. if not form['display_account_level'] \
  759. or aa_id[3].level <= form['display_account_level']:
  760. res = {
  761. 'id': id,
  762. 'type': aa_id[3].type,
  763. 'code': aa_id[3].code,
  764. 'name': (aa_id[2] and not aa_id[1])
  765. and 'TOTAL %s' % (aa_id[3].name.upper())
  766. or aa_id[3].name,
  767. 'parent_id': aa_id[3].parent_id and aa_id[3].parent_id.id,
  768. 'level': aa_id[3].level,
  769. 'label': aa_id[1],
  770. 'total': aa_id[2],
  771. 'change_sign': credit_account_ids
  772. and (id in credit_account_ids and -1 or 1) or 1
  773. }
  774. if form['columns'] == 'qtr':
  775. for pn in range(1, 5):
  776. if form['inf_type'] == 'IS':
  777. d, c, b = map(z, [
  778. all_account_period.get(pn - 1).
  779. get(id).get('debit', 0.0),
  780. all_account_period.get(pn - 1).
  781. get(id).get('credit', 0.0),
  782. all_account_period.get(pn - 1).
  783. get(id).get('balance', 0.0)])
  784. res.update({
  785. 'dbr%s' % pn: self.exchange(d),
  786. 'cdr%s' % pn: self.exchange(c),
  787. 'bal%s' % pn: self.exchange(b),
  788. })
  789. else:
  790. i, d, c = map(z, [
  791. all_account_period.get(pn - 1).
  792. get(id).get('balanceinit', 0.0),
  793. all_account_period.get(pn - 1).
  794. get(id).get('debit', 0.0),
  795. all_account_period.get(pn - 1).
  796. get(id).get('credit', 0.0)])
  797. b = z(i + d - c)
  798. res.update({
  799. 'dbr%s' % pn: self.exchange(d),
  800. 'cdr%s' % pn: self.exchange(c),
  801. 'bal%s' % pn: self.exchange(b),
  802. })
  803. if form['inf_type'] == 'IS':
  804. d, c, b = map(z, [
  805. all_account_period.get('all').get(id).
  806. get('debit', 0.0),
  807. all_account_period.get('all').get(id).
  808. get('credit', 0.0),
  809. all_account_period.get('all').get(id).
  810. get('balance')])
  811. res.update({
  812. 'dbr5': self.exchange(d),
  813. 'cdr5': self.exchange(c),
  814. 'bal5': self.exchange(b),
  815. })
  816. else:
  817. i, d, c = map(z, [
  818. all_account_period.get('all').get(id).
  819. get('balanceinit', 0.0),
  820. all_account_period.get('all').get(id).
  821. get('debit', 0.0),
  822. all_account_period.get('all').get(id).
  823. get('credit', 0.0)])
  824. b = z(i + d - c)
  825. res.update({
  826. 'dbr5': self.exchange(d),
  827. 'cdr5': self.exchange(c),
  828. 'bal5': self.exchange(b),
  829. })
  830. elif form['columns'] == 'thirteen':
  831. pn = 1
  832. for p_num in range(12):
  833. if form['inf_type'] == 'IS':
  834. d, c, b = map(z, [
  835. all_account_period.get(p_num).
  836. get(id).get('debit', 0.0),
  837. all_account_period.get(p_num).
  838. get(id).get('credit', 0.0),
  839. all_account_period.get(p_num).
  840. get(id).get('balance', 0.0)])
  841. res.update({
  842. 'dbr%s' % pn: self.exchange(d),
  843. 'cdr%s' % pn: self.exchange(c),
  844. 'bal%s' % pn: self.exchange(b),
  845. })
  846. else:
  847. i, d, c = map(z, [
  848. all_account_period.get(p_num).
  849. get(id).get('balanceinit', 0.0),
  850. all_account_period.get(p_num).
  851. get(id).get('debit', 0.0),
  852. all_account_period.get(p_num).
  853. get(id).get('credit', 0.0)])
  854. b = z(i + d - c)
  855. res.update({
  856. 'dbr%s' % pn: self.exchange(d),
  857. 'cdr%s' % pn: self.exchange(c),
  858. 'bal%s' % pn: self.exchange(b),
  859. })
  860. pn += 1
  861. if form['inf_type'] == 'IS':
  862. d, c, b = map(z, [
  863. all_account_period.get('all').get(id).
  864. get('debit', 0.0),
  865. all_account_period.get('all').get(id).
  866. get('credit', 0.0),
  867. all_account_period.get('all').get(id).
  868. get('balance', 0.0)])
  869. res.update({
  870. 'dbr13': self.exchange(d),
  871. 'cdr13': self.exchange(c),
  872. 'bal13': self.exchange(b),
  873. })
  874. else:
  875. i, d, c = map(z, [
  876. all_account_period.get('all').get(id).
  877. get('balanceinit', 0.0),
  878. all_account_period.get('all').get(id).
  879. get('debit', 0.0),
  880. all_account_period.get('all').get(id).
  881. get('credit', 0.0)])
  882. b = z(i + d - c)
  883. res.update({
  884. 'dbr13': self.exchange(d),
  885. 'cdr13': self.exchange(c),
  886. 'bal13': self.exchange(b),
  887. })
  888. else:
  889. i, d, c = map(z, [
  890. all_account_period.get('all').get(id).
  891. get('balanceinit', 0.0),
  892. all_account_period.get('all').get(id).
  893. get('debit', 0.0),
  894. all_account_period.get('all').get(id).
  895. get('credit', 0.0)])
  896. b = z(i + d - c)
  897. res.update({
  898. 'balanceinit': self.exchange(i),
  899. 'debit': self.exchange(d),
  900. 'credit': self.exchange(c),
  901. 'ytd': self.exchange(d - c),
  902. })
  903. if form['inf_type'] == 'IS' and form['columns'] == 'one':
  904. res.update({
  905. 'balance': self.exchange(d - c),
  906. })
  907. else:
  908. res.update({
  909. 'balance': self.exchange(b),
  910. })
  911. #
  912. # Check whether we must include this line in the report or not
  913. #
  914. to_include = False
  915. if form['columns'] in ('thirteen', 'qtr'):
  916. to_test = [False]
  917. if form['display_account'] == 'mov' and aa_id[3].parent_id:
  918. # Include accounts with movements
  919. for x in range(pn - 1):
  920. to_test.append(res.get(
  921. 'dbr%s' % x, 0.0) >= 0.005 and True or False)
  922. to_test.append(res.get(
  923. 'cdr%s' % x, 0.0) >= 0.005 and True or False)
  924. if any(to_test):
  925. to_include = True
  926. elif form['display_account'] == 'bal' and aa_id[3].\
  927. parent_id:
  928. # Include accounts with balance
  929. for x in range(pn - 1):
  930. to_test.append(res.get(
  931. 'bal%s' % x, 0.0) >= 0.005 and True or False)
  932. if any(to_test):
  933. to_include = True
  934. elif form['display_account'] == 'bal_mov' and aa_id[3].\
  935. parent_id:
  936. # Include accounts with balance or movements
  937. for x in range(pn - 1):
  938. to_test.append(res.get(
  939. 'bal%s' % x, 0.0) >= 0.005 and True or False)
  940. to_test.append(res.get(
  941. 'dbr%s' % x, 0.0) >= 0.005 and True or False)
  942. to_test.append(res.get(
  943. 'cdr%s' % x, 0.0) >= 0.005 and True or False)
  944. if any(to_test):
  945. to_include = True
  946. else:
  947. # Include all accounts
  948. to_include = True
  949. else:
  950. if form['display_account'] == 'mov' and aa_id[3].parent_id:
  951. # Include accounts with movements
  952. if abs(d) >= 0.005 or abs(c) >= 0.005:
  953. to_include = True
  954. elif form['display_account'] == 'bal' and aa_id[3].\
  955. parent_id:
  956. # Include accounts with balance
  957. if abs(b) >= 0.005:
  958. to_include = True
  959. elif form['display_account'] == 'bal_mov' and aa_id[3].\
  960. parent_id:
  961. # Include accounts with balance or movements
  962. if abs(b) >= 0.005 \
  963. or abs(d) >= 0.005 \
  964. or abs(c) >= 0.005:
  965. to_include = True
  966. else:
  967. # Include all accounts
  968. to_include = True
  969. # ~ ANALYTIC LEDGER
  970. if to_include and form['analytic_ledger'] \
  971. and form['columns'] == 'four' \
  972. and form['inf_type'] == 'BS' \
  973. and res['type'] in ('other', 'liquidity',
  974. 'receivable', 'payable'):
  975. res['mayor'] = self._get_analytic_ledger(res, ctx=ctx_end)
  976. elif to_include and form['journal_ledger'] \
  977. and form['columns'] == 'four' \
  978. and form['inf_type'] == 'BS' \
  979. and res['type'] in ('other', 'liquidity',
  980. 'receivable', 'payable'):
  981. res['journal'] = self._get_journal_ledger(res, ctx=ctx_end)
  982. elif to_include and form['partner_balance'] \
  983. and form['columns'] == 'four' \
  984. and form['inf_type'] == 'BS' \
  985. and res['type'] in ('other', 'liquidity',
  986. 'receivable', 'payable'):
  987. res['partner'] = self._get_partner_balance(
  988. res, ctx_i['periods'], ctx=ctx_end)
  989. else:
  990. res['mayor'] = []
  991. if to_include:
  992. result_acc.append(res)
  993. #
  994. # Check whether we must sumarize this line in the report
  995. # or not
  996. #
  997. if form['tot_check'] and (res['id'] in account_list) \
  998. and (res['id'] not in tot):
  999. if form['columns'] == 'qtr':
  1000. tot_check = True
  1001. tot[res['id']] = True
  1002. tot_bal1 += res.get('bal1', 0.0)
  1003. tot_bal2 += res.get('bal2', 0.0)
  1004. tot_bal3 += res.get('bal3', 0.0)
  1005. tot_bal4 += res.get('bal4', 0.0)
  1006. tot_bal5 += res.get('bal5', 0.0)
  1007. elif form['columns'] == 'thirteen':
  1008. tot_check = True
  1009. tot[res['id']] = True
  1010. tot_bal1 += res.get('bal1', 0.0)
  1011. tot_bal2 += res.get('bal2', 0.0)
  1012. tot_bal3 += res.get('bal3', 0.0)
  1013. tot_bal4 += res.get('bal4', 0.0)
  1014. tot_bal5 += res.get('bal5', 0.0)
  1015. tot_bal6 += res.get('bal6', 0.0)
  1016. tot_bal7 += res.get('bal7', 0.0)
  1017. tot_bal8 += res.get('bal8', 0.0)
  1018. tot_bal9 += res.get('bal9', 0.0)
  1019. tot_bal10 += res.get('bal10', 0.0)
  1020. tot_bal11 += res.get('bal11', 0.0)
  1021. tot_bal12 += res.get('bal12', 0.0)
  1022. tot_bal13 += res.get('bal13', 0.0)
  1023. else:
  1024. tot_check = True
  1025. tot[res['id']] = True
  1026. tot_bin += res['balanceinit']
  1027. tot_deb += res['debit']
  1028. tot_crd += res['credit']
  1029. tot_ytd += res['ytd']
  1030. tot_eje += res['balance']
  1031. if tot_check:
  1032. str_label = form['lab_str']
  1033. res2 = {
  1034. 'type': 'view',
  1035. 'name': 'TOTAL %s' % (str_label),
  1036. 'label': False,
  1037. 'total': True,
  1038. }
  1039. if form['columns'] == 'qtr':
  1040. res2.update(dict(
  1041. bal1=z(tot_bal1),
  1042. bal2=z(tot_bal2),
  1043. bal3=z(tot_bal3),
  1044. bal4=z(tot_bal4),
  1045. bal5=z(tot_bal5),))
  1046. elif form['columns'] == 'thirteen':
  1047. res2.update(dict(
  1048. bal1=z(tot_bal1),
  1049. bal2=z(tot_bal2),
  1050. bal3=z(tot_bal3),
  1051. bal4=z(tot_bal4),
  1052. bal5=z(tot_bal5),
  1053. bal6=z(tot_bal6),
  1054. bal7=z(tot_bal7),
  1055. bal8=z(tot_bal8),
  1056. bal9=z(tot_bal9),
  1057. bal10=z(tot_bal10),
  1058. bal11=z(tot_bal11),
  1059. bal12=z(tot_bal12),
  1060. bal13=z(tot_bal13),))
  1061. else:
  1062. res2.update({
  1063. 'balanceinit': tot_bin,
  1064. 'debit': tot_deb,
  1065. 'credit': tot_crd,
  1066. 'ytd': tot_ytd,
  1067. 'balance': tot_eje,
  1068. })
  1069. result_acc.append(res2)
  1070. return result_acc
  1071. report_sxw.report_sxw(
  1072. 'report.afr.1cols',
  1073. 'wizard.report',
  1074. 'account_financial_report/report/balance_full.rml',
  1075. parser=account_balance,
  1076. header=False)
  1077. report_sxw.report_sxw(
  1078. 'report.afr.2cols',
  1079. 'wizard.report',
  1080. 'account_financial_report/report/balance_full_2_cols.rml',
  1081. parser=account_balance,
  1082. header=False)
  1083. report_sxw.report_sxw(
  1084. 'report.afr.4cols',
  1085. 'wizard.report',
  1086. 'account_financial_report/report/balance_full_4_cols.rml',
  1087. parser=account_balance,
  1088. header=False)
  1089. report_sxw.report_sxw(
  1090. 'report.afr.analytic.ledger',
  1091. 'wizard.report',
  1092. 'account_financial_report/report/balance_full_4_cols_analytic_ledger.rml',
  1093. parser=account_balance,
  1094. header=False)
  1095. report_sxw.report_sxw(
  1096. 'report.afr.partner.balance',
  1097. 'wizard.report',
  1098. 'account_financial_report/report/balance_full_4_cols_partner_balance.rml',
  1099. parser=account_balance,
  1100. header=False)
  1101. report_sxw.report_sxw(
  1102. 'report.afr.journal.ledger',
  1103. 'wizard.report',
  1104. 'account_financial_report/report/balance_full_4_cols_journal_ledger.rml',
  1105. parser=account_balance,
  1106. header=False)
  1107. report_sxw.report_sxw(
  1108. 'report.afr.5cols',
  1109. 'wizard.report',
  1110. 'account_financial_report/report/balance_full_5_cols.rml',
  1111. parser=account_balance,
  1112. header=False)
  1113. report_sxw.report_sxw(
  1114. 'report.afr.qtrcols',
  1115. 'wizard.report',
  1116. 'account_financial_report/report/balance_full_qtr_cols.rml',
  1117. parser=account_balance,
  1118. header=False)
  1119. report_sxw.report_sxw(
  1120. 'report.afr.13cols',
  1121. 'wizard.report',
  1122. 'account_financial_report/report/balance_full_13_cols.rml',
  1123. parser=account_balance,
  1124. header=False)