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.

1043 lines
40 KiB

9 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 defaultdict, 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 odoo import api, fields, models, _
  13. from odoo.exceptions import UserError
  14. from odoo.tools.safe_eval import safe_eval
  15. from .aep import AccountingExpressionProcessor as AEP
  16. from .aggregate import _sum, _avg, _min, _max
  17. from .accounting_none import AccountingNone
  18. from .simple_array import SimpleArray
  19. from .mis_safe_eval import mis_safe_eval, DataError, NameDataError
  20. from .mis_report_style import (
  21. TYPE_NUM, TYPE_PCT, TYPE_STR, CMP_DIFF, CMP_PCT, CMP_NONE
  22. )
  23. _logger = logging.getLogger(__name__)
  24. class AutoStruct(object):
  25. def __init__(self, **kwargs):
  26. for k, v in kwargs.items():
  27. setattr(self, k, v)
  28. class KpiMatrixRow(object):
  29. # TODO: ultimately, the kpi matrix will become ignorant of KPI's and
  30. # accounts and know about rows, columns, sub columns and styles only.
  31. # It is already ignorant of period and only knowns about columns.
  32. # This will require a correct abstraction for expanding row details.
  33. def __init__(self, matrix, kpi, account_id=None, parent_row=None):
  34. self._matrix = matrix
  35. self.kpi = kpi
  36. self.account_id = account_id
  37. self.description = ''
  38. self.parent_row = parent_row
  39. if not self.account_id:
  40. self.style_props = self._matrix._style_model.merge([
  41. self.kpi.report_id.style_id,
  42. self.kpi.style_id])
  43. else:
  44. self.style_props = self._matrix._style_model.merge([
  45. self.kpi.report_id.style_id,
  46. self.kpi.auto_expand_accounts_style_id])
  47. @property
  48. def label(self):
  49. if not self.account_id:
  50. return self.kpi.description
  51. else:
  52. return self._matrix.get_account_name(self.account_id)
  53. @property
  54. def row_id(self):
  55. if not self.account_id:
  56. return self.kpi.name
  57. else:
  58. return '{}:{}'.format(self.kpi.name, self.account_id)
  59. def iter_cell_tuples(self, cols=None):
  60. if cols is None:
  61. cols = self._matrix.iter_cols()
  62. for col in cols:
  63. yield col.get_cell_tuple_for_row(self)
  64. def iter_cells(self, subcols=None):
  65. if subcols is None:
  66. subcols = self._matrix.iter_subcols()
  67. for subcol in subcols:
  68. yield subcol.get_cell_for_row(self)
  69. class KpiMatrixCol(object):
  70. def __init__(self, label, description, locals_dict, subkpis):
  71. self.label = label
  72. self.description = description
  73. self.locals_dict = locals_dict
  74. self.colspan = subkpis and len(subkpis) or 1
  75. self._subcols = []
  76. self.subkpis = subkpis
  77. if not subkpis:
  78. subcol = KpiMatrixSubCol(self, '', '', 0)
  79. self._subcols.append(subcol)
  80. else:
  81. for i, subkpi in enumerate(subkpis):
  82. subcol = KpiMatrixSubCol(self, subkpi.description, '', i)
  83. self._subcols.append(subcol)
  84. self._cell_tuples_by_row = {} # {row: (cells tuple)}
  85. def _set_cell_tuple(self, row, cell_tuple):
  86. self._cell_tuples_by_row[row] = cell_tuple
  87. def iter_subcols(self):
  88. return self._subcols
  89. def iter_cell_tuples(self):
  90. return self._cell_tuples_by_row.values()
  91. def get_cell_tuple_for_row(self, row):
  92. return self._cell_tuples_by_row.get(row)
  93. class KpiMatrixSubCol(object):
  94. def __init__(self, col, label, description, index=0):
  95. self.col = col
  96. self.label = label
  97. self.description = description
  98. self.index = index
  99. @property
  100. def subkpi(self):
  101. if self.col.subkpis:
  102. return self.col.subkpis[self.index]
  103. def iter_cells(self):
  104. for cell_tuple in self.col.iter_cell_tuples():
  105. yield cell_tuple[self.index]
  106. def get_cell_for_row(self, row):
  107. cell_tuple = self.col.get_cell_tuple_for_row(row)
  108. if cell_tuple is None:
  109. return None
  110. return cell_tuple[self.index]
  111. class KpiMatrixCell(object):
  112. def __init__(self, row, subcol,
  113. val, val_rendered, val_comment,
  114. style_props,
  115. drilldown_arg):
  116. self.row = row
  117. self.subcol = subcol
  118. self.val = val
  119. self.val_rendered = val_rendered
  120. self.val_comment = val_comment
  121. self.style_props = style_props
  122. self.drilldown_arg = drilldown_arg
  123. class KpiMatrix(object):
  124. def __init__(self, env):
  125. # cache language id for faster rendering
  126. lang_model = env['res.lang']
  127. self.lang = lang_model._lang_get(env.user.lang)
  128. self._style_model = env['mis.report.style']
  129. self._account_model = env['account.account']
  130. # data structures
  131. # { kpi: KpiMatrixRow }
  132. self._kpi_rows = OrderedDict()
  133. # { kpi: {account_id: KpiMatrixRow} }
  134. self._detail_rows = {}
  135. # { col_key: KpiMatrixCol }
  136. self._cols = OrderedDict()
  137. # { col_key (left of comparison): [(col_key, base_col_key)] }
  138. self._comparison_todo = defaultdict(list)
  139. self._comparison_cols = defaultdict(list)
  140. # { account_id: account_name }
  141. self._account_names = {}
  142. def declare_kpi(self, kpi):
  143. """ Declare a new kpi (row) in the matrix.
  144. Invoke this first for all kpi, in display order.
  145. """
  146. self._kpi_rows[kpi] = KpiMatrixRow(self, kpi)
  147. self._detail_rows[kpi] = {}
  148. def declare_col(self, col_key, label, description,
  149. locals_dict, subkpis):
  150. """ Declare a new column, giving it an identifier (key).
  151. Invoke this and declare_comparison in display order.
  152. """
  153. col = KpiMatrixCol(label, description, locals_dict, subkpis)
  154. self._cols[col_key] = col
  155. return col
  156. def declare_comparison(self, col_key, base_col_key):
  157. """ Declare a new comparison column.
  158. Invoke this and declare_col in display order.
  159. """
  160. last_col_key = list(self._cols.keys())[-1]
  161. self._comparison_todo[last_col_key].append(
  162. (col_key, base_col_key))
  163. def set_values(self, kpi, col_key, vals,
  164. drilldown_args):
  165. """ Set values for a kpi and a colum.
  166. Invoke this after declaring the kpi and the column.
  167. """
  168. self.set_values_detail_account(kpi, col_key, None, vals,
  169. drilldown_args)
  170. def set_values_detail_account(self, kpi, col_key, account_id, vals,
  171. drilldown_args):
  172. """ Set values for a kpi and a column and a detail account.
  173. Invoke this after declaring the kpi and the column.
  174. """
  175. if not account_id:
  176. row = self._kpi_rows[kpi]
  177. else:
  178. kpi_row = self._kpi_rows[kpi]
  179. if account_id in self._detail_rows[kpi]:
  180. row = self._detail_rows[kpi][account_id]
  181. else:
  182. row = KpiMatrixRow(self, kpi, account_id, parent_row=kpi_row)
  183. self._detail_rows[kpi][account_id] = row
  184. col = self._cols[col_key]
  185. cell_tuple = []
  186. assert len(vals) == col.colspan
  187. assert len(drilldown_args) == col.colspan
  188. for val, drilldown_arg, subcol in \
  189. izip(vals, drilldown_args, col.iter_subcols()):
  190. if isinstance(val, DataError):
  191. val_rendered = val.name
  192. val_comment = val.msg
  193. else:
  194. val_rendered = self._style_model.render(
  195. self.lang, row.style_props, kpi.type, val)
  196. if subcol.subkpi:
  197. val_comment = u'{}.{} = {}'.format(
  198. row.kpi.name,
  199. subcol.subkpi.name,
  200. row.kpi._get_expression_for_subkpi(subcol.subkpi))
  201. else:
  202. val_comment = u'{} = {}'.format(
  203. row.kpi.name,
  204. row.kpi.expression)
  205. cell_style_props = row.style_props
  206. if row.kpi.style_expression:
  207. # evaluate style expression
  208. try:
  209. style_name = mis_safe_eval(row.kpi.style_expression,
  210. col.locals_dict)
  211. except:
  212. _logger.error("Error evaluating style expression <%s>",
  213. row.kpi.style_expression, exc_info=True)
  214. if style_name:
  215. style = self._style_model.search(
  216. [('name', '=', style_name)])
  217. if style:
  218. cell_style_props = self._style_model.merge(
  219. [row.style_props, style[0]])
  220. else:
  221. _logger.error("Style '%s' not found.", style_name)
  222. cell = KpiMatrixCell(row, subcol, val, val_rendered, val_comment,
  223. cell_style_props, drilldown_arg)
  224. cell_tuple.append(cell)
  225. assert len(cell_tuple) == col.colspan
  226. col._set_cell_tuple(row, cell_tuple)
  227. def compute_comparisons(self):
  228. """ Compute comparisons.
  229. Invoke this after setting all values.
  230. """
  231. for pos_col_key, comparisons in self._comparison_todo.items():
  232. for col_key, base_col_key in comparisons:
  233. col = self._cols[col_key]
  234. base_col = self._cols[base_col_key]
  235. common_subkpis = set(col.subkpis) & set(base_col.subkpis)
  236. if (col.subkpis or base_col.subkpis) and not common_subkpis:
  237. raise UserError('Columns {} and {} are not comparable'.
  238. format(col.description,
  239. base_col.description))
  240. label = u'{} vs {}'.\
  241. format(col.label, base_col.label)
  242. comparison_col = KpiMatrixCol(label, None, {},
  243. sorted(common_subkpis,
  244. key=lambda s: s.sequence))
  245. for row in self.iter_rows():
  246. cell_tuple = col.get_cell_tuple_for_row(row)
  247. base_cell_tuple = base_col.get_cell_tuple_for_row(row)
  248. if cell_tuple is None and base_cell_tuple is None:
  249. continue
  250. if cell_tuple is None:
  251. vals = [AccountingNone] * \
  252. (len(common_subkpis) or 1)
  253. else:
  254. vals = [cell.val for cell in cell_tuple
  255. if not common_subkpis or
  256. cell.subcol.subkpi in common_subkpis]
  257. if base_cell_tuple is None:
  258. base_vals = [AccountingNone] * \
  259. (len(common_subkpis) or 1)
  260. else:
  261. base_vals = [cell.val for cell in base_cell_tuple
  262. if not common_subkpis or
  263. cell.subcol.subkpi in common_subkpis]
  264. comparison_cell_tuple = []
  265. for val, base_val, comparison_subcol in \
  266. izip(vals,
  267. base_vals,
  268. comparison_col.iter_subcols()):
  269. # TODO FIXME average factors
  270. delta, delta_r, style_r = \
  271. self._style_model.compare_and_render(
  272. self.lang, row.style_props,
  273. row.kpi.type, row.kpi.compare_method,
  274. val, base_val, 1, 1)
  275. comparison_cell_tuple.append(KpiMatrixCell(
  276. row, comparison_subcol, delta, delta_r, None,
  277. style_r, None))
  278. comparison_col._set_cell_tuple(row, comparison_cell_tuple)
  279. self._comparison_cols[pos_col_key].append(comparison_col)
  280. def iter_rows(self):
  281. """ Iterate rows in display order.
  282. yields KpiMatrixRow.
  283. """
  284. for kpi_row in self._kpi_rows.values():
  285. yield kpi_row
  286. detail_rows = self._detail_rows[kpi_row.kpi].values()
  287. detail_rows = sorted(detail_rows, key=lambda r: r.description)
  288. for detail_row in detail_rows:
  289. yield detail_row
  290. def iter_cols(self):
  291. """ Iterate columns in display order.
  292. yields KpiMatrixCol: one for each column or comparison.
  293. """
  294. for col_key, col in self._cols.items():
  295. yield col
  296. for comparison_col in self._comparison_cols[col_key]:
  297. yield comparison_col
  298. def iter_subcols(self):
  299. """ Iterate sub columns in display order.
  300. yields KpiMatrixSubCol: one for each subkpi in each column
  301. and comparison.
  302. """
  303. for col in self.iter_cols():
  304. for subcol in col.iter_subcols():
  305. yield subcol
  306. def _load_account_names(self):
  307. account_ids = set()
  308. for detail_rows in self._detail_rows.values():
  309. account_ids.update(detail_rows.keys())
  310. account_ids = list(account_ids)
  311. accounts = self._account_model.search([('id', 'in', account_ids)])
  312. self._account_names = {a.id: u'{} {}'.format(a.code, a.name)
  313. for a in accounts}
  314. def get_account_name(self, account_id):
  315. if account_id not in self._account_names:
  316. self._load_account_names()
  317. return self._account_names[account_id]
  318. def as_dict(self):
  319. header = [{'cols': []}, {'cols': []}]
  320. for col in self.iter_cols():
  321. header[0]['cols'].append({
  322. 'label': col.label,
  323. 'description': col.description,
  324. 'colspan': col.colspan,
  325. })
  326. for subcol in col.iter_subcols():
  327. header[1]['cols'].append({
  328. 'label': subcol.label,
  329. 'description': subcol.description,
  330. 'colspan': 1,
  331. })
  332. body = []
  333. for row in self.iter_rows():
  334. row_data = {
  335. 'row_id': row.row_id,
  336. 'parent_row_id': (row.parent_row and
  337. row.parent_row.row_id or None),
  338. 'label': row.label,
  339. 'description': row.description,
  340. 'style': self._style_model.to_css_style(
  341. row.style_props),
  342. 'cells': []
  343. }
  344. for cell in row.iter_cells():
  345. if cell is None:
  346. # TODO use subcol style here
  347. row_data['cells'].append({})
  348. else:
  349. if cell.val is AccountingNone or \
  350. isinstance(cell.val, DataError):
  351. val = None
  352. else:
  353. val = cell.val
  354. col_data = {
  355. 'val': val,
  356. 'val_r': cell.val_rendered,
  357. 'val_c': cell.val_comment,
  358. 'style': self._style_model.to_css_style(
  359. cell.style_props, no_indent=True),
  360. }
  361. if cell.drilldown_arg:
  362. col_data['drilldown_arg'] = cell.drilldown_arg
  363. row_data['cells'].append(col_data)
  364. body.append(row_data)
  365. return {
  366. 'header': header,
  367. 'body': body,
  368. }
  369. def _utc_midnight(d, tz_name, add_day=0):
  370. d = fields.Datetime.from_string(d) + datetime.timedelta(days=add_day)
  371. utc_tz = pytz.timezone('UTC')
  372. context_tz = pytz.timezone(tz_name)
  373. local_timestamp = context_tz.localize(d, is_dst=False)
  374. return fields.Datetime.to_string(local_timestamp.astimezone(utc_tz))
  375. def _python_var(var_str):
  376. return re.sub(r'\W|^(?=\d)', '_', var_str).lower()
  377. def _is_valid_python_var(name):
  378. return re.match("[_A-Za-z][_a-zA-Z0-9]*$", name)
  379. class MisReportKpi(models.Model):
  380. """ A KPI is an element (ie a line) of a MIS report.
  381. In addition to a name and description, it has an expression
  382. to compute it based on queries defined in the MIS report.
  383. It also has various informations defining how to render it
  384. (numeric or percentage or a string, a prefix, a suffix, divider) and
  385. how to render comparison of two values of the KPI.
  386. KPI's have a sequence and are ordered inside the MIS report.
  387. """
  388. _name = 'mis.report.kpi'
  389. name = fields.Char(size=32, required=True,
  390. string='Name')
  391. description = fields.Char(required=True,
  392. string='Description',
  393. translate=True)
  394. multi = fields.Boolean()
  395. expression = fields.Char(
  396. compute='_compute_expression',
  397. inverse='_inverse_expression')
  398. expression_ids = fields.One2many('mis.report.kpi.expression', 'kpi_id')
  399. auto_expand_accounts = fields.Boolean(string='Display details by account')
  400. auto_expand_accounts_style_id = fields.Many2one(
  401. string="Style for account detail rows",
  402. comodel_name="mis.report.style",
  403. required=False
  404. )
  405. style_id = fields.Many2one(
  406. string="Style",
  407. comodel_name="mis.report.style",
  408. required=False
  409. )
  410. style_expression = fields.Char(
  411. string='Style expression',
  412. help='An expression that returns a style depending on the KPI value. '
  413. 'Such style is applied on top of the row style.')
  414. type = fields.Selection([(TYPE_NUM, _('Numeric')),
  415. (TYPE_PCT, _('Percentage')),
  416. (TYPE_STR, _('String'))],
  417. required=True,
  418. string='Value type',
  419. default=TYPE_NUM)
  420. compare_method = fields.Selection([(CMP_DIFF, _('Difference')),
  421. (CMP_PCT, _('Percentage')),
  422. (CMP_NONE, _('None'))],
  423. required=True,
  424. string='Comparison Method',
  425. default=CMP_PCT)
  426. sequence = fields.Integer(string='Sequence', default=100)
  427. report_id = fields.Many2one('mis.report',
  428. string='Report',
  429. ondelete='cascade')
  430. _order = 'sequence, id'
  431. @api.constrains('name')
  432. def _check_name(self):
  433. for record in self:
  434. if not _is_valid_python_var(record.name):
  435. raise UserError(_('The name must be a valid python '
  436. 'identifier'))
  437. @api.onchange('name')
  438. def _onchange_name(self):
  439. if self.name and not _is_valid_python_var(self.name):
  440. return {
  441. 'warning': {
  442. 'title': 'Invalid name %s' % self.name,
  443. 'message': 'The name must be a valid python identifier'
  444. }
  445. }
  446. @api.multi
  447. @api.depends('expression_ids.subkpi_id.name', 'expression_ids.name')
  448. def _compute_expression(self):
  449. for kpi in self:
  450. l = []
  451. for expression in kpi.expression_ids:
  452. if expression.subkpi_id:
  453. l.append(u'{}\xa0=\xa0{}'.format(
  454. expression.subkpi_id.name, expression.name))
  455. else:
  456. l.append(
  457. expression.name or 'AccountingNone')
  458. kpi.expression = ',\n'.join(l)
  459. @api.multi
  460. def _inverse_expression(self):
  461. for kpi in self:
  462. if kpi.multi:
  463. raise UserError(_('Can not update a multi kpi from '
  464. 'the kpi line'))
  465. if kpi.expression_ids:
  466. kpi.expression_ids[0].write({
  467. 'name': kpi.expression,
  468. 'subkpi_id': None})
  469. for expression in kpi.expression_ids[1:]:
  470. expression.unlink()
  471. else:
  472. kpi.write({
  473. 'expression_ids': [(0, 0, {
  474. 'name': kpi.expression
  475. })]
  476. })
  477. @api.onchange('multi')
  478. def _onchange_multi(self):
  479. for kpi in self:
  480. if not kpi.multi:
  481. if kpi.expression_ids:
  482. kpi.expression = kpi.expression_ids[0].name
  483. else:
  484. kpi.expression = None
  485. else:
  486. expressions = []
  487. for subkpi in kpi.report_id.subkpi_ids:
  488. expressions.append((0, 0, {
  489. 'name': kpi.expression,
  490. 'subkpi_id': subkpi.id,
  491. }))
  492. kpi.expression_ids = expressions
  493. @api.onchange('description')
  494. def _onchange_description(self):
  495. """ construct name from description """
  496. if self.description and not self.name:
  497. self.name = _python_var(self.description)
  498. @api.onchange('type')
  499. def _onchange_type(self):
  500. if self.type == TYPE_NUM:
  501. self.compare_method = CMP_PCT
  502. elif self.type == TYPE_PCT:
  503. self.compare_method = CMP_DIFF
  504. elif self.type == TYPE_STR:
  505. self.compare_method = CMP_NONE
  506. def _get_expression_for_subkpi(self, subkpi):
  507. for expression in self.expression_ids:
  508. if expression.subkpi_id == subkpi:
  509. return expression.name or 'AccountingNone'
  510. return 'AccountingNone'
  511. def _get_expressions(self, subkpis):
  512. if subkpis and self.multi:
  513. return [
  514. self._get_expression_for_subkpi(subkpi)
  515. for subkpi in subkpis
  516. ]
  517. else:
  518. if self.expression_ids:
  519. assert len(self.expression_ids) == 1
  520. assert not self.expression_ids[0].subkpi_id
  521. return [self.expression_ids[0].name or 'AccountingNone']
  522. else:
  523. return ['AccountingNone']
  524. class MisReportSubkpi(models.Model):
  525. _name = 'mis.report.subkpi'
  526. _order = 'sequence'
  527. sequence = fields.Integer()
  528. report_id = fields.Many2one('mis.report')
  529. name = fields.Char(size=32, required=True,
  530. string='Name')
  531. description = fields.Char(required=True,
  532. string='Description',
  533. translate=True)
  534. expression_ids = fields.One2many('mis.report.kpi.expression', 'subkpi_id')
  535. @api.constrains('name')
  536. def _check_name(self):
  537. for record in self:
  538. if not _is_valid_python_var(record.name):
  539. raise UserError(_('The name must be a valid python '
  540. 'identifier'))
  541. @api.onchange('name')
  542. def _onchange_name(self):
  543. if self.name and not _is_valid_python_var(self.name):
  544. return {
  545. 'warning': {
  546. 'title': 'Invalid name %s' % self.name,
  547. 'message': 'The name must be a valid python identifier'
  548. }
  549. }
  550. @api.onchange('description')
  551. def _onchange_description(self):
  552. """ construct name from description """
  553. if self.description and not self.name:
  554. self.name = _python_var(self.description)
  555. @api.multi
  556. def unlink(self):
  557. for subkpi in self:
  558. subkpi.expression_ids.unlink()
  559. return super(MisReportSubkpi, self).unlink()
  560. class MisReportKpiExpression(models.Model):
  561. """ A KPI Expression is an expression of a line of a MIS report Kpi.
  562. It's used to compute the kpi value.
  563. """
  564. _name = 'mis.report.kpi.expression'
  565. _order = 'sequence, name'
  566. sequence = fields.Integer(
  567. related='subkpi_id.sequence',
  568. store=True,
  569. readonly=True)
  570. name = fields.Char(string='Expression')
  571. kpi_id = fields.Many2one('mis.report.kpi', required=True)
  572. # TODO FIXME set readonly=True when onchange('subkpi_ids') below works
  573. subkpi_id = fields.Many2one(
  574. 'mis.report.subkpi',
  575. readonly=False)
  576. _sql_constraints = [
  577. ('subkpi_kpi_unique', 'unique(subkpi_id, kpi_id)',
  578. 'Sub KPI must be used once and only once for each KPI'),
  579. ]
  580. class MisReportQuery(models.Model):
  581. """ A query to fetch arbitrary data for a MIS report.
  582. A query works on a model and has a domain and list of fields to fetch.
  583. At runtime, the domain is expanded with a "and" on the date/datetime field.
  584. """
  585. _name = 'mis.report.query'
  586. @api.depends('field_ids')
  587. def _compute_field_names(self):
  588. for record in self:
  589. field_names = [field.name for field in record.field_ids]
  590. record.field_names = ', '.join(field_names)
  591. name = fields.Char(size=32, required=True,
  592. string='Name')
  593. model_id = fields.Many2one('ir.model', required=True,
  594. string='Model')
  595. field_ids = fields.Many2many('ir.model.fields', required=True,
  596. string='Fields to fetch')
  597. field_names = fields.Char(compute='_compute_field_names',
  598. string='Fetched fields name')
  599. aggregate = fields.Selection([('sum', _('Sum')),
  600. ('avg', _('Average')),
  601. ('min', _('Min')),
  602. ('max', _('Max'))],
  603. string='Aggregate')
  604. date_field = fields.Many2one('ir.model.fields', required=True,
  605. string='Date field',
  606. domain=[('ttype', 'in',
  607. ('date', 'datetime'))])
  608. domain = fields.Char(string='Domain')
  609. report_id = fields.Many2one('mis.report', string='Report',
  610. ondelete='cascade')
  611. _order = 'name'
  612. @api.constrains('name')
  613. def _check_name(self):
  614. for record in self:
  615. if not _is_valid_python_var(record.name):
  616. raise UserError(_('The name must be a valid python '
  617. 'identifier'))
  618. class MisReport(models.Model):
  619. """ A MIS report template (without period information)
  620. The MIS report holds:
  621. * a list of explicit queries; the result of each query is
  622. stored in a variable with same name as a query, containing as list
  623. of data structures populated with attributes for each fields to fetch;
  624. when queries have an aggregate method and no fields to group, it returns
  625. a data structure with the aggregated fields
  626. * a list of KPI to be evaluated based on the variables resulting
  627. from the accounting data and queries (KPI expressions can references
  628. queries and accounting expression - see AccoutingExpressionProcessor)
  629. """
  630. _name = 'mis.report'
  631. name = fields.Char(required=True,
  632. string='Name', translate=True)
  633. description = fields.Char(required=False,
  634. string='Description', translate=True)
  635. style_id = fields.Many2one(string="Style",
  636. comodel_name="mis.report.style")
  637. query_ids = fields.One2many('mis.report.query', 'report_id',
  638. string='Queries',
  639. copy=True)
  640. kpi_ids = fields.One2many('mis.report.kpi', 'report_id',
  641. string='KPI\'s',
  642. copy=True)
  643. subkpi_ids = fields.One2many('mis.report.subkpi', 'report_id',
  644. string="Sub KPI",
  645. copy=True)
  646. @api.onchange('subkpi_ids')
  647. def _on_change_subkpi_ids(self):
  648. """ Update kpi expressions when subkpis change on the report,
  649. so the list of kpi expressions is always up-to-date """
  650. for kpi in self.kpi_ids:
  651. if not kpi.multi:
  652. continue
  653. new_subkpis = set([subkpi for subkpi in self.subkpi_ids])
  654. expressions = []
  655. for expression in kpi.expression_ids:
  656. assert expression.subkpi_id # must be true if kpi is multi
  657. if expression.subkpi_id not in self.subkpi_ids:
  658. expressions.append((2, expression.id, None)) # remove
  659. else:
  660. new_subkpis.remove(expression.subkpi_id) # no change
  661. for subkpi in new_subkpis:
  662. # TODO FIXME this does not work, while the remove above works
  663. expressions.append((0, None, {
  664. 'name': False,
  665. 'subkpi_id': subkpi.id,
  666. })) # add empty expressions for new subkpis
  667. if expressions:
  668. kpi.expressions_ids = expressions
  669. @api.multi
  670. def get_wizard_report_action(self):
  671. action = self.env.ref('mis_builder.mis_report_instance_view_action')
  672. res = action.read()[0]
  673. view = self.env.ref('mis_builder.wizard_mis_report_instance_view_form')
  674. res.update({
  675. 'view_id': view.id,
  676. 'views': [(view.id, 'form')],
  677. 'target': 'new',
  678. 'context': {
  679. 'default_report_id': self.id,
  680. 'default_name': self.name,
  681. 'default_temporary': True,
  682. }
  683. })
  684. return res
  685. @api.multi
  686. def copy(self, default=None):
  687. self.ensure_one()
  688. default = dict(default or {})
  689. default['name'] = _('%s (copy)') % self.name
  690. return super(MisReport, self).copy(default)
  691. # TODO: kpi name cannot be start with query name
  692. @api.multi
  693. def prepare_kpi_matrix(self):
  694. self.ensure_one()
  695. kpi_matrix = KpiMatrix(self.env)
  696. for kpi in self.kpi_ids:
  697. kpi_matrix.declare_kpi(kpi)
  698. return kpi_matrix
  699. @api.multi
  700. def _prepare_aep(self, company):
  701. self.ensure_one()
  702. aep = AEP(company)
  703. for kpi in self.kpi_ids:
  704. for expression in kpi.expression_ids:
  705. if expression.name:
  706. aep.parse_expr(expression.name)
  707. aep.done_parsing()
  708. return aep
  709. def prepare_locals_dict(self):
  710. return {
  711. 'sum': _sum,
  712. 'min': _min,
  713. 'max': _max,
  714. 'len': len,
  715. 'avg': _avg,
  716. 'AccountingNone': AccountingNone,
  717. 'SimpleArray': SimpleArray,
  718. }
  719. @api.multi
  720. def _fetch_queries(self, date_from, date_to,
  721. get_additional_query_filter=None):
  722. self.ensure_one()
  723. res = {}
  724. for query in self.query_ids:
  725. model = self.env[query.model_id.model]
  726. eval_context = {
  727. 'env': self.env,
  728. 'time': time,
  729. 'datetime': datetime,
  730. 'dateutil': dateutil,
  731. # deprecated
  732. 'uid': self.env.uid,
  733. 'context': self.env.context,
  734. }
  735. domain = query.domain and \
  736. safe_eval(query.domain, eval_context) or []
  737. if get_additional_query_filter:
  738. domain.extend(get_additional_query_filter(query))
  739. if query.date_field.ttype == 'date':
  740. domain.extend([(query.date_field.name, '>=', date_from),
  741. (query.date_field.name, '<=', date_to)])
  742. else:
  743. datetime_from = _utc_midnight(
  744. date_from, self._context.get('tz', 'UTC'))
  745. datetime_to = _utc_midnight(
  746. date_to, self._context.get('tz', 'UTC'), add_day=1)
  747. domain.extend([(query.date_field.name, '>=', datetime_from),
  748. (query.date_field.name, '<', datetime_to)])
  749. field_names = [f.name for f in query.field_ids]
  750. all_stored = all([model._fields[f].store for f in field_names])
  751. if not query.aggregate:
  752. data = model.search_read(domain, field_names)
  753. res[query.name] = [AutoStruct(**d) for d in data]
  754. elif query.aggregate == 'sum' and all_stored:
  755. # use read_group to sum stored fields
  756. data = model.read_group(
  757. domain, field_names, [])
  758. s = AutoStruct(count=data[0]['__count'])
  759. for field_name in field_names:
  760. try:
  761. v = data[0][field_name]
  762. except KeyError:
  763. _logger.error('field %s not found in read_group '
  764. 'for %s; not summable?',
  765. field_name, model._name)
  766. v = AccountingNone
  767. setattr(s, field_name, v)
  768. res[query.name] = s
  769. else:
  770. data = model.search_read(domain, field_names)
  771. s = AutoStruct(count=len(data))
  772. if query.aggregate == 'min':
  773. agg = _min
  774. elif query.aggregate == 'max':
  775. agg = _max
  776. elif query.aggregate == 'avg':
  777. agg = _avg
  778. elif query.aggregate == 'sum':
  779. agg = _sum
  780. for field_name in field_names:
  781. setattr(s, field_name,
  782. agg([d[field_name] for d in data]))
  783. res[query.name] = s
  784. return res
  785. @api.multi
  786. def declare_and_compute_period(self, kpi_matrix,
  787. col_key,
  788. col_label,
  789. col_description,
  790. aep,
  791. date_from, date_to,
  792. target_move,
  793. subkpis_filter=None,
  794. get_additional_move_line_filter=None,
  795. get_additional_query_filter=None,
  796. locals_dict=None):
  797. """ Evaluate a report for a given period, populating a KpiMatrix.
  798. :param kpi_matrix: the KpiMatrix object to be populated created
  799. with prepare_kpi_matrix()
  800. :param col_key: the period key to use when populating the KpiMatrix
  801. :param aep: an AccountingExpressionProcessor instance created
  802. using _prepare_aep()
  803. :param date_from, date_to: the starting and ending date
  804. :param target_move: all|posted
  805. :param get_additional_move_line_filter: a bound method that takes
  806. no arguments and returns
  807. a domain compatible with
  808. account.move.line
  809. :param get_additional_query_filter: a bound method that takes a single
  810. query argument and returns a
  811. domain compatible with the query
  812. underlying model
  813. :param locals_dict: personalized locals dictionary used as evaluation
  814. context for the KPI expressions
  815. """
  816. self.ensure_one()
  817. # prepare the localsdict
  818. if locals_dict is None:
  819. locals_dict = {}
  820. locals_dict.update(self.prepare_locals_dict())
  821. # fetch non-accounting queries
  822. locals_dict.update(self._fetch_queries(
  823. date_from, date_to, get_additional_query_filter))
  824. # use AEP to do the accounting queries
  825. additional_move_line_filter = None
  826. if get_additional_move_line_filter:
  827. additional_move_line_filter = get_additional_move_line_filter()
  828. aep.do_queries(date_from, date_to,
  829. target_move,
  830. additional_move_line_filter)
  831. if subkpis_filter:
  832. subkpis = [subkpi for subkpi in self.subkpi_ids
  833. if subkpi in subkpis_filter]
  834. else:
  835. subkpis = self.subkpi_ids
  836. col = kpi_matrix.declare_col(col_key,
  837. col_label, col_description,
  838. locals_dict, subkpis)
  839. compute_queue = self.kpi_ids
  840. recompute_queue = []
  841. while True:
  842. for kpi in compute_queue:
  843. # build the list of expressions for this kpi
  844. expressions = kpi._get_expressions(subkpis)
  845. vals = []
  846. drilldown_args = []
  847. name_error = False
  848. for expression in expressions:
  849. replaced_expr = aep.replace_expr(expression)
  850. vals.append(
  851. mis_safe_eval(replaced_expr, locals_dict))
  852. if isinstance(vals[-1], NameDataError):
  853. name_error = True
  854. if replaced_expr != expression:
  855. drilldown_args.append({
  856. 'period_id': col_key,
  857. 'expr': expression,
  858. })
  859. else:
  860. drilldown_args.append(None)
  861. if name_error:
  862. recompute_queue.append(kpi)
  863. else:
  864. # no error, set it in locals_dict so it can be used
  865. # in computing other kpis
  866. if len(expressions) == 1:
  867. locals_dict[kpi.name] = vals[0]
  868. else:
  869. locals_dict[kpi.name] = SimpleArray(vals)
  870. # even in case of name error we set the result in the matrix
  871. # so the name error will be displayed if it cannot be
  872. # resolved by recomputing later
  873. if len(expressions) == 1 and col.colspan > 1:
  874. if isinstance(vals[0], tuple):
  875. vals = vals[0]
  876. assert len(vals) == col.colspan
  877. elif isinstance(vals[0], DataError):
  878. vals = (vals[0],) * col.colspan
  879. else:
  880. raise UserError(_("Probably not your fault... but I'm "
  881. "really curious to know how you "
  882. "managed to raise this error so "
  883. "I can handle one more corner "
  884. "case!"))
  885. if len(drilldown_args) != col.colspan:
  886. drilldown_args = [None] * col.colspan
  887. kpi_matrix.set_values(
  888. kpi, col_key, vals, drilldown_args)
  889. if not kpi.auto_expand_accounts or name_error:
  890. continue
  891. for account_id, replaced_exprs in \
  892. aep.replace_exprs_by_account_id(expressions):
  893. vals = []
  894. drilldown_args = []
  895. for expression, replaced_expr in \
  896. izip(expressions, replaced_exprs):
  897. vals.append(mis_safe_eval(replaced_expr, locals_dict))
  898. if replaced_expr != expression:
  899. drilldown_args.append({
  900. 'period_id': col_key,
  901. 'expr': expression,
  902. 'account_id': account_id
  903. })
  904. else:
  905. drilldown_args.append(None)
  906. kpi_matrix.set_values_detail_account(
  907. kpi, col_key, account_id, vals, drilldown_args)
  908. if len(recompute_queue) == 0:
  909. # nothing to recompute, we are done
  910. break
  911. if len(recompute_queue) == len(compute_queue):
  912. # could not compute anything in this iteration
  913. # (ie real Name errors or cyclic dependency)
  914. # so we stop trying
  915. break
  916. # try again
  917. compute_queue = recompute_queue
  918. recompute_queue = []