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.

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