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.

347 lines
16 KiB

  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Copyright (c) 2011 Camptocamp SA (http://www.camptocamp.com)
  5. #
  6. # Author: Guewen Baconnier (Camptocamp)
  7. #
  8. # WARNING: This program as such is intended to be used by professional
  9. # programmers who take the whole responsability of assessing all potential
  10. # consequences resulting from its eventual inadequacies and bugs
  11. # End users who are looking for a ready-to-use solution with commercial
  12. # garantees and support are strongly adviced to contract a Free Software
  13. # Service Company
  14. #
  15. # This program is Free Software; you can redistribute it and/or
  16. # modify it under the terms of the GNU General Public License
  17. # as published by the Free Software Foundation; either version 2
  18. # of the License, or (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, write to the Free Software
  27. # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  28. #
  29. ##############################################################################
  30. import time
  31. from lxml import etree
  32. from datetime import datetime
  33. from openerp.osv import fields, orm
  34. from openerp.tools.translate import _
  35. def previous_year_date(date, nb_prev=1):
  36. if not date:
  37. return False
  38. parsed_date = datetime.strptime(date, '%Y-%m-%d')
  39. previous_date = datetime(year=parsed_date.year - nb_prev,
  40. month=parsed_date.month,
  41. day=parsed_date.day)
  42. return previous_date
  43. class AccountBalanceCommonWizard(orm.TransientModel):
  44. """Will launch trial balance report and pass required args"""
  45. _inherit = "account.common.account.report"
  46. _name = "account.common.balance.report"
  47. _description = "Common Balance Report"
  48. # an update module should be done if changed
  49. # in order to create fields in db
  50. COMPARISON_LEVEL = 3
  51. COMPARE_SELECTION = [('filter_no', 'No Comparison'),
  52. ('filter_year', 'Fiscal Year'),
  53. ('filter_date', 'Date'),
  54. ('filter_period', 'Periods'),
  55. ('filter_opening', 'Opening Only')]
  56. M2O_DYNAMIC_FIELDS = [f % index for f in ["comp%s_fiscalyear_id",
  57. "comp%s_period_from",
  58. "comp%s_period_to"]
  59. for index in range(COMPARISON_LEVEL)]
  60. SIMPLE_DYNAMIC_FIELDS = [f % index for f in ["comp%s_filter",
  61. "comp%s_date_from",
  62. "comp%s_date_to"]
  63. for index in range(COMPARISON_LEVEL)]
  64. DYNAMIC_FIELDS = M2O_DYNAMIC_FIELDS + SIMPLE_DYNAMIC_FIELDS
  65. def _get_account_ids(self, cr, uid, context=None):
  66. res = False
  67. if context.get('active_model', False) == 'account.account' and context.get('active_ids', False):
  68. res = context['active_ids']
  69. return res
  70. _columns = {
  71. 'account_ids': fields.many2many('account.account', string='Filter on accounts',
  72. help="Only selected accounts will be printed. Leave empty to print all accounts."),
  73. 'filter': fields.selection([('filter_no', 'No Filters'),
  74. ('filter_date', 'Date'),
  75. ('filter_period', 'Periods'),
  76. ('filter_opening', 'Opening Only')],
  77. "Filter by",
  78. required=True,
  79. help='Filter by date: no opening balance will be displayed. '
  80. '(opening balance can only be computed based on period to be correct).'),
  81. }
  82. for index in range(COMPARISON_LEVEL):
  83. _columns.update(
  84. {"comp%s_filter" % index: fields.selection(COMPARE_SELECTION, string='Compare By', required=True),
  85. "comp%s_fiscalyear_id" % index: fields.many2one('account.fiscalyear', 'Fiscal Year'),
  86. "comp%s_period_from" % index: fields.many2one('account.period', 'Start Period'),
  87. "comp%s_period_to" % index: fields.many2one('account.period', 'End Period'),
  88. "comp%s_date_from" % index: fields.date("Start Date"),
  89. "comp%s_date_to" % index: fields.date("End Date")})
  90. _defaults = {
  91. 'account_ids': _get_account_ids,
  92. }
  93. def _check_fiscalyear(self, cr, uid, ids, context=None):
  94. obj = self.read(cr, uid, ids[0], ['fiscalyear_id', 'filter'], context=context)
  95. if not obj['fiscalyear_id'] and obj['filter'] == 'filter_no':
  96. return False
  97. return True
  98. _constraints = [
  99. (_check_fiscalyear, 'When no Fiscal year is selected, you must choose to filter by periods or by date.', ['filter']),
  100. ]
  101. def default_get(self, cr, uid, fields, context=None):
  102. """
  103. To get default values for the object.
  104. @param self: The object pointer.
  105. @param cr: A database cursor
  106. @param uid: ID of the user currently logged in
  107. @param fields: List of fields for which we want default values
  108. @param context: A standard dictionary
  109. @return: A dictionary which of fields with values.
  110. """
  111. res = super(AccountBalanceCommonWizard, self).default_get(cr, uid, fields, context=context)
  112. for index in range(self.COMPARISON_LEVEL):
  113. field = "comp%s_filter" % (index,)
  114. if not res.get(field, False):
  115. res[field] = 'filter_no'
  116. return res
  117. def fields_view_get(self, cr, uid, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
  118. res = super(AccountBalanceCommonWizard, self).fields_view_get(cr, uid, view_id, view_type, context=context, toolbar=toolbar, submenu=submenu)
  119. res['fields'].update(self.fields_get(cr, uid,
  120. allfields=self.DYNAMIC_FIELDS,
  121. context=context, write_access=True))
  122. eview = etree.fromstring(res['arch'])
  123. placeholder = eview.xpath("//page[@name='placeholder']")
  124. if placeholder:
  125. placeholder = placeholder[0]
  126. for index in range(self.COMPARISON_LEVEL):
  127. page = etree.Element(
  128. 'page',
  129. {'name': "comp%s" % index,
  130. 'string': _("Comparison %s") % (index + 1, )})
  131. group = etree.Element('group')
  132. page.append(group)
  133. def modifiers_and_append(elem):
  134. orm.setup_modifiers(elem)
  135. group.append(elem)
  136. modifiers_and_append(etree.Element(
  137. 'field',
  138. {'name': "comp%s_filter" % index,
  139. 'on_change': "onchange_comp_filter(%(index)s, filter, comp%(index)s_filter, fiscalyear_id, date_from, date_to)" % {'index': index}}))
  140. modifiers_and_append(etree.Element(
  141. 'field',
  142. {'name': "comp%s_fiscalyear_id" % index,
  143. 'attrs':
  144. "{'required': [('comp%(index)s_filter','in',('filter_year','filter_opening'))]," \
  145. " 'invisible': [('comp%(index)s_filter','not in',('filter_year','filter_opening'))]}" % {'index': index}}))
  146. dates_attrs = "{'required': [('comp%(index)s_filter','=','filter_date')], " \
  147. " 'invisible': [('comp%(index)s_filter','!=','filter_date')]}" % {'index': index}
  148. modifiers_and_append(etree.Element(
  149. 'separator',
  150. {'string': _('Dates'),
  151. 'colspan': '4',
  152. 'attrs': dates_attrs}))
  153. modifiers_and_append(etree.Element(
  154. 'field',
  155. {'name': "comp%s_date_from" % index,
  156. 'attrs': dates_attrs}))
  157. modifiers_and_append(etree.Element(
  158. 'field',
  159. {'name': "comp%s_date_to" % index,
  160. 'attrs': dates_attrs}))
  161. periods_attrs = "{'required': [('comp%(index)s_filter','=','filter_period')]," \
  162. " 'invisible': [('comp%(index)s_filter','!=','filter_period')]}" % {'index': index}
  163. periods_domain = "[('special', '=', False)]"
  164. modifiers_and_append(etree.Element(
  165. 'separator',
  166. {'string': _('Periods'),
  167. 'colspan': '4',
  168. 'attrs': periods_attrs}))
  169. modifiers_and_append(etree.Element(
  170. 'field',
  171. {'name': "comp%s_period_from" % index,
  172. 'attrs': periods_attrs,
  173. 'domain': periods_domain}))
  174. modifiers_and_append(etree.Element(
  175. 'field',
  176. {'name': "comp%s_period_to" % index,
  177. 'attrs': periods_attrs,
  178. 'domain': periods_domain}))
  179. placeholder.addprevious(page)
  180. placeholder.getparent().remove(placeholder)
  181. res['arch'] = etree.tostring(eview)
  182. return res
  183. def onchange_filter(self, cr, uid, ids, filter='filter_no', fiscalyear_id=False, context=None):
  184. res = {}
  185. if filter == 'filter_no':
  186. res['value'] = {'period_from': False, 'period_to': False, 'date_from': False, 'date_to': False}
  187. if filter == 'filter_date':
  188. if fiscalyear_id:
  189. fyear = self.pool.get('account.fiscalyear').browse(cr, uid, fiscalyear_id, context=context)
  190. date_from = fyear.date_start
  191. date_to = fyear.date_stop > time.strftime('%Y-%m-%d') and time.strftime('%Y-%m-%d') or fyear.date_stop
  192. else:
  193. date_from, date_to = time.strftime('%Y-01-01'), time.strftime('%Y-%m-%d')
  194. res['value'] = {'period_from': False, 'period_to': False, 'date_from': date_from, 'date_to': date_to}
  195. if filter == 'filter_period' and fiscalyear_id:
  196. start_period = end_period = False
  197. cr.execute('''
  198. SELECT * FROM (SELECT p.id
  199. FROM account_period p
  200. LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
  201. WHERE f.id = %s
  202. AND COALESCE(p.special, FALSE) = FALSE
  203. ORDER BY p.date_start ASC
  204. LIMIT 1) AS period_start
  205. UNION ALL
  206. SELECT * FROM (SELECT p.id
  207. FROM account_period p
  208. LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
  209. WHERE f.id = %s
  210. AND p.date_start < NOW()
  211. AND COALESCE(p.special, FALSE) = FALSE
  212. ORDER BY p.date_stop DESC
  213. LIMIT 1) AS period_stop''', (fiscalyear_id, fiscalyear_id))
  214. periods = [i[0] for i in cr.fetchall()]
  215. if periods:
  216. start_period = end_period = periods[0]
  217. if len(periods) > 1:
  218. end_period = periods[1]
  219. res['value'] = {'period_from': start_period, 'period_to': end_period, 'date_from': False, 'date_to': False}
  220. return res
  221. def onchange_comp_filter(self, cr, uid, ids, index, main_filter='filter_no', comp_filter='filter_no', fiscalyear_id=False, start_date=False, stop_date=False, context=None):
  222. res = {}
  223. fy_obj = self.pool.get('account.fiscalyear')
  224. last_fiscalyear_id = False
  225. if fiscalyear_id:
  226. fiscalyear = fy_obj.browse(cr, uid, fiscalyear_id, context=context)
  227. last_fiscalyear_ids = fy_obj.search(cr, uid, [('date_stop', '<', fiscalyear.date_start)],
  228. limit=self.COMPARISON_LEVEL, order='date_start desc', context=context)
  229. if last_fiscalyear_ids:
  230. if len(last_fiscalyear_ids) > index:
  231. last_fiscalyear_id = last_fiscalyear_ids[index] # first element for the comparison 1, second element for the comparison 2
  232. fy_id_field = "comp%s_fiscalyear_id" % (index,)
  233. period_from_field = "comp%s_period_from" % (index,)
  234. period_to_field = "comp%s_period_to" % (index,)
  235. date_from_field = "comp%s_date_from" % (index,)
  236. date_to_field = "comp%s_date_to" % (index,)
  237. if comp_filter == 'filter_no':
  238. res['value'] = {
  239. fy_id_field: False,
  240. period_from_field: False,
  241. period_to_field: False,
  242. date_from_field: False,
  243. date_to_field: False
  244. }
  245. if comp_filter in ('filter_year', 'filter_opening'):
  246. res['value'] = {
  247. fy_id_field: last_fiscalyear_id,
  248. period_from_field: False,
  249. period_to_field: False,
  250. date_from_field: False,
  251. date_to_field: False
  252. }
  253. if comp_filter == 'filter_date':
  254. dates = {}
  255. if main_filter == 'filter_date':
  256. dates = {
  257. 'date_start': previous_year_date(start_date, index + 1).strftime('%Y-%m-%d'),
  258. 'date_stop': previous_year_date(stop_date, index + 1).strftime('%Y-%m-%d'),
  259. }
  260. elif last_fiscalyear_id:
  261. dates = fy_obj.read(cr, uid, last_fiscalyear_id, ['date_start', 'date_stop'], context=context)
  262. res['value'] = {fy_id_field: False, period_from_field: False, period_to_field: False, date_from_field: dates.get('date_start', False), date_to_field: dates.get('date_stop', False)}
  263. if comp_filter == 'filter_period' and last_fiscalyear_id:
  264. start_period = end_period = False
  265. cr.execute('''
  266. SELECT * FROM (SELECT p.id
  267. FROM account_period p
  268. LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
  269. WHERE f.id = %(fiscalyear)s
  270. AND COALESCE(p.special, FALSE) = FALSE
  271. ORDER BY p.date_start ASC
  272. LIMIT 1) AS period_start
  273. UNION ALL
  274. SELECT * FROM (SELECT p.id
  275. FROM account_period p
  276. LEFT JOIN account_fiscalyear f ON (p.fiscalyear_id = f.id)
  277. WHERE f.id = %(fiscalyear)s
  278. AND p.date_start < NOW()
  279. AND COALESCE(p.special, FALSE) = FALSE
  280. ORDER BY p.date_stop DESC
  281. LIMIT 1) AS period_stop''', {'fiscalyear': last_fiscalyear_id})
  282. periods = [i[0] for i in cr.fetchall()]
  283. if periods and len(periods) > 1:
  284. start_period = end_period = periods[0]
  285. if len(periods) > 1:
  286. end_period = periods[1]
  287. res['value'] = {fy_id_field: False,
  288. period_from_field: start_period,
  289. period_to_field: end_period,
  290. date_from_field: False,
  291. date_to_field: False}
  292. return res
  293. def pre_print_report(self, cr, uid, ids, data, context=None):
  294. data = super(AccountBalanceCommonWizard, self).pre_print_report(
  295. cr, uid, ids, data, context)
  296. if context is None:
  297. context = {}
  298. # will be used to attach the report on the main account
  299. data['ids'] = [data['form']['chart_account_id']]
  300. fields_to_read = ['account_ids', ]
  301. fields_to_read += self.DYNAMIC_FIELDS
  302. vals = self.read(cr, uid, ids, fields_to_read, context=context)[0]
  303. # extract the id from the m2o tuple (id, name)
  304. for field in self.M2O_DYNAMIC_FIELDS:
  305. if isinstance(vals[field], tuple):
  306. vals[field] = vals[field][0]
  307. vals['max_comparison'] = self.COMPARISON_LEVEL
  308. data['form'].update(vals)
  309. return data