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.

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