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.

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