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.

733 lines
29 KiB

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