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.

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