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.

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