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.

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