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.

1032 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),
  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. def _compute_expression(self):
  448. for kpi in self:
  449. l = []
  450. for expression in kpi.expression_ids:
  451. if expression.subkpi_id:
  452. l.append(u'{}\xa0=\xa0{}'.format(
  453. expression.subkpi_id.name, expression.name))
  454. else:
  455. l.append(
  456. expression.name or 'AccountingNone')
  457. kpi.expression = ',\n'.join(l)
  458. @api.multi
  459. def _inverse_expression(self):
  460. for kpi in self:
  461. if kpi.multi:
  462. raise UserError(_('Can not update a multi kpi from '
  463. 'the kpi line'))
  464. if kpi.expression_ids:
  465. kpi.expression_ids[0].write({
  466. 'name': kpi.expression,
  467. 'subkpi_id': None})
  468. for expression in kpi.expression_ids[1:]:
  469. expression.unlink()
  470. else:
  471. kpi.write({
  472. 'expression_ids': [(0, 0, {
  473. 'name': kpi.expression
  474. })]
  475. })
  476. @api.onchange('multi')
  477. def _onchange_multi(self):
  478. for kpi in self:
  479. if not kpi.multi:
  480. if kpi.expression_ids:
  481. kpi.expression = kpi.expression_ids[0].name
  482. else:
  483. kpi.expression = None
  484. else:
  485. expressions = []
  486. for subkpi in kpi.report_id.subkpi_ids:
  487. expressions.append((0, 0, {
  488. 'name': kpi.expression,
  489. 'subkpi_id': subkpi.id,
  490. }))
  491. kpi.expression_ids = expressions
  492. @api.onchange('description')
  493. def _onchange_description(self):
  494. """ construct name from description """
  495. if self.description and not self.name:
  496. self.name = _python_var(self.description)
  497. @api.onchange('type')
  498. def _onchange_type(self):
  499. if self.type == TYPE_NUM:
  500. self.compare_method = CMP_PCT
  501. elif self.type == TYPE_PCT:
  502. self.compare_method = CMP_DIFF
  503. elif self.type == TYPE_STR:
  504. self.compare_method = CMP_NONE
  505. def get_expression_for_subkpi(self, subkpi):
  506. for expression in self.expression_ids:
  507. if expression.subkpi_id == subkpi:
  508. return expression.name
  509. class MisReportSubkpi(models.Model):
  510. _name = 'mis.report.subkpi'
  511. _order = 'sequence'
  512. sequence = fields.Integer()
  513. report_id = fields.Many2one('mis.report')
  514. name = fields.Char(size=32, required=True,
  515. string='Name')
  516. description = fields.Char(required=True,
  517. string='Description',
  518. translate=True)
  519. expression_ids = fields.One2many('mis.report.kpi.expression', 'subkpi_id')
  520. @api.constrains('name')
  521. def _check_name(self):
  522. for record in self:
  523. if not _is_valid_python_var(record.name):
  524. raise UserError(_('The name must be a valid python '
  525. 'identifier'))
  526. @api.onchange('name')
  527. def _onchange_name(self):
  528. if self.name and not _is_valid_python_var(self.name):
  529. return {
  530. 'warning': {
  531. 'title': 'Invalid name %s' % self.name,
  532. 'message': 'The name must be a valid python identifier'
  533. }
  534. }
  535. @api.onchange('description')
  536. def _onchange_description(self):
  537. """ construct name from description """
  538. if self.description and not self.name:
  539. self.name = _python_var(self.description)
  540. @api.multi
  541. def unlink(self):
  542. for subkpi in self:
  543. subkpi.expression_ids.unlink()
  544. return super(MisReportSubkpi, self).unlink()
  545. class MisReportKpiExpression(models.Model):
  546. """ A KPI Expression is an expression of a line of a MIS report Kpi.
  547. It's used to compute the kpi value.
  548. """
  549. _name = 'mis.report.kpi.expression'
  550. _order = 'sequence, name'
  551. sequence = fields.Integer(
  552. related='subkpi_id.sequence',
  553. store=True,
  554. readonly=True)
  555. name = fields.Char(string='Expression')
  556. kpi_id = fields.Many2one('mis.report.kpi')
  557. # TODO FIXME set readonly=True when onchange('subkpi_ids') below works
  558. subkpi_id = fields.Many2one(
  559. 'mis.report.subkpi',
  560. readonly=False)
  561. _sql_constraints = [
  562. ('subkpi_kpi_unique', 'unique(subkpi_id, kpi_id)',
  563. 'Sub KPI must be used once and only once for each KPI'),
  564. ]
  565. class MisReportQuery(models.Model):
  566. """ A query to fetch arbitrary data for a MIS report.
  567. A query works on a model and has a domain and list of fields to fetch.
  568. At runtime, the domain is expanded with a "and" on the date/datetime field.
  569. """
  570. _name = 'mis.report.query'
  571. @api.depends('field_ids')
  572. def _compute_field_names(self):
  573. for record in self:
  574. field_names = [field.name for field in record.field_ids]
  575. record.field_names = ', '.join(field_names)
  576. name = fields.Char(size=32, required=True,
  577. string='Name')
  578. model_id = fields.Many2one('ir.model', required=True,
  579. string='Model')
  580. field_ids = fields.Many2many('ir.model.fields', required=True,
  581. string='Fields to fetch')
  582. field_names = fields.Char(compute='_compute_field_names',
  583. string='Fetched fields name')
  584. aggregate = fields.Selection([('sum', _('Sum')),
  585. ('avg', _('Average')),
  586. ('min', _('Min')),
  587. ('max', _('Max'))],
  588. string='Aggregate')
  589. date_field = fields.Many2one('ir.model.fields', required=True,
  590. string='Date field',
  591. domain=[('ttype', 'in',
  592. ('date', 'datetime'))])
  593. domain = fields.Char(string='Domain')
  594. report_id = fields.Many2one('mis.report', string='Report',
  595. ondelete='cascade')
  596. _order = 'name'
  597. @api.constrains('name')
  598. def _check_name(self):
  599. for record in self:
  600. if not _is_valid_python_var(record.name):
  601. raise UserError(_('The name must be a valid python '
  602. 'identifier'))
  603. class MisReport(models.Model):
  604. """ A MIS report template (without period information)
  605. The MIS report holds:
  606. * a list of explicit queries; the result of each query is
  607. stored in a variable with same name as a query, containing as list
  608. of data structures populated with attributes for each fields to fetch;
  609. when queries have an aggregate method and no fields to group, it returns
  610. a data structure with the aggregated fields
  611. * a list of KPI to be evaluated based on the variables resulting
  612. from the accounting data and queries (KPI expressions can references
  613. queries and accounting expression - see AccoutingExpressionProcessor)
  614. """
  615. _name = 'mis.report'
  616. name = fields.Char(required=True,
  617. string='Name', translate=True)
  618. description = fields.Char(required=False,
  619. string='Description', translate=True)
  620. style_id = fields.Many2one(string="Style",
  621. comodel_name="mis.report.style")
  622. query_ids = fields.One2many('mis.report.query', 'report_id',
  623. string='Queries',
  624. copy=True)
  625. kpi_ids = fields.One2many('mis.report.kpi', 'report_id',
  626. string='KPI\'s',
  627. copy=True)
  628. subkpi_ids = fields.One2many('mis.report.subkpi', 'report_id',
  629. string="Sub KPI",
  630. copy=True)
  631. @api.onchange('subkpi_ids')
  632. def _on_change_subkpi_ids(self):
  633. """ Update kpi expressions when subkpis change on the report,
  634. so the list of kpi expressions is always up-to-date """
  635. for kpi in self.kpi_ids:
  636. if not kpi.multi:
  637. continue
  638. new_subkpis = set([subkpi for subkpi in self.subkpi_ids])
  639. expressions = []
  640. for expression in kpi.expression_ids:
  641. assert expression.subkpi_id # must be true if kpi is multi
  642. if expression.subkpi_id not in self.subkpi_ids:
  643. expressions.append((2, expression.id, None)) # remove
  644. else:
  645. new_subkpis.remove(expression.subkpi_id) # no change
  646. for subkpi in new_subkpis:
  647. # TODO FIXME this does not work, while the remove above works
  648. expressions.append((0, None, {
  649. 'name': False,
  650. 'subkpi_id': subkpi.id,
  651. })) # add empty expressions for new subkpis
  652. if expressions:
  653. kpi.expressions_ids = expressions
  654. @api.multi
  655. def get_wizard_report_action(self):
  656. action = self.env.ref('mis_builder.mis_report_instance_view_action')
  657. res = action.read()[0]
  658. view = self.env.ref('mis_builder.wizard_mis_report_instance_view_form')
  659. res.update({
  660. 'view_id': view.id,
  661. 'views': [(view.id, 'form')],
  662. 'target': 'new',
  663. 'context': {
  664. 'default_report_id': self.id,
  665. 'default_name': self.name,
  666. 'default_temporary': True,
  667. }
  668. })
  669. return res
  670. @api.multi
  671. def copy(self, default=None):
  672. self.ensure_one()
  673. default = dict(default or {})
  674. default['name'] = _('%s (copy)') % self.name
  675. return super(MisReport, self).copy(default)
  676. # TODO: kpi name cannot be start with query name
  677. @api.multi
  678. def prepare_kpi_matrix(self):
  679. self.ensure_one()
  680. kpi_matrix = KpiMatrix(self.env)
  681. for kpi in self.kpi_ids:
  682. kpi_matrix.declare_kpi(kpi)
  683. return kpi_matrix
  684. @api.multi
  685. def prepare_aep(self, company):
  686. self.ensure_one()
  687. aep = AEP(company)
  688. for kpi in self.kpi_ids:
  689. for expression in kpi.expression_ids:
  690. aep.parse_expr(expression.name)
  691. aep.done_parsing()
  692. return aep
  693. def prepare_locals_dict(self):
  694. return {
  695. 'sum': _sum,
  696. 'min': _min,
  697. 'max': _max,
  698. 'len': len,
  699. 'avg': _avg,
  700. 'AccountingNone': AccountingNone,
  701. 'SimpleArray': SimpleArray,
  702. }
  703. @api.multi
  704. def _fetch_queries(self, date_from, date_to,
  705. get_additional_query_filter=None):
  706. self.ensure_one()
  707. res = {}
  708. for query in self.query_ids:
  709. model = self.env[query.model_id.model]
  710. eval_context = {
  711. 'env': self.env,
  712. 'time': time,
  713. 'datetime': datetime,
  714. 'dateutil': dateutil,
  715. # deprecated
  716. 'uid': self.env.uid,
  717. 'context': self.env.context,
  718. }
  719. domain = query.domain and \
  720. safe_eval(query.domain, eval_context) or []
  721. if get_additional_query_filter:
  722. domain.extend(get_additional_query_filter(query))
  723. if query.date_field.ttype == 'date':
  724. domain.extend([(query.date_field.name, '>=', date_from),
  725. (query.date_field.name, '<=', date_to)])
  726. else:
  727. datetime_from = _utc_midnight(
  728. date_from, self._context.get('tz', 'UTC'))
  729. datetime_to = _utc_midnight(
  730. date_to, self._context.get('tz', 'UTC'), add_day=1)
  731. domain.extend([(query.date_field.name, '>=', datetime_from),
  732. (query.date_field.name, '<', datetime_to)])
  733. field_names = [f.name for f in query.field_ids]
  734. all_stored = all([model._fields[f].store for f in field_names])
  735. if not query.aggregate:
  736. data = model.search_read(domain, field_names)
  737. res[query.name] = [AutoStruct(**d) for d in data]
  738. elif query.aggregate == 'sum' and all_stored:
  739. # use read_group to sum stored fields
  740. data = model.read_group(
  741. domain, field_names, [])
  742. s = AutoStruct(count=data[0]['__count'])
  743. for field_name in field_names:
  744. try:
  745. v = data[0][field_name]
  746. except KeyError:
  747. _logger.error('field %s not found in read_group '
  748. 'for %s; not summable?',
  749. field_name, model._name)
  750. v = AccountingNone
  751. setattr(s, field_name, v)
  752. res[query.name] = s
  753. else:
  754. data = model.search_read(domain, field_names)
  755. s = AutoStruct(count=len(data))
  756. if query.aggregate == 'min':
  757. agg = _min
  758. elif query.aggregate == 'max':
  759. agg = _max
  760. elif query.aggregate == 'avg':
  761. agg = _avg
  762. elif query.aggregate == 'sum':
  763. agg = _sum
  764. for field_name in field_names:
  765. setattr(s, field_name,
  766. agg([d[field_name] for d in data]))
  767. res[query.name] = s
  768. return res
  769. @api.multi
  770. def declare_and_compute_period(self, kpi_matrix,
  771. col_key,
  772. col_label,
  773. col_description,
  774. aep,
  775. date_from, date_to,
  776. target_move,
  777. subkpis_filter=None,
  778. get_additional_move_line_filter=None,
  779. get_additional_query_filter=None,
  780. locals_dict=None):
  781. """ Evaluate a report for a given period, populating a KpiMatrix.
  782. :param kpi_matrix: the KpiMatrix object to be populated created
  783. with prepare_kpi_matrix()
  784. :param col_key: the period key to use when populating the KpiMatrix
  785. :param aep: an AccountingExpressionProcessor instance created
  786. using _prepare_aep()
  787. :param date_from, date_to: the starting and ending date
  788. :param target_move: all|posted
  789. :param get_additional_move_line_filter: a bound method that takes
  790. no arguments and returns
  791. a domain compatible with
  792. account.move.line
  793. :param get_additional_query_filter: a bound method that takes a single
  794. query argument and returns a
  795. domain compatible with the query
  796. underlying model
  797. :param locals_dict: personalized locals dictionary used as evaluation
  798. context for the KPI expressions
  799. """
  800. self.ensure_one()
  801. # prepare the localsdict
  802. if locals_dict is None:
  803. locals_dict = {}
  804. locals_dict.update(self.prepare_locals_dict())
  805. # fetch non-accounting queries
  806. locals_dict.update(self._fetch_queries(
  807. date_from, date_to, get_additional_query_filter))
  808. # use AEP to do the accounting queries
  809. additional_move_line_filter = None
  810. if get_additional_move_line_filter:
  811. additional_move_line_filter = get_additional_move_line_filter()
  812. aep.do_queries(date_from, date_to,
  813. target_move,
  814. additional_move_line_filter)
  815. if subkpis_filter:
  816. subkpis = [subkpi for subkpi in self.subkpi_ids
  817. if subkpi in subkpis_filter]
  818. else:
  819. subkpis = self.subkpi_ids
  820. col = kpi_matrix.declare_col(col_key,
  821. col_label, col_description,
  822. locals_dict, subkpis)
  823. compute_queue = self.kpi_ids
  824. recompute_queue = []
  825. while True:
  826. for kpi in compute_queue:
  827. # build the list of expressions for this kpi
  828. expressions = []
  829. for expression in kpi.expression_ids:
  830. if expression.subkpi_id and \
  831. subkpis_filter and \
  832. expression.subkpi_id not in subkpis_filter:
  833. continue
  834. expressions.append(expression.name)
  835. vals = []
  836. drilldown_args = []
  837. name_error = False
  838. for expression in expressions:
  839. replaced_expr = aep.replace_expr(expression)
  840. vals.append(
  841. mis_safe_eval(replaced_expr, locals_dict))
  842. if isinstance(vals[-1], NameDataError):
  843. name_error = True
  844. if replaced_expr != expression:
  845. drilldown_args.append({
  846. 'period_id': col_key,
  847. 'expr': expression,
  848. })
  849. else:
  850. drilldown_args.append(None)
  851. if name_error:
  852. recompute_queue.append(kpi)
  853. else:
  854. # no error, set it in locals_dict so it can be used
  855. # in computing other kpis
  856. if len(expressions) == 1:
  857. locals_dict[kpi.name] = vals[0]
  858. else:
  859. locals_dict[kpi.name] = SimpleArray(vals)
  860. # even in case of name error we set the result in the matrix
  861. # so the name error will be displayed if it cannot be
  862. # resolved by recomputing later
  863. if len(expressions) == 1 and col.colspan > 1:
  864. if isinstance(vals[0], tuple):
  865. vals = vals[0]
  866. assert len(vals) == col.colspan
  867. elif isinstance(vals[0], DataError):
  868. vals = (vals[0],) * col.colspan
  869. else:
  870. raise UserError(_("Probably not your fault... but I'm "
  871. "really curious to know how you "
  872. "managed to raise this error so "
  873. "I can handle one more corner "
  874. "case!"))
  875. if len(drilldown_args) != col.colspan:
  876. drilldown_args = [None] * col.colspan
  877. kpi_matrix.set_values(
  878. kpi, col_key, vals, drilldown_args)
  879. if not kpi.auto_expand_accounts or name_error:
  880. continue
  881. for account_id, replaced_exprs in \
  882. aep.replace_exprs_by_account_id(expressions):
  883. vals = []
  884. drilldown_args = []
  885. for expression, replaced_expr in \
  886. izip(expressions, replaced_exprs):
  887. vals.append(mis_safe_eval(replaced_expr, locals_dict))
  888. if replaced_expr != expression:
  889. drilldown_args.append({
  890. 'period_id': col_key,
  891. 'expr': expression,
  892. 'account_id': account_id
  893. })
  894. else:
  895. drilldown_args.append(None)
  896. kpi_matrix.set_values_detail_account(
  897. kpi, col_key, account_id, vals, drilldown_args)
  898. if len(recompute_queue) == 0:
  899. # nothing to recompute, we are done
  900. break
  901. if len(recompute_queue) == len(compute_queue):
  902. # could not compute anything in this iteration
  903. # (ie real Name errors or cyclic dependency)
  904. # so we stop trying
  905. break
  906. # try again
  907. compute_queue = recompute_queue
  908. recompute_queue = []