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.

1489 lines
56 KiB

9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
  1. # -*- coding: utf-8 -*-
  2. # © 2014-2016 ACSONE SA/NV (<http://acsone.eu>)
  3. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  4. from collections import OrderedDict
  5. import datetime
  6. import dateutil
  7. from itertools import izip
  8. import logging
  9. import re
  10. import time
  11. import pytz
  12. from openerp import api, exceptions, fields, models, _
  13. from openerp.tools.safe_eval import safe_eval
  14. from .aep import AccountingExpressionProcessor as AEP
  15. from .aggregate import _sum, _avg, _min, _max
  16. from .accounting_none import AccountingNone
  17. from openerp.exceptions import UserError
  18. from .simple_array import SimpleArray
  19. from .mis_safe_eval import mis_safe_eval, DataError
  20. _logger = logging.getLogger(__name__)
  21. class AutoStruct(object):
  22. def __init__(self, **kwargs):
  23. for k, v in kwargs.items():
  24. setattr(self, k, v)
  25. class KpiMatrixRow(object):
  26. def __init__(self, matrix, kpi, account_id=None, parent_row=None):
  27. self._matrix = matrix
  28. self.kpi = kpi
  29. self.account_id = account_id
  30. self.comment = ''
  31. self.parent_row = parent_row
  32. @property
  33. def description(self):
  34. if not self.account_id:
  35. return self.kpi.description
  36. else:
  37. return self._matrix.get_account_name(self.account_id)
  38. @property
  39. def style(self):
  40. if not self.account_id:
  41. return self.kpi.style
  42. else:
  43. return None # TODO style for expanded accounts
  44. def iter_cell_tuples(self, cols):
  45. for col in cols:
  46. yield col.get_cell_tuple_for_row(self)
  47. def iter_cells(self, subcols):
  48. for subcol in subcols:
  49. yield subcol.get_cell_for_row(self)
  50. class KpiMatrixCol(object):
  51. def __init__(self, description, comment, locals_dict, subkpis):
  52. self.description = description
  53. self.comment = comment
  54. self.locals_dict = locals_dict
  55. self.colspan = subkpis and len(subkpis) or 1
  56. self._subcols = []
  57. if not subkpis:
  58. subcol = KpiMatrixSubCol(self, '', '', 0)
  59. self._subcols.append(subcol)
  60. else:
  61. for i, subkpi in enumerate(subkpis):
  62. subcol = KpiMatrixSubCol(self, subkpi.description, '', i)
  63. self._subcols.append(subcol)
  64. self._cell_tuples_by_row = {} # {row: (cells tuple)}
  65. def _set_cell_tuple(self, row, cell_tuple):
  66. self._cell_tuples_by_row[row] = cell_tuple
  67. def iter_subcols(self):
  68. return self._subcols
  69. def iter_cell_tuples(self):
  70. return self._cells_by_row.values()
  71. def get_cell_tuple_for_row(self, row):
  72. return self._cell_tuples_by_row.get(row)
  73. class KpiMatrixSubCol(object):
  74. def __init__(self, col, description, comment, index=0):
  75. self.col = col
  76. self.description = description
  77. self.comment = comment
  78. self.index = index
  79. def iter_cells(self):
  80. for cells in self.col.iter_cell_tuples():
  81. yield cells[self.index]
  82. def get_cell_for_row(self, row):
  83. cell_tuple = self.col.get_cell_tuple_for_row(row)
  84. if cell_tuple is None:
  85. return None
  86. return cell_tuple[self.index]
  87. class KpiMatrixCell(object):
  88. def __init__(self, row, subcol,
  89. val, val_rendered, val_comment,
  90. style=None, drilldown_key=None):
  91. self.row = row
  92. self.subcol = subcol
  93. self.val = val
  94. self.val_rendered = val_rendered
  95. self.val_comment = val_comment
  96. self.drilldown_key = None
  97. class KpiMatrix(object):
  98. def __init__(self, env):
  99. # cache language id for faster rendering
  100. lang_model = env['res.lang']
  101. lang_id = lang_model._lang_get(env.user.lang)
  102. self.lang = lang_model.browse(lang_id)
  103. # data structures
  104. self._kpi_rows = OrderedDict() # { kpi: KpiMatrixRow }
  105. self._detail_rows = {} # { kpi: {account_id: KpiMatrixRow} }
  106. self._cols = OrderedDict() # { period_key: KpiMatrixCol }
  107. self._account_model = env['account.account']
  108. self._account_names = {} # { account_id: account_name }
  109. def declare_kpi(self, kpi):
  110. self._kpi_rows[kpi] = KpiMatrixRow(self, kpi)
  111. self._detail_rows[kpi] = {}
  112. def declare_period(self, period_key, description, comment,
  113. locals_dict, subkpis):
  114. self._cols[period_key] = KpiMatrixCol(description, comment,
  115. locals_dict, subkpis)
  116. def set_values(self, kpi, period_key, vals):
  117. self.set_values_detail_account(kpi, period_key, None, vals)
  118. def set_values_detail_account(self, kpi, period_key, account_id, vals):
  119. if not account_id:
  120. row = self._kpi_rows[kpi]
  121. else:
  122. kpi_row = self._kpi_rows[kpi]
  123. if account_id in self._detail_rows[kpi]:
  124. row = self._detail_rows[kpi][account_id]
  125. else:
  126. row = KpiMatrixRow(self, kpi, account_id, parent_row=kpi_row)
  127. self._detail_rows[kpi][account_id] = row
  128. col = self._cols[period_key]
  129. cell_tuple = []
  130. assert len(vals) == col.colspan
  131. for val, subcol in izip(vals, col.iter_subcols()):
  132. if isinstance(val, DataError):
  133. val_rendered = val.name
  134. val_comment = val.msg
  135. else:
  136. val_rendered = kpi.render(self.lang, val)
  137. val_comment = '' # TODO FIXME get subkpi expression
  138. # TODO style
  139. # TODO drilldown_key
  140. cell = KpiMatrixCell(row, subcol, val, val_rendered, val_comment)
  141. cell_tuple.append(cell)
  142. col._set_cell_tuple(row, cell_tuple)
  143. def iter_rows(self):
  144. for kpi_row in self._kpi_rows.values():
  145. yield kpi_row
  146. detail_rows = self._detail_rows[kpi_row.kpi].values()
  147. detail_rows = sorted(detail_rows, key=lambda r: r.description)
  148. for detail_row in detail_rows:
  149. yield detail_row
  150. def iter_cols(self):
  151. return self._cols.values()
  152. def iter_subcols(self):
  153. for col in self.iter_cols():
  154. for subcol in col.iter_subcols():
  155. yield subcol
  156. def _load_account_names(self):
  157. account_ids = set()
  158. for detail_rows in self._detail_rows.values():
  159. account_ids.update(detail_rows.keys())
  160. account_ids = list(account_ids)
  161. accounts = self._account_model.search([('id', 'in', account_ids)])
  162. self._account_names = {a.id: u'{} {}'.format(a.code, a.name)
  163. for a in accounts}
  164. def get_account_name(self, account_id):
  165. if account_id not in self._account_names:
  166. self._load_account_names()
  167. return self._account_names[account_id]
  168. def _get_selection_label(selection, value):
  169. for v, l in selection:
  170. if v == value:
  171. return l
  172. return ''
  173. def _utc_midnight(d, tz_name, add_day=0):
  174. d = fields.Datetime.from_string(d) + datetime.timedelta(days=add_day)
  175. utc_tz = pytz.timezone('UTC')
  176. context_tz = pytz.timezone(tz_name)
  177. local_timestamp = context_tz.localize(d, is_dst=False)
  178. return fields.Datetime.to_string(local_timestamp.astimezone(utc_tz))
  179. def _python_var(var_str):
  180. return re.sub(r'\W|^(?=\d)', '_', var_str).lower()
  181. def _is_valid_python_var(name):
  182. return re.match("[_A-Za-z][_a-zA-Z0-9]*$", name)
  183. class MisReportKpi(models.Model):
  184. """ A KPI is an element (ie a line) of a MIS report.
  185. In addition to a name and description, it has an expression
  186. to compute it based on queries defined in the MIS report.
  187. It also has various informations defining how to render it
  188. (numeric or percentage or a string, a prefix, a suffix, divider) and
  189. how to render comparison of two values of the KPI.
  190. KPI's have a sequence and are ordered inside the MIS report.
  191. """
  192. _name = 'mis.report.kpi'
  193. name = fields.Char(size=32, required=True,
  194. string='Name')
  195. description = fields.Char(required=True,
  196. string='Description',
  197. translate=True)
  198. multi = fields.Boolean()
  199. expression = fields.Char(
  200. compute='_compute_expression',
  201. inverse='_inverse_expression')
  202. expression_ids = fields.One2many('mis.report.kpi.expression', 'kpi_id')
  203. auto_expand_accounts = fields.Boolean(string='Display details by account')
  204. style = fields.Many2one(
  205. string="Default style for KPI",
  206. comodel_name="mis.report.kpi.style",
  207. required=False
  208. )
  209. style_expression = fields.Char(
  210. string='Style expression',
  211. help='An expression that returns a style name for the kpi style')
  212. type = fields.Selection([('num', _('Numeric')),
  213. ('pct', _('Percentage')),
  214. ('str', _('String'))],
  215. required=True,
  216. string='Type',
  217. default='num')
  218. divider = fields.Selection([('1e-6', _('µ')),
  219. ('1e-3', _('m')),
  220. ('1', _('1')),
  221. ('1e3', _('k')),
  222. ('1e6', _('M'))],
  223. string='Factor',
  224. default='1')
  225. dp = fields.Integer(string='Rounding', default=0)
  226. prefix = fields.Char(size=16, string='Prefix')
  227. suffix = fields.Char(size=16, string='Suffix')
  228. compare_method = fields.Selection([('diff', _('Difference')),
  229. ('pct', _('Percentage')),
  230. ('none', _('None'))],
  231. required=True,
  232. string='Comparison Method',
  233. default='pct')
  234. sequence = fields.Integer(string='Sequence', default=100)
  235. report_id = fields.Many2one('mis.report',
  236. string='Report',
  237. ondelete='cascade')
  238. _order = 'sequence, id'
  239. @api.one
  240. @api.constrains('name')
  241. def _check_name(self):
  242. if not _is_valid_python_var(self.name):
  243. raise exceptions.Warning(_('The name must be a valid '
  244. 'python identifier'))
  245. @api.onchange('name')
  246. def _onchange_name(self):
  247. if self.name and not _is_valid_python_var(self.name):
  248. return {
  249. 'warning': {
  250. 'title': 'Invalid name %s' % self.name,
  251. 'message': 'The name must be a valid python identifier'
  252. }
  253. }
  254. @api.multi
  255. def _compute_expression(self):
  256. for kpi in self:
  257. l = []
  258. for expression in kpi.expression_ids:
  259. if expression.subkpi_id:
  260. l.append('{}={}'.format(
  261. expression.subkpi_id.name, expression.name))
  262. else:
  263. l.append(
  264. expression.name or 'AccountingNone')
  265. kpi.expression = ',\n'.join(l)
  266. @api.multi
  267. def _inverse_expression(self):
  268. for kpi in self:
  269. if kpi.multi:
  270. raise UserError('Can not update a multi kpi from the kpi line')
  271. if kpi.expression_ids:
  272. kpi.expression_ids[0].write({
  273. 'name': kpi.expression,
  274. 'subkpi_id': None})
  275. for expression in kpi.expression_ids[1:]:
  276. expression.unlink()
  277. else:
  278. kpi.write({
  279. 'expression_ids': [(0, 0, {
  280. 'name': kpi.expression
  281. })]
  282. })
  283. @api.onchange('multi')
  284. def _onchange_multi(self):
  285. for kpi in self:
  286. if not kpi.multi:
  287. if kpi.expression_ids:
  288. kpi.expression = kpi.expression_ids[0].name
  289. else:
  290. kpi.expression = None
  291. else:
  292. expressions = []
  293. for subkpi in kpi.report_id.subkpi_ids:
  294. expressions.append((0, 0, {
  295. 'name': kpi.expression,
  296. 'subkpi_id': subkpi.id,
  297. }))
  298. kpi.expression_ids = expressions
  299. @api.onchange('description')
  300. def _onchange_description(self):
  301. """ construct name from description """
  302. if self.description and not self.name:
  303. self.name = _python_var(self.description)
  304. @api.onchange('type')
  305. def _onchange_type(self):
  306. if self.type == 'num':
  307. self.compare_method = 'pct'
  308. self.divider = '1'
  309. self.dp = 0
  310. elif self.type == 'pct':
  311. self.compare_method = 'diff'
  312. self.divider = '1'
  313. self.dp = 0
  314. elif self.type == 'str':
  315. self.compare_method = 'none'
  316. self.divider = ''
  317. self.dp = 0
  318. def render(self, lang, value):
  319. """ render a KPI value as a unicode string, ready for display """
  320. assert len(self) == 1
  321. if value is None or value is AccountingNone:
  322. return ''
  323. elif self.type == 'num':
  324. return self._render_num(lang, value, self.divider,
  325. self.dp, self.prefix, self.suffix)
  326. elif self.type == 'pct':
  327. return self._render_num(lang, value, 0.01,
  328. self.dp, '', '%')
  329. else:
  330. return unicode(value)
  331. def render_comparison(self, lang, value, base_value,
  332. average_value, average_base_value):
  333. """ render the comparison of two KPI values, ready for display
  334. If the difference is 0, an empty string is returned.
  335. """
  336. assert len(self) == 1
  337. if value is None:
  338. value = AccountingNone
  339. if base_value is None:
  340. base_value = AccountingNone
  341. if self.type == 'pct':
  342. delta = value - base_value
  343. if delta and round(delta, self.dp) != 0:
  344. return self._render_num(
  345. lang,
  346. delta,
  347. 0.01, self.dp, '', _('pp'),
  348. sign='+')
  349. elif self.type == 'num':
  350. if value and average_value:
  351. value = value / float(average_value)
  352. if base_value and average_base_value:
  353. base_value = base_value / float(average_base_value)
  354. if self.compare_method == 'diff':
  355. delta = value - base_value
  356. if delta and round(delta, self.dp) != 0:
  357. return self._render_num(
  358. lang,
  359. delta,
  360. self.divider, self.dp, self.prefix, self.suffix,
  361. sign='+')
  362. elif self.compare_method == 'pct':
  363. if base_value and round(base_value, self.dp) != 0:
  364. delta = (value - base_value) / abs(base_value)
  365. if delta and round(delta, self.dp) != 0:
  366. return self._render_num(
  367. lang,
  368. delta,
  369. 0.01, self.dp, '', '%',
  370. sign='+')
  371. return ''
  372. def _render_num(self, lang, value, divider,
  373. dp, prefix, suffix, sign='-'):
  374. divider_label = _get_selection_label(
  375. self._columns['divider'].selection, divider)
  376. if divider_label == '1':
  377. divider_label = ''
  378. # format number following user language
  379. value = round(value / float(divider or 1), dp) or 0
  380. value = lang.format(
  381. '%%%s.%df' % (sign, dp),
  382. value,
  383. grouping=True)
  384. value = u'%s\N{NO-BREAK SPACE}%s\N{NO-BREAK SPACE}%s%s' % \
  385. (prefix or '', value, divider_label, suffix or '')
  386. value = value.replace('-', u'\N{NON-BREAKING HYPHEN}')
  387. return value
  388. class MisReportSubkpi(models.Model):
  389. _name = 'mis.report.subkpi'
  390. _order = 'sequence'
  391. sequence = fields.Integer()
  392. report_id = fields.Many2one('mis.report')
  393. name = fields.Char(size=32, required=True,
  394. string='Name')
  395. description = fields.Char(required=True,
  396. string='Description',
  397. translate=True)
  398. expression_ids = fields.One2many('mis.report.kpi.expression', 'subkpi_id')
  399. @api.one
  400. @api.constrains('name')
  401. def _check_name(self):
  402. if not _is_valid_python_var(self.name):
  403. raise exceptions.Warning(_('The name must be a valid '
  404. 'python identifier'))
  405. @api.onchange('name')
  406. def _onchange_name(self):
  407. if self.name and not _is_valid_python_var(self.name):
  408. return {
  409. 'warning': {
  410. 'title': 'Invalid name %s' % self.name,
  411. 'message': 'The name must be a valid python identifier'
  412. }
  413. }
  414. @api.onchange('description')
  415. def _onchange_description(self):
  416. """ construct name from description """
  417. if self.description and not self.name:
  418. self.name = _python_var(self.description)
  419. @api.multi
  420. def unlink(self):
  421. for subkpi in self:
  422. subkpi.expression_ids.unlink()
  423. return super(MisReportSubkpi, self).unlink()
  424. class MisReportKpiExpression(models.Model):
  425. """ A KPI Expression is an expression of a line of a MIS report Kpi.
  426. It's used to compute the kpi value.
  427. """
  428. _name = 'mis.report.kpi.expression'
  429. _order = 'sequence, name'
  430. sequence = fields.Integer(
  431. related='subkpi_id.sequence',
  432. store=True,
  433. readonly=True)
  434. name = fields.Char(string='Expression')
  435. kpi_id = fields.Many2one('mis.report.kpi')
  436. # TODO FIXME set readonly=True when onchange('subkpi_ids') below works
  437. subkpi_id = fields.Many2one(
  438. 'mis.report.subkpi',
  439. readonly=False)
  440. _sql_constraints = [
  441. ('subkpi_kpi_unique', 'unique(subkpi_id, kpi_id)',
  442. 'Sub KPI must be used once and only once for each KPI'),
  443. ]
  444. class MisReportQuery(models.Model):
  445. """ A query to fetch arbitrary data for a MIS report.
  446. A query works on a model and has a domain and list of fields to fetch.
  447. At runtime, the domain is expanded with a "and" on the date/datetime field.
  448. """
  449. _name = 'mis.report.query'
  450. @api.one
  451. @api.depends('field_ids')
  452. def _compute_field_names(self):
  453. field_names = [field.name for field in self.field_ids]
  454. self.field_names = ', '.join(field_names)
  455. name = fields.Char(size=32, required=True,
  456. string='Name')
  457. model_id = fields.Many2one('ir.model', required=True,
  458. string='Model')
  459. field_ids = fields.Many2many('ir.model.fields', required=True,
  460. string='Fields to fetch')
  461. field_names = fields.Char(compute='_compute_field_names',
  462. string='Fetched fields name')
  463. aggregate = fields.Selection([('sum', _('Sum')),
  464. ('avg', _('Average')),
  465. ('min', _('Min')),
  466. ('max', _('Max'))],
  467. string='Aggregate')
  468. date_field = fields.Many2one('ir.model.fields', required=True,
  469. string='Date field',
  470. domain=[('ttype', 'in',
  471. ('date', 'datetime'))])
  472. domain = fields.Char(string='Domain')
  473. report_id = fields.Many2one('mis.report', string='Report',
  474. ondelete='cascade')
  475. _order = 'name'
  476. @api.one
  477. @api.constrains('name')
  478. def _check_name(self):
  479. if not _is_valid_python_var(self.name):
  480. raise exceptions.Warning(_('The name must be a valid '
  481. 'python identifier'))
  482. class MisReport(models.Model):
  483. """ A MIS report template (without period information)
  484. The MIS report holds:
  485. * a list of explicit queries; the result of each query is
  486. stored in a variable with same name as a query, containing as list
  487. of data structures populated with attributes for each fields to fetch;
  488. when queries have an aggregate method and no fields to group, it returns
  489. a data structure with the aggregated fields
  490. * a list of KPI to be evaluated based on the variables resulting
  491. from the accounting data and queries (KPI expressions can references
  492. queries and accounting expression - see AccoutingExpressionProcessor)
  493. """
  494. _name = 'mis.report'
  495. name = fields.Char(required=True,
  496. string='Name', translate=True)
  497. description = fields.Char(required=False,
  498. string='Description', translate=True)
  499. query_ids = fields.One2many('mis.report.query', 'report_id',
  500. string='Queries',
  501. copy=True)
  502. kpi_ids = fields.One2many('mis.report.kpi', 'report_id',
  503. string='KPI\'s',
  504. copy=True)
  505. subkpi_ids = fields.One2many('mis.report.subkpi', 'report_id',
  506. string="Sub KPI",
  507. copy=True)
  508. @api.onchange('subkpi_ids')
  509. def _on_change_subkpi_ids(self):
  510. """ Update kpi expressions when subkpis change on the report,
  511. so the list of kpi expressions is always up-to-date """
  512. for kpi in self.kpi_ids:
  513. if not kpi.multi:
  514. continue
  515. new_subkpis = set([subkpi for subkpi in self.subkpi_ids])
  516. expressions = []
  517. for expression in kpi.expression_ids:
  518. assert expression.subkpi_id # must be true if kpi is multi
  519. if expression.subkpi_id not in self.subkpi_ids:
  520. expressions.append((2, expression.id, None)) # remove
  521. else:
  522. new_subkpis.remove(expression.subkpi_id) # no change
  523. for subkpi in new_subkpis:
  524. # TODO FIXME this does not work, while the remove above works
  525. expressions.append((0, None, {
  526. 'name': False,
  527. 'subkpi_id': subkpi.id,
  528. })) # add empty expressions for new subkpis
  529. if expressions:
  530. kpi.expressions_ids = expressions
  531. @api.multi
  532. def get_wizard_report_action(self):
  533. action = self.env.ref('mis_builder.mis_report_instance_view_action')
  534. res = action.read()[0]
  535. view = self.env.ref('mis_builder.wizard_mis_report_instance_view_form')
  536. res.update({
  537. 'view_id': view.id,
  538. 'views': [(view.id, 'form')],
  539. 'target': 'new',
  540. 'context': {
  541. 'default_report_id': self.id,
  542. 'default_name': self.name,
  543. 'default_temporary': True,
  544. }
  545. })
  546. return res
  547. @api.one
  548. def copy(self, default=None):
  549. default = dict(default or {})
  550. default['name'] = _('%s (copy)') % self.name
  551. return super(MisReport, self).copy(default)
  552. # TODO: kpi name cannot be start with query name
  553. @api.multi
  554. def _prepare_kpi_matrix(self):
  555. self.ensure_one()
  556. kpi_matrix = KpiMatrix(self.env)
  557. for kpi in self.kpi_ids:
  558. kpi_matrix.declare_kpi(kpi)
  559. return kpi_matrix
  560. @api.multi
  561. def _prepare_aep(self, company):
  562. self.ensure_one()
  563. aep = AEP(self.env)
  564. for kpi in self.kpi_ids:
  565. for expression in kpi.expression_ids:
  566. aep.parse_expr(expression.name)
  567. aep.done_parsing(company)
  568. return aep
  569. @api.multi
  570. def _fetch_queries(self, date_from, date_to,
  571. get_additional_query_filter=None):
  572. self.ensure_one()
  573. res = {}
  574. for query in self.query_ids:
  575. model = self.env[query.model_id.model]
  576. eval_context = {
  577. 'env': self.env,
  578. 'time': time,
  579. 'datetime': datetime,
  580. 'dateutil': dateutil,
  581. # deprecated
  582. 'uid': self.env.uid,
  583. 'context': self.env.context,
  584. }
  585. domain = query.domain and \
  586. safe_eval(query.domain, eval_context) or []
  587. if get_additional_query_filter:
  588. domain.extend(get_additional_query_filter(query))
  589. if query.date_field.ttype == 'date':
  590. domain.extend([(query.date_field.name, '>=', date_from),
  591. (query.date_field.name, '<=', date_to)])
  592. else:
  593. datetime_from = _utc_midnight(
  594. date_from, self._context.get('tz', 'UTC'))
  595. datetime_to = _utc_midnight(
  596. date_to, self._context.get('tz', 'UTC'), add_day=1)
  597. domain.extend([(query.date_field.name, '>=', datetime_from),
  598. (query.date_field.name, '<', datetime_to)])
  599. field_names = [f.name for f in query.field_ids]
  600. if not query.aggregate:
  601. data = model.search_read(domain, field_names)
  602. res[query.name] = [AutoStruct(**d) for d in data]
  603. elif query.aggregate == 'sum':
  604. data = model.read_group(
  605. domain, field_names, [])
  606. s = AutoStruct(count=data[0]['__count'])
  607. for field_name in field_names:
  608. v = data[0][field_name]
  609. setattr(s, field_name, v)
  610. res[query.name] = s
  611. else:
  612. data = model.search_read(domain, field_names)
  613. s = AutoStruct(count=len(data))
  614. if query.aggregate == 'min':
  615. agg = _min
  616. elif query.aggregate == 'max':
  617. agg = _max
  618. elif query.aggregate == 'avg':
  619. agg = _avg
  620. for field_name in field_names:
  621. setattr(s, field_name,
  622. agg([d[field_name] for d in data]))
  623. res[query.name] = s
  624. return res
  625. @api.multi
  626. def _compute_period(self, kpi_matrix,
  627. period_key, period_description, period_comment,
  628. aep,
  629. date_from, date_to,
  630. target_move,
  631. company,
  632. subkpis_filter=None,
  633. get_additional_move_line_filter=None,
  634. get_additional_query_filter=None):
  635. """ Evaluate a report for a given period, populating a KpiMatrix.
  636. :param kpi_matrix: the KpiMatrix object to be populated
  637. :param period_key: the period key to use when populating the KpiMatrix
  638. :param aep: an AccountingExpressionProcessor instance created
  639. using _prepare_aep()
  640. :param date_from, date_to: the starting and ending date
  641. :param target_move: all|posted
  642. :param company:
  643. :param get_additional_move_line_filter: a bound method that takes
  644. no arguments and returns
  645. a domain compatible with
  646. account.move.line
  647. :param get_additional_query_filter: a bound method that takes a single
  648. query argument and returns a
  649. domain compatible with the query
  650. underlying model
  651. """
  652. self.ensure_one()
  653. locals_dict = {
  654. 'sum': _sum,
  655. 'min': _min,
  656. 'max': _max,
  657. 'len': len,
  658. 'avg': _avg,
  659. 'AccountingNone': AccountingNone,
  660. 'SimpleArray': SimpleArray,
  661. }
  662. # fetch non-accounting queries
  663. locals_dict.update(self._fetch_queries(
  664. date_from, date_to, get_additional_query_filter))
  665. # use AEP to do the accounting queries
  666. additional_move_line_filter = None
  667. if get_additional_move_line_filter:
  668. additional_move_line_filter = get_additional_move_line_filter()
  669. aep.do_queries(company,
  670. date_from, date_to,
  671. target_move,
  672. additional_move_line_filter)
  673. if subkpis_filter:
  674. subkpis = [subkpi for subkpi in self.subkpi_ids
  675. if subkpi in subkpis_filter]
  676. else:
  677. subkpis = self.subkpi_ids
  678. kpi_matrix.declare_period(period_key,
  679. period_description, period_comment,
  680. locals_dict, subkpis)
  681. compute_queue = self.kpi_ids
  682. recompute_queue = []
  683. while True:
  684. for kpi in compute_queue:
  685. # build the list of expressions for this kpi
  686. expressions = []
  687. for expression in kpi.expression_ids:
  688. if expression.subkpi_id and \
  689. subkpis_filter and \
  690. expression.subkpi_id not in subkpis_filter:
  691. continue
  692. expressions.append(expression.name)
  693. vals = []
  694. try:
  695. for expression in expressions:
  696. replaced_expr = aep.replace_expr(expression)
  697. vals.append(
  698. mis_safe_eval(replaced_expr, locals_dict))
  699. except NameError:
  700. recompute_queue.append(kpi)
  701. break
  702. else:
  703. # no error, set it in locals_dict so it can be used
  704. # in computing other kpis
  705. if len(expressions) == 1:
  706. locals_dict[kpi.name] = vals[0]
  707. else:
  708. locals_dict[kpi.name] = SimpleArray(vals)
  709. kpi_matrix.set_values(kpi, period_key, vals)
  710. if not kpi.auto_expand_accounts:
  711. continue
  712. for account_id, replaced_exprs in \
  713. aep.replace_exprs_by_account_id(expressions):
  714. account_id_vals = []
  715. for replaced_expr in replaced_exprs:
  716. account_id_vals.append(
  717. mis_safe_eval(replaced_expr, locals_dict))
  718. kpi_matrix.set_values_detail_account(
  719. kpi, period_key, account_id, account_id_vals)
  720. if len(recompute_queue) == 0:
  721. # nothing to recompute, we are done
  722. break
  723. if len(recompute_queue) == len(compute_queue):
  724. # could not compute anything in this iteration
  725. # (ie real Name errors or cyclic dependency)
  726. # so we stop trying
  727. break
  728. # try again
  729. compute_queue = recompute_queue
  730. recompute_queue = []
  731. class MisReportInstancePeriod(models.Model):
  732. """ A MIS report instance has the logic to compute
  733. a report template for a given date period.
  734. Periods have a duration (day, week, fiscal period) and
  735. are defined as an offset relative to a pivot date.
  736. """
  737. @api.one
  738. @api.depends('report_instance_id.pivot_date', 'type', 'offset',
  739. 'duration', 'report_instance_id.comparison_mode')
  740. def _compute_dates(self):
  741. self.date_from = False
  742. self.date_to = False
  743. self.valid = False
  744. report = self.report_instance_id
  745. d = fields.Date.from_string(report.pivot_date)
  746. if not report.comparison_mode:
  747. self.date_from = report.date_from
  748. self.date_to = report.date_to
  749. self.valid = True
  750. elif self.mode == 'fix':
  751. self.date_from = self.manual_date_from
  752. self.date_to = self.manual_date_to
  753. self.valid = True
  754. elif self.type == 'd':
  755. date_from = d + datetime.timedelta(days=self.offset)
  756. date_to = date_from + \
  757. datetime.timedelta(days=self.duration - 1)
  758. self.date_from = fields.Date.to_string(date_from)
  759. self.date_to = fields.Date.to_string(date_to)
  760. self.valid = True
  761. elif self.type == 'w':
  762. date_from = d - datetime.timedelta(d.weekday())
  763. date_from = date_from + datetime.timedelta(days=self.offset * 7)
  764. date_to = date_from + \
  765. datetime.timedelta(days=(7 * self.duration) - 1)
  766. self.date_from = fields.Date.to_string(date_from)
  767. self.date_to = fields.Date.to_string(date_to)
  768. self.valid = True
  769. elif self.type == 'date_range':
  770. date_range_obj = self.env['date.range']
  771. current_periods = date_range_obj.search(
  772. [('type_id', '=', self.date_range_type_id.id),
  773. ('date_start', '<=', d),
  774. ('date_end', '>=', d),
  775. ('company_id', '=', self.report_instance_id.company_id.id)])
  776. if current_periods:
  777. all_periods = date_range_obj.search(
  778. [('type_id', '=', self.date_range_type_id.id),
  779. ('company_id', '=',
  780. self.report_instance_id.company_id.id)],
  781. order='date_start')
  782. all_period_ids = [p.id for p in all_periods]
  783. p = all_period_ids.index(current_periods[0].id) + self.offset
  784. if p >= 0 and p + self.duration <= len(all_period_ids):
  785. periods = all_periods[p:p + self.duration]
  786. self.date_from = periods[0].date_start
  787. self.date_to = periods[-1].date_end
  788. self.valid = True
  789. _name = 'mis.report.instance.period'
  790. name = fields.Char(size=32, required=True,
  791. string='Description', translate=True)
  792. mode = fields.Selection([('fix', 'Fix'),
  793. ('relative', 'Relative'),
  794. ], required=True,
  795. default='fix')
  796. type = fields.Selection([('d', _('Day')),
  797. ('w', _('Week')),
  798. ('date_range', _('Date Range'))
  799. ],
  800. string='Period type')
  801. date_range_type_id = fields.Many2one(
  802. comodel_name='date.range.type', string='Date Range Type')
  803. offset = fields.Integer(string='Offset',
  804. help='Offset from current period',
  805. default=-1)
  806. duration = fields.Integer(string='Duration',
  807. help='Number of periods',
  808. default=1)
  809. date_from = fields.Date(compute='_compute_dates', string="From")
  810. date_to = fields.Date(compute='_compute_dates', string="To")
  811. manual_date_from = fields.Date(string="From")
  812. manual_date_to = fields.Date(string="To")
  813. date_range_id = fields.Many2one(
  814. comodel_name='date.range',
  815. string='Date Range')
  816. valid = fields.Boolean(compute='_compute_dates',
  817. type='boolean',
  818. string='Valid')
  819. sequence = fields.Integer(string='Sequence', default=100)
  820. report_instance_id = fields.Many2one('mis.report.instance',
  821. string='Report Instance',
  822. ondelete='cascade')
  823. comparison_column_ids = fields.Many2many(
  824. comodel_name='mis.report.instance.period',
  825. relation='mis_report_instance_period_rel',
  826. column1='period_id',
  827. column2='compare_period_id',
  828. string='Compare with')
  829. normalize_factor = fields.Integer(
  830. string='Factor',
  831. help='Factor to use to normalize the period (used in comparison',
  832. default=1)
  833. subkpi_ids = fields.Many2many(
  834. 'mis.report.subkpi',
  835. string="Sub KPI Filter")
  836. _order = 'sequence, id'
  837. _sql_constraints = [
  838. ('duration', 'CHECK (duration>0)',
  839. 'Wrong duration, it must be positive!'),
  840. ('normalize_factor', 'CHECK (normalize_factor>0)',
  841. 'Wrong normalize factor, it must be positive!'),
  842. ('name_unique', 'unique(name, report_instance_id)',
  843. 'Period name should be unique by report'),
  844. ]
  845. @api.onchange('date_range_id')
  846. def onchange_date_range(self):
  847. for record in self:
  848. record.manual_date_from = record.date_range_id.date_start
  849. record.manual_date_to = record.date_range_id.date_end
  850. record.name = record.date_range_id.name
  851. @api.multi
  852. def _get_additional_move_line_filter(self):
  853. """ Prepare a filter to apply on all move lines
  854. This filter is applied with a AND operator on all
  855. accounting expression domains. This hook is intended
  856. to be inherited, and is useful to implement filtering
  857. on analytic dimensions or operational units.
  858. Returns an Odoo domain expression (a python list)
  859. compatible with account.move.line."""
  860. self.ensure_one()
  861. return []
  862. @api.multi
  863. def _get_additional_query_filter(self, query):
  864. """ Prepare an additional filter to apply on the query
  865. This filter is combined to the query domain with a AND
  866. operator. This hook is intended
  867. to be inherited, and is useful to implement filtering
  868. on analytic dimensions or operational units.
  869. Returns an Odoo domain expression (a python list)
  870. compatible with the model of the query."""
  871. self.ensure_one()
  872. return []
  873. @api.multi
  874. def drilldown(self, expr):
  875. self.ensure_one()
  876. # TODO FIXME: drilldown by account
  877. if AEP.has_account_var(expr):
  878. aep = AEP(self.env)
  879. aep.parse_expr(expr)
  880. aep.done_parsing(self.report_instance_id.company_id)
  881. domain = aep.get_aml_domain_for_expr(
  882. expr,
  883. self.date_from, self.date_to,
  884. self.report_instance_id.target_move,
  885. self.report_instance_id.company_id)
  886. domain.extend(self._get_additional_move_line_filter())
  887. return {
  888. 'name': expr + ' - ' + self.name,
  889. 'domain': domain,
  890. 'type': 'ir.actions.act_window',
  891. 'res_model': 'account.move.line',
  892. 'views': [[False, 'list'], [False, 'form']],
  893. 'view_type': 'list',
  894. 'view_mode': 'list',
  895. 'target': 'current',
  896. }
  897. else:
  898. return False
  899. @api.multi
  900. def _render_period(self, kpi_matrix, lang_id, aep):
  901. """ Compute and render a mis report instance period
  902. It returns a dictionary keyed on kpi.name with a list of dictionaries
  903. with the following values (one item in the list for each subkpi):
  904. * val: the evaluated kpi, or None if there is no data or an error
  905. * val_r: the rendered kpi as a string, or #ERR, #DIV
  906. * val_c: a comment (explaining the error, typically)
  907. * style: the css style of the kpi
  908. (may change in the future!)
  909. * prefix: a prefix to display in front of the rendered value
  910. * suffix: a prefix to display after rendered value
  911. * dp: the decimal precision of the kpi
  912. * is_percentage: true if the kpi is of percentage type
  913. (may change in the future!)
  914. * expr: the kpi expression
  915. * drilldown: true if the drilldown method of
  916. mis.report.instance.period is going to do something
  917. useful in this kpi
  918. """
  919. # TODO FIXME remove this method
  920. self.ensure_one()
  921. # first invoke the compute method on the mis report template
  922. # passing it all the information regarding period and filters
  923. self.report_instance_id.report_id._compute_period(
  924. kpi_matrix, self,
  925. aep,
  926. self.date_from, self.date_to,
  927. self.report_instance_id.target_move,
  928. self.report_instance_id.company_id,
  929. self.subkpi_ids,
  930. self._get_additional_move_line_filter,
  931. self._get_additional_query_filter,
  932. )
  933. # second, render it to something that can be used by the widget
  934. res = {}
  935. mis_report_kpi_style = self.env['mis.report.kpi.style']
  936. for kpi_name, kpi, vals in kpi_matrix.iter_kpi_vals(self):
  937. res[kpi_name] = []
  938. try:
  939. # TODO FIXME check style_expression evaluation wrt subkpis
  940. kpi_style = None
  941. if kpi.style_expression:
  942. style_name = safe_eval(kpi.style_expression,
  943. kpi_matrix.get_locals_dict(self))
  944. styles = mis_report_kpi_style.search(
  945. [('name', '=', style_name)])
  946. kpi_style = styles and styles[0]
  947. except:
  948. _logger.warning("error evaluating css stype expression %s",
  949. kpi.style, exc_info=True)
  950. default_vals = {
  951. 'prefix': kpi.prefix,
  952. 'suffix': kpi.suffix,
  953. 'dp': kpi.dp,
  954. 'is_percentage': kpi.type == 'pct',
  955. 'period_id': self.id,
  956. 'style': '',
  957. 'xlsx_style': {},
  958. }
  959. if kpi_style:
  960. default_vals.update({
  961. 'style': kpi_style.to_css_style(),
  962. 'xlsx_style': kpi_style.to_xlsx_forma_properties(),
  963. })
  964. for idx, subkpi_val in enumerate(vals):
  965. vals = default_vals.copy()
  966. if isinstance(subkpi_val, DataError):
  967. vals.update({
  968. 'val': subkpi_val.name,
  969. 'val_r': subkpi_val.name,
  970. 'val_c': subkpi_val.msg,
  971. 'drilldown': False,
  972. })
  973. else:
  974. if kpi.multi:
  975. expression = kpi.expression_ids[idx].name
  976. comment = '{}.{} = {}'.format(
  977. kpi.name,
  978. kpi.expression_ids[idx].subkpi_id.name,
  979. expression)
  980. else:
  981. expression = kpi.expression
  982. comment = '{} = {}'.format(
  983. kpi.name,
  984. expression)
  985. drilldown = (subkpi_val is not AccountingNone and
  986. AEP.has_account_var(expression))
  987. vals.update({
  988. 'val': (None
  989. if subkpi_val is AccountingNone
  990. else subkpi_val),
  991. 'val_r': kpi.render(lang_id, subkpi_val),
  992. 'val_c': comment,
  993. 'expr': expression,
  994. 'drilldown': drilldown,
  995. })
  996. res[kpi_name].append(vals)
  997. return res
  998. class MisReportInstance(models.Model):
  999. """The MIS report instance combines everything to compute
  1000. a MIS report template for a set of periods."""
  1001. @api.one
  1002. @api.depends('date')
  1003. def _compute_pivot_date(self):
  1004. if self.date:
  1005. self.pivot_date = self.date
  1006. else:
  1007. self.pivot_date = fields.Date.context_today(self)
  1008. @api.model
  1009. def _default_company(self):
  1010. return self.env['res.company'].\
  1011. _company_default_get('mis.report.instance')
  1012. _name = 'mis.report.instance'
  1013. name = fields.Char(required=True,
  1014. string='Name', translate=True)
  1015. description = fields.Char(related='report_id.description',
  1016. readonly=True)
  1017. date = fields.Date(string='Base date',
  1018. help='Report base date '
  1019. '(leave empty to use current date)')
  1020. pivot_date = fields.Date(compute='_compute_pivot_date',
  1021. string="Pivot date")
  1022. report_id = fields.Many2one('mis.report',
  1023. required=True,
  1024. string='Report')
  1025. period_ids = fields.One2many('mis.report.instance.period',
  1026. 'report_instance_id',
  1027. required=True,
  1028. string='Periods',
  1029. copy=True)
  1030. target_move = fields.Selection([('posted', 'All Posted Entries'),
  1031. ('all', 'All Entries')],
  1032. string='Target Moves',
  1033. required=True,
  1034. default='posted')
  1035. company_id = fields.Many2one(comodel_name='res.company',
  1036. string='Company',
  1037. default=_default_company,
  1038. required=True)
  1039. landscape_pdf = fields.Boolean(string='Landscape PDF')
  1040. comparison_mode = fields.Boolean(
  1041. compute="_compute_comparison_mode",
  1042. inverse="_inverse_comparison_mode")
  1043. date_range_id = fields.Many2one(
  1044. comodel_name='date.range',
  1045. string='Date Range')
  1046. date_from = fields.Date(string="From")
  1047. date_to = fields.Date(string="To")
  1048. temporary = fields.Boolean(default=False)
  1049. @api.multi
  1050. def save_report(self):
  1051. self.ensure_one()
  1052. self.write({'temporary': False})
  1053. action = self.env.ref('mis_builder.mis_report_instance_view_action')
  1054. res = action.read()[0]
  1055. view = self.env.ref('mis_builder.mis_report_instance_view_form')
  1056. res.update({
  1057. 'views': [(view.id, 'form')],
  1058. 'res_id': self.id,
  1059. })
  1060. return res
  1061. @api.model
  1062. def _vacuum_report(self, hours=24):
  1063. clear_date = fields.Datetime.to_string(
  1064. datetime.datetime.now() - datetime.timedelta(hours=hours))
  1065. reports = self.search([
  1066. ('write_date', '<', clear_date),
  1067. ('temporary', '=', True),
  1068. ])
  1069. _logger.debug('Vacuum %s Temporary MIS Builder Report', len(reports))
  1070. return reports.unlink()
  1071. @api.one
  1072. def copy(self, default=None):
  1073. default = dict(default or {})
  1074. default['name'] = _('%s (copy)') % self.name
  1075. return super(MisReportInstance, self).copy(default)
  1076. def _format_date(self, date):
  1077. # format date following user language
  1078. lang_model = self.env['res.lang']
  1079. lang_id = lang_model._lang_get(self.env.user.lang)
  1080. date_format = lang_model.browse(lang_id).date_format
  1081. return datetime.datetime.strftime(
  1082. fields.Date.from_string(date), date_format)
  1083. @api.multi
  1084. @api.depends('date_from')
  1085. def _compute_comparison_mode(self):
  1086. for instance in self:
  1087. instance.comparison_mode = bool(instance.period_ids) and\
  1088. not bool(instance.date_from)
  1089. @api.multi
  1090. def _inverse_comparison_mode(self):
  1091. for record in self:
  1092. if not record.comparison_mode:
  1093. if not record.date_from:
  1094. record.date_from = datetime.now()
  1095. if not record.date_to:
  1096. record.date_to = datetime.now()
  1097. record.period_ids.unlink()
  1098. record.write({'period_ids': [
  1099. (0, 0, {
  1100. 'name': 'Default',
  1101. 'type': 'd',
  1102. })
  1103. ]})
  1104. else:
  1105. record.date_from = None
  1106. record.date_to = None
  1107. @api.onchange('date_range_id')
  1108. def onchange_date_range(self):
  1109. for record in self:
  1110. record.date_from = record.date_range_id.date_start
  1111. record.date_to = record.date_range_id.date_end
  1112. @api.multi
  1113. def preview(self):
  1114. assert len(self) == 1
  1115. view_id = self.env.ref('mis_builder.'
  1116. 'mis_report_instance_result_view_form')
  1117. return {
  1118. 'type': 'ir.actions.act_window',
  1119. 'res_model': 'mis.report.instance',
  1120. 'res_id': self.id,
  1121. 'view_mode': 'form',
  1122. 'view_type': 'form',
  1123. 'view_id': view_id.id,
  1124. 'target': 'current',
  1125. }
  1126. @api.multi
  1127. def print_pdf(self):
  1128. self.ensure_one()
  1129. return {
  1130. 'name': 'MIS report instance QWEB PDF report',
  1131. 'model': 'mis.report.instance',
  1132. 'type': 'ir.actions.report.xml',
  1133. 'report_name': 'mis_builder.report_mis_report_instance',
  1134. 'report_type': 'qweb-pdf',
  1135. 'context': self.env.context,
  1136. }
  1137. @api.multi
  1138. def export_xls(self):
  1139. self.ensure_one()
  1140. return {
  1141. 'name': 'MIS report instance XLSX report',
  1142. 'model': 'mis.report.instance',
  1143. 'type': 'ir.actions.report.xml',
  1144. 'report_name': 'mis.report.instance.xlsx',
  1145. 'report_type': 'xlsx',
  1146. 'context': self.env.context,
  1147. }
  1148. @api.multi
  1149. def display_settings(self):
  1150. assert len(self.ids) <= 1
  1151. view_id = self.env.ref('mis_builder.mis_report_instance_view_form')
  1152. return {
  1153. 'type': 'ir.actions.act_window',
  1154. 'res_model': 'mis.report.instance',
  1155. 'res_id': self.id if self.id else False,
  1156. 'view_mode': 'form',
  1157. 'view_type': 'form',
  1158. 'views': [(view_id.id, 'form')],
  1159. 'view_id': view_id.id,
  1160. 'target': 'current',
  1161. }
  1162. @api.multi
  1163. def compute(self):
  1164. self.ensure_one()
  1165. aep = self.report_id._prepare_aep(self.company_id)
  1166. kpi_matrix = self.report_id._prepare_kpi_matrix()
  1167. for period in self.period_ids:
  1168. # add the column header
  1169. if period.duration == 1 and period.type == 'd':
  1170. comment = self._format_date(period.date_from)
  1171. else:
  1172. # from, to
  1173. date_from = self._format_date(period.date_from)
  1174. date_to = self._format_date(period.date_to)
  1175. comment = _('from %s to %s') % (date_from, date_to)
  1176. self.report_id._compute_period(
  1177. kpi_matrix,
  1178. period.id,
  1179. period.name,
  1180. comment,
  1181. aep,
  1182. period.date_from,
  1183. period.date_to,
  1184. self.target_move,
  1185. self.company_id,
  1186. period.subkpi_ids,
  1187. period._get_additional_move_line_filter,
  1188. period._get_additional_query_filter)
  1189. header = [{'cols': []}, {'cols': []}]
  1190. for col in kpi_matrix.iter_cols():
  1191. header[0]['cols'].append({
  1192. 'description': col.description,
  1193. 'comment': col.comment,
  1194. 'colspan': col.colspan,
  1195. })
  1196. for subcol in col.iter_subcols():
  1197. header[1]['cols'].append({
  1198. 'description': subcol.description,
  1199. 'comment': subcol.comment,
  1200. 'colspan': 1,
  1201. })
  1202. content = []
  1203. for row in kpi_matrix.iter_rows():
  1204. row_data = {
  1205. 'row_id': id(row),
  1206. 'parent_row_id': row.parent_row and id(row.parent_row) or None,
  1207. 'description': row.description,
  1208. 'comment': row.comment,
  1209. 'style': row.style and row.style.to_css_style() or '',
  1210. 'cols': []
  1211. }
  1212. for cell in row.iter_cells(kpi_matrix.iter_subcols()):
  1213. if cell is None:
  1214. row_data['cols'].append({})
  1215. else:
  1216. row_data['cols'].append({
  1217. 'val': (cell.val
  1218. if cell.val is not AccountingNone else None),
  1219. 'val_r': cell.val_rendered,
  1220. 'val_c': cell.val_comment,
  1221. # TODO FIXME style
  1222. # TODO FIXME drilldown
  1223. })
  1224. content.append(row_data)
  1225. return {
  1226. 'header': header,
  1227. 'content': content,
  1228. }
  1229. @api.multi
  1230. def old_compute(self):
  1231. self.ensure_one()
  1232. aep = self.report_id._prepare_aep(self.company_id)
  1233. # fetch user language only once
  1234. # TODO: is this necessary?
  1235. lang = self.env.user.lang
  1236. if not lang:
  1237. lang = 'en_US'
  1238. lang_id = self.env['res.lang'].search([('code', '=', lang)]).id
  1239. # compute kpi values for each period
  1240. kpi_values_by_period_ids = {}
  1241. kpi_matrix = KpiMatrix(lang_id)
  1242. for period in self.period_ids:
  1243. if not period.valid:
  1244. continue
  1245. kpi_values = period._render_period(kpi_matrix, lang_id, aep)
  1246. kpi_values_by_period_ids[period.id] = kpi_values
  1247. kpi_matrix.load_account_names(self.env['account.account'])
  1248. # prepare header and content
  1249. header = [{
  1250. 'kpi_name': '',
  1251. 'cols': []
  1252. }, {
  1253. 'kpi_name': '',
  1254. 'cols': []
  1255. }]
  1256. content = []
  1257. rows_by_kpi_name = {}
  1258. for kpi_name, kpi_description, kpi in kpi_matrix.iter_kpis():
  1259. props = {
  1260. 'kpi_name': kpi_description,
  1261. 'cols': [],
  1262. 'default_style': '',
  1263. 'default_xlsx_style': {},
  1264. }
  1265. rows_by_kpi_name[kpi_name] = props
  1266. if kpi.style:
  1267. props.update({
  1268. 'default_style': kpi.style.to_css_style(),
  1269. 'default_xlsx_style': kpi.style.to_xlsx_format_properties()
  1270. })
  1271. content.append(rows_by_kpi_name[kpi_name])
  1272. # populate header and content
  1273. for period in self.period_ids:
  1274. if not period.valid:
  1275. continue
  1276. # add the column header
  1277. if period.duration > 1 or period.type in ('w', 'date_range'):
  1278. # from, to
  1279. date_from = self._format_date(lang_id, period.date_from)
  1280. date_to = self._format_date(lang_id, period.date_to)
  1281. header_date = _('from %s to %s') % (date_from, date_to)
  1282. else:
  1283. header_date = self._format_date(lang_id, period.date_from)
  1284. subkpis = period.subkpi_ids or \
  1285. period.report_instance_id.report_id.subkpi_ids
  1286. header[0]['cols'].append(dict(
  1287. name=period.name,
  1288. date=header_date,
  1289. colspan=len(subkpis) or 1,
  1290. ))
  1291. if subkpis:
  1292. for subkpi in subkpis:
  1293. header[1]['cols'].append(dict(
  1294. name=subkpi.description,
  1295. colspan=1,
  1296. ))
  1297. else:
  1298. header[1]['cols'].append(dict(
  1299. name="",
  1300. colspan=1,
  1301. ))
  1302. # add kpi values
  1303. kpi_values = kpi_values_by_period_ids[period.id]
  1304. for kpi_name in kpi_values:
  1305. rows_by_kpi_name[kpi_name]['cols'] += kpi_values[kpi_name]
  1306. # add comparison columns
  1307. for compare_col in period.comparison_column_ids:
  1308. compare_kpi_values = \
  1309. kpi_values_by_period_ids.get(compare_col.id)
  1310. if compare_kpi_values:
  1311. # add the comparison column header
  1312. header[0]['cols'].append(
  1313. dict(name=_('%s vs %s') % (period.name,
  1314. compare_col.name),
  1315. date=''))
  1316. # add comparison values
  1317. for kpi in self.report_id.kpi_ids:
  1318. rows_by_kpi_name[kpi.name]['cols'].append({
  1319. 'val_r': kpi.render_comparison(
  1320. lang_id,
  1321. kpi_values[kpi.name]['val'],
  1322. compare_kpi_values[kpi.name]['val'],
  1323. period.normalize_factor,
  1324. compare_col.normalize_factor)
  1325. })
  1326. return {
  1327. 'report_name': self.name,
  1328. 'header': header,
  1329. 'content': content,
  1330. }