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.

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