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.

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