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.

360 lines
16 KiB

13 years ago
13 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. class account_balance(report_sxw.rml_parse):
  36. def __init__(self, cr, uid, name, context):
  37. super(account_balance, self).__init__(cr, uid, name, context)
  38. self.sum_debit = 0.00
  39. self.sum_credit = 0.00
  40. self.sum_balance = 0.00
  41. self.sum_debit_fy = 0.00
  42. self.sum_credit_fy = 0.00
  43. self.sum_balance_fy = 0.00
  44. self.date_lst = []
  45. self.date_lst_string = ''
  46. self.localcontext.update({
  47. 'time': time,
  48. 'lines': self.lines,
  49. 'get_fiscalyear_text': self.get_fiscalyear_text,
  50. 'get_periods_and_date_text': self.get_periods_and_date_text,
  51. 'get_informe_text': self.get_informe_text,
  52. 'get_month':self.get_month,
  53. 'exchange_name':self.exchange_name,
  54. })
  55. self.context = context
  56. def get_fiscalyear_text(self, form):
  57. """
  58. Returns the fiscal year text used on the report.
  59. """
  60. fiscalyear_obj = self.pool.get('account.fiscalyear')
  61. fiscalyear = None
  62. if form.get('fiscalyear'):
  63. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, form['fiscalyear'])
  64. return fiscalyear.name or fiscalyear.code
  65. else:
  66. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, fiscalyear_obj.find(self.cr, self.uid))
  67. return "%s*" % (fiscalyear.name or fiscalyear.code)
  68. def get_informe_text(self, form):
  69. """
  70. Returns the header text used on the report.
  71. """
  72. inf_type = {
  73. 'bgen' : ' Balance General',
  74. 'bcom' : ' Balance de Comprobacion',
  75. 'edogp': 'Estado de Ganancias y Perdidas',
  76. 'bdl' : 'Diario Legal'
  77. }
  78. return inf_type[form['inf_type']]
  79. def get_month(self, form):
  80. '''
  81. return day, year and month
  82. '''
  83. if form['filter'] in ['bydate', 'all']:
  84. months=["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"]
  85. mes = months[time.strptime(form['date_to'],"%Y-%m-%d")[1]-1]
  86. ano = time.strptime(form['date_to'],"%Y-%m-%d")[0]
  87. dia = time.strptime(form['date_to'],"%Y-%m-%d")[2]
  88. return 'Período del '+self.formatLang(form['date_from'], date=True)+' al '+self.formatLang(form['date_to'], date=True)
  89. elif form['filter'] in ['byperiod', 'all']:
  90. aux=[]
  91. period_obj = self.pool.get('account.period')
  92. for period in period_obj.browse(self.cr, self.uid, form['periods']):
  93. aux.append(period.date_start)
  94. aux.append(period.date_stop)
  95. sorted(aux)
  96. return 'Período del '+self.formatLang(aux[0], date=True)+' al '+self.formatLang(aux[-1], date=True)
  97. def get_periods_and_date_text(self, form):
  98. """
  99. Returns the text with the periods/dates used on the report.
  100. """
  101. period_obj = self.pool.get('account.period')
  102. periods_str = None
  103. fiscalyear_id = form['fiscalyear'] or fiscalyear_obj.find(self.cr, self.uid)
  104. period_ids = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear_id),('special','=',False)])
  105. if form['filter'] in ['byperiod', 'all']:
  106. period_ids = form['periods']
  107. periods_str = ', '.join([period.name or period.code for period in period_obj.browse(self.cr, self.uid, period_ids)])
  108. dates_str = None
  109. if form['filter'] in ['bydate', 'all']:
  110. dates_str = self.formatLang(form['date_from'], date=True) + ' - ' + self.formatLang(form['date_to'], date=True) + ' '
  111. return {'periods':periods_str, 'date':dates_str}
  112. def exchange_name(self, form):
  113. 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'])
  114. if not form['currency_id']:
  115. self.to_currency_id = self.from_currency_id
  116. else:
  117. self.to_currency_id = form['currency_id'] and type(form['currency_id']) in (list, tuple) and form['currency_id'][0] or form['currency_id']
  118. return self.pool.get('res.currency').browse(self.cr, self.uid, self.to_currency_id).name
  119. def exchange(self, from_amount):
  120. if self.from_currency_id == self.to_currency_id:
  121. return from_amount
  122. curr_obj = self.pool.get('res.currency')
  123. return curr_obj.compute(self.cr, self.uid, self.from_currency_id, self.to_currency_id, from_amount)
  124. def get_company_currency(self, company_id):
  125. rc_obj = self.pool.get('res.company')
  126. return rc_obj.browse(self.cr, self.uid, company_id).currency_id.id
  127. def lines(self, form, level=0):
  128. """
  129. Returns all the data needed for the report lines
  130. (account info plus debit/credit/balance in the selected period
  131. and the full year)
  132. """
  133. 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'])
  134. if not form['currency_id']:
  135. self.to_currency_id = self.from_currency_id
  136. else:
  137. self.to_currency_id = form['currency_id'] and type(form['currency_id']) in (list, tuple) and form['currency_id'][0] or form['currency_id']
  138. tot_check = False
  139. tot_bin = 0.0
  140. tot_deb = 0.0
  141. tot_crd = 0.0
  142. tot_eje = 0.0
  143. if form.has_key('account_list') and form['account_list']:
  144. account_ids = form['account_list']
  145. del form['account_list']
  146. res = {}
  147. result_acc = []
  148. accounts_levels = {}
  149. account_obj = self.pool.get('account.account')
  150. period_obj = self.pool.get('account.period')
  151. fiscalyear_obj = self.pool.get('account.fiscalyear')
  152. if form.get('fiscalyear'):
  153. if type(form.get('fiscalyear')) in (list,tuple):
  154. fiscalyear = form['fiscalyear'] and form['fiscalyear'][0]
  155. elif type(form.get('fiscalyear')) in (int,):
  156. fiscalyear = form['fiscalyear']
  157. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, fiscalyear)
  158. #
  159. # Get the accounts
  160. #
  161. def _get_children_and_consol(cr, uid, ids, level, context={}):
  162. aa_obj = self.pool.get('account.account')
  163. ids2=[]
  164. temp=[]
  165. read_data= aa_obj.read(cr, uid, ids,['id','child_id','level','type'], context)
  166. for data in read_data:
  167. if data['child_id'] and data['level'] < level and data['type']!='consolidation':
  168. ids2.append([data['id'],True, False])
  169. temp=[]
  170. for x in data['child_id']:
  171. temp.append(x)
  172. ids2 += _get_children_and_consol(cr, uid, temp, level, context)
  173. ids2.append([data['id'],False,True])
  174. else:
  175. ids2.append([data['id'],True,True])
  176. return ids2
  177. 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)
  178. if child_ids:
  179. account_ids = child_ids
  180. account_obj = self.pool.get('account.account')
  181. period_obj = self.pool.get('account.period')
  182. fiscalyear_obj = self.pool.get('account.fiscalyear')
  183. #############################################################################
  184. # Calculate the period Debit/Credit #
  185. # (from the selected period or all the non special periods in the fy) #
  186. #############################################################################
  187. ctx = self.context.copy()
  188. ctx['filter'] = form.get('filter','all')
  189. ctx['fiscalyear'] = fiscalyear.id
  190. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('special','=',False)])
  191. if form['filter'] in ['byperiod', 'all']:
  192. ctx['periods'] = period_obj.search(self.cr, self.uid, [('id','in',form['periods'] or ctx['periods']),('special','=',False)])
  193. if form['filter'] in ['bydate', 'all']:
  194. ctx['date_from'] = form['date_from']
  195. ctx['date_to'] = form['date_to']
  196. accounts=[]
  197. val = account_obj.browse(self.cr, self.uid, [aa_id[0] for aa_id in account_ids], ctx)
  198. c = 0
  199. for aa_id in account_ids:
  200. new_acc = {
  201. 'id' :val[c].id,
  202. 'type' :val[c].type,
  203. 'code' :val[c].code,
  204. 'name' :val[c].name,
  205. 'debit' :val[c].debit,
  206. 'credit' :val[c].credit,
  207. 'parent_id' :val[c].parent_id and val[c].parent_id.id,
  208. 'level' :val[c].level,
  209. 'label' :aa_id[1],
  210. 'total' :aa_id[2],
  211. }
  212. c += 1
  213. accounts.append(new_acc)
  214. def missing_period():
  215. ctx['fiscalyear'] = fiscalyear_obj.search(self.cr, self.uid, [('date_stop','<',fiscalyear.date_start)],order='date_stop') and \
  216. fiscalyear_obj.search(self.cr, self.uid, [('date_stop','<',fiscalyear.date_start)],order='date_stop')[-1] or []
  217. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',ctx['fiscalyear']),('date_stop','<',fiscalyear.date_start)])
  218. #############################################################################
  219. # Calculate the period initial Balance #
  220. # (fy balance minus the balance from the start of the selected period #
  221. # to the end of the year) #
  222. #############################################################################
  223. ctx = self.context.copy()
  224. ctx['filter'] = form.get('filter','all')
  225. ctx['fiscalyear'] = fiscalyear.id
  226. if form['filter'] in ['byperiod', 'all']:
  227. ctx['periods'] = form['periods']
  228. date_start = min([period.date_start for period in period_obj.browse(self.cr, self.uid, ctx['periods'])])
  229. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_stop','<=',date_start)])
  230. if not ctx['periods']:
  231. missing_period()
  232. elif form['filter'] in ['bydate']:
  233. ctx['date_from'] = fiscalyear.date_start
  234. ctx['date_to'] = form['date_from']
  235. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_stop','<=',ctx['date_to'])])
  236. elif form['filter'] == 'none':
  237. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('special','=',True)])
  238. date_start = min([period.date_start for period in period_obj.browse(self.cr, self.uid, ctx['periods'])])
  239. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_start','<=',date_start),('special','=',True)])
  240. period_balanceinit = {}
  241. for acc in account_obj.browse(self.cr, self.uid, [x[0] for x in account_ids], ctx):
  242. period_balanceinit[acc['id']] = acc.balance
  243. #
  244. # Generate the report lines (checking each account)
  245. #
  246. tot = {}
  247. for account in accounts:
  248. account_id = account['id']
  249. accounts_levels[account_id] = account['level']
  250. #
  251. # Check if we need to include this level
  252. #
  253. if not form['display_account_level'] or account['level'] <= form['display_account_level']:
  254. #
  255. # Copy the account values
  256. #
  257. res = {
  258. 'id' : account_id,
  259. 'type' : account['type'],
  260. 'code': account['code'],
  261. 'name': (account['total'] and not account['label']) and 'TOTAL %s'%(account['name'].upper()) or account['name'],
  262. 'level': account['level'],
  263. 'balanceinit': self.exchange(period_balanceinit[account_id]),
  264. 'debit': self.exchange(account['debit']),
  265. 'credit': self.exchange(account['credit']),
  266. 'balance': self.exchange(period_balanceinit[account_id]+account['debit']-account['credit']),
  267. 'parent_id': account['parent_id'],
  268. 'bal_type': '',
  269. 'label': account['label'],
  270. 'total': account['total'],
  271. }
  272. #
  273. # Round the values to zero if needed (-0.000001 ~= 0)
  274. #
  275. if abs(res['balance']) < 0.5 * 10**-4:
  276. res['balance'] = 0.0
  277. #
  278. # Check whether we must include this line in the report or not
  279. #
  280. if form['display_account'] == 'con_movimiento' and account['parent_id']:
  281. # Include accounts with movements
  282. if abs(res['balance']) >= 0.5 * 10**-int(2):
  283. result_acc.append(res)
  284. elif form['display_account'] == 'con_balance' and account['parent_id']:
  285. # Include accounts with balance
  286. if abs(res['balance']) >= 0.5 * 10**-4:
  287. result_acc.append(res)
  288. else:
  289. # Include all accounts
  290. result_acc.append(res)
  291. if form['tot_check'] and res['type'] == 'view' and res['level'] == 1 and (res['id'] not in tot):
  292. tot_check = True
  293. tot[res['id']] = True
  294. tot_bin += res['balanceinit']
  295. tot_deb += res['debit']
  296. tot_crd += res['credit']
  297. tot_eje += res['balance']
  298. if tot_check:
  299. str_label = form['lab_str']
  300. res2 = {
  301. 'type' : 'view',
  302. 'name': 'TOTAL %s'%(str_label),
  303. 'balanceinit': tot_bin,
  304. 'debit': tot_deb,
  305. 'credit': tot_crd,
  306. 'balance': tot_eje,
  307. 'label': False,
  308. 'total': True,
  309. }
  310. result_acc.append(res2)
  311. return result_acc
  312. report_sxw.report_sxw('report.account.account.balance.gene.2',
  313. 'wizard.report.account.balance.gene.2',
  314. 'account_financial_report/report/balance_full_2_cols.rml',
  315. parser=account_balance,
  316. header=False)