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.

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