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.

728 lines
28 KiB

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