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.

1074 lines
49 KiB

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