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.

1004 lines
37 KiB

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