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.

380 lines
18 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. 'bcom' : ' Balance de Comprobacion',
  76. 'edogp': 'Estado de Ganancias y Perdidas',
  77. 'bml': 'Libro Mayor Legal',
  78. 'bdl' : 'Diario Legal'
  79. }
  80. return inf_type[form['inf_type']]
  81. def get_month(self, form):
  82. '''
  83. return day, year and month
  84. '''
  85. if form['filter'] in ['bydate', 'all']:
  86. months=["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"]
  87. mes = months[time.strptime(form['date_to'],"%Y-%m-%d")[1]-1]
  88. ano = time.strptime(form['date_to'],"%Y-%m-%d")[0]
  89. dia = time.strptime(form['date_to'],"%Y-%m-%d")[2]
  90. return 'Período del '+self.formatLang(form['date_from'], date=True)+' al '+self.formatLang(form['date_to'], date=True)
  91. elif form['filter'] in ['byperiod', 'all']:
  92. aux=[]
  93. period_obj = self.pool.get('account.period')
  94. for period in period_obj.browse(self.cr, self.uid, form['periods']):
  95. aux.append(period.date_start)
  96. aux.append(period.date_stop)
  97. sorted(aux)
  98. return _('Período del ')+self.formatLang(aux[0], date=True)+_(' al ')+self.formatLang(aux[-1], date=True)
  99. def get_periods_and_date_text(self, form):
  100. """
  101. Returns the text with the periods/dates used on the report.
  102. """
  103. period_obj = self.pool.get('account.period')
  104. periods_str = None
  105. fiscalyear_id = form['fiscalyear'] or fiscalyear_obj.find(self.cr, self.uid)
  106. period_ids = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear_id),('special','=',False)])
  107. if form['filter'] in ['byperiod', 'all']:
  108. period_ids = form['periods']
  109. periods_str = ', '.join([period.name or period.code for period in period_obj.browse(self.cr, self.uid, period_ids)])
  110. dates_str = None
  111. if form['filter'] in ['bydate', 'all']:
  112. dates_str = self.formatLang(form['date_from'], date=True) + ' - ' + self.formatLang(form['date_to'], date=True) + ' '
  113. return {'periods':periods_str, 'date':dates_str}
  114. def special_period(self, periods):
  115. period_obj = self.pool.get('account.period')
  116. period_brw = period_obj.browse(self.cr, self.uid, periods)
  117. period_counter = [True for i in period_brw if not i.special]
  118. if not period_counter:
  119. return True
  120. return False
  121. def exchange_name(self, form):
  122. 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'])
  123. if not form['currency_id']:
  124. self.to_currency_id = self.from_currency_id
  125. else:
  126. self.to_currency_id = form['currency_id'] and type(form['currency_id']) in (list, tuple) and form['currency_id'][0] or form['currency_id']
  127. return self.pool.get('res.currency').browse(self.cr, self.uid, self.to_currency_id).name
  128. def exchange(self, from_amount):
  129. if self.from_currency_id == self.to_currency_id:
  130. return from_amount
  131. curr_obj = self.pool.get('res.currency')
  132. return curr_obj.compute(self.cr, self.uid, self.from_currency_id, self.to_currency_id, from_amount)
  133. def get_company_currency(self, company_id):
  134. rc_obj = self.pool.get('res.company')
  135. return rc_obj.browse(self.cr, self.uid, company_id).currency_id.id
  136. def get_company_credit_accounts(self, company_id):
  137. rc_obj = self.pool.get('res.company')
  138. return [brw.id for brw in rc_obj.browse(self.cr, self.uid, company_id).credit_account_ids]
  139. def lines(self, form, level=0):
  140. """
  141. Returns all the data needed for the report lines
  142. (account info plus debit/credit/balance in the selected period
  143. and the full year)
  144. """
  145. 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'])
  146. if not form['currency_id']:
  147. self.to_currency_id = self.from_currency_id
  148. else:
  149. self.to_currency_id = form['currency_id'] and type(form['currency_id']) in (list, tuple) and form['currency_id'][0] or form['currency_id']
  150. tot_check = False
  151. tot_bin = 0.0
  152. tot_deb = 0.0
  153. tot_crd = 0.0
  154. tot_eje = 0.0
  155. if form.has_key('account_list') and form['account_list']:
  156. account_ids = form['account_list']
  157. del form['account_list']
  158. 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'])
  159. print 'Primer print de credit_account_ids ', credit_account_ids
  160. res = {}
  161. result_acc = []
  162. account_obj = self.pool.get('account.account')
  163. period_obj = self.pool.get('account.period')
  164. fiscalyear_obj = self.pool.get('account.fiscalyear')
  165. if form.get('fiscalyear'):
  166. if type(form.get('fiscalyear')) in (list,tuple):
  167. fiscalyear = form['fiscalyear'] and form['fiscalyear'][0]
  168. elif type(form.get('fiscalyear')) in (int,):
  169. fiscalyear = form['fiscalyear']
  170. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, fiscalyear)
  171. #
  172. # Get the accounts
  173. #
  174. def _get_children_and_consol(cr, uid, ids, level, context={},change_sign=False):
  175. aa_obj = self.pool.get('account.account')
  176. ids2=[]
  177. for aa_brw in aa_obj.browse(cr, uid, ids, context):
  178. if aa_brw.child_id and aa_brw.level < level and aa_brw.type !='consolidation':
  179. if not change_sign:
  180. ids2.append([aa_brw.id,True, False,aa_brw])
  181. ids2 += _get_children_and_consol(cr, uid, [x.id for x in aa_brw.child_id], level, context,change_sign=change_sign)
  182. if change_sign:
  183. ids2.append(aa_brw.id)
  184. else:
  185. ids2.append([aa_brw.id,False,True,aa_brw])
  186. else:
  187. if change_sign:
  188. ids2.append(aa_brw.id)
  189. else:
  190. ids2.append([aa_brw.id,True,True,aa_brw])
  191. return ids2
  192. 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)
  193. credit_account_ids = _get_children_and_consol(self.cr, self.uid, credit_account_ids, 100,self.context,change_sign=True)
  194. print 'credit_account_ids ', credit_account_ids
  195. account_obj = self.pool.get('account.account')
  196. period_obj = self.pool.get('account.period')
  197. fiscalyear_obj = self.pool.get('account.fiscalyear')
  198. #############################################################################
  199. # Calculate the period Debit/Credit #
  200. # (from the selected period or all the non special periods in the fy) #
  201. #############################################################################
  202. ctx_end = self.context.copy()
  203. ctx_end['filter'] = form.get('filter','all')
  204. ctx_end['fiscalyear'] = fiscalyear.id
  205. #~ ctx_end['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('special','=',False)])
  206. if ctx_end['filter'] not in ['bydate','none']:
  207. special = self.special_period(form['periods'])
  208. else:
  209. special = False
  210. if form['filter'] in ['byperiod', 'all']:
  211. if special:
  212. ctx_end['periods'] = period_obj.search(self.cr, self.uid, [('id','in',form['periods'] or ctx_end.get('periods',False))])
  213. else:
  214. ctx_end['periods'] = period_obj.search(self.cr, self.uid, [('id','in',form['periods'] or ctx_end.get('periods',False)),('special','=',False)])
  215. if form['filter'] in ['bydate','all','none']:
  216. ctx_end['date_from'] = form['date_from']
  217. ctx_end['date_to'] = form['date_to']
  218. def missing_period():
  219. ctx_init['fiscalyear'] = fiscalyear_obj.search(self.cr, self.uid, [('date_stop','<',fiscalyear.date_start)],order='date_stop') and \
  220. fiscalyear_obj.search(self.cr, self.uid, [('date_stop','<',fiscalyear.date_start)],order='date_stop')[-1] or []
  221. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',ctx_init['fiscalyear']),('date_stop','<',fiscalyear.date_start)])
  222. #############################################################################
  223. # Calculate the period initial Balance #
  224. # (fy balance minus the balance from the start of the selected period #
  225. # to the end of the year) #
  226. #############################################################################
  227. ctx_init = self.context.copy()
  228. ctx_init['filter'] = form.get('filter','all')
  229. ctx_init['fiscalyear'] = fiscalyear.id
  230. if form['filter'] in ['byperiod', 'all']:
  231. ctx_init['periods'] = form['periods']
  232. date_start = min([period.date_start for period in period_obj.browse(self.cr, self.uid, ctx_init['periods'])])
  233. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_stop','<=',date_start)])
  234. if not ctx_init['periods']:
  235. missing_period()
  236. elif form['filter'] in ['bydate']:
  237. ctx_init['date_from'] = fiscalyear.date_start
  238. ctx_init['date_to'] = form['date_from']
  239. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_stop','<=',ctx_init['date_to'])])
  240. elif form['filter'] == 'none':
  241. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('special','=',True)])
  242. date_start = min([period.date_start for period in period_obj.browse(self.cr, self.uid, ctx_init['periods'])])
  243. ctx_init['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_start','<=',date_start),('special','=',True)])
  244. def z(n):
  245. return abs(n) < 0.005 and 0.0 or n
  246. #
  247. # Generate the report lines (checking each account)
  248. #
  249. tot = {}
  250. for aa_id in account_ids:
  251. id = aa_id[0]
  252. #
  253. # Check if we need to include this level
  254. #
  255. if not form['display_account_level'] or account['level'] <= form['display_account_level']:
  256. res = {
  257. 'id' : id,
  258. 'type' : aa_id[3].type,
  259. 'code' : aa_id[3].code,
  260. 'name' : (aa_id[2] and not aa_id[1]) and 'TOTAL %s'%(aa_id[3].name.upper()) or aa_id[3].name,
  261. 'parent_id' : aa_id[3].parent_id and aa_id[3].parent_id.id,
  262. 'level' : aa_id[3].level,
  263. 'label' : aa_id[1],
  264. 'total' : aa_id[2],
  265. 'change_sign' : credit_account_ids and (id in credit_account_ids and -1 or 1) or 1
  266. }
  267. if form['columns'] != 'thirteen':
  268. aa_brw_init = account_obj.browse(self.cr, self.uid, id, ctx_init)
  269. aa_brw_end = account_obj.browse(self.cr, self.uid, id, ctx_end)
  270. i,d,c = map(z,[aa_brw_init.balance,aa_brw_end.debit,aa_brw_end.credit])
  271. b = z(i+d-c)
  272. res.update({
  273. 'balanceinit': self.exchange(i),
  274. 'debit': self.exchange(d),
  275. 'credit': self.exchange(c),
  276. 'balance': self.exchange(b),
  277. })
  278. #
  279. # Check whether we must include this line in the report or not
  280. #
  281. if form['display_account'] == 'mov' and aa_id[3].parent_id:
  282. # Include accounts with movements
  283. if abs(d) >= 0.005 or abs(c) >= 0.005:
  284. result_acc.append(res)
  285. elif form['display_account'] == 'bal' and aa_id[3].parent_id:
  286. # Include accounts with balance
  287. if abs(b) >= 0.005:
  288. result_acc.append(res)
  289. elif form['display_account'] == 'bal_mov' and aa_id[3].parent_id:
  290. # Include accounts with balance or movements
  291. if abs(b) >= 0.005 or abs(d) >= 0.005 or abs(c) >= 0.005:
  292. result_acc.append(res)
  293. else:
  294. # Include all accounts
  295. result_acc.append(res)
  296. if form['tot_check'] and res['type'] == 'view' and res['level'] == 1 and (res['id'] not in tot):
  297. tot_check = True
  298. tot[res['id']] = True
  299. tot_bin += res['balanceinit']
  300. tot_deb += res['debit']
  301. tot_crd += res['credit']
  302. tot_eje += res['balance']
  303. #if (form['tot_check'] and res['type']=='view' and res['level']==1 and (res['id'] not in tot)):
  304. if tot_check:
  305. str_label = form['lab_str']
  306. res2 = {
  307. 'type' : 'view',
  308. 'name': 'TOTAL %s'%(str_label),
  309. 'balanceinit': tot_bin,
  310. 'debit': tot_deb,
  311. 'credit': tot_crd,
  312. 'balance': tot_eje,
  313. 'label': False,
  314. 'total': True,
  315. }
  316. result_acc.append(res2)
  317. return result_acc
  318. report_sxw.report_sxw('report.afr.1cols',
  319. 'wizard.report',
  320. 'account_financial_report/report/balance_full.rml',
  321. parser=account_balance,
  322. header=False)
  323. report_sxw.report_sxw('report.afr.2cols',
  324. 'wizard.report',
  325. 'account_financial_report/report/balance_full_2_cols.rml',
  326. parser=account_balance,
  327. header=False)
  328. report_sxw.report_sxw('report.afr.4cols',
  329. 'wizard.report',
  330. 'account_financial_report/report/balance_full_4_cols.rml',
  331. parser=account_balance,
  332. header=False)