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.

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