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.

702 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
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 re
  26. import traceback
  27. import pytz
  28. from openerp import api, fields, models, _
  29. from openerp.tools.safe_eval import safe_eval
  30. from .aep import AccountingExpressionProcessor as AEP
  31. class AutoStruct(object):
  32. def __init__(self, **kwargs):
  33. for k, v in kwargs.items():
  34. setattr(self, k, v)
  35. def _get_selection_label(selection, value):
  36. for v, l in selection:
  37. if v == value:
  38. return l
  39. return ''
  40. def _utc_midnight(d, tz_name, add_day=0):
  41. d = fields.Date.from_string(d)
  42. if add_day:
  43. d = 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.registry['res.lang'].format(
  179. self.env.cr, self.env.uid, [lang_id],
  180. '%%%s.%df' % (sign, dp),
  181. value,
  182. grouping=True,
  183. context=self.env.context)
  184. value = u'%s\N{NO-BREAK SPACE}%s%s' % \
  185. (value, divider_label, suffix or '')
  186. value = value.replace('-', u'\N{NON-BREAKING HYPHEN}')
  187. return value
  188. class MisReportQuery(models.Model):
  189. """ A query to fetch arbitrary data for a MIS report.
  190. A query works on a model and has a domain and list of fields to fetch.
  191. At runtime, the domain is expanded with a "and" on the date/datetime field.
  192. """
  193. _name = 'mis.report.query'
  194. @api.one
  195. @api.depends('field_ids')
  196. def _compute_field_names(self):
  197. field_names = [field.name for field in self.field_ids]
  198. self.field_names = ', '.join(field_names)
  199. name = fields.Char(size=32, required=True,
  200. string='Name')
  201. model_id = fields.Many2one('ir.model', required=True,
  202. string='Model')
  203. field_ids = fields.Many2many('ir.model.fields', required=True,
  204. string='Fields to fetch')
  205. field_names = fields.Char(compute='_compute_field_names',
  206. string='Fetched fields name')
  207. aggregate = fields.Selection([('sum', _('Sum')),
  208. ('avg', _('Average')),
  209. ('min', _('Min')),
  210. ('max', _('Max'))],
  211. string='Aggregate')
  212. date_field = fields.Many2one('ir.model.fields', required=True,
  213. string='Date field',
  214. domain=[('ttype', 'in',
  215. ('date', 'datetime'))])
  216. domain = fields.Char(string='Domain')
  217. report_id = fields.Many2one('mis.report', string='Report',
  218. ondelete='cascade')
  219. _order = 'name'
  220. @api.one
  221. @api.constrains('name')
  222. def _check_name(self):
  223. return _is_valid_python_var(self.name)
  224. class MisReport(models.Model):
  225. """ A MIS report template (without period information)
  226. The MIS report holds:
  227. * a list of explicit queries; the result of each query is
  228. stored in a variable with same name as a query, containing as list
  229. of data structures populated with attributes for each fields to fetch;
  230. when queries have an aggregate method and no fields to group, it returns
  231. a data structure with the aggregated fields
  232. * a list of KPI to be evaluated based on the variables resulting
  233. from the accounting data and queries (KPI expressions can references
  234. queries and accounting expression - see AccoutingExpressionProcessor)
  235. """
  236. _name = 'mis.report'
  237. name = fields.Char(required=True,
  238. string='Name', translate=True)
  239. description = fields.Char(required=False,
  240. string='Description', translate=True)
  241. query_ids = fields.One2many('mis.report.query', 'report_id',
  242. string='Queries')
  243. kpi_ids = fields.One2many('mis.report.kpi', 'report_id',
  244. string='KPI\'s')
  245. # TODO: kpi name cannot be start with query name
  246. class MisReportInstancePeriod(models.Model):
  247. """ A MIS report instance has the logic to compute
  248. a report template for a given date period.
  249. Periods have a duration (day, week, fiscal period) and
  250. are defined as an offset relative to a pivot date.
  251. """
  252. @api.one
  253. @api.depends('report_instance_id.pivot_date', 'type', 'offset', 'duration')
  254. def _compute_dates(self):
  255. self.date_from = False
  256. self.date_to = False
  257. self.period_from = False
  258. self.period_to = False
  259. self.valid = False
  260. d = fields.Date.from_string(self.report_instance_id.pivot_date)
  261. if self.type == 'd':
  262. date_from = d + timedelta(days=self.offset)
  263. date_to = date_from + timedelta(days=self.duration - 1)
  264. self.date_from = fields.Date.to_string(date_from)
  265. self.date_to = fields.Date.to_string(date_to)
  266. self.valid = True
  267. elif self.type == 'w':
  268. date_from = d - timedelta(d.weekday())
  269. date_from = date_from + timedelta(days=self.offset * 7)
  270. date_to = date_from + timedelta(days=(7 * self.duration) - 1)
  271. self.date_from = fields.Date.to_string(date_from)
  272. self.date_to = fields.Date.to_string(date_to)
  273. self.valid = True
  274. elif self.type == 'fp':
  275. current_periods = self.env['account.period'].search(
  276. [('special', '=', False),
  277. ('date_start', '<=', d),
  278. ('date_stop', '>=', d),
  279. ('company_id', '=',
  280. self.report_instance_id.company_id.id)])
  281. if current_periods:
  282. all_periods = self.env['account.period'].search(
  283. [('special', '=', False),
  284. ('company_id', '=',
  285. self.report_instance_id.company_id.id)],
  286. order='date_start')
  287. all_period_ids = [p.id for p in all_periods]
  288. p = all_period_ids.index(current_periods[0].id) + self.offset
  289. if p >= 0 and p + self.duration <= len(all_period_ids):
  290. periods = all_periods[p:p + self.duration]
  291. self.date_from = periods[0].date_start
  292. self.date_to = periods[-1].date_stop
  293. self.period_from = periods[0]
  294. self.period_to = periods[-1]
  295. self.valid = True
  296. _name = 'mis.report.instance.period'
  297. name = fields.Char(size=32, required=True,
  298. string='Description', translate=True)
  299. type = fields.Selection([('d', _('Day')),
  300. ('w', _('Week')),
  301. ('fp', _('Fiscal Period')),
  302. # ('fy', _('Fiscal Year'))
  303. ],
  304. required=True,
  305. string='Period type')
  306. offset = fields.Integer(string='Offset',
  307. help='Offset from current period',
  308. default=-1)
  309. duration = fields.Integer(string='Duration',
  310. help='Number of periods',
  311. default=1)
  312. date_from = fields.Date(compute='_compute_dates', string="From")
  313. date_to = fields.Date(compute='_compute_dates', string="To")
  314. period_from = fields.Many2one(compute='_compute_dates',
  315. comodel_name='account.period',
  316. string="From period")
  317. period_to = fields.Many2one(compute='_compute_dates',
  318. comodel_name='account.period',
  319. string="To period")
  320. valid = fields.Boolean(compute='_compute_dates',
  321. type='boolean',
  322. string='Valid')
  323. sequence = fields.Integer(string='Sequence', default=100)
  324. report_instance_id = fields.Many2one('mis.report.instance',
  325. string='Report Instance',
  326. ondelete='cascade')
  327. comparison_column_ids = fields.Many2many(
  328. comodel_name='mis.report.instance.period',
  329. relation='mis_report_instance_period_rel',
  330. column1='period_id',
  331. column2='compare_period_id',
  332. string='Compare with')
  333. normalize_factor = fields.Integer(
  334. string='Factor',
  335. help='Factor to use to normalize the period (used in comparison',
  336. default=1)
  337. _order = 'sequence, id'
  338. _sql_constraints = [
  339. ('duration', 'CHECK (duration>0)',
  340. 'Wrong duration, it must be positive!'),
  341. ('normalize_factor', 'CHECK (normalize_factor>0)',
  342. 'Wrong normalize factor, it must be positive!'),
  343. ('name_unique', 'unique(name, report_instance_id)',
  344. 'Period name should be unique by report'),
  345. ]
  346. @api.multi
  347. def drilldown(self, expr):
  348. assert len(self) == 1
  349. if AEP.has_account_var(expr):
  350. aep = AEP(self.env)
  351. aep.parse_expr(expr)
  352. aep.done_parsing(self.report_instance_id.root_account)
  353. domain = aep.get_aml_domain_for_expr(
  354. expr,
  355. self.date_from, self.date_to,
  356. self.period_from, self.period_to,
  357. self.report_instance_id.target_move)
  358. return {
  359. 'name': expr + ' - ' + self.name,
  360. 'domain': domain,
  361. 'type': 'ir.actions.act_window',
  362. 'res_model': 'account.move.line',
  363. 'views': [[False, 'list'], [False, 'form']],
  364. 'view_type': 'list',
  365. 'view_mode': 'list',
  366. 'target': 'current',
  367. }
  368. else:
  369. return False
  370. def _fetch_queries(self):
  371. assert len(self) == 1
  372. res = {}
  373. for query in self.report_instance_id.report_id.query_ids:
  374. model = self.env[query.model_id.model]
  375. domain = query.domain and safe_eval(query.domain) or []
  376. if query.date_field.ttype == 'date':
  377. domain.extend([(query.date_field.name, '>=', self.date_from),
  378. (query.date_field.name, '<=', self.date_to)])
  379. else:
  380. datetime_from = _utc_midnight(
  381. self.date_from, self._context.get('tz', 'UTC'))
  382. datetime_to = _utc_midnight(
  383. self.date_to, self._context.get('tz', 'UTC'), add_day=1)
  384. domain.extend([(query.date_field.name, '>=', datetime_from),
  385. (query.date_field.name, '<', datetime_to)])
  386. # TODO: we probably don't need company_id here
  387. if model._columns.get('company_id'):
  388. domain.extend(['|', ('company_id', '=', False),
  389. ('company_id', '=',
  390. self.report_instance_id.company_id.id)])
  391. field_names = [f.name for f in query.field_ids]
  392. if not query.aggregate:
  393. data = model.search_read(domain, field_names)
  394. res[query.name] = [AutoStruct(**d) for d in data]
  395. elif query.aggregate == 'sum':
  396. data = model.read_group(
  397. domain, field_names, [])
  398. s = AutoStruct(count=data[0]['__count'])
  399. for field_name in field_names:
  400. v = data[0][field_name]
  401. setattr(s, field_name, v)
  402. res[query.name] = s
  403. else:
  404. data = model.search_read(domain, field_names)
  405. s = AutoStruct(count=len(data))
  406. if query.aggregate == 'min':
  407. agg = min
  408. elif query.aggregate == 'max':
  409. agg = max
  410. elif query.aggregate == 'avg':
  411. agg = lambda l: sum(l) / float(len(l))
  412. for field_name in field_names:
  413. setattr(s, field_name,
  414. agg([d[field_name] for d in data]))
  415. res[query.name] = s
  416. return res
  417. def _compute(self, lang_id, aep):
  418. res = {}
  419. localdict = {
  420. 'registry': self.pool,
  421. 'sum': sum,
  422. 'min': min,
  423. 'max': max,
  424. 'len': len,
  425. 'avg': lambda l: sum(l) / float(len(l)),
  426. }
  427. localdict.update(self._fetch_queries())
  428. aep.do_queries(self.date_from, self.date_to,
  429. self.period_from, self.period_to,
  430. self.report_instance_id.target_move)
  431. compute_queue = self.report_instance_id.report_id.kpi_ids
  432. recompute_queue = []
  433. while True:
  434. for kpi in compute_queue:
  435. try:
  436. kpi_val_comment = kpi.name + " = " + kpi.expression
  437. kpi_eval_expression = aep.replace_expr(kpi.expression)
  438. kpi_val = safe_eval(kpi_eval_expression, localdict)
  439. except ZeroDivisionError:
  440. kpi_val = None
  441. kpi_val_rendered = '#DIV/0'
  442. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  443. except (NameError, ValueError):
  444. recompute_queue.append(kpi)
  445. kpi_val = None
  446. kpi_val_rendered = '#ERR'
  447. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  448. except:
  449. kpi_val = None
  450. kpi_val_rendered = '#ERR'
  451. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  452. else:
  453. kpi_val_rendered = kpi.render(lang_id, kpi_val)
  454. localdict[kpi.name] = kpi_val
  455. try:
  456. kpi_style = None
  457. if kpi.css_style:
  458. kpi_style = safe_eval(kpi.css_style, localdict)
  459. except:
  460. # TODO: log warning
  461. kpi_style = None
  462. drilldown = (kpi_val is not None and
  463. AEP.has_account_var(kpi.expression))
  464. res[kpi.name] = {
  465. 'val': kpi_val,
  466. 'val_r': kpi_val_rendered,
  467. 'val_c': kpi_val_comment,
  468. 'style': kpi_style,
  469. 'suffix': kpi.suffix,
  470. 'dp': kpi.dp,
  471. 'is_percentage': kpi.type == 'pct',
  472. 'period_id': self.id,
  473. 'expr': kpi.expression,
  474. 'drilldown': drilldown,
  475. }
  476. if len(recompute_queue) == 0:
  477. # nothing to recompute, we are done
  478. break
  479. if len(recompute_queue) == len(compute_queue):
  480. # could not compute anything in this iteration
  481. # (ie real Value errors or cyclic dependency)
  482. # so we stop trying
  483. break
  484. # try again
  485. compute_queue = recompute_queue
  486. recompute_queue = []
  487. return res
  488. class MisReportInstance(models.Model):
  489. """The MIS report instance combines everything to compute
  490. a MIS report template for a set of periods."""
  491. @api.one
  492. @api.depends('date')
  493. def _compute_pivot_date(self):
  494. if self.date:
  495. self.pivot_date = self.date
  496. else:
  497. self.pivot_date = fields.Date.context_today(self)
  498. _name = 'mis.report.instance'
  499. name = fields.Char(required=True,
  500. string='Name', translate=True)
  501. description = fields.Char(required=False,
  502. string='Description', translate=True)
  503. date = fields.Date(string='Base date',
  504. help='Report base date '
  505. '(leave empty to use current date)')
  506. pivot_date = fields.Date(compute='_compute_pivot_date',
  507. string="Pivot date")
  508. report_id = fields.Many2one('mis.report',
  509. required=True,
  510. string='Report')
  511. period_ids = fields.One2many('mis.report.instance.period',
  512. 'report_instance_id',
  513. required=True,
  514. string='Periods')
  515. target_move = fields.Selection([('posted', 'All Posted Entries'),
  516. ('all', 'All Entries')],
  517. string='Target Moves',
  518. required=True,
  519. default='posted')
  520. company_id = fields.Many2one(comodel_name='res.company',
  521. string='Company',
  522. readonly=True,
  523. related='root_account.company_id',
  524. store=True)
  525. root_account = fields.Many2one(comodel_name='account.account',
  526. domain='[("parent_id", "=", False)]',
  527. string="Account chart",
  528. required=True)
  529. landscape_pdf = fields.Boolean(string='Landscape PDF')
  530. def _format_date(self, lang_id, date):
  531. # format date following user language
  532. date_format = self.env['res.lang'].browse(lang_id).date_format
  533. return datetime.strftime(fields.Date.from_string(date), date_format)
  534. @api.multi
  535. def preview(self):
  536. assert len(self) == 1
  537. view_id = self.env.ref('mis_builder.'
  538. 'mis_report_instance_result_view_form')
  539. return {
  540. 'type': 'ir.actions.act_window',
  541. 'res_model': 'mis.report.instance',
  542. 'res_id': self.id,
  543. 'view_mode': 'form',
  544. 'view_type': 'form',
  545. 'view_id': view_id.id,
  546. 'target': 'new',
  547. }
  548. @api.multi
  549. def compute(self):
  550. assert len(self) == 1
  551. # prepare AccountingExpressionProcessor
  552. aep = AEP(self.env)
  553. for kpi in self.report_id.kpi_ids:
  554. aep.parse_expr(kpi.expression)
  555. aep.done_parsing(self.root_account)
  556. # fetch user language only once
  557. # TODO: is this necessary?
  558. lang = self.env.user.lang
  559. if not lang:
  560. lang = 'en_US'
  561. lang_id = self.env['res.lang'].search([('code', '=', lang)]).id
  562. # compute kpi values for each period
  563. kpi_values_by_period_ids = {}
  564. for period in self.period_ids:
  565. if not period.valid:
  566. continue
  567. kpi_values = period._compute(lang_id, aep)
  568. kpi_values_by_period_ids[period.id] = kpi_values
  569. # prepare header and content
  570. header = []
  571. header.append({
  572. 'kpi_name': '',
  573. 'cols': []
  574. })
  575. content = []
  576. rows_by_kpi_name = {}
  577. for kpi in self.report_id.kpi_ids:
  578. rows_by_kpi_name[kpi.name] = {
  579. 'kpi_name': kpi.description,
  580. 'cols': [],
  581. 'default_style': kpi.default_css_style
  582. }
  583. content.append(rows_by_kpi_name[kpi.name])
  584. # populate header and content
  585. for period in self.period_ids:
  586. if not period.valid:
  587. continue
  588. # add the column header
  589. # TODO: format period.date_from
  590. header[0]['cols'].append(dict(
  591. name=period.name,
  592. date=(period.duration > 1 or period.type == 'w') and
  593. _('from %s to %s' %
  594. (period.period_from and period.period_from.name
  595. or self._format_date(lang_id, period.date_from),
  596. period.period_to and period.period_to.name
  597. or self._format_date(lang_id, period.date_to)))
  598. or period.period_from and period.period_from.name or
  599. period.date_from))
  600. # add kpi values
  601. kpi_values = kpi_values_by_period_ids[period.id]
  602. for kpi_name in kpi_values:
  603. rows_by_kpi_name[kpi_name]['cols'].append(kpi_values[kpi_name])
  604. # add comparison columns
  605. for compare_col in period.comparison_column_ids:
  606. compare_kpi_values = \
  607. kpi_values_by_period_ids.get(compare_col.id)
  608. if compare_kpi_values:
  609. # add the comparison column header
  610. # TODO: make 'vs' translatable
  611. header[0]['cols'].append(
  612. dict(name='%s vs %s' % (period.name, compare_col.name),
  613. date=''))
  614. # add comparison values
  615. for kpi in self.report_id.kpi_ids:
  616. rows_by_kpi_name[kpi.name]['cols'].append({
  617. 'val_r': kpi.render_comparison(
  618. lang_id,
  619. kpi_values[kpi.name]['val'],
  620. compare_kpi_values[kpi.name]['val'],
  621. period.normalize_factor,
  622. compare_col.normalize_factor)
  623. })
  624. return {'header': header,
  625. 'content': content}