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.

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