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.

383 lines
17 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. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. ##############################################################################
  20. import xml
  21. import copy
  22. from operator import itemgetter
  23. import time
  24. import datetime
  25. from report import report_sxw
  26. from tools import config
  27. class account_analisis_cuentas(report_sxw.rml_parse):
  28. def __init__(self, cr, uid, name, context):
  29. super(account_analisis_cuentas, self).__init__(cr, uid, name, context)
  30. self.sum_debit = 0.00
  31. self.sum_credit = 0.00
  32. self.sum_balance = 0.00
  33. self.sum_debit_fy = 0.00
  34. self.sum_credit_fy = 0.00
  35. self.sum_balance_fy = 0.00
  36. self.date_lst = []
  37. self.date_lst_string = ''
  38. self.localcontext.update({
  39. 'time': time,
  40. 'lines': self.lines,
  41. 'get_fiscalyear_text': self.get_fiscalyear_text,
  42. 'get_periods_and_date_text': self.get_periods_and_date_text,
  43. 'get_inf_text': self.get_informe_text,
  44. 'set_fecha': self.set_fecha,
  45. })
  46. self.context = context
  47. def set_fecha(self, fecha):
  48. f = fecha.split('-')
  49. date = datetime.date(int(f[0]),int(f[1]),int(f[2]))
  50. return str(date.strftime("%d/%m/%Y"))
  51. def get_fiscalyear_text(self, form):
  52. """
  53. Returns the fiscal year text used on the report.
  54. """
  55. fiscalyear_obj = self.pool.get('account.fiscalyear')
  56. fiscalyear = None
  57. if form.get('fiscalyear'):
  58. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, form['fiscalyear'])
  59. return fiscalyear.name or fiscalyear.code
  60. else:
  61. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, fiscalyear_obj.find(self.cr, self.uid))
  62. return "%s*" % (fiscalyear.name or fiscalyear.code)
  63. def get_informe_text(self, form):
  64. """
  65. Returns the header text used on the report.
  66. """
  67. inf_type = {
  68. 'bgen' : ' Balance General',
  69. 'bcom' : ' Balance de Comprobacion',
  70. 'edogp': 'Estado de Ganancias y Perdidas',
  71. 'bac': ' Analisis de Cuentas',
  72. 'bml': ' Mayor Analitico'
  73. }
  74. return inf_type[form['inf_type']]
  75. def get_periods_and_date_text(self, form):
  76. """
  77. Returns the text with the periods/dates used on the report.
  78. """
  79. period_obj = self.pool.get('account.period')
  80. periods_str = None
  81. fiscalyear_id = form['fiscalyear'] or fiscalyear_obj.find(self.cr, self.uid)
  82. period_ids = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear_id), ('special','=',False)])
  83. if form['filter'] in ['byperiod', 'all']:
  84. period_ids = form['periods']
  85. periods_str = ', '.join([period.name or period.code for period in period_obj.browse(self.cr, self.uid, period_ids)])
  86. dates_str = None
  87. if form['filter'] in ['bydate', 'all']:
  88. dates_str = self.formatLang(form['date_from'], date=True) + ' - ' + self.formatLang(form['date_to'], date=True) + ' '
  89. return {'periods':periods_str, 'date':dates_str}
  90. def es_especial(self, periods):
  91. period_obj = self.pool.get('account.period')
  92. period_brws = period_obj.browse(self.cr, self.uid, periods)
  93. tod=0
  94. for p_b in period_brws:
  95. if p_b.special:
  96. tod = tod + 1
  97. if tod == len(periods):
  98. return True
  99. else:
  100. return False
  101. def calcular_debito_credito(self, account, form):
  102. res = {}
  103. if form['filter'] in ('bydate','none'):
  104. #Para filtrar por 'fechas' o 'sin filtro', este porque se envia el año fiscal por fecha.
  105. where = """ and aml.date between '%s' and '%s'"""%(form['date_from'],form['date_to'])
  106. elif form['filter'] == 'byperiod':
  107. #Para filtrar por periodos
  108. periodos = str(form['periods']).replace("[","(").replace("]",")")
  109. where = """ and aml.period_id in %s"""%(periodos)
  110. else:
  111. #Para filtrar por periodos y fechas
  112. periodos = str(form['periods']).replace("[","(").replace("]",")")
  113. where = """ and aml.period_id in %s and aml.date between '%s' and '%s'"""%(periodos,form['date_from'],form['date_to'])
  114. if form.get('state'):
  115. estado = " and am.state = '%s'"%form['state']
  116. where = where + estado
  117. analytic_list = str(form['analytic_list']).replace("[","(").replace("]",")")
  118. where = where + " and aaa.id in " + analytic_list
  119. account_list = str(account).replace("[","(").replace("]",")")
  120. where = where + " and aa.id in " + account_list
  121. sql_saldos = """select aml.account_id as id,
  122. COALESCE(SUM(aml.debit), 0) as debit,
  123. COALESCE(SUM(aml.credit), 0) as credit
  124. from account_move_line aml
  125. inner join account_analytic_account aaa on aml.analytic_account_id = aaa.id
  126. inner join account_journal aj on aj.id = aml.journal_id
  127. inner join account_account aa on aa.id = aml.account_id
  128. inner join account_period ap on ap.id = aml.period_id
  129. inner join account_move am on am.id = aml.move_id
  130. where aml.state <> 'draft'""" + where + \
  131. """ group by aml.account_id"""
  132. self.cr.execute(sql_saldos)
  133. resultat = self.cr.dictfetchall()
  134. for det in resultat:
  135. res[det['id']] = {
  136. 'debit': det['debit'],
  137. 'credit': det['credit'],
  138. }
  139. return res
  140. def _get_analisis_cuenta_analitica(self, account, form):
  141. res = []
  142. if form['filter'] in ('bydate','none'):
  143. #Para filtrar por 'fechas' o 'sin filtro', este porque se envia el año fiscal por fecha.
  144. where = """ and aml.date between '%s' and '%s'"""%(form['date_from'],form['date_to'])
  145. elif form['filter'] == 'byperiod':
  146. #Para filtrar por periodos
  147. periodos = str(form['periods']).replace("[","(").replace("]",")")
  148. where = """ and aml.period_id in %s"""%(periodos)
  149. else:
  150. #Para filtrar por periodos y fechas
  151. periodos = str(form['periods']).replace("[","(").replace("]",")")
  152. where = """ and aml.period_id in %s and aml.date between '%s' and '%s'"""%(periodos,form['date_from'],form['date_to'])
  153. if form.get('state'):
  154. estado = " and am.state = '%s'"%form['state']
  155. where = where + estado
  156. where = where + " and aa.id = '%s'"%(account['id'])
  157. analytic_list = str(form['analytic_list']).replace("[","(").replace("]",")")
  158. where = where + " and aaa.id in " + analytic_list
  159. sql_detalle = """select aml.id as id, aj.name as diario,
  160. aa.name as descripcion,
  161. (select name from res_partner where aml.partner_id = id) as partner,
  162. aa.code as cuenta, aml.name || ' -- Ref: ' || aml.ref as ref,
  163. case when aml.debit is null then 0.00 else aml.debit end as debit,
  164. case when aml.credit is null then 0.00 else aml.credit end as credit,
  165. aml.date as fecha, ap.name as periodo,
  166. aaa.code as analitica
  167. from account_move_line aml
  168. inner join account_analytic_account aaa on aml.analytic_account_id = aaa.id
  169. inner join account_journal aj on aj.id = aml.journal_id
  170. inner join account_account aa on aa.id = aml.account_id
  171. inner join account_period ap on ap.id = aml.period_id
  172. inner join account_move am on am.id = aml.move_id
  173. where aml.state <> 'draft'""" + where + \
  174. """ order by analitica, fecha"""
  175. self.cr.execute(sql_detalle)
  176. resultat = self.cr.dictfetchall()
  177. balance = account['balanceinit']
  178. for det in resultat:
  179. balance += det['debit'] - det['credit']
  180. res.append({
  181. 'id': det['id'],
  182. 'date': det['fecha'],
  183. 'journal':det['diario'],
  184. 'ref': det['ref'],
  185. 'debit': det['debit'],
  186. 'credit': det['credit'],
  187. 'analytic': det['analitica'],
  188. 'period': det['periodo'],
  189. 'balance': balance,
  190. })
  191. return res
  192. def lines(self, form, ids={}, done=None, level=0):
  193. """
  194. Returns all the data needed for the report lines
  195. (account info plus debit/credit/balance in the selected period
  196. and the full year)
  197. """
  198. tot_bin = 0.0
  199. tot_deb = 0.0
  200. tot_crd = 0.0
  201. tot_eje = 0.0
  202. if not ids:
  203. ids = self.ids
  204. if not ids:
  205. return []
  206. if not done:
  207. done = {}
  208. if form.has_key('account_list') and form['account_list']:
  209. account_ids = form['account_list']
  210. del form['account_list']
  211. res = {}
  212. result_acc = []
  213. accounts_levels = {}
  214. account_obj = self.pool.get('account.account')
  215. period_obj = self.pool.get('account.period')
  216. fiscalyear_obj = self.pool.get('account.fiscalyear')
  217. # Get the fiscal year
  218. fiscalyear = None
  219. if form.get('fiscalyear'):
  220. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, form['fiscalyear'])
  221. else:
  222. fiscalyear = fiscalyear_obj.browse(self.cr, self.uid, fiscalyear_obj.find(self.cr, self.uid))
  223. #
  224. # Get the accounts
  225. #
  226. def _get_children_and_consol(cr, uid, ids, level, context={}):
  227. aa_obj = self.pool.get('account.account')
  228. ids2=[]
  229. temp=[]
  230. read_data= aa_obj.read(cr, uid, ids,['id','child_id','level','type'], context)
  231. for data in read_data:
  232. if data['child_id'] and data['level'] < level and data['type']!='consolidation':
  233. #ids2.append([data['id'],'Label', 'Total'])
  234. ids2.append([data['id'],True, False])
  235. temp=[]
  236. for x in data['child_id']:
  237. temp.append(x)
  238. ids2 += _get_children_and_consol(cr, uid, temp, level, context)
  239. ids2.append([data['id'],False,True])
  240. else:
  241. ids2.append([data['id'],True,True])
  242. return ids2
  243. 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)
  244. if child_ids:
  245. account_ids = child_ids
  246. account_obj = self.pool.get('account.account')
  247. period_obj = self.pool.get('account.period')
  248. fiscalyear_obj = self.pool.get('account.fiscalyear')
  249. #############################################################################
  250. # Calculate the period Debit/Credit #
  251. # (from the selected period or all the non special periods in the fy) #
  252. #############################################################################
  253. ctx = self.context.copy()
  254. ctx['filter'] = form.get('filter','all')
  255. ctx['fiscalyear'] = fiscalyear.id
  256. if ctx['filter'] not in ['bydate','none']:
  257. especial = self.es_especial(form['periods'])
  258. else:
  259. especial = False
  260. if form['filter'] in ['byperiod', 'all']:
  261. if especial:
  262. ctx['periods'] = period_obj.search(self.cr, self.uid, [('id','in',form['periods'] or ctx['periods'])])
  263. else:
  264. ctx['periods'] = period_obj.search(self.cr, self.uid, [('id','in',form['periods'] or ctx['periods']), ('special','=',False)])
  265. if form['filter'] in ['bydate','all','none']:
  266. ctx['date_from'] = form['date_from']
  267. ctx['date_to'] = form['date_to']
  268. accounts=[]
  269. val = account_obj.browse(self.cr, self.uid, [aa_id[0] for aa_id in account_ids], ctx)
  270. """DESDE AQUI VOY A COMENZAR A CAMBIAR"""
  271. #Extraer cuentas que no son tipo vista
  272. cuenta_ids = {}
  273. for cue in val:
  274. if cue.type != 'view':
  275. cuenta_ids[cue.id] = cue
  276. account_ids = self.calcular_debito_credito(cuenta_ids.keys(), form)
  277. if account_ids != {}:
  278. for acc in account_ids.keys():
  279. new_acc = {
  280. 'id' :acc,
  281. 'type' :cuenta_ids[acc].type,
  282. 'code' :str(cuenta_ids[acc].code),
  283. 'name' :cuenta_ids[acc].name.upper(),
  284. 'parent_id' :cuenta_ids[acc].parent_id and cuenta_ids[acc].parent_id.id,
  285. 'level' :cuenta_ids[acc].level,
  286. 'label' :True,
  287. 'total' :True,
  288. 'debit' :account_ids[acc]['debit'],
  289. 'credit' :account_ids[acc]['credit'],
  290. }
  291. accounts.append(new_acc)
  292. def missing_period():
  293. ctx['fiscalyear'] = fiscalyear_obj.search(self.cr, self.uid, [('date_stop','<',fiscalyear.date_start)],order='date_stop') and \
  294. fiscalyear_obj.search(self.cr, self.uid, [('date_stop','<',fiscalyear.date_start)],order='date_stop')[-1] or []
  295. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',ctx['fiscalyear']),('date_stop','<',fiscalyear.date_start)])
  296. #############################################################################
  297. # Calculate the period initial Balance #
  298. # (fy balance minus the balance from the start of the selected period #
  299. # to the end of the year) #
  300. #############################################################################
  301. ctx = self.context.copy()
  302. if form.get('state'):
  303. ctx['state'] = form['state']
  304. if form.get('analytic_list'):
  305. ctx['analytic_list'] = form['analytic_list']
  306. ctx['filter'] = form.get('filter','all')
  307. ctx['fiscalyear'] = fiscalyear.id
  308. if form['filter'] in ['byperiod']:
  309. ctx['periods'] = form['periods']
  310. date_start = min([period.date_start for period in period_obj.browse(self.cr, self.uid, ctx['periods'])])
  311. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_stop','<=',date_start)])
  312. if not ctx['periods']:
  313. missing_period()
  314. elif form['filter'] in ['bydate', 'all']:
  315. ctx['date_from'] = fiscalyear.date_start
  316. ctx['date_to'] = form['date_from']
  317. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_stop','<=',ctx['date_to'])])
  318. elif form['filter'] == 'none':
  319. ctx['date_from'] = form['date_from']
  320. ctx['date_to'] = form['date_to']
  321. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('special','=',True)])
  322. date_start = min([period.date_start for period in period_obj.browse(self.cr, self.uid, ctx['periods'])])
  323. ctx['periods'] = period_obj.search(self.cr, self.uid, [('fiscalyear_id','=',fiscalyear.id),('date_start','<=',date_start),('special','=',True)])
  324. for acc in accounts:
  325. if especial:
  326. acc['balanceinit'] = 0.0
  327. acc['balance'] = acc['debit'] - acc['credit']
  328. else:
  329. account_ids_ant = self.calcular_debito_credito([acc['id']], ctx)
  330. if account_ids_ant != {}:
  331. acc['balanceinit'] = account_ids_ant[acc['id']]['debit'] - account_ids_ant[acc['id']]['credit']
  332. acc['balance'] = acc['balanceinit'] + acc['debit'] - acc['credit']
  333. else:
  334. acc['balanceinit'] = 0.0
  335. acc['balance'] = acc['debit'] - acc['credit']
  336. for acc_anl in accounts:
  337. acc_anl['analisis'] = self._get_analisis_cuenta_analitica(acc_anl,form)
  338. accounts.sort(key=lambda x: x['code'])
  339. return accounts
  340. report_sxw.report_sxw('report.wizard.reporte.comprobacion.analisis.cuentas', 'wizard.reporte.comprobacion', 'l10n_ve_account_financial_report/report/analisis_cuentas.rml', parser=account_analisis_cuentas, header=False)