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.

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