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.

408 lines
18 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' \
  68. and context.get('active_ids', False):
  69. res = context['active_ids']
  70. return res
  71. _columns = {
  72. 'account_ids': fields.many2many(
  73. 'account.account', string='Filter on accounts',
  74. help="Only selected accounts will be printed. Leave empty to \
  75. print all accounts."),
  76. 'filter': fields.selection(
  77. [('filter_no', 'No Filters'),
  78. ('filter_date', 'Date'),
  79. ('filter_period', 'Periods'),
  80. ('filter_opening', 'Opening Only')],
  81. "Filter by",
  82. required=True,
  83. help='Filter by date: no opening balance will be displayed. '
  84. '(opening balance can only be computed based on period to be \
  85. correct).'),
  86. }
  87. for index in range(COMPARISON_LEVEL):
  88. _columns.update(
  89. {"comp%s_filter" % index:
  90. fields.selection(
  91. COMPARE_SELECTION, string='Compare By', required=True),
  92. "comp%s_fiscalyear_id" % index:
  93. fields.many2one('account.fiscalyear', 'Fiscal Year'),
  94. "comp%s_period_from" % index:
  95. fields.many2one('account.period', 'Start Period'),
  96. "comp%s_period_to" % index:
  97. fields.many2one('account.period', 'End Period'),
  98. "comp%s_date_from" % index:
  99. fields.date("Start Date"),
  100. "comp%s_date_to" % index:
  101. fields.date("End Date")})
  102. _defaults = {
  103. 'account_ids': _get_account_ids,
  104. }
  105. def _check_fiscalyear(self, cr, uid, ids, context=None):
  106. obj = self.read(
  107. cr, uid, ids[0], ['fiscalyear_id', 'filter'], context=context)
  108. if not obj['fiscalyear_id'] and obj['filter'] == 'filter_no':
  109. return False
  110. return True
  111. _constraints = [
  112. (_check_fiscalyear,
  113. 'When no Fiscal year is selected, you must choose to filter by \
  114. periods or by date.', ['filter']),
  115. ]
  116. def default_get(self, cr, uid, fields, context=None):
  117. """
  118. To get default values for the object.
  119. @param self: The object pointer.
  120. @param cr: A database cursor
  121. @param uid: ID of the user currently logged in
  122. @param fields: List of fields for which we want default values
  123. @param context: A standard dictionary
  124. @return: A dictionary which of fields with values.
  125. """
  126. res = super(AccountBalanceCommonWizard, self).default_get(
  127. cr, uid, fields, context=context)
  128. for index in range(self.COMPARISON_LEVEL):
  129. field = "comp%s_filter" % (index,)
  130. if not res.get(field, False):
  131. res[field] = 'filter_no'
  132. return res
  133. def fields_view_get(self, cr, uid, view_id=None, view_type='form',
  134. context=None, toolbar=False, submenu=False):
  135. res = super(AccountBalanceCommonWizard, self).fields_view_get(
  136. cr, uid, view_id, view_type, context=context, toolbar=toolbar,
  137. submenu=submenu)
  138. res['fields'].update(self.fields_get(cr, uid,
  139. allfields=self.DYNAMIC_FIELDS,
  140. context=context, write_access=True))
  141. eview = etree.fromstring(res['arch'])
  142. placeholder = eview.xpath("//page[@name='placeholder']")
  143. if placeholder:
  144. placeholder = placeholder[0]
  145. for index in range(self.COMPARISON_LEVEL):
  146. page = etree.Element(
  147. 'page',
  148. {'name': "comp%s" % index,
  149. 'string': _("Comparison %s") % (index + 1, )})
  150. group = etree.Element('group')
  151. page.append(group)
  152. def modifiers_and_append(elem):
  153. orm.setup_modifiers(elem)
  154. group.append(elem)
  155. modifiers_and_append(etree.Element(
  156. 'field',
  157. {'name': "comp%s_filter" % index,
  158. 'on_change': "onchange_comp_filter(%(index)s, filter,\
  159. comp%(index)s_filter, fiscalyear_id, date_from, date_to)"
  160. % {'index': index}}))
  161. modifiers_and_append(etree.Element(
  162. 'field',
  163. {'name': "comp%s_fiscalyear_id" % index,
  164. 'attrs':
  165. "{'required': [('comp%(index)s_filter','in',\
  166. ('filter_year','filter_opening'))],"
  167. " 'invisible': [('comp%(index)s_filter','not in',\
  168. ('filter_year','filter_opening'))]}" % {'index': index}}))
  169. dates_attrs = "{'required': [('comp%(index)s_filter','=',\
  170. 'filter_date')], " \
  171. " 'invisible': [('comp%(index)s_filter','!=',\
  172. 'filter_date')]}" % {
  173. 'index': index}
  174. modifiers_and_append(etree.Element(
  175. 'separator',
  176. {'string': _('Dates'),
  177. 'colspan': '4',
  178. 'attrs': dates_attrs}))
  179. modifiers_and_append(etree.Element(
  180. 'field',
  181. {'name': "comp%s_date_from" % index,
  182. 'attrs': dates_attrs}))
  183. modifiers_and_append(etree.Element(
  184. 'field',
  185. {'name': "comp%s_date_to" % index,
  186. 'attrs': dates_attrs}))
  187. periods_attrs = "{'required': [('comp%(index)s_filter','=',\
  188. 'filter_period')]," \
  189. " 'invisible': [('comp%(index)s_filter','!=',\
  190. 'filter_period')]}" % {
  191. 'index': index}
  192. periods_domain = "[('special', '=', False)]"
  193. modifiers_and_append(etree.Element(
  194. 'separator',
  195. {'string': _('Periods'),
  196. 'colspan': '4',
  197. 'attrs': periods_attrs}))
  198. modifiers_and_append(etree.Element(
  199. 'field',
  200. {'name': "comp%s_period_from" % index,
  201. 'attrs': periods_attrs,
  202. 'domain': periods_domain}))
  203. modifiers_and_append(etree.Element(
  204. 'field',
  205. {'name': "comp%s_period_to" % index,
  206. 'attrs': periods_attrs,
  207. 'domain': periods_domain}))
  208. placeholder.addprevious(page)
  209. placeholder.getparent().remove(placeholder)
  210. res['arch'] = etree.tostring(eview)
  211. return res
  212. def onchange_filter(self, cr, uid, ids, filter='filter_no',
  213. fiscalyear_id=False, context=None):
  214. res = {}
  215. if filter == 'filter_no':
  216. res['value'] = {'period_from': False,
  217. 'period_to': False,
  218. 'date_from': False,
  219. 'date_to': False}
  220. if filter == 'filter_date':
  221. if fiscalyear_id:
  222. fyear = self.pool.get('account.fiscalyear').browse(
  223. cr, uid, fiscalyear_id, context=context)
  224. date_from = fyear.date_start
  225. date_to = fyear.date_stop > time.strftime(
  226. '%Y-%m-%d') and time.strftime('%Y-%m-%d') \
  227. or fyear.date_stop
  228. else:
  229. date_from, date_to = time.strftime(
  230. '%Y-01-01'), time.strftime('%Y-%m-%d')
  231. res['value'] = {'period_from': False, 'period_to':
  232. False, 'date_from': date_from, 'date_to': date_to}
  233. if filter == 'filter_period' and fiscalyear_id:
  234. start_period = end_period = False
  235. cr.execute('''
  236. SELECT * FROM (SELECT p.id
  237. FROM account_period p
  238. LEFT JOIN account_fiscalyear f
  239. ON (p.fiscalyear_id = f.id)
  240. WHERE f.id = %s
  241. AND COALESCE(p.special, FALSE) = FALSE
  242. ORDER BY p.date_start ASC
  243. LIMIT 1) AS period_start
  244. UNION ALL
  245. SELECT * FROM (SELECT p.id
  246. FROM account_period p
  247. LEFT JOIN account_fiscalyear f
  248. ON (p.fiscalyear_id = f.id)
  249. WHERE f.id = %s
  250. AND p.date_start < NOW()
  251. AND COALESCE(p.special, FALSE) = FALSE
  252. ORDER BY p.date_stop DESC
  253. LIMIT 1) AS period_stop''',
  254. (fiscalyear_id, fiscalyear_id))
  255. periods = [i[0] for i in cr.fetchall()]
  256. if periods:
  257. start_period = end_period = periods[0]
  258. if len(periods) > 1:
  259. end_period = periods[1]
  260. res['value'] = {'period_from': start_period, 'period_to':
  261. end_period, 'date_from': False, 'date_to': False}
  262. return res
  263. def onchange_comp_filter(self, cr, uid, ids, index,
  264. main_filter='filter_no', comp_filter='filter_no',
  265. fiscalyear_id=False, start_date=False,
  266. stop_date=False, context=None):
  267. res = {}
  268. fy_obj = self.pool.get('account.fiscalyear')
  269. last_fiscalyear_id = False
  270. if fiscalyear_id:
  271. fiscalyear = fy_obj.browse(cr, uid, fiscalyear_id, context=context)
  272. last_fiscalyear_ids = fy_obj.search(
  273. cr, uid, [('date_stop', '<', fiscalyear.date_start)],
  274. limit=self.COMPARISON_LEVEL, order='date_start desc',
  275. context=context)
  276. if last_fiscalyear_ids:
  277. if len(last_fiscalyear_ids) > index:
  278. # first element for the comparison 1, second element for
  279. # the comparison 2
  280. last_fiscalyear_id = last_fiscalyear_ids[index]
  281. fy_id_field = "comp%s_fiscalyear_id" % (index,)
  282. period_from_field = "comp%s_period_from" % (index,)
  283. period_to_field = "comp%s_period_to" % (index,)
  284. date_from_field = "comp%s_date_from" % (index,)
  285. date_to_field = "comp%s_date_to" % (index,)
  286. if comp_filter == 'filter_no':
  287. res['value'] = {
  288. fy_id_field: False,
  289. period_from_field: False,
  290. period_to_field: False,
  291. date_from_field: False,
  292. date_to_field: False
  293. }
  294. if comp_filter in ('filter_year', 'filter_opening'):
  295. res['value'] = {
  296. fy_id_field: last_fiscalyear_id,
  297. period_from_field: False,
  298. period_to_field: False,
  299. date_from_field: False,
  300. date_to_field: False
  301. }
  302. if comp_filter == 'filter_date':
  303. dates = {}
  304. if main_filter == 'filter_date':
  305. dates = {
  306. 'date_start': previous_year_date(start_date, index + 1).
  307. strftime('%Y-%m-%d'),
  308. 'date_stop': previous_year_date(stop_date, index + 1).
  309. strftime('%Y-%m-%d'),
  310. }
  311. elif last_fiscalyear_id:
  312. dates = fy_obj.read(
  313. cr, uid, last_fiscalyear_id, ['date_start', 'date_stop'],
  314. context=context)
  315. res['value'] = {fy_id_field: False,
  316. period_from_field: False,
  317. period_to_field: False,
  318. date_from_field: dates.get('date_start', False),
  319. date_to_field: dates.get('date_stop', False)}
  320. if comp_filter == 'filter_period' and last_fiscalyear_id:
  321. start_period = end_period = False
  322. cr.execute('''
  323. SELECT * FROM (SELECT p.id
  324. FROM account_period p
  325. LEFT JOIN account_fiscalyear f
  326. ON (p.fiscalyear_id = f.id)
  327. WHERE f.id = %(fiscalyear)s
  328. AND COALESCE(p.special, FALSE) = FALSE
  329. ORDER BY p.date_start ASC
  330. LIMIT 1) AS period_start
  331. UNION ALL
  332. SELECT * FROM (SELECT p.id
  333. FROM account_period p
  334. LEFT JOIN account_fiscalyear f
  335. ON (p.fiscalyear_id = f.id)
  336. WHERE f.id = %(fiscalyear)s
  337. AND p.date_start < NOW()
  338. AND COALESCE(p.special, FALSE) = FALSE
  339. ORDER BY p.date_stop DESC
  340. LIMIT 1) AS period_stop''',
  341. {'fiscalyear': last_fiscalyear_id})
  342. periods = [i[0] for i in cr.fetchall()]
  343. if periods and len(periods) > 1:
  344. start_period = end_period = periods[0]
  345. if len(periods) > 1:
  346. end_period = periods[1]
  347. res['value'] = {fy_id_field: False,
  348. period_from_field: start_period,
  349. period_to_field: end_period,
  350. date_from_field: False,
  351. date_to_field: False}
  352. return res
  353. def pre_print_report(self, cr, uid, ids, data, context=None):
  354. data = super(AccountBalanceCommonWizard, self).pre_print_report(
  355. cr, uid, ids, data, context)
  356. if context is None:
  357. context = {}
  358. # will be used to attach the report on the main account
  359. data['ids'] = [data['form']['chart_account_id']]
  360. fields_to_read = ['account_ids', ]
  361. fields_to_read += self.DYNAMIC_FIELDS
  362. vals = self.read(cr, uid, ids, fields_to_read, context=context)[0]
  363. # extract the id from the m2o tuple (id, name)
  364. for field in self.M2O_DYNAMIC_FIELDS:
  365. if isinstance(vals[field], tuple):
  366. vals[field] = vals[field][0]
  367. vals['max_comparison'] = self.COMPARISON_LEVEL
  368. data['form'].update(vals)
  369. return data