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.

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