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.

703 lines
28 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 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. # TODO: change compare_method, divider and dp for all 3 types
  118. if self.type == 'pct':
  119. self.compare_method = 'diff'
  120. elif self.type == 'str':
  121. self.compare_method = 'none'
  122. self.divider = ''
  123. self.dp = 0
  124. def render(self, lang_id, value):
  125. """ render a KPI value as a unicode string, ready for display """
  126. assert len(self) == 1
  127. if value is None:
  128. return '#N/A'
  129. elif self.type == 'num':
  130. return self._render_num(lang_id, value, self.divider,
  131. self.dp, self.suffix)
  132. elif self.type == 'pct':
  133. return self._render_num(lang_id, value, 0.01,
  134. self.dp, '%')
  135. else:
  136. return unicode(value)
  137. def render_comparison(self, lang_id, value, base_value,
  138. average_value, average_base_value):
  139. """ render the comparison of two KPI values, ready for display """
  140. assert len(self) == 1
  141. if value is None or base_value is None:
  142. return ''
  143. if self.type == 'pct':
  144. return self._render_num(
  145. lang_id,
  146. value - base_value,
  147. 0.01, self.dp, _('pp'), sign='+')
  148. elif self.type == 'num':
  149. if average_value:
  150. value = value / float(average_value)
  151. if average_base_value:
  152. base_value = base_value / float(average_base_value)
  153. if self.compare_method == 'diff':
  154. return self._render_num(
  155. lang_id,
  156. value - base_value,
  157. self.divider, self.dp, self.suffix, sign='+')
  158. elif self.compare_method == 'pct':
  159. if round(base_value, self.dp) != 0:
  160. return self._render_num(
  161. lang_id,
  162. (value - base_value) / abs(base_value),
  163. 0.01, self.dp, '%', sign='+')
  164. return ''
  165. def _render_num(self, lang_id, value, divider,
  166. dp, suffix, sign='-'):
  167. divider_label = _get_selection_label(
  168. self._columns['divider'].selection, divider)
  169. if divider_label == '1':
  170. divider_label = ''
  171. # format number following user language
  172. value = round(value / float(divider or 1), dp) or 0
  173. value = self.env.registry['res.lang'].format(
  174. self.env.cr, self.env.uid, [lang_id],
  175. '%%%s.%df' % (sign, dp),
  176. value,
  177. grouping=True,
  178. context=self.env.context)
  179. value = u'%s\N{NO-BREAK SPACE}%s%s' % \
  180. (value, divider_label, suffix or '')
  181. value = value.replace('-', u'\N{NON-BREAKING HYPHEN}')
  182. return value
  183. class MisReportQuery(models.Model):
  184. """ A query to fetch arbitrary data for a MIS report.
  185. A query works on a model and has a domain and list of fields to fetch.
  186. At runtime, the domain is expanded with a "and" on the date/datetime field.
  187. """
  188. _name = 'mis.report.query'
  189. @api.one
  190. @api.depends('field_ids')
  191. def _compute_field_names(self):
  192. field_names = [field.name for field in self.field_ids]
  193. self.field_names = ', '.join(field_names)
  194. name = fields.Char(size=32, required=True,
  195. string='Name')
  196. model_id = fields.Many2one('ir.model', required=True,
  197. string='Model')
  198. field_ids = fields.Many2many('ir.model.fields', required=True,
  199. string='Fields to fetch')
  200. field_names = fields.Char(compute='_compute_field_names',
  201. string='Fetched fields name')
  202. aggregate = fields.Selection([('sum', _('Sum')),
  203. ('avg', _('Average')),
  204. ('min', _('Min')),
  205. ('max', _('Max'))],
  206. string='Aggregate')
  207. date_field = fields.Many2one('ir.model.fields', required=True,
  208. string='Date field',
  209. domain=[('ttype', 'in',
  210. ('date', 'datetime'))])
  211. domain = fields.Char(string='Domain')
  212. report_id = fields.Many2one('mis.report', string='Report',
  213. ondelete='cascade')
  214. _order = 'name'
  215. @api.one
  216. @api.constrains('name')
  217. def _check_name(self):
  218. return _is_valid_python_var(self.name)
  219. class MisReport(models.Model):
  220. """ A MIS report template (without period information)
  221. The MIS report holds:
  222. * a list of explicit queries; the result of each query is
  223. stored in a variable with same name as a query, containing as list
  224. of data structures populated with attributes for each fields to fetch;
  225. when queries have an aggregate method and no fields to group, it returns
  226. a data structure with the aggregated fields
  227. * a list of KPI to be evaluated based on the variables resulting
  228. from the accounting data and queries (KPI expressions can references
  229. queries and accounting expression - see AccoutingExpressionProcessor)
  230. """
  231. _name = 'mis.report'
  232. name = fields.Char(required=True,
  233. string='Name', translate=True)
  234. description = fields.Char(required=False,
  235. string='Description', translate=True)
  236. query_ids = fields.One2many('mis.report.query', 'report_id',
  237. string='Queries')
  238. kpi_ids = fields.One2many('mis.report.kpi', 'report_id',
  239. string='KPI\'s')
  240. # TODO: kpi name cannot be start with query name
  241. class MisReportInstancePeriod(models.Model):
  242. """ A MIS report instance has the logic to compute
  243. a report template for a given date period.
  244. Periods have a duration (day, week, fiscal period) and
  245. are defined as an offset relative to a pivot date.
  246. """
  247. @api.one
  248. @api.depends('report_instance_id.pivot_date', 'type', 'offset', 'duration')
  249. def _compute_dates(self):
  250. self.date_from = False
  251. self.date_to = False
  252. self.period_from = False
  253. self.period_to = False
  254. self.valid = False
  255. d = fields.Date.from_string(self.report_instance_id.pivot_date)
  256. if self.type == 'd':
  257. date_from = d + timedelta(days=self.offset)
  258. date_to = date_from + timedelta(days=self.duration - 1)
  259. self.date_from = fields.Date.to_string(date_from)
  260. self.date_to = fields.Date.to_string(date_to)
  261. self.valid = True
  262. elif self.type == 'w':
  263. date_from = d - timedelta(d.weekday())
  264. date_from = date_from + timedelta(days=self.offset * 7)
  265. date_to = date_from + timedelta(days=(7 * 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 == 'fp':
  270. current_periods = self.env['account.period'].search(
  271. [('special', '=', False),
  272. ('date_start', '<=', d),
  273. ('date_stop', '>=', d),
  274. ('company_id', '=',
  275. self.report_instance_id.company_id.id)])
  276. if current_periods:
  277. all_periods = self.env['account.period'].search(
  278. [('special', '=', False),
  279. ('company_id', '=',
  280. self.report_instance_id.company_id.id)],
  281. order='date_start')
  282. all_period_ids = [p.id for p in all_periods]
  283. p = all_period_ids.index(current_periods[0].id) + self.offset
  284. if p >= 0 and p + self.duration <= len(all_period_ids):
  285. periods = all_periods[p:p + self.duration]
  286. self.date_from = periods[0].date_start
  287. self.date_to = periods[-1].date_stop
  288. self.period_from = periods[0]
  289. self.period_to = periods[-1]
  290. self.valid = True
  291. _name = 'mis.report.instance.period'
  292. name = fields.Char(size=32, required=True,
  293. string='Description', translate=True)
  294. type = fields.Selection([('d', _('Day')),
  295. ('w', _('Week')),
  296. ('fp', _('Fiscal Period')),
  297. # ('fy', _('Fiscal Year'))
  298. ],
  299. required=True,
  300. string='Period type')
  301. offset = fields.Integer(string='Offset',
  302. help='Offset from current period',
  303. default=-1)
  304. duration = fields.Integer(string='Duration',
  305. help='Number of periods',
  306. default=1)
  307. date_from = fields.Date(compute='_compute_dates', string="From")
  308. date_to = fields.Date(compute='_compute_dates', string="To")
  309. period_from = fields.Many2one(compute='_compute_dates',
  310. comodel_name='account.period',
  311. string="From period")
  312. period_to = fields.Many2one(compute='_compute_dates',
  313. comodel_name='account.period',
  314. string="To period")
  315. valid = fields.Boolean(compute='_compute_dates',
  316. type='boolean',
  317. string='Valid')
  318. sequence = fields.Integer(string='Sequence', default=100)
  319. report_instance_id = fields.Many2one('mis.report.instance',
  320. string='Report Instance',
  321. ondelete='cascade')
  322. comparison_column_ids = fields.Many2many(
  323. comodel_name='mis.report.instance.period',
  324. relation='mis_report_instance_period_rel',
  325. column1='period_id',
  326. column2='compare_period_id',
  327. string='Compare with')
  328. normalize_factor = fields.Integer(
  329. string='Factor',
  330. help='Factor to use to normalize the period (used in comparison',
  331. default=1)
  332. _order = 'sequence, id'
  333. _sql_constraints = [
  334. ('duration', 'CHECK (duration>0)',
  335. 'Wrong duration, it must be positive!'),
  336. ('normalize_factor', 'CHECK (normalize_factor>0)',
  337. 'Wrong normalize factor, it must be positive!'),
  338. ('name_unique', 'unique(name, report_instance_id)',
  339. 'Period name should be unique by report'),
  340. ]
  341. @api.multi
  342. def drilldown(self, expr):
  343. assert len(self) == 1
  344. if AEP.has_account_var(expr):
  345. aep = AEP(self.env)
  346. aep.parse_expr(expr)
  347. aep.done_parsing(self.report_instance_id.root_account)
  348. domain = aep.get_aml_domain_for_expr(
  349. expr,
  350. self.date_from, self.date_to,
  351. self.period_from, self.period_to,
  352. self.report_instance_id.target_move)
  353. return {
  354. 'name': expr + ' - ' + self.name,
  355. 'domain': domain,
  356. 'type': 'ir.actions.act_window',
  357. 'res_model': 'account.move.line',
  358. 'views': [[False, 'list'], [False, 'form']],
  359. 'view_type': 'list',
  360. 'view_mode': 'list',
  361. 'target': 'current',
  362. }
  363. else:
  364. return False
  365. def _fetch_queries(self):
  366. assert len(self) == 1
  367. res = {}
  368. for query in self.report_instance_id.report_id.query_ids:
  369. model = self.env[query.model_id.model]
  370. domain = query.domain and safe_eval(query.domain) or []
  371. if query.date_field.ttype == 'date':
  372. domain.extend([(query.date_field.name, '>=', self.date_from),
  373. (query.date_field.name, '<=', self.date_to)])
  374. else:
  375. datetime_from = _utc_midnight(
  376. self.date_from, self._context.get('tz', 'UTC'))
  377. datetime_to = _utc_midnight(
  378. self.date_to, self._context.get('tz', 'UTC'), add_day=1)
  379. domain.extend([(query.date_field.name, '>=', datetime_from),
  380. (query.date_field.name, '<', datetime_to)])
  381. # TODO: we probably don't need company_id here
  382. if model._columns.get('company_id'):
  383. domain.extend(['|', ('company_id', '=', False),
  384. ('company_id', '=',
  385. self.report_instance_id.company_id.id)])
  386. field_names = [f.name for f in query.field_ids]
  387. if not query.aggregate:
  388. data = model.search_read(domain, field_names)
  389. res[query.name] = [AutoStruct(**d) for d in data]
  390. elif query.aggregate == 'sum':
  391. data = model.read_group(
  392. domain, field_names, [])
  393. s = AutoStruct(count=data[0]['__count'])
  394. for field_name in field_names:
  395. v = data[0][field_name]
  396. setattr(s, field_name, v)
  397. res[query.name] = s
  398. else:
  399. data = model.search_read(domain, field_names)
  400. s = AutoStruct(count=len(data))
  401. if query.aggregate == 'min':
  402. agg = min
  403. elif query.aggregate == 'max':
  404. agg = max
  405. elif query.aggregate == 'avg':
  406. agg = lambda l: sum(l) / float(len(l))
  407. for field_name in field_names:
  408. setattr(s, field_name,
  409. agg([d[field_name] for d in data]))
  410. res[query.name] = s
  411. return res
  412. def _compute(self, lang_id, aep):
  413. res = {}
  414. localdict = {
  415. 'registry': self.pool,
  416. 'sum': sum,
  417. 'min': min,
  418. 'max': max,
  419. 'len': len,
  420. 'avg': lambda l: sum(l) / float(len(l)),
  421. }
  422. localdict.update(self._fetch_queries())
  423. aep.do_queries(self.date_from, self.date_to,
  424. self.period_from, self.period_to,
  425. self.report_instance_id.target_move)
  426. compute_queue = self.report_instance_id.report_id.kpi_ids
  427. recompute_queue = []
  428. while True:
  429. for kpi in compute_queue:
  430. try:
  431. kpi_val_comment = kpi.name + " = " + kpi.expression
  432. kpi_eval_expression = aep.replace_expr(kpi.expression)
  433. kpi_val = safe_eval(kpi_eval_expression, localdict)
  434. except ZeroDivisionError:
  435. kpi_val = None
  436. kpi_val_rendered = '#DIV/0'
  437. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  438. except (NameError, ValueError):
  439. recompute_queue.append(kpi)
  440. kpi_val = None
  441. kpi_val_rendered = '#ERR'
  442. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  443. except:
  444. kpi_val = None
  445. kpi_val_rendered = '#ERR'
  446. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  447. else:
  448. kpi_val_rendered = kpi.render(lang_id, kpi_val)
  449. localdict[kpi.name] = kpi_val
  450. try:
  451. kpi_style = None
  452. if kpi.css_style:
  453. kpi_style = safe_eval(kpi.css_style, localdict)
  454. except:
  455. # TODO: log warning
  456. kpi_style = None
  457. drilldown = (kpi_val is not None and
  458. AEP.has_account_var(kpi.expression))
  459. res[kpi.name] = {
  460. 'val': kpi_val,
  461. 'val_r': kpi_val_rendered,
  462. 'val_c': kpi_val_comment,
  463. 'style': kpi_style,
  464. 'suffix': kpi.suffix,
  465. 'dp': kpi.dp,
  466. 'is_percentage': kpi.type == 'pct',
  467. 'period_id': self.id,
  468. 'expr': kpi.expression,
  469. 'drilldown': drilldown,
  470. }
  471. if len(recompute_queue) == 0:
  472. # nothing to recompute, we are done
  473. break
  474. if len(recompute_queue) == len(compute_queue):
  475. # could not compute anything in this iteration
  476. # (ie real Value errors or cyclic dependency)
  477. # so we stop trying
  478. break
  479. # try again
  480. compute_queue = recompute_queue
  481. recompute_queue = []
  482. return res
  483. class MisReportInstance(models.Model):
  484. """The MIS report instance combines everything to compute
  485. a MIS report template for a set of periods."""
  486. @api.one
  487. @api.depends('date')
  488. def _compute_pivot_date(self):
  489. if self.date:
  490. self.pivot_date = self.date
  491. else:
  492. self.pivot_date = fields.Date.context_today(self)
  493. @api.one
  494. @api.depends('company_id')
  495. def _compute_root_account(self):
  496. self.root_account = False
  497. accounts = self.env['account.account'].search(
  498. [('parent_id', '=', False),
  499. ('company_id', '=', self.company_id.id)])
  500. if len(accounts) == 1:
  501. self.root_account = accounts[0]
  502. _name = 'mis.report.instance'
  503. name = fields.Char(required=True,
  504. string='Name', translate=True)
  505. description = fields.Char(required=False,
  506. string='Description', translate=True)
  507. date = fields.Date(string='Base date',
  508. help='Report base date '
  509. '(leave empty to use current date)')
  510. pivot_date = fields.Date(compute='_compute_pivot_date',
  511. string="Pivot date")
  512. report_id = fields.Many2one('mis.report',
  513. required=True,
  514. string='Report')
  515. period_ids = fields.One2many('mis.report.instance.period',
  516. 'report_instance_id',
  517. required=True,
  518. string='Periods')
  519. target_move = fields.Selection([('posted', 'All Posted Entries'),
  520. ('all', 'All Entries')],
  521. string='Target Moves', required=True,
  522. default='posted')
  523. company_id = fields.Many2one('res.company', 'Company', required=True,
  524. default=lambda self: self.env['res.company'].
  525. _company_default_get('mis.report.instance'))
  526. root_account = fields.Many2one(compute='_compute_root_account',
  527. comodel_name='account.account',
  528. string="Account chart")
  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}