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.

1046 lines
39 KiB

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