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.

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