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.

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