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.

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