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.

728 lines
28 KiB

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