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.

750 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. If the difference is 0, an empty string is returned.
  133. """
  134. assert len(self) == 1
  135. if value is None:
  136. value = AccountingNone
  137. if base_value is None:
  138. base_value = AccountingNone
  139. if self.type == 'pct':
  140. delta = value - base_value
  141. if delta and round(delta, self.dp) != 0:
  142. return self._render_num(
  143. lang_id,
  144. delta,
  145. 0.01, self.dp, '', _('pp'),
  146. sign='+')
  147. elif self.type == 'num':
  148. if value and average_value:
  149. value = value / float(average_value)
  150. if base_value and average_base_value:
  151. base_value = base_value / float(average_base_value)
  152. if self.compare_method == 'diff':
  153. delta = value - base_value
  154. if delta and round(delta, self.dp) != 0:
  155. return self._render_num(
  156. lang_id,
  157. delta,
  158. self.divider, self.dp, self.prefix, self.suffix,
  159. sign='+')
  160. elif self.compare_method == 'pct':
  161. if base_value and round(base_value, self.dp) != 0:
  162. delta = (value - base_value) / abs(base_value)
  163. if delta and round(delta, self.dp) != 0:
  164. return self._render_num(
  165. lang_id,
  166. delta,
  167. 0.01, self.dp, '', '%',
  168. sign='+')
  169. return ''
  170. def _render_num(self, lang_id, value, divider,
  171. dp, prefix, suffix, sign='-'):
  172. divider_label = _get_selection_label(
  173. self._columns['divider'].selection, divider)
  174. if divider_label == '1':
  175. divider_label = ''
  176. # format number following user language
  177. value = round(value / float(divider or 1), dp) or 0
  178. value = self.env['res.lang'].browse(lang_id).format(
  179. '%%%s.%df' % (sign, dp),
  180. value,
  181. grouping=True)
  182. value = u'%s\N{NARROW NO-BREAK SPACE}%s\N{NO-BREAK SPACE}%s%s' % \
  183. (prefix or '', value, divider_label, suffix or '')
  184. value = value.replace('-', u'\N{NON-BREAKING HYPHEN}')
  185. return value
  186. class MisReportQuery(models.Model):
  187. """ A query to fetch arbitrary data for a MIS report.
  188. A query works on a model and has a domain and list of fields to fetch.
  189. At runtime, the domain is expanded with a "and" on the date/datetime field.
  190. """
  191. _name = 'mis.report.query'
  192. @api.one
  193. @api.depends('field_ids')
  194. def _compute_field_names(self):
  195. field_names = [field.name for field in self.field_ids]
  196. self.field_names = ', '.join(field_names)
  197. name = fields.Char(size=32, required=True,
  198. string='Name')
  199. model_id = fields.Many2one('ir.model', required=True,
  200. string='Model')
  201. field_ids = fields.Many2many('ir.model.fields', required=True,
  202. string='Fields to fetch')
  203. field_names = fields.Char(compute='_compute_field_names',
  204. string='Fetched fields name')
  205. aggregate = fields.Selection([('sum', _('Sum')),
  206. ('avg', _('Average')),
  207. ('min', _('Min')),
  208. ('max', _('Max'))],
  209. string='Aggregate')
  210. date_field = fields.Many2one('ir.model.fields', required=True,
  211. string='Date field',
  212. domain=[('ttype', 'in',
  213. ('date', 'datetime'))])
  214. domain = fields.Char(string='Domain')
  215. report_id = fields.Many2one('mis.report', string='Report',
  216. ondelete='cascade')
  217. _order = 'name'
  218. @api.one
  219. @api.constrains('name')
  220. def _check_name(self):
  221. if not _is_valid_python_var(self.name):
  222. raise exceptions.Warning(_('The name must be a valid '
  223. 'python identifier'))
  224. class MisReport(models.Model):
  225. """ A MIS report template (without period information)
  226. The MIS report holds:
  227. * a list of explicit queries; the result of each query is
  228. stored in a variable with same name as a query, containing as list
  229. of data structures populated with attributes for each fields to fetch;
  230. when queries have an aggregate method and no fields to group, it returns
  231. a data structure with the aggregated fields
  232. * a list of KPI to be evaluated based on the variables resulting
  233. from the accounting data and queries (KPI expressions can references
  234. queries and accounting expression - see AccoutingExpressionProcessor)
  235. """
  236. _name = 'mis.report'
  237. name = fields.Char(required=True,
  238. string='Name', translate=True)
  239. description = fields.Char(required=False,
  240. string='Description', translate=True)
  241. query_ids = fields.One2many('mis.report.query', 'report_id',
  242. string='Queries',
  243. copy=True)
  244. kpi_ids = fields.One2many('mis.report.kpi', 'report_id',
  245. string='KPI\'s',
  246. copy=True)
  247. @api.one
  248. def copy(self, default=None):
  249. default = dict(default or {})
  250. default['name'] = _('%s (copy)') % self.name
  251. return super(MisReport, self).copy(default)
  252. # TODO: kpi name cannot be start with query name
  253. class MisReportInstancePeriod(models.Model):
  254. """ A MIS report instance has the logic to compute
  255. a report template for a given date period.
  256. Periods have a duration (day, week, fiscal period) and
  257. are defined as an offset relative to a pivot date.
  258. """
  259. @api.one
  260. @api.depends('report_instance_id.pivot_date', 'type', 'offset', 'duration')
  261. def _compute_dates(self):
  262. self.date_from = False
  263. self.date_to = False
  264. self.valid = False
  265. d = fields.Date.from_string(self.report_instance_id.pivot_date)
  266. if self.type == 'd':
  267. date_from = d + datetime.timedelta(days=self.offset)
  268. date_to = date_from + \
  269. datetime.timedelta(days=self.duration - 1)
  270. self.date_from = fields.Date.to_string(date_from)
  271. self.date_to = fields.Date.to_string(date_to)
  272. self.valid = True
  273. elif self.type == 'w':
  274. date_from = d - datetime.timedelta(d.weekday())
  275. date_from = date_from + datetime.timedelta(days=self.offset * 7)
  276. date_to = date_from + \
  277. datetime.timedelta(days=(7 * self.duration) - 1)
  278. self.date_from = fields.Date.to_string(date_from)
  279. self.date_to = fields.Date.to_string(date_to)
  280. self.valid = True
  281. _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. # ('fy', _('Fiscal Year'))
  287. ],
  288. required=True,
  289. string='Period type')
  290. offset = fields.Integer(string='Offset',
  291. help='Offset from current period',
  292. default=-1)
  293. duration = fields.Integer(string='Duration',
  294. help='Number of periods',
  295. default=1)
  296. date_from = fields.Date(compute='_compute_dates', string="From")
  297. date_to = fields.Date(compute='_compute_dates', string="To")
  298. valid = fields.Boolean(compute='_compute_dates',
  299. type='boolean',
  300. string='Valid')
  301. sequence = fields.Integer(string='Sequence', default=100)
  302. report_instance_id = fields.Many2one('mis.report.instance',
  303. string='Report Instance',
  304. ondelete='cascade')
  305. comparison_column_ids = fields.Many2many(
  306. comodel_name='mis.report.instance.period',
  307. relation='mis_report_instance_period_rel',
  308. column1='period_id',
  309. column2='compare_period_id',
  310. string='Compare with')
  311. normalize_factor = fields.Integer(
  312. string='Factor',
  313. help='Factor to use to normalize the period (used in comparison',
  314. default=1)
  315. _order = 'sequence, id'
  316. _sql_constraints = [
  317. ('duration', 'CHECK (duration>0)',
  318. 'Wrong duration, it must be positive!'),
  319. ('normalize_factor', 'CHECK (normalize_factor>0)',
  320. 'Wrong normalize factor, it must be positive!'),
  321. ('name_unique', 'unique(name, report_instance_id)',
  322. 'Period name should be unique by report'),
  323. ]
  324. @api.multi
  325. def _get_additional_move_line_filter(self):
  326. """ Prepare a filter to apply on all move lines
  327. This filter is applied with a AND operator on all
  328. accounting expression domains. This hook is intended
  329. to be inherited, and is useful to implement filtering
  330. on analytic dimensions or operational units.
  331. Returns an Odoo domain expression (a python list)
  332. compatible with account.move.line."""
  333. self.ensure_one()
  334. return []
  335. @api.multi
  336. def _get_additional_query_filter(self, query):
  337. """ Prepare an additional filter to apply on the query
  338. This filter is combined to the query domain with a AND
  339. operator. This hook is intended
  340. to be inherited, and is useful to implement filtering
  341. on analytic dimensions or operational units.
  342. Returns an Odoo domain expression (a python list)
  343. compatible with the model of the query."""
  344. self.ensure_one()
  345. return []
  346. @api.multi
  347. def drilldown(self, expr):
  348. assert len(self) == 1
  349. if AEP.has_account_var(expr):
  350. aep = AEP(self.env)
  351. aep.parse_expr(expr)
  352. aep.done_parsing()
  353. domain = aep.get_aml_domain_for_expr(
  354. expr,
  355. self.date_from, self.date_to,
  356. self.report_instance_id.target_move)
  357. domain.extend(self._get_additional_move_line_filter())
  358. return {
  359. 'name': expr + ' - ' + self.name,
  360. 'domain': domain,
  361. 'type': 'ir.actions.act_window',
  362. 'res_model': 'account.move.line',
  363. 'views': [[False, 'list'], [False, 'form']],
  364. 'view_type': 'list',
  365. 'view_mode': 'list',
  366. 'target': 'current',
  367. }
  368. else:
  369. return False
  370. def _fetch_queries(self):
  371. assert len(self) == 1
  372. res = {}
  373. for query in self.report_instance_id.report_id.query_ids:
  374. model = self.env[query.model_id.model]
  375. eval_context = {
  376. 'env': self.env,
  377. 'time': time,
  378. 'datetime': datetime,
  379. 'dateutil': dateutil,
  380. # deprecated
  381. 'uid': self.env.uid,
  382. 'context': self.env.context,
  383. }
  384. domain = query.domain and \
  385. safe_eval(query.domain, eval_context) or []
  386. domain.extend(self._get_additional_query_filter(query))
  387. if query.date_field.ttype == 'date':
  388. domain.extend([(query.date_field.name, '>=', self.date_from),
  389. (query.date_field.name, '<=', self.date_to)])
  390. else:
  391. datetime_from = _utc_midnight(
  392. self.date_from, self._context.get('tz', 'UTC'))
  393. datetime_to = _utc_midnight(
  394. self.date_to, self._context.get('tz', 'UTC'), add_day=1)
  395. domain.extend([(query.date_field.name, '>=', datetime_from),
  396. (query.date_field.name, '<', datetime_to)])
  397. field_names = [f.name for f in query.field_ids]
  398. if not query.aggregate:
  399. data = model.search_read(domain, field_names)
  400. res[query.name] = [AutoStruct(**d) for d in data]
  401. elif query.aggregate == 'sum':
  402. data = model.read_group(
  403. domain, field_names, [])
  404. s = AutoStruct(count=data[0]['__count'])
  405. for field_name in field_names:
  406. v = data[0][field_name]
  407. setattr(s, field_name, v)
  408. res[query.name] = s
  409. else:
  410. data = model.search_read(domain, field_names)
  411. s = AutoStruct(count=len(data))
  412. if query.aggregate == 'min':
  413. agg = _min
  414. elif query.aggregate == 'max':
  415. agg = _max
  416. elif query.aggregate == 'avg':
  417. agg = _avg
  418. for field_name in field_names:
  419. setattr(s, field_name,
  420. agg([d[field_name] for d in data]))
  421. res[query.name] = s
  422. return res
  423. def _compute(self, lang_id, aep):
  424. res = {}
  425. localdict = {
  426. 'registry': self.pool,
  427. 'sum': _sum,
  428. 'min': _min,
  429. 'max': _max,
  430. 'len': len,
  431. 'avg': _avg,
  432. 'AccountingNone': AccountingNone,
  433. }
  434. localdict.update(self._fetch_queries())
  435. aep.do_queries(self.date_from, self.date_to,
  436. self.report_instance_id.target_move,
  437. self._get_additional_move_line_filter())
  438. compute_queue = self.report_instance_id.report_id.kpi_ids
  439. recompute_queue = []
  440. while True:
  441. for kpi in compute_queue:
  442. try:
  443. kpi_val_comment = kpi.name + " = " + kpi.expression
  444. kpi_eval_expression = aep.replace_expr(kpi.expression)
  445. kpi_val = safe_eval(kpi_eval_expression, localdict)
  446. localdict[kpi.name] = kpi_val
  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. try:
  463. kpi_style = None
  464. if kpi.css_style:
  465. kpi_style = safe_eval(kpi.css_style, localdict)
  466. except:
  467. _logger.warning("error evaluating css stype expression %s",
  468. kpi.css_style, exc_info=True)
  469. kpi_style = None
  470. drilldown = (kpi_val is not None and
  471. AEP.has_account_var(kpi.expression))
  472. res[kpi.name] = {
  473. 'val': None if kpi_val is AccountingNone else kpi_val,
  474. 'val_r': kpi_val_rendered,
  475. 'val_c': kpi_val_comment,
  476. 'style': kpi_style,
  477. 'prefix': kpi.prefix,
  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. landscape_pdf = fields.Boolean(string='Landscape PDF')
  532. def _format_date(self, lang_id, date):
  533. # format date following user language
  534. date_format = self.env['res.lang'].browse(lang_id).date_format
  535. return datetime.datetime.strftime(
  536. fields.Date.from_string(date), date_format)
  537. @api.multi
  538. def preview(self):
  539. assert len(self) == 1
  540. view_id = self.env.ref('mis_builder.'
  541. 'mis_report_instance_result_view_form')
  542. return {
  543. 'type': 'ir.actions.act_window',
  544. 'res_model': 'mis.report.instance',
  545. 'res_id': self.id,
  546. 'view_mode': 'form',
  547. 'view_type': 'form',
  548. 'view_id': view_id.id,
  549. 'target': 'current',
  550. }
  551. @api.multi
  552. def print_pdf(self):
  553. self.ensure_one()
  554. return {
  555. 'name': 'MIS report instance QWEB PDF report',
  556. 'model': 'mis.report.instance',
  557. 'type': 'ir.actions.report.xml',
  558. 'report_name': 'mis_builder.report_mis_report_instance',
  559. 'report_type': 'qweb-pdf',
  560. 'context': self.env.context,
  561. }
  562. @api.multi
  563. def export_xls(self):
  564. self.ensure_one()
  565. return {
  566. 'name': 'MIS report instance XLSX report',
  567. 'model': 'mis.report.instance',
  568. 'type': 'ir.actions.report.xml',
  569. 'report_name': 'mis.report.instance.xlsx',
  570. 'report_type': 'xlsx',
  571. 'context': self.env.context,
  572. }
  573. @api.multi
  574. def display_settings(self):
  575. assert len(self.ids) <= 1
  576. view_id = self.env.ref('mis_builder.mis_report_instance_view_form')
  577. return {
  578. 'type': 'ir.actions.act_window',
  579. 'res_model': 'mis.report.instance',
  580. 'res_id': self.id if self.id else False,
  581. 'view_mode': 'form',
  582. 'view_type': 'form',
  583. 'views': [(view_id.id, 'form')],
  584. 'view_id': view_id.id,
  585. 'target': 'current',
  586. }
  587. @api.multi
  588. def compute(self):
  589. assert len(self) == 1
  590. # prepare AccountingExpressionProcessor
  591. aep = AEP(self.env)
  592. for kpi in self.report_id.kpi_ids:
  593. aep.parse_expr(kpi.expression)
  594. aep.done_parsing()
  595. # fetch user language only once
  596. # TODO: is this necessary?
  597. lang = self.env.user.lang
  598. if not lang:
  599. lang = 'en_US'
  600. lang_id = self.env['res.lang'].search([('code', '=', lang)]).id
  601. # compute kpi values for each period
  602. kpi_values_by_period_ids = {}
  603. for period in self.period_ids:
  604. if not period.valid:
  605. continue
  606. kpi_values = period._compute(lang_id, aep)
  607. kpi_values_by_period_ids[period.id] = kpi_values
  608. # prepare header and content
  609. header = []
  610. header.append({
  611. 'kpi_name': '',
  612. 'cols': []
  613. })
  614. content = []
  615. rows_by_kpi_name = {}
  616. for kpi in self.report_id.kpi_ids:
  617. rows_by_kpi_name[kpi.name] = {
  618. 'kpi_name': kpi.description,
  619. 'cols': [],
  620. 'default_style': kpi.default_css_style
  621. }
  622. content.append(rows_by_kpi_name[kpi.name])
  623. # populate header and content
  624. for period in self.period_ids:
  625. if not period.valid:
  626. continue
  627. # add the column header
  628. if period.duration > 1 or period.type == 'w':
  629. # from, to
  630. date_from = self._format_date(lang_id, period.date_from)
  631. date_to = self._format_date(lang_id, period.date_to)
  632. header_date = _('from %s to %s') % (date_from, date_to)
  633. else:
  634. header_date = self._format_date(lang_id, period.date_from)
  635. header[0]['cols'].append(dict(name=period.name, date=header_date))
  636. # add kpi values
  637. kpi_values = kpi_values_by_period_ids[period.id]
  638. for kpi_name in kpi_values:
  639. rows_by_kpi_name[kpi_name]['cols'].append(kpi_values[kpi_name])
  640. # add comparison columns
  641. for compare_col in period.comparison_column_ids:
  642. compare_kpi_values = \
  643. kpi_values_by_period_ids.get(compare_col.id)
  644. if compare_kpi_values:
  645. # add the comparison column header
  646. header[0]['cols'].append(
  647. dict(name=_('%s vs %s') % (period.name,
  648. compare_col.name),
  649. date=''))
  650. # add comparison values
  651. for kpi in self.report_id.kpi_ids:
  652. rows_by_kpi_name[kpi.name]['cols'].append({
  653. 'val_r': kpi.render_comparison(
  654. lang_id,
  655. kpi_values[kpi.name]['val'],
  656. compare_kpi_values[kpi.name]['val'],
  657. period.normalize_factor,
  658. compare_col.normalize_factor)
  659. })
  660. return {'header': header,
  661. 'content': content}