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.

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