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.

548 lines
25 KiB

  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. class account_balance(report_sxw.rml_parse):
  37. def __init__(self, cr, uid, name, context):
  38. super(account_balance, self).__init__(cr, uid, name, context)
  39. self.sum_debit = 0.00
  40. self.sum_credit = 0.00
  41. self.sum_balance = 0.00
  42. self.sum_debit_fy = 0.00
  43. self.sum_credit_fy = 0.00
  44. self.sum_balance_fy = 0.00
  45. self.date_lst = []
  46. self.date_lst_string = ''
  47. self.localcontext.update({
  48. 'time': time,
  49. 'lines': self.lines,
  50. 'get_fiscalyear_text': self.get_fiscalyear_text,
  51. 'get_periods_and_date_text': self.get_periods_and_date_text,
  52. 'get_informe_text': self.get_informe_text,
  53. 'get_month':self.get_month,
  54. 'exchange_name':self.exchange_name,
  55. })
  56. self.context = context
  57. def get_fiscalyear_text(self, form):
  58. """
  59. Returns the fiscal year text used on the report.
  60. """
  61. fiscalyear_obj = self.pool.get('account.fiscalyear')
  62. fiscalyear = None
  63. if form.get('fiscalyear'):
  64. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, form['fiscalyear'])
  65. return fiscalyear.name or fiscalyear.code
  66. else:
  67. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, fiscalyear_obj.find(self.cr, self.uid))
  68. return "%s*" % (fiscalyear.name or fiscalyear.code)
  69. def get_informe_text(self, form):
  70. """
  71. Returns the header text used on the report.
  72. """
  73. inf_type = {
  74. 'bgen' : 'Balance General',
  75. 'IS' : 'Income Statement',
  76. 'bcom' : 'Balance de Comprobacion',
  77. 'edogp': 'Estado de Ganancias y Perdidas',
  78. 'bml' : 'Libro Mayor Legal',
  79. 'bdl' : 'Diario Legal'
  80. }
  81. return inf_type[form['inf_type']]
  82. def get_month(self, form):
  83. '''
  84. return day, year and month
  85. '''
  86. if form['filter'] in ['bydate', 'all']:
  87. months=["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"]
  88. mes = months[time.strptime(form['date_to'],"%Y-%m-%d")[1]-1]
  89. ano = time.strptime(form['date_to'],"%Y-%m-%d")[0]
  90. dia = time.strptime(form['date_to'],"%Y-%m-%d")[2]
  91. return 'Período del '+self.formatLang(form['date_from'], date=True)+' al '+self.formatLang(form['date_to'], date=True)
  92. elif form['filter'] in ['byperiod', 'all']:
  93. aux=[]
  94. period_obj = self.pool.get('account.period')
  95. for period in period_obj.browse(self.cr, self.uid, form['periods']):
  96. aux.append(period.date_start)
  97. aux.append(period.date_stop)
  98. sorted(aux)
  99. return _('Período del ')+self.formatLang(aux[0], date=True)+_(' al ')+self.formatLang(aux[-1], date=True)
  100. def get_periods_and_date_text(self, form):
  101. """
  102. Returns the text with the periods/dates used on the report.
  103. """
  104. period_obj = self.pool.get('account.period')
  105. periods_str = None
  106. fiscalyear_id = form['fiscalyear'] or fiscalyear_obj.find(self.cr, self.uid)
  107. period_ids = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear_id),('special','=',False)])
  108. if form['filter'] in ['byperiod', 'all']:
  109. period_ids = form['periods']
  110. periods_str = ', '.join([period.name or period.code for period in period_obj.browse(self.cr, self.uid, period_ids)])
  111. dates_str = None
  112. if form['filter'] in ['bydate', 'all']:
  113. dates_str = self.formatLang(form['date_from'], date=True) + ' - ' + self.formatLang(form['date_to'], date=True) + ' '
  114. return {'periods':periods_str, 'date':dates_str}
  115. def special_period(self, periods):
  116. period_obj = self.pool.get('account.period')
  117. period_brw = period_obj.browse(self.cr, self.uid, periods)
  118. period_counter = [True for i in period_brw if not i.special]
  119. if not period_counter:
  120. return True
  121. return False
  122. def exchange_name(self, form):
  123. self.from_currency_id = self.get_company_currency(form['company_id'] and type(form['company_id']) in (list,tuple) and form['company_id'][0] or form['company_id'])
  124. if not form['currency_id']:
  125. self.to_currency_id = self.from_currency_id
  126. else:
  127. self.to_currency_id = form['currency_id'] and type(form['currency_id']) in (list, tuple) and form['currency_id'][0] or form['currency_id']
  128. return self.pool.get('res.currency').browse(self.cr, self.uid, self.to_currency_id).name
  129. def exchange(self, from_amount):
  130. if self.from_currency_id == self.to_currency_id:
  131. return from_amount
  132. curr_obj = self.pool.get('res.currency')
  133. return curr_obj.compute(self.cr, self.uid, self.from_currency_id, self.to_currency_id, from_amount)
  134. def get_company_currency(self, company_id):
  135. rc_obj = self.pool.get('res.company')
  136. return rc_obj.browse(self.cr, self.uid, company_id).currency_id.id
  137. def get_company_credit_accounts(self, company_id):
  138. rc_obj = self.pool.get('res.company')
  139. return [brw.id for brw in rc_obj.browse(self.cr, self.uid, company_id).credit_account_ids]
  140. def lines(self, form, level=0):
  141. """
  142. Returns all the data needed for the report lines
  143. (account info plus debit/credit/balance in the selected period
  144. and the full year)
  145. """
  146. account_obj = self.pool.get('account.account')
  147. period_obj = self.pool.get('account.period')
  148. fiscalyear_obj = self.pool.get('account.fiscalyear')
  149. def _get_children_and_consol(cr, uid, ids, level, context={},change_sign=False):
  150. aa_obj = self.pool.get('account.account')
  151. ids2=[]
  152. for aa_brw in aa_obj.browse(cr, uid, ids, context):
  153. if aa_brw.child_id and aa_brw.level < level and aa_brw.type !='consolidation':
  154. if not change_sign:
  155. ids2.append([aa_brw.id,True, False,aa_brw])
  156. ids2 += _get_children_and_consol(cr, uid, [x.id for x in aa_brw.child_id], level, context,change_sign=change_sign)
  157. if change_sign:
  158. ids2.append(aa_brw.id)
  159. else:
  160. ids2.append([aa_brw.id,False,True,aa_brw])
  161. else:
  162. if change_sign:
  163. ids2.append(aa_brw.id)
  164. else:
  165. ids2.append([aa_brw.id,True,True,aa_brw])
  166. return ids2
  167. #############################################################################
  168. # CONTEXT FOR ENDIND BALANCE #
  169. #############################################################################
  170. def _ctx_end(ctx):
  171. ctx_end = ctx
  172. ctx_end['filter'] = form.get('filter','all')
  173. ctx_end['fiscalyear'] = fiscalyear.id
  174. #~ ctx_end['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('special','=',False)])
  175. if ctx_end['filter'] not in ['bydate','none']:
  176. special = self.special_period(form['periods'])
  177. else:
  178. special = False
  179. if form['filter'] in ['byperiod', 'all']:
  180. if special:
  181. ctx_end['periods'] = period_obj.search(self.cr, self.uid, [('id','in',form['periods'] or ctx_end.get('periods',False))])
  182. else:
  183. ctx_end['periods'] = period_obj.search(self.cr, self.uid, [('id','in',form['periods'] or ctx_end.get('periods',False)),('special','=',False)])
  184. if form['filter'] in ['bydate','all','none']:
  185. ctx_end['date_from'] = form['date_from']
  186. ctx_end['date_to'] = form['date_to']
  187. return ctx_end.copy()
  188. def missing_period(ctx_init):
  189. ctx_init['fiscalyear'] = fiscalyear_obj.search(self.cr, self.uid, [('date_stop','<',fiscalyear.date_start)],order='date_stop') and \
  190. fiscalyear_obj.search(self.cr, self.uid, [('date_stop','<',fiscalyear.date_start)],order='date_stop')[-1] or []
  191. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',ctx_init['fiscalyear']),('date_stop','<',fiscalyear.date_start)])
  192. return ctx_init
  193. #############################################################################
  194. # CONTEXT FOR INITIAL BALANCE #
  195. #############################################################################
  196. def _ctx_init(ctx):
  197. ctx_init = self.context.copy()
  198. ctx_init['filter'] = form.get('filter','all')
  199. ctx_init['fiscalyear'] = fiscalyear.id
  200. if form['filter'] in ['byperiod', 'all']:
  201. ctx_init['periods'] = form['periods']
  202. date_start = min([period.date_start for period in period_obj.browse(self.cr, self.uid, ctx_init['periods'])])
  203. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_stop','<=',date_start)])
  204. if not ctx_init['periods']:
  205. ctx_init = missing_period(ctx_init.copy())
  206. elif form['filter'] in ['bydate']:
  207. ctx_init['date_from'] = fiscalyear.date_start
  208. ctx_init['date_to'] = form['date_from']
  209. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_stop','<=',ctx_init['date_to'])])
  210. elif form['filter'] == 'none':
  211. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('special','=',True)])
  212. date_start = min([period.date_start for period in period_obj.browse(self.cr, self.uid, ctx_init['periods'])])
  213. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_start','<=',date_start),('special','=',True)])
  214. return ctx_init.copy()
  215. def z(n):
  216. return abs(n) < 0.005 and 0.0 or n
  217. self.from_currency_id = self.get_company_currency(form['company_id'] and type(form['company_id']) in (list,tuple) and form['company_id'][0] or form['company_id'])
  218. if not form['currency_id']:
  219. self.to_currency_id = self.from_currency_id
  220. else:
  221. self.to_currency_id = form['currency_id'] and type(form['currency_id']) in (list, tuple) and form['currency_id'][0] or form['currency_id']
  222. if form.has_key('account_list') and form['account_list']:
  223. account_ids = form['account_list']
  224. del form['account_list']
  225. credit_account_ids = self.get_company_credit_accounts(form['company_id'] and type(form['company_id']) in (list,tuple) and form['company_id'][0] or form['company_id'])
  226. print 'Primer print de credit_account_ids ', credit_account_ids
  227. if form.get('fiscalyear'):
  228. if type(form.get('fiscalyear')) in (list,tuple):
  229. fiscalyear = form['fiscalyear'] and form['fiscalyear'][0]
  230. elif type(form.get('fiscalyear')) in (int,):
  231. fiscalyear = form['fiscalyear']
  232. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, fiscalyear)
  233. ################################################################
  234. # Get the accounts #
  235. ################################################################
  236. account_ids = _get_children_and_consol(self.cr, self.uid, account_ids, form['display_account_level'] and form['display_account_level'] or 100,self.context)
  237. credit_account_ids = _get_children_and_consol(self.cr, self.uid, credit_account_ids, 100,self.context,change_sign=True)
  238. print 'credit_account_ids ', credit_account_ids
  239. #
  240. # Generate the report lines (checking each account)
  241. #
  242. tot_check = False
  243. if form['columns'] != 'thirteen':
  244. ctx_init = _ctx_init(self.context.copy())
  245. ctx_end = _ctx_end(self.context.copy())
  246. tot_bin = 0.0
  247. tot_deb = 0.0
  248. tot_crd = 0.0
  249. tot_eje = 0.0
  250. elif form['columns'] == 'thirteen':
  251. tot_bal1 = 0.0
  252. tot_bal2 = 0.0
  253. tot_bal3 = 0.0
  254. tot_bal4 = 0.0
  255. tot_bal5 = 0.0
  256. tot_bal6 = 0.0
  257. tot_bal7 = 0.0
  258. tot_bal8 = 0.0
  259. tot_bal9 = 0.0
  260. tot_bal10 = 0.0
  261. tot_bal11 = 0.0
  262. tot_bal12 = 0.0
  263. tot_bal13 = 0.0
  264. res = {}
  265. result_acc = []
  266. tot = {}
  267. if form['columns'] == 'thirteen':
  268. period_ids = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('special','=',False)],order='date_start asc')
  269. print 'TODOS LOS PERIODS ',period_ids
  270. for aa_id in account_ids:
  271. id = aa_id[0]
  272. #
  273. # Check if we need to include this level
  274. #
  275. if not form['display_account_level'] or account['level'] <= form['display_account_level']:
  276. res = {
  277. 'id' : id,
  278. 'type' : aa_id[3].type,
  279. 'code' : aa_id[3].code,
  280. 'name' : (aa_id[2] and not aa_id[1]) and 'TOTAL %s'%(aa_id[3].name.upper()) or aa_id[3].name,
  281. 'parent_id' : aa_id[3].parent_id and aa_id[3].parent_id.id,
  282. 'level' : aa_id[3].level,
  283. 'label' : aa_id[1],
  284. 'total' : aa_id[2],
  285. 'change_sign' : credit_account_ids and (id in credit_account_ids and -1 or 1) or 1
  286. }
  287. if form['columns'] != 'thirteen':
  288. aa_brw_init = account_obj.browse(self.cr, self.uid, id, ctx_init)
  289. aa_brw_end = account_obj.browse(self.cr, self.uid, id, ctx_end)
  290. i,d,c = map(z,[aa_brw_init.balance,aa_brw_end.debit,aa_brw_end.credit])
  291. b = z(i+d-c)
  292. res.update({
  293. 'balanceinit': self.exchange(i),
  294. 'debit': self.exchange(d),
  295. 'credit': self.exchange(c),
  296. 'balance': self.exchange(b),
  297. })
  298. elif form['columns'] == 'thirteen':
  299. pn = 1
  300. for p_id in period_ids:
  301. form['periods'] = [p_id]
  302. ctx_init = _ctx_init(self.context.copy())
  303. aa_brw_init = account_obj.browse(self.cr, self.uid, id, ctx_init)
  304. ctx_end = _ctx_end(self.context.copy())
  305. aa_brw_end = account_obj.browse(self.cr, self.uid, id, ctx_end)
  306. if form['inf_type'] == 'IS':
  307. d,c,b = map(z,[aa_brw_end.debit,aa_brw_end.credit,aa_brw_end.balance])
  308. res.update({
  309. 'dbr%s'%pn: self.exchange(d),
  310. 'cdr%s'%pn: self.exchange(c),
  311. 'bal%s'%pn: self.exchange(b),
  312. })
  313. else:
  314. i,d,c = map(z,[aa_brw_init.balance,aa_brw_end.debit,aa_brw_end.credit])
  315. b = z(i+d-c)
  316. res.update({
  317. 'dbr%s'%pn: self.exchange(d),
  318. 'cdr%s'%pn: self.exchange(c),
  319. 'bal%s'%pn: self.exchange(b),
  320. })
  321. pn +=1
  322. form['periods'] = period_ids
  323. ctx_init = _ctx_init(self.context.copy())
  324. aa_brw_init = account_obj.browse(self.cr, self.uid, id, ctx_init)
  325. ctx_end = _ctx_end(self.context.copy())
  326. aa_brw_end = account_obj.browse(self.cr, self.uid, id, ctx_end)
  327. if form['inf_type'] == 'IS':
  328. d,c,b = map(z,[aa_brw_end.debit,aa_brw_end.credit,aa_brw_end.balance])
  329. res.update({
  330. 'dbr13': self.exchange(d),
  331. 'cdr13': self.exchange(c),
  332. 'bal13': self.exchange(b),
  333. })
  334. else:
  335. i,d,c = map(z,[aa_brw_init.balance,aa_brw_end.debit,aa_brw_end.credit])
  336. b = z(i+d-c)
  337. res.update({
  338. 'dbr13': self.exchange(d),
  339. 'cdr13': self.exchange(c),
  340. 'bal13': self.exchange(b),
  341. })
  342. #
  343. # Check whether we must include this line in the report or not
  344. #
  345. to_include = False
  346. if form['columns'] != 'thirteen':
  347. if form['display_account'] == 'mov' and aa_id[3].parent_id:
  348. # Include accounts with movements
  349. if abs(d) >= 0.005 or abs(c) >= 0.005:
  350. to_include = True
  351. elif form['display_account'] == 'bal' and aa_id[3].parent_id:
  352. # Include accounts with balance
  353. if abs(b) >= 0.005:
  354. to_include = True
  355. elif form['display_account'] == 'bal_mov' and aa_id[3].parent_id:
  356. # Include accounts with balance or movements
  357. if abs(b) >= 0.005 or abs(d) >= 0.005 or abs(c) >= 0.005:
  358. to_include = True
  359. else:
  360. # Include all accounts
  361. to_include = True
  362. elif form['columns'] == 'thirteen':
  363. to_test = [False]
  364. if form['display_account'] == 'mov' and aa_id[3].parent_id:
  365. # Include accounts with movements
  366. for x in range(pn-1):
  367. to_test.append(res.get('dbr%s'%x,0.0) >= 0.005 and True or False)
  368. to_test.append(res.get('cdr%s'%x,0.0) >= 0.005 and True or False)
  369. if any(to_test):
  370. to_include = True
  371. elif form['display_account'] == 'bal' and aa_id[3].parent_id:
  372. # Include accounts with balance
  373. for x in range(pn-1):
  374. to_test.append(res.get('bal%s'%x,0.0) >= 0.005 and True or False)
  375. if any(to_test):
  376. to_include = True
  377. elif form['display_account'] == 'bal_mov' and aa_id[3].parent_id:
  378. # Include accounts with balance or movements
  379. for x in range(pn-1):
  380. to_test.append(res.get('bal%s'%x,0.0) >= 0.005 and True or False)
  381. to_test.append(res.get('dbr%s'%x,0.0) >= 0.005 and True or False)
  382. to_test.append(res.get('cdr%s'%x,0.0) >= 0.005 and True or False)
  383. if any(to_test):
  384. to_include = True
  385. else:
  386. # Include all accounts
  387. to_include = True
  388. if to_include:
  389. result_acc.append(res)
  390. #
  391. # Check whether we must sumarize this line in the report or not
  392. #
  393. if form['tot_check'] and res['type'] == 'view' and res['level'] == 1 and (res['id'] not in tot):
  394. if form['columns'] != 'thirteen':
  395. tot_check = True
  396. tot[res['id']] = True
  397. tot_bin += res['balanceinit']
  398. tot_deb += res['debit']
  399. tot_crd += res['credit']
  400. tot_eje += res['balance']
  401. if form['columns'] == 'thirteen':
  402. tot_check = True
  403. tot[res['id']] = True
  404. tot_bal1 += res.get('bal1',0.0)
  405. tot_bal2 += res.get('bal2',0.0)
  406. tot_bal3 += res.get('bal3',0.0)
  407. tot_bal4 += res.get('bal4',0.0)
  408. tot_bal5 += res.get('bal5',0.0)
  409. tot_bal6 += res.get('bal6',0.0)
  410. tot_bal7 += res.get('bal7',0.0)
  411. tot_bal8 += res.get('bal8',0.0)
  412. tot_bal9 += res.get('bal9',0.0)
  413. tot_bal10 += res.get('bal10',0.0)
  414. tot_bal11 += res.get('bal11',0.0)
  415. tot_bal12 += res.get('bal12',0.0)
  416. tot_bal13 += res.get('bal13',0.0)
  417. if tot_check:
  418. str_label = form['lab_str']
  419. res2 = {
  420. 'type' : 'view',
  421. 'name': 'TOTAL %s'%(str_label),
  422. 'label': False,
  423. 'total': True,
  424. }
  425. if form['columns'] != 'thirteen':
  426. res2.update({
  427. 'balanceinit': tot_bin,
  428. 'debit': tot_deb,
  429. 'credit': tot_crd,
  430. 'balance': tot_eje,
  431. })
  432. if form['columns'] == 'thirteen':
  433. res2.update(dict(
  434. bal1 = tot_bal1,
  435. bal2 = tot_bal2,
  436. bal3 = tot_bal3,
  437. bal4 = tot_bal4,
  438. bal5 = tot_bal5,
  439. bal6 = tot_bal6,
  440. bal7 = tot_bal7,
  441. bal8 = tot_bal8,
  442. bal9 = tot_bal9,
  443. bal10 = tot_bal10,
  444. bal11 = tot_bal11,
  445. bal12 = tot_bal12,
  446. bal13 = tot_bal13,))
  447. result_acc.append(res2)
  448. return result_acc
  449. report_sxw.report_sxw('report.afr.1cols',
  450. 'wizard.report',
  451. 'account_financial_report/report/balance_full.rml',
  452. parser=account_balance,
  453. header=False)
  454. report_sxw.report_sxw('report.afr.2cols',
  455. 'wizard.report',
  456. 'account_financial_report/report/balance_full_2_cols.rml',
  457. parser=account_balance,
  458. header=False)
  459. report_sxw.report_sxw('report.afr.4cols',
  460. 'wizard.report',
  461. 'account_financial_report/report/balance_full_4_cols.rml',
  462. parser=account_balance,
  463. header=False)
  464. report_sxw.report_sxw('report.afr.13cols',
  465. 'wizard.report',
  466. 'account_financial_report/report/balance_full_13_cols.rml',
  467. parser=account_balance,
  468. header=False)