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.

385 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 lines(self, form, level=0):
  137. """
  138. Returns all the data needed for the report lines
  139. (account info plus debit/credit/balance in the selected period
  140. and the full year)
  141. """
  142. 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'])
  143. if not form['currency_id']:
  144. self.to_currency_id = self.from_currency_id
  145. else:
  146. self.to_currency_id = form['currency_id'] and type(form['currency_id']) in (list, tuple) and form['currency_id'][0] or form['currency_id']
  147. tot_check = False
  148. tot_bin = 0.0
  149. tot_deb = 0.0
  150. tot_crd = 0.0
  151. tot_eje = 0.0
  152. if form.has_key('account_list') and form['account_list']:
  153. account_ids = form['account_list']
  154. del form['account_list']
  155. res = {}
  156. result_acc = []
  157. accounts_levels = {}
  158. account_obj = self.pool.get('account.account')
  159. period_obj = self.pool.get('account.period')
  160. fiscalyear_obj = self.pool.get('account.fiscalyear')
  161. if form.get('fiscalyear'):
  162. if type(form.get('fiscalyear')) in (list,tuple):
  163. fiscalyear = form['fiscalyear'] and form['fiscalyear'][0]
  164. elif type(form.get('fiscalyear')) in (int,):
  165. fiscalyear = form['fiscalyear']
  166. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, fiscalyear)
  167. #
  168. # Get the accounts
  169. #
  170. def _get_children_and_consol(cr, uid, ids, level, context={}):
  171. aa_obj = self.pool.get('account.account')
  172. ids2=[]
  173. for aa_brw in aa_obj.browse(cr, uid, ids, context):
  174. if aa_brw.child_id and aa_brw.level < level and aa_brw.type !='consolidation':
  175. ids2.append([aa_brw.id,True, False])
  176. ids2 += _get_children_and_consol(cr, uid, [x.id for x in aa_brw.child_id], level, context)
  177. ids2.append([aa_brw.id,False,True])
  178. else:
  179. ids2.append([aa_brw.id,True,True])
  180. return ids2
  181. child_ids = _get_children_and_consol(self.cr, self.uid, account_ids, form['display_account_level'] and form['display_account_level'] or 100,self.context)
  182. if child_ids:
  183. account_ids = child_ids
  184. account_obj = self.pool.get('account.account')
  185. period_obj = self.pool.get('account.period')
  186. fiscalyear_obj = self.pool.get('account.fiscalyear')
  187. #############################################################################
  188. # Calculate the period Debit/Credit #
  189. # (from the selected period or all the non special periods in the fy) #
  190. #############################################################################
  191. ctx = self.context.copy()
  192. ctx['filter'] = form.get('filter','all')
  193. ctx['fiscalyear'] = fiscalyear.id
  194. #~ ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('special','=',False)])
  195. if ctx['filter'] not in ['bydate','none']:
  196. special = self.special_period(form['periods'])
  197. else:
  198. special = False
  199. if form['filter'] in ['byperiod', 'all']:
  200. if special:
  201. ctx['periods'] = period_obj.search(self.cr, self.uid, [('id','in',form['periods'] or ctx.get('periods',False))])
  202. else:
  203. ctx['periods'] = period_obj.search(self.cr, self.uid, [('id','in',form['periods'] or ctx.get('periods',False)),('special','=',False)])
  204. if form['filter'] in ['bydate','all','none']:
  205. ctx['date_from'] = form['date_from']
  206. ctx['date_to'] = form['date_to']
  207. accounts=[]
  208. val = account_obj.browse(self.cr, self.uid, [aa_id[0] for aa_id in account_ids], ctx)
  209. c = 0
  210. for aa_id in account_ids:
  211. new_acc = {
  212. 'id' :val[c].id,
  213. 'type' :val[c].type,
  214. 'code' :val[c].code,
  215. 'name' :val[c].name,
  216. 'debit' :val[c].debit,
  217. 'credit' :val[c].credit,
  218. 'parent_id' :val[c].parent_id and val[c].parent_id.id,
  219. 'level' :val[c].level,
  220. 'label' :aa_id[1],
  221. 'total' :aa_id[2],
  222. }
  223. c += 1
  224. accounts.append(new_acc)
  225. def missing_period():
  226. ctx['fiscalyear'] = fiscalyear_obj.search(self.cr, self.uid, [('date_stop','<',fiscalyear.date_start)],order='date_stop') and \
  227. fiscalyear_obj.search(self.cr, self.uid, [('date_stop','<',fiscalyear.date_start)],order='date_stop')[-1] or []
  228. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',ctx['fiscalyear']),('date_stop','<',fiscalyear.date_start)])
  229. #############################################################################
  230. # Calculate the period initial Balance #
  231. # (fy balance minus the balance from the start of the selected period #
  232. # to the end of the year) #
  233. #############################################################################
  234. ctx = self.context.copy()
  235. ctx['filter'] = form.get('filter','all')
  236. ctx['fiscalyear'] = fiscalyear.id
  237. if form['filter'] in ['byperiod', 'all']:
  238. ctx['periods'] = form['periods']
  239. date_start = min([period.date_start for period in period_obj.browse(self.cr, self.uid, ctx['periods'])])
  240. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_stop','<=',date_start)])
  241. if not ctx['periods']:
  242. missing_period()
  243. elif form['filter'] in ['bydate']:
  244. ctx['date_from'] = fiscalyear.date_start
  245. ctx['date_to'] = form['date_from']
  246. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_stop','<=',ctx['date_to'])])
  247. elif form['filter'] == 'none':
  248. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('special','=',True)])
  249. date_start = min([period.date_start for period in period_obj.browse(self.cr, self.uid, ctx['periods'])])
  250. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_start','<=',date_start),('special','=',True)])
  251. period_balanceinit = {}
  252. for acc in account_obj.browse(self.cr, self.uid, [x[0] for x in account_ids], ctx):
  253. if special:
  254. period_balanceinit[acc['id']] = 0.0
  255. else:
  256. period_balanceinit[acc['id']] = acc.balance
  257. #
  258. # Generate the report lines (checking each account)
  259. #
  260. tot = {}
  261. for account in accounts:
  262. account_id = account['id']
  263. accounts_levels[account_id] = account['level']
  264. #
  265. # Check if we need to include this level
  266. #
  267. if not form['display_account_level'] or account['level'] <= form['display_account_level']:
  268. #
  269. # Copy the account values
  270. #
  271. res = {
  272. 'id' : account_id,
  273. 'type' : account['type'],
  274. 'code': account['code'],
  275. 'name': (account['total'] and not account['label']) and 'TOTAL %s'%(account['name'].upper()) or account['name'],
  276. 'level': account['level'],
  277. 'balanceinit': self.exchange(period_balanceinit[account_id]),
  278. 'debit': self.exchange(account['debit']),
  279. 'credit': self.exchange(account['credit']),
  280. 'balance': self.exchange(period_balanceinit[account_id]+account['debit']-account['credit']),
  281. 'parent_id': account['parent_id'],
  282. 'bal_type': '',
  283. 'label': account['label'],
  284. 'total': account['total'],
  285. }
  286. #
  287. # Round the values to zero if needed (-0.000001 ~= 0)
  288. #
  289. if abs(res['balance']) < 0.5 * 10**-4:
  290. res['balance'] = 0.0
  291. #
  292. # Check whether we must include this line in the report or not
  293. #
  294. if form['display_account'] == 'con_movimiento' and account['parent_id']:
  295. # Include accounts with movements
  296. if abs(res['debit']) >= 0.5 * 10**-int(2) or abs(res['credit']) >= 0.5 * 10**-int(2):
  297. result_acc.append(res)
  298. elif form['display_account'] == 'con_balance' and account['parent_id']:
  299. # Include accounts with balance
  300. if abs(res['balance']) >= 0.5 * 10**-4:
  301. result_acc.append(res)
  302. else:
  303. # Include all accounts
  304. result_acc.append(res)
  305. if form['tot_check'] and res['type'] == 'view' and res['level'] == 1 and (res['id'] not in tot):
  306. tot_check = True
  307. tot[res['id']] = True
  308. tot_bin += res['balanceinit']
  309. tot_deb += res['debit']
  310. tot_crd += res['credit']
  311. tot_eje += res['balance']
  312. #if (form['tot_check'] and res['type']=='view' and res['level']==1 and (res['id'] not in tot)):
  313. if tot_check:
  314. str_label = form['lab_str']
  315. res2 = {
  316. 'type' : 'view',
  317. 'name': 'TOTAL %s'%(str_label),
  318. 'balanceinit': tot_bin,
  319. 'debit': tot_deb,
  320. 'credit': tot_crd,
  321. 'balance': tot_eje,
  322. 'label': False,
  323. 'total': True,
  324. }
  325. result_acc.append(res2)
  326. return result_acc
  327. report_sxw.report_sxw('report.wizard.report.reporte',
  328. 'wizard.report',
  329. 'account_financial_report/report/balance_full_4_cols.rml',
  330. parser=account_balance,
  331. header=False)
  332. report_sxw.report_sxw('report.account.account.balance.gene.2',
  333. 'wizard.report.account.balance.gene.2',
  334. 'account_financial_report/report/balance_full_2_cols.rml',
  335. parser=account_balance,
  336. header=False)
  337. report_sxw.report_sxw('report.account.account.balance.gene',
  338. 'wizard.report.account.balance.gene',
  339. 'account_financial_report/report/balance_full.rml',
  340. parser=account_balance,
  341. header=False)