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.

803 lines
31 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. # -*- coding: utf-8 -*-
  2. # © 2014-2015 ACSONE SA/NV (<http://acsone.eu>)
  3. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  4. import datetime
  5. import dateutil
  6. import logging
  7. import re
  8. import time
  9. import traceback
  10. import pytz
  11. from openerp import api, fields, models, _
  12. from openerp.tools.safe_eval import safe_eval
  13. from .aep import AccountingExpressionProcessor as AEP
  14. from .aggregate import _sum, _avg, _min, _max
  15. from .accounting_none import AccountingNone
  16. _logger = logging.getLogger(__name__)
  17. class AutoStruct(object):
  18. def __init__(self, **kwargs):
  19. for k, v in kwargs.items():
  20. setattr(self, k, v)
  21. def _get_selection_label(selection, value):
  22. for v, l in selection:
  23. if v == value:
  24. return l
  25. return ''
  26. def _utc_midnight(d, tz_name, add_day=0):
  27. d = fields.Datetime.from_string(d) + datetime.timedelta(days=add_day)
  28. utc_tz = pytz.timezone('UTC')
  29. context_tz = pytz.timezone(tz_name)
  30. local_timestamp = context_tz.localize(d, is_dst=False)
  31. return fields.Datetime.to_string(local_timestamp.astimezone(utc_tz))
  32. def _python_var(var_str):
  33. return re.sub(r'\W|^(?=\d)', '_', var_str).lower()
  34. def _is_valid_python_var(name):
  35. return re.match("[_A-Za-z][_a-zA-Z0-9]*$", name)
  36. class MisReportKpi(models.Model):
  37. """ A KPI is an element (ie a line) of a MIS report.
  38. In addition to a name and description, it has an expression
  39. to compute it based on queries defined in the MIS report.
  40. It also has various informations defining how to render it
  41. (numeric or percentage or a string, a prefix, a suffix, divider) and
  42. how to render comparison of two values of the KPI.
  43. KPI's have a sequence and are ordered inside the MIS report.
  44. """
  45. _name = 'mis.report.kpi'
  46. name = fields.Char(size=32, required=True,
  47. string='Name')
  48. description = fields.Char(required=True,
  49. string='Description',
  50. translate=True)
  51. expression = fields.Char(required=True,
  52. string='Expression')
  53. default_css_style = fields.Char(string='Default CSS style')
  54. css_style = fields.Char(string='CSS style expression')
  55. type = fields.Selection([('num', _('Numeric')),
  56. ('pct', _('Percentage')),
  57. ('str', _('String'))],
  58. required=True,
  59. string='Type',
  60. default='num')
  61. divider = fields.Selection([('1e-6', _('µ')),
  62. ('1e-3', _('m')),
  63. ('1', _('1')),
  64. ('1e3', _('k')),
  65. ('1e6', _('M'))],
  66. string='Factor',
  67. default='1')
  68. dp = fields.Integer(string='Rounding', default=0)
  69. prefix = fields.Char(size=16, string='Prefix')
  70. suffix = fields.Char(size=16, string='Suffix')
  71. compare_method = fields.Selection([('diff', _('Difference')),
  72. ('pct', _('Percentage')),
  73. ('none', _('None'))],
  74. required=True,
  75. string='Comparison Method',
  76. default='pct')
  77. sequence = fields.Integer(string='Sequence', default=100)
  78. report_id = fields.Many2one('mis.report',
  79. string='Report',
  80. ondelete='cascade')
  81. _order = 'sequence, id'
  82. @api.one
  83. @api.constrains('name')
  84. def _check_name(self):
  85. return _is_valid_python_var(self.name)
  86. @api.onchange('name')
  87. def _onchange_name(self):
  88. if self.name and not _is_valid_python_var(self.name):
  89. return {
  90. 'warning': {
  91. 'title': 'Invalid name %s' % self.name,
  92. 'message': 'The name must be a valid python identifier'
  93. }
  94. }
  95. @api.onchange('description')
  96. def _onchange_description(self):
  97. """ construct name from description """
  98. if self.description and not self.name:
  99. self.name = _python_var(self.description)
  100. @api.onchange('type')
  101. def _onchange_type(self):
  102. if self.type == 'num':
  103. self.compare_method = 'pct'
  104. self.divider = '1'
  105. self.dp = 0
  106. elif self.type == 'pct':
  107. self.compare_method = 'diff'
  108. self.divider = '1'
  109. self.dp = 0
  110. elif self.type == 'str':
  111. self.compare_method = 'none'
  112. self.divider = ''
  113. self.dp = 0
  114. def render(self, lang_id, value):
  115. """ render a KPI value as a unicode string, ready for display """
  116. assert len(self) == 1
  117. if value is None or value is AccountingNone:
  118. return ''
  119. elif self.type == 'num':
  120. return self._render_num(lang_id, value, self.divider,
  121. self.dp, self.prefix, self.suffix)
  122. elif self.type == 'pct':
  123. return self._render_num(lang_id, value, 0.01,
  124. self.dp, '', '%')
  125. else:
  126. return unicode(value)
  127. def render_comparison(self, lang_id, value, base_value,
  128. average_value, average_base_value):
  129. """ render the comparison of two KPI values, ready for display
  130. If the difference is 0, an empty string is returned.
  131. """
  132. assert len(self) == 1
  133. if value is None:
  134. value = AccountingNone
  135. if base_value is None:
  136. base_value = AccountingNone
  137. if self.type == 'pct':
  138. delta = value - base_value
  139. if delta and round(delta, self.dp) != 0:
  140. return self._render_num(
  141. lang_id,
  142. delta,
  143. 0.01, self.dp, '', _('pp'),
  144. sign='+')
  145. elif self.type == 'num':
  146. if value and average_value:
  147. value = value / float(average_value)
  148. if base_value and average_base_value:
  149. base_value = base_value / float(average_base_value)
  150. if self.compare_method == 'diff':
  151. delta = value - base_value
  152. if delta and round(delta, self.dp) != 0:
  153. return self._render_num(
  154. lang_id,
  155. delta,
  156. self.divider, self.dp, self.prefix, self.suffix,
  157. sign='+')
  158. elif self.compare_method == 'pct':
  159. if base_value and round(base_value, self.dp) != 0:
  160. delta = (value - base_value) / abs(base_value)
  161. if delta and round(delta, self.dp) != 0:
  162. return self._render_num(
  163. lang_id,
  164. delta,
  165. 0.01, self.dp, '', '%',
  166. sign='+')
  167. return ''
  168. def _render_num(self, lang_id, value, divider,
  169. dp, prefix, suffix, sign='-'):
  170. divider_label = _get_selection_label(
  171. self._columns['divider'].selection, divider)
  172. if divider_label == '1':
  173. divider_label = ''
  174. # format number following user language
  175. value = round(value / float(divider or 1), dp) or 0
  176. value = self.env['res.lang'].browse(lang_id).format(
  177. '%%%s.%df' % (sign, dp),
  178. value,
  179. grouping=True)
  180. value = u'%s\N{NARROW NO-BREAK SPACE}%s\N{NO-BREAK SPACE}%s%s' % \
  181. (prefix or '', value, divider_label, suffix or '')
  182. value = value.replace('-', u'\N{NON-BREAKING HYPHEN}')
  183. return value
  184. class MisReportQuery(models.Model):
  185. """ A query to fetch arbitrary data for a MIS report.
  186. A query works on a model and has a domain and list of fields to fetch.
  187. At runtime, the domain is expanded with a "and" on the date/datetime field.
  188. """
  189. _name = 'mis.report.query'
  190. @api.one
  191. @api.depends('field_ids')
  192. def _compute_field_names(self):
  193. field_names = [field.name for field in self.field_ids]
  194. self.field_names = ', '.join(field_names)
  195. name = fields.Char(size=32, required=True,
  196. string='Name')
  197. model_id = fields.Many2one('ir.model', required=True,
  198. string='Model')
  199. field_ids = fields.Many2many('ir.model.fields', required=True,
  200. string='Fields to fetch')
  201. field_names = fields.Char(compute='_compute_field_names',
  202. string='Fetched fields name')
  203. aggregate = fields.Selection([('sum', _('Sum')),
  204. ('avg', _('Average')),
  205. ('min', _('Min')),
  206. ('max', _('Max'))],
  207. string='Aggregate')
  208. date_field = fields.Many2one('ir.model.fields', required=True,
  209. string='Date field',
  210. domain=[('ttype', 'in',
  211. ('date', 'datetime'))])
  212. domain = fields.Char(string='Domain')
  213. report_id = fields.Many2one('mis.report', string='Report',
  214. ondelete='cascade')
  215. _order = 'name'
  216. @api.one
  217. @api.constrains('name')
  218. def _check_name(self):
  219. return _is_valid_python_var(self.name)
  220. class MisReport(models.Model):
  221. """ A MIS report template (without period information)
  222. The MIS report holds:
  223. * a list of explicit queries; the result of each query is
  224. stored in a variable with same name as a query, containing as list
  225. of data structures populated with attributes for each fields to fetch;
  226. when queries have an aggregate method and no fields to group, it returns
  227. a data structure with the aggregated fields
  228. * a list of KPI to be evaluated based on the variables resulting
  229. from the accounting data and queries (KPI expressions can references
  230. queries and accounting expression - see AccoutingExpressionProcessor)
  231. """
  232. _name = 'mis.report'
  233. name = fields.Char(required=True,
  234. string='Name', translate=True)
  235. description = fields.Char(required=False,
  236. string='Description', translate=True)
  237. query_ids = fields.One2many('mis.report.query', 'report_id',
  238. string='Queries',
  239. copy=True)
  240. kpi_ids = fields.One2many('mis.report.kpi', 'report_id',
  241. string='KPI\'s',
  242. copy=True)
  243. @api.one
  244. def copy(self, default=None):
  245. default = dict(default or {})
  246. default['name'] = _('%s (copy)') % self.name
  247. return super(MisReport, self).copy(default)
  248. # TODO: kpi name cannot be start with query name
  249. class MisReportInstancePeriod(models.Model):
  250. """ A MIS report instance has the logic to compute
  251. a report template for a given date period.
  252. Periods have a duration (day, week, fiscal period) and
  253. are defined as an offset relative to a pivot date.
  254. """
  255. @api.one
  256. @api.depends('report_instance_id.pivot_date', 'type', 'offset', 'duration')
  257. def _compute_dates(self):
  258. self.date_from = False
  259. self.date_to = False
  260. self.period_from = False
  261. self.period_to = False
  262. self.valid = False
  263. d = fields.Date.from_string(self.report_instance_id.pivot_date)
  264. if self.type == 'd':
  265. date_from = d + datetime.timedelta(days=self.offset)
  266. date_to = date_from + \
  267. datetime.timedelta(days=self.duration - 1)
  268. self.date_from = fields.Date.to_string(date_from)
  269. self.date_to = fields.Date.to_string(date_to)
  270. self.valid = True
  271. elif self.type == 'w':
  272. date_from = d - datetime.timedelta(d.weekday())
  273. date_from = date_from + datetime.timedelta(days=self.offset * 7)
  274. date_to = date_from + \
  275. datetime.timedelta(days=(7 * self.duration) - 1)
  276. self.date_from = fields.Date.to_string(date_from)
  277. self.date_to = fields.Date.to_string(date_to)
  278. self.valid = True
  279. elif self.type == 'fp':
  280. current_periods = self.env['account.period'].search(
  281. [('special', '=', False),
  282. ('date_start', '<=', d),
  283. ('date_stop', '>=', d),
  284. ('company_id', '=',
  285. self.report_instance_id.company_id.id)])
  286. if current_periods:
  287. all_periods = self.env['account.period'].search(
  288. [('special', '=', False),
  289. ('company_id', '=',
  290. self.report_instance_id.company_id.id)],
  291. order='date_start')
  292. all_period_ids = [p.id for p in all_periods]
  293. p = all_period_ids.index(current_periods[0].id) + self.offset
  294. if p >= 0 and p + self.duration <= len(all_period_ids):
  295. periods = all_periods[p:p + self.duration]
  296. self.date_from = periods[0].date_start
  297. self.date_to = periods[-1].date_stop
  298. self.period_from = periods[0]
  299. self.period_to = periods[-1]
  300. self.valid = True
  301. _name = 'mis.report.instance.period'
  302. name = fields.Char(size=32, required=True,
  303. string='Description', translate=True)
  304. type = fields.Selection([('d', _('Day')),
  305. ('w', _('Week')),
  306. ('fp', _('Fiscal Period')),
  307. # ('fy', _('Fiscal Year'))
  308. ],
  309. required=True,
  310. string='Period type')
  311. offset = fields.Integer(string='Offset',
  312. help='Offset from current period',
  313. default=-1)
  314. duration = fields.Integer(string='Duration',
  315. help='Number of periods',
  316. default=1)
  317. date_from = fields.Date(compute='_compute_dates', string="From")
  318. date_to = fields.Date(compute='_compute_dates', string="To")
  319. period_from = fields.Many2one(compute='_compute_dates',
  320. comodel_name='account.period',
  321. string="From period")
  322. period_to = fields.Many2one(compute='_compute_dates',
  323. comodel_name='account.period',
  324. string="To period")
  325. valid = fields.Boolean(compute='_compute_dates',
  326. type='boolean',
  327. string='Valid')
  328. sequence = fields.Integer(string='Sequence', default=100)
  329. report_instance_id = fields.Many2one('mis.report.instance',
  330. string='Report Instance',
  331. ondelete='cascade')
  332. comparison_column_ids = fields.Many2many(
  333. comodel_name='mis.report.instance.period',
  334. relation='mis_report_instance_period_rel',
  335. column1='period_id',
  336. column2='compare_period_id',
  337. string='Compare with')
  338. normalize_factor = fields.Integer(
  339. string='Factor',
  340. help='Factor to use to normalize the period (used in comparison',
  341. default=1)
  342. _order = 'sequence, id'
  343. _sql_constraints = [
  344. ('duration', 'CHECK (duration>0)',
  345. 'Wrong duration, it must be positive!'),
  346. ('normalize_factor', 'CHECK (normalize_factor>0)',
  347. 'Wrong normalize factor, it must be positive!'),
  348. ('name_unique', 'unique(name, report_instance_id)',
  349. 'Period name should be unique by report'),
  350. ]
  351. @api.multi
  352. def _get_additional_move_line_filter(self):
  353. """ Prepare a filter to apply on all move lines
  354. This filter is applied with a AND operator on all
  355. accounting expression domains. This hook is intended
  356. to be inherited, and is useful to implement filtering
  357. on analytic dimensions or operational units.
  358. Returns an Odoo domain expression (a python list)
  359. compatible with account.move.line."""
  360. self.ensure_one()
  361. return []
  362. @api.multi
  363. def _get_additional_query_filter(self, query):
  364. """ Prepare an additional filter to apply on the query
  365. This filter is combined to the query domain with a AND
  366. operator. This hook is intended
  367. to be inherited, and is useful to implement filtering
  368. on analytic dimensions or operational units.
  369. Returns an Odoo domain expression (a python list)
  370. compatible with the model of the query."""
  371. self.ensure_one()
  372. return []
  373. @api.multi
  374. def drilldown(self, expr):
  375. assert len(self) == 1
  376. if AEP.has_account_var(expr):
  377. aep = AEP(self.env)
  378. aep.parse_expr(expr)
  379. aep.done_parsing(self.report_instance_id.root_account)
  380. domain = aep.get_aml_domain_for_expr(
  381. expr,
  382. self.date_from, self.date_to,
  383. self.period_from, self.period_to,
  384. self.report_instance_id.target_move)
  385. domain.extend(self._get_additional_move_line_filter())
  386. return {
  387. 'name': expr + ' - ' + self.name,
  388. 'domain': domain,
  389. 'type': 'ir.actions.act_window',
  390. 'res_model': 'account.move.line',
  391. 'views': [[False, 'list'], [False, 'form']],
  392. 'view_type': 'list',
  393. 'view_mode': 'list',
  394. 'target': 'current',
  395. }
  396. else:
  397. return False
  398. def _fetch_queries(self):
  399. assert len(self) == 1
  400. res = {}
  401. for query in self.report_instance_id.report_id.query_ids:
  402. model = self.env[query.model_id.model]
  403. eval_context = {
  404. 'env': self.env,
  405. 'time': time,
  406. 'datetime': datetime,
  407. 'dateutil': dateutil,
  408. # deprecated
  409. 'uid': self.env.uid,
  410. 'context': self.env.context,
  411. }
  412. domain = query.domain and \
  413. safe_eval(query.domain, eval_context) or []
  414. domain.extend(self._get_additional_query_filter(query))
  415. if query.date_field.ttype == 'date':
  416. domain.extend([(query.date_field.name, '>=', self.date_from),
  417. (query.date_field.name, '<=', self.date_to)])
  418. else:
  419. datetime_from = _utc_midnight(
  420. self.date_from, self._context.get('tz', 'UTC'))
  421. datetime_to = _utc_midnight(
  422. self.date_to, self._context.get('tz', 'UTC'), add_day=1)
  423. domain.extend([(query.date_field.name, '>=', datetime_from),
  424. (query.date_field.name, '<', datetime_to)])
  425. field_names = [f.name for f in query.field_ids]
  426. if not query.aggregate:
  427. data = model.search_read(domain, field_names)
  428. res[query.name] = [AutoStruct(**d) for d in data]
  429. elif query.aggregate == 'sum':
  430. data = model.read_group(
  431. domain, field_names, [])
  432. s = AutoStruct(count=data[0]['__count'])
  433. for field_name in field_names:
  434. v = data[0][field_name]
  435. setattr(s, field_name, v)
  436. res[query.name] = s
  437. else:
  438. data = model.search_read(domain, field_names)
  439. s = AutoStruct(count=len(data))
  440. if query.aggregate == 'min':
  441. agg = _min
  442. elif query.aggregate == 'max':
  443. agg = _max
  444. elif query.aggregate == 'avg':
  445. agg = _avg
  446. for field_name in field_names:
  447. setattr(s, field_name,
  448. agg([d[field_name] for d in data]))
  449. res[query.name] = s
  450. return res
  451. def _compute(self, lang_id, aep):
  452. res = {}
  453. localdict = {
  454. 'registry': self.pool,
  455. 'sum': _sum,
  456. 'min': _min,
  457. 'max': _max,
  458. 'len': len,
  459. 'avg': _avg,
  460. 'AccountingNone': AccountingNone,
  461. }
  462. localdict.update(self._fetch_queries())
  463. aep.do_queries(self.date_from, self.date_to,
  464. self.period_from, self.period_to,
  465. self.report_instance_id.target_move,
  466. self._get_additional_move_line_filter())
  467. compute_queue = self.report_instance_id.report_id.kpi_ids
  468. recompute_queue = []
  469. while True:
  470. for kpi in compute_queue:
  471. try:
  472. kpi_val_comment = kpi.name + " = " + kpi.expression
  473. kpi_eval_expression = aep.replace_expr(kpi.expression)
  474. kpi_val = safe_eval(kpi_eval_expression, localdict)
  475. localdict[kpi.name] = kpi_val
  476. except ZeroDivisionError:
  477. kpi_val = None
  478. kpi_val_rendered = '#DIV/0'
  479. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  480. except (NameError, ValueError):
  481. recompute_queue.append(kpi)
  482. kpi_val = None
  483. kpi_val_rendered = '#ERR'
  484. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  485. except:
  486. kpi_val = None
  487. kpi_val_rendered = '#ERR'
  488. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  489. else:
  490. kpi_val_rendered = kpi.render(lang_id, kpi_val)
  491. try:
  492. kpi_style = None
  493. if kpi.css_style:
  494. kpi_style = safe_eval(kpi.css_style, localdict)
  495. except:
  496. _logger.warning("error evaluating css stype expression %s",
  497. kpi.css_style, exc_info=True)
  498. kpi_style = None
  499. drilldown = (kpi_val is not None and
  500. AEP.has_account_var(kpi.expression))
  501. res[kpi.name] = {
  502. 'val': None if kpi_val is AccountingNone else kpi_val,
  503. 'val_r': kpi_val_rendered,
  504. 'val_c': kpi_val_comment,
  505. 'style': kpi_style,
  506. 'prefix': kpi.prefix,
  507. 'suffix': kpi.suffix,
  508. 'dp': kpi.dp,
  509. 'is_percentage': kpi.type == 'pct',
  510. 'period_id': self.id,
  511. 'expr': kpi.expression,
  512. 'drilldown': drilldown,
  513. }
  514. if len(recompute_queue) == 0:
  515. # nothing to recompute, we are done
  516. break
  517. if len(recompute_queue) == len(compute_queue):
  518. # could not compute anything in this iteration
  519. # (ie real Value errors or cyclic dependency)
  520. # so we stop trying
  521. break
  522. # try again
  523. compute_queue = recompute_queue
  524. recompute_queue = []
  525. return res
  526. class MisReportInstance(models.Model):
  527. """The MIS report instance combines everything to compute
  528. a MIS report template for a set of periods."""
  529. @api.one
  530. @api.depends('date')
  531. def _compute_pivot_date(self):
  532. if self.date:
  533. self.pivot_date = self.date
  534. else:
  535. self.pivot_date = fields.Date.context_today(self)
  536. _name = 'mis.report.instance'
  537. name = fields.Char(required=True,
  538. string='Name', translate=True)
  539. description = fields.Char(required=False,
  540. string='Description', translate=True)
  541. date = fields.Date(string='Base date',
  542. help='Report base date '
  543. '(leave empty to use current date)')
  544. pivot_date = fields.Date(compute='_compute_pivot_date',
  545. string="Pivot date")
  546. report_id = fields.Many2one('mis.report',
  547. required=True,
  548. string='Report')
  549. period_ids = fields.One2many('mis.report.instance.period',
  550. 'report_instance_id',
  551. required=True,
  552. string='Periods',
  553. copy=True)
  554. target_move = fields.Selection([('posted', 'All Posted Entries'),
  555. ('all', 'All Entries')],
  556. string='Target Moves',
  557. required=True,
  558. default='posted')
  559. company_id = fields.Many2one(comodel_name='res.company',
  560. string='Company',
  561. readonly=True,
  562. related='root_account.company_id',
  563. store=True)
  564. root_account = fields.Many2one(comodel_name='account.account',
  565. domain='[("parent_id", "=", False)]',
  566. string="Account chart",
  567. required=True)
  568. landscape_pdf = fields.Boolean(string='Landscape PDF')
  569. @api.one
  570. def copy(self, default=None):
  571. default = dict(default or {})
  572. default['name'] = _('%s (copy)') % self.name
  573. return super(MisReportInstance, self).copy(default)
  574. def _format_date(self, lang_id, date):
  575. # format date following user language
  576. date_format = self.env['res.lang'].browse(lang_id).date_format
  577. return datetime.datetime.strftime(
  578. fields.Date.from_string(date), date_format)
  579. @api.multi
  580. def preview(self):
  581. assert len(self) == 1
  582. view_id = self.env.ref('mis_builder.'
  583. 'mis_report_instance_result_view_form')
  584. return {
  585. 'type': 'ir.actions.act_window',
  586. 'res_model': 'mis.report.instance',
  587. 'res_id': self.id,
  588. 'view_mode': 'form',
  589. 'view_type': 'form',
  590. 'view_id': view_id.id,
  591. 'target': 'current',
  592. }
  593. @api.multi
  594. def print_pdf(self):
  595. self.ensure_one()
  596. data = {'context': self.env.context}
  597. return {
  598. 'name': 'MIS report instance QWEB PDF report',
  599. 'model': 'mis.report.instance',
  600. 'type': 'ir.actions.report.xml',
  601. 'report_name': 'mis_builder.report_mis_report_instance',
  602. 'report_type': 'qweb-pdf',
  603. 'context': self.env.context,
  604. 'data': data,
  605. }
  606. @api.multi
  607. def export_xls(self):
  608. self.ensure_one()
  609. return {
  610. 'name': 'MIS report instance XLS report',
  611. 'model': 'mis.report.instance',
  612. 'type': 'ir.actions.report.xml',
  613. 'report_name': 'mis.report.instance.xls',
  614. 'report_type': 'xls',
  615. 'context': self.env.context,
  616. }
  617. @api.multi
  618. def display_settings(self):
  619. assert len(self._ids) <= 1
  620. view_id = self.env.ref('mis_builder.mis_report_instance_view_form')
  621. return {
  622. 'type': 'ir.actions.act_window',
  623. 'res_model': 'mis.report.instance',
  624. 'res_id': self.id if self.id else False,
  625. 'view_mode': 'form',
  626. 'view_type': 'form',
  627. 'views': [(view_id.id, 'form')],
  628. 'view_id': view_id.id,
  629. 'target': 'current',
  630. }
  631. @api.multi
  632. def compute(self):
  633. assert len(self) == 1
  634. # prepare AccountingExpressionProcessor
  635. aep = AEP(self.env)
  636. for kpi in self.report_id.kpi_ids:
  637. aep.parse_expr(kpi.expression)
  638. aep.done_parsing(self.root_account)
  639. # fetch user language only once
  640. # TODO: is this necessary?
  641. lang = self.env.user.lang
  642. if not lang:
  643. lang = 'en_US'
  644. lang_id = self.env['res.lang'].search([('code', '=', lang)]).id
  645. # compute kpi values for each period
  646. kpi_values_by_period_ids = {}
  647. for period in self.period_ids:
  648. if not period.valid:
  649. continue
  650. kpi_values = period._compute(lang_id, aep)
  651. kpi_values_by_period_ids[period.id] = kpi_values
  652. # prepare header and content
  653. header = []
  654. header.append({
  655. 'kpi_name': '',
  656. 'cols': []
  657. })
  658. content = []
  659. rows_by_kpi_name = {}
  660. for kpi in self.report_id.kpi_ids:
  661. rows_by_kpi_name[kpi.name] = {
  662. 'kpi_name': kpi.description,
  663. 'cols': [],
  664. 'default_style': kpi.default_css_style
  665. }
  666. content.append(rows_by_kpi_name[kpi.name])
  667. # populate header and content
  668. for period in self.period_ids:
  669. if not period.valid:
  670. continue
  671. # add the column header
  672. if period.duration > 1 or period.type == 'w':
  673. # from, to
  674. if period.period_from and period.period_to:
  675. date_from = period.period_from.name
  676. date_to = period.period_to.name
  677. else:
  678. date_from = self._format_date(lang_id, period.date_from)
  679. date_to = self._format_date(lang_id, period.date_to)
  680. header_date = _('from %s to %s') % (date_from, date_to)
  681. else:
  682. # one period or one day
  683. if period.period_from and period.period_to:
  684. header_date = period.period_from.name
  685. else:
  686. header_date = self._format_date(lang_id, period.date_from)
  687. header[0]['cols'].append(dict(name=period.name, date=header_date))
  688. # add kpi values
  689. kpi_values = kpi_values_by_period_ids[period.id]
  690. for kpi_name in kpi_values:
  691. rows_by_kpi_name[kpi_name]['cols'].append(kpi_values[kpi_name])
  692. # add comparison columns
  693. for compare_col in period.comparison_column_ids:
  694. compare_kpi_values = \
  695. kpi_values_by_period_ids.get(compare_col.id)
  696. if compare_kpi_values:
  697. # add the comparison column header
  698. header[0]['cols'].append(
  699. dict(name=_('%s vs %s') % (period.name,
  700. compare_col.name),
  701. date=''))
  702. # add comparison values
  703. for kpi in self.report_id.kpi_ids:
  704. rows_by_kpi_name[kpi.name]['cols'].append({
  705. 'val_r': kpi.render_comparison(
  706. lang_id,
  707. kpi_values[kpi.name]['val'],
  708. compare_kpi_values[kpi.name]['val'],
  709. period.normalize_factor,
  710. compare_col.normalize_factor)
  711. })
  712. return {'header': header,
  713. 'content': content}