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.

297 lines
14 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. from osv import osv, fields
  29. import pooler
  30. import time
  31. from tools.translate import _
  32. class wizard_report(osv.osv_memory):
  33. _name = "wizard.report"
  34. _columns = {
  35. 'afr_id': fields.many2one('afr', 'Custom Report', help='If you have already set a Custom Report, Select it Here.'),
  36. 'company_id': fields.many2one('res.company', 'Company', required=True),
  37. 'currency_id': fields.many2one('res.currency', 'Currency', help="Currency at which this report will be expressed. If not selected will be used the one set in the company"),
  38. 'inf_type': fields.selection([('BS', 'Balance Sheet'), ('IS', 'Income Statement')], 'Type', required=True),
  39. 'columns': fields.selection([('one', 'End. Balance'), ('two', 'Debit | Credit'), ('four', 'Initial | Debit | Credit | YTD'), ('five', 'Initial | Debit | Credit | Period | YTD'), ('qtr', "4 QTR's | YTD"), ('thirteen', '12 Months | YTD')], 'Columns', required=True),
  40. 'display_account': fields.selection([('all', 'All Accounts'), ('bal', 'With Balance'), ('mov', 'With movements'), ('bal_mov', 'With Balance / Movements')], 'Display accounts'),
  41. 'display_account_level': fields.integer('Up to level', help='Display accounts up to this level (0 to show all)'),
  42. 'account_list': fields.many2many('account.account', 'rel_wizard_account', 'account_list', 'account_id', 'Root accounts', required=True),
  43. 'fiscalyear': fields.many2one('account.fiscalyear', 'Fiscal year', help='Fiscal Year for this report', required=True),
  44. 'periods': fields.many2many('account.period', 'rel_wizard_period', 'wizard_id', 'period_id', 'Periods', help='All periods in the fiscal year if empty'),
  45. 'analytic_ledger': fields.boolean('Analytic Ledger', help="Allows to Generate an Analytic Ledger for accounts with moves. Available when Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"),
  46. 'journal_ledger': fields.boolean('Journal Ledger', help="Allows to Generate an Journal Ledger for accounts with moves. Available when Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"),
  47. 'partner_balance': fields.boolean('Partner Balance', help="Allows to "
  48. "Generate a Partner Balance for accounts with moves. Available when "
  49. "Balance Sheet and 'Initial | Debit | Credit | YTD' are selected"),
  50. 'tot_check': fields.boolean('Summarize?', help='Checking will add a new line at the end of the Report which will Summarize Columns in Report'),
  51. 'lab_str': fields.char('Description', help='Description for the Summary', size=128),
  52. 'target_move': fields.selection([('posted', 'All Posted Entries'),
  53. ('all', 'All Entries'),
  54. ], 'Entries to Include', required=True,
  55. help='Print All Accounting Entries or just Posted Accounting Entries'),
  56. 'narration': fields.text('Notes', readonly=True),
  57. #~ Deprecated fields
  58. 'filter': fields.selection([('bydate', 'By Date'), ('byperiod', 'By Period'), ('all', 'By Date and Period'), ('none', 'No Filter')], 'Date/Period Filter'),
  59. 'date_to': fields.date('End date'),
  60. 'date_from': fields.date('Start date'),
  61. }
  62. _defaults = {
  63. 'date_from': lambda *a: time.strftime('%Y-%m-%d'),
  64. 'date_to': lambda *a: time.strftime('%Y-%m-%d'),
  65. 'filter': lambda *a: 'byperiod',
  66. 'display_account_level': lambda *a: 0,
  67. 'inf_type': lambda *a: 'BS',
  68. 'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'account.invoice', context=c),
  69. 'fiscalyear': lambda self, cr, uid, c: self.pool.get('account.fiscalyear').find(cr, uid),
  70. 'display_account': lambda *a: 'bal_mov',
  71. 'columns': lambda *a: 'five',
  72. 'target_move': 'posted',
  73. }
  74. def onchange_inf_type(self, cr, uid, ids, inf_type, context=None):
  75. if context is None:
  76. context = {}
  77. res = {'value': {}}
  78. if inf_type != 'BS':
  79. res['value'].update({'analytic_ledger': False})
  80. return res
  81. def onchange_columns(self, cr, uid, ids, columns, fiscalyear, periods, context=None):
  82. if context is None:
  83. context = {}
  84. res = {'value': {}}
  85. p_obj = self.pool.get("account.period")
  86. all_periods = p_obj.search(cr, uid, [('fiscalyear_id', '=', fiscalyear), (
  87. 'special', '=', False)], context=context)
  88. s = set(periods[0][2])
  89. t = set(all_periods)
  90. go = periods[0][2] and s.issubset(t) or False
  91. if columns != 'four':
  92. res['value'].update({'analytic_ledger': False})
  93. if columns in ('qtr', 'thirteen'):
  94. res['value'].update({'periods': all_periods})
  95. else:
  96. if go:
  97. res['value'].update({'periods': periods})
  98. else:
  99. res['value'].update({'periods': []})
  100. return res
  101. def onchange_analytic_ledger(self, cr, uid, ids, company_id, analytic_ledger, context=None):
  102. if context is None:
  103. context = {}
  104. context['company_id'] = company_id
  105. res = {'value': {}}
  106. cur_id = self.pool.get('res.company').browse(
  107. cr, uid, company_id, context=context).currency_id.id
  108. res['value'].update({'currency_id': cur_id})
  109. return res
  110. def onchange_company_id(self, cr, uid, ids, company_id, context=None):
  111. if context is None:
  112. context = {}
  113. context['company_id'] = company_id
  114. res = {'value': {}}
  115. if not company_id:
  116. return res
  117. cur_id = self.pool.get('res.company').browse(
  118. cr, uid, company_id, context=context).currency_id.id
  119. fy_id = self.pool.get('account.fiscalyear').find(
  120. cr, uid, context=context)
  121. res['value'].update({'fiscalyear': fy_id})
  122. res['value'].update({'currency_id': cur_id})
  123. res['value'].update({'account_list': []})
  124. res['value'].update({'periods': []})
  125. res['value'].update({'afr_id': None})
  126. return res
  127. def onchange_afr_id(self, cr, uid, ids, afr_id, context=None):
  128. if context is None:
  129. context = {}
  130. res = {'value': {}}
  131. if not afr_id:
  132. return res
  133. afr_brw = self.pool.get('afr').browse(cr, uid, afr_id, context=context)
  134. res['value'].update({
  135. 'currency_id': afr_brw.currency_id and afr_brw.currency_id.id or afr_brw.company_id.currency_id.id})
  136. res['value'].update({'inf_type': afr_brw.inf_type or 'BS'})
  137. res['value'].update({'columns': afr_brw.columns or 'five'})
  138. res['value'].update({
  139. 'display_account': afr_brw.display_account or 'bal_mov'})
  140. res['value'].update({
  141. 'display_account_level': afr_brw.display_account_level or 0})
  142. res['value'].update({
  143. 'fiscalyear': afr_brw.fiscalyear_id and afr_brw.fiscalyear_id.id})
  144. res['value'].update({'account_list': [
  145. acc.id for acc in afr_brw.account_ids]})
  146. res['value'].update({'periods': [p.id for p in afr_brw.period_ids]})
  147. res['value'].update({
  148. 'analytic_ledger': afr_brw.analytic_ledger or False})
  149. res['value'].update({'tot_check': afr_brw.tot_check or False})
  150. res['value'].update({'narration': afr_brw.narration or ''})
  151. res['value'].update({'lab_str': afr_brw.lab_str or _(
  152. 'Write a Description for your Summary Total')})
  153. return res
  154. def _get_defaults(self, cr, uid, data, context=None):
  155. if context is None:
  156. context = {}
  157. user = pooler.get_pool(cr.dbname).get(
  158. 'res.users').browse(cr, uid, uid, context=context)
  159. if user.company_id:
  160. company_id = user.company_id.id
  161. else:
  162. company_id = pooler.get_pool(cr.dbname).get(
  163. 'res.company').search(cr, uid, [('parent_id', '=', False)])[0]
  164. data['form']['company_id'] = company_id
  165. fiscalyear_obj = pooler.get_pool(cr.dbname).get('account.fiscalyear')
  166. data['form']['fiscalyear'] = fiscalyear_obj.find(cr, uid)
  167. data['form']['context'] = context
  168. return data['form']
  169. def _check_state(self, cr, uid, data, context=None):
  170. if context is None:
  171. context = {}
  172. if data['form']['filter'] == 'bydate':
  173. self._check_date(cr, uid, data, context)
  174. return data['form']
  175. def _check_date(self, cr, uid, data, context=None):
  176. if context is None:
  177. context = {}
  178. if data['form']['date_from'] > data['form']['date_to']:
  179. raise osv.except_osv(_('Error !'), (
  180. 'La fecha final debe ser mayor a la inicial'))
  181. sql = """SELECT f.id, f.date_start, f.date_stop
  182. FROM account_fiscalyear f
  183. WHERE '%s' = f.id """ % (data['form']['fiscalyear'])
  184. cr.execute(sql)
  185. res = cr.dictfetchall()
  186. if res:
  187. if (data['form']['date_to'] > res[0]['date_stop'] or data['form']['date_from'] < res[0]['date_start']):
  188. raise osv.except_osv(_('UserError'), 'Las fechas deben estar entre %s y %s' % (
  189. res[0]['date_start'], res[0]['date_stop']))
  190. else:
  191. return 'report'
  192. else:
  193. raise osv.except_osv(_('UserError'), 'No existe periodo fiscal')
  194. def period_span(self, cr, uid, ids, fy_id, context=None):
  195. if context is None:
  196. context = {}
  197. ap_obj = self.pool.get('account.period')
  198. fy_id = fy_id and type(fy_id) in (list, tuple) and fy_id[0] or fy_id
  199. if not ids:
  200. #~ No hay periodos
  201. return ap_obj.search(cr, uid, [('fiscalyear_id', '=', fy_id), ('special', '=', False)], order='date_start asc')
  202. ap_brws = ap_obj.browse(cr, uid, ids, context=context)
  203. date_start = min([period.date_start for period in ap_brws])
  204. date_stop = max([period.date_stop for period in ap_brws])
  205. return ap_obj.search(cr, uid, [('fiscalyear_id', '=', fy_id), ('special', '=', False), ('date_start', '>=', date_start), ('date_stop', '<=', date_stop)], order='date_start asc')
  206. def print_report(self, cr, uid, ids, data, context=None):
  207. if context is None:
  208. context = {}
  209. data = {}
  210. data['ids'] = context.get('active_ids', [])
  211. data['model'] = context.get('active_model', 'ir.ui.menu')
  212. data['form'] = self.read(cr, uid, ids[0])
  213. if data['form']['filter'] == 'byperiod':
  214. del data['form']['date_from']
  215. del data['form']['date_to']
  216. data['form']['periods'] = self.period_span(cr, uid, data[
  217. 'form']['periods'], data['form']['fiscalyear'])
  218. elif data['form']['filter'] == 'bydate':
  219. self._check_date(cr, uid, data)
  220. del data['form']['periods']
  221. elif data['form']['filter'] == 'none':
  222. del data['form']['date_from']
  223. del data['form']['date_to']
  224. del data['form']['periods']
  225. else:
  226. self._check_date(cr, uid, data)
  227. lis2 = str(data['form']['periods']).replace(
  228. "[", "(").replace("]", ")")
  229. sqlmm = """select min(p.date_start) as inicio, max(p.date_stop) as fin
  230. from account_period p
  231. where p.id in %s""" % lis2
  232. cr.execute(sqlmm)
  233. minmax = cr.dictfetchall()
  234. if minmax:
  235. if (data['form']['date_to'] < minmax[0]['inicio']) or (data['form']['date_from'] > minmax[0]['fin']):
  236. raise osv.except_osv(_('Error !'), _(
  237. 'La interseccion entre el periodo y fecha es vacio'))
  238. if data['form']['columns'] == 'one':
  239. name = 'afr.1cols'
  240. if data['form']['columns'] == 'two':
  241. name = 'afr.2cols'
  242. if data['form']['columns'] == 'four':
  243. if data['form']['analytic_ledger'] and data['form']['inf_type'] == 'BS':
  244. name = 'afr.analytic.ledger'
  245. elif data['form']['journal_ledger'] and data['form']['inf_type'] == 'BS':
  246. name = 'afr.journal.ledger'
  247. elif data['form']['partner_balance'] and data['form']['inf_type'] == 'BS':
  248. name = 'afr.partner.balance'
  249. else:
  250. name = 'afr.4cols'
  251. if data['form']['columns'] == 'five':
  252. name = 'afr.5cols'
  253. if data['form']['columns'] == 'qtr':
  254. name = 'afr.qtrcols'
  255. if data['form']['columns'] == 'thirteen':
  256. name = 'afr.13cols'
  257. return {'type': 'ir.actions.report.xml', 'report_name': name, 'datas': data}
  258. wizard_report()