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.

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