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.

1279 lines
47 KiB

9 years ago
9 years ago
9 years ago
10 years ago
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 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, exceptions, fields, models, _
  13. from openerp.tools.safe_eval import safe_eval
  14. from .aep import AccountingExpressionProcessor as AEP
  15. from .aggregate import _sum, _avg, _min, _max
  16. from .accounting_none import AccountingNone
  17. from openerp.exceptions import UserError
  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):
  45. for col in cols:
  46. yield col.get_cell_tuple_for_row(self)
  47. def iter_cells(self, subcols):
  48. for subcol in subcols:
  49. yield subcol.get_cell_for_row(self)
  50. class KpiMatrixCol(object):
  51. def __init__(self, description, comment, locals_dict, subkpis):
  52. self.description = description
  53. self.comment = comment
  54. self.locals_dict = locals_dict
  55. self.colspan = subkpis and len(subkpis) or 1
  56. self._subcols = []
  57. if not subkpis:
  58. subcol = KpiMatrixSubCol(self, '', '', 0)
  59. self._subcols.append(subcol)
  60. else:
  61. for i, subkpi in enumerate(subkpis):
  62. subcol = KpiMatrixSubCol(self, subkpi.description, '', i)
  63. self._subcols.append(subcol)
  64. self._cell_tuples_by_row = {} # {row: (cells tuple)}
  65. def _set_cell_tuple(self, row, cell_tuple):
  66. self._cell_tuples_by_row[row] = cell_tuple
  67. def iter_subcols(self):
  68. return self._subcols
  69. def iter_cell_tuples(self):
  70. return self._cells_by_row.values()
  71. def get_cell_tuple_for_row(self, row):
  72. return self._cell_tuples_by_row.get(row)
  73. class KpiMatrixSubCol(object):
  74. def __init__(self, col, description, comment, index=0):
  75. self.col = col
  76. self.description = description
  77. self.comment = comment
  78. self.index = index
  79. def iter_cells(self):
  80. for cells in self.col.iter_cell_tuples():
  81. yield cells[self.index]
  82. def get_cell_for_row(self, row):
  83. cell_tuple = self.col.get_cell_tuple_for_row(row)
  84. if cell_tuple is None:
  85. return None
  86. return cell_tuple[self.index]
  87. class KpiMatrixCell(object):
  88. def __init__(self, row, subcol,
  89. val, val_rendered, val_comment,
  90. style=None, drilldown_key=None):
  91. self.row = row
  92. self.subcol = subcol
  93. self.val = val
  94. self.val_rendered = val_rendered
  95. self.val_comment = val_comment
  96. self.drilldown_key = None
  97. class KpiMatrix(object):
  98. def __init__(self, env):
  99. # cache language id for faster rendering
  100. lang_model = env['res.lang']
  101. lang_id = lang_model._lang_get(env.user.lang)
  102. self.lang = lang_model.browse(lang_id)
  103. # data structures
  104. self._kpi_rows = OrderedDict() # { kpi: KpiMatrixRow }
  105. self._detail_rows = {} # { kpi: {account_id: KpiMatrixRow} }
  106. self._cols = OrderedDict() # { period_key: KpiMatrixCol }
  107. self._account_model = env['account.account']
  108. self._account_names = {} # { account_id: account_name }
  109. def declare_kpi(self, kpi):
  110. self._kpi_rows[kpi] = KpiMatrixRow(self, kpi)
  111. self._detail_rows[kpi] = {}
  112. def declare_period(self, period_key, description, comment,
  113. locals_dict, subkpis):
  114. self._cols[period_key] = KpiMatrixCol(description, comment,
  115. locals_dict, subkpis)
  116. def set_values(self, kpi, period_key, vals):
  117. self.set_values_detail_account(kpi, period_key, None, vals)
  118. def set_values_detail_account(self, kpi, period_key, account_id, vals):
  119. if not account_id:
  120. row = self._kpi_rows[kpi]
  121. else:
  122. kpi_row = self._kpi_rows[kpi]
  123. if account_id in self._detail_rows[kpi]:
  124. row = self._detail_rows[kpi][account_id]
  125. else:
  126. row = KpiMatrixRow(self, kpi, account_id, parent_row=kpi_row)
  127. self._detail_rows[kpi][account_id] = row
  128. col = self._cols[period_key]
  129. cell_tuple = []
  130. assert len(vals) == col.colspan
  131. for val, subcol in izip(vals, col.iter_subcols()):
  132. if isinstance(val, DataError):
  133. val_rendered = val.name
  134. val_comment = val.msg
  135. else:
  136. val_rendered = kpi.render(self.lang, val)
  137. val_comment = '' # TODO FIXME get subkpi expression
  138. # TODO style
  139. # TODO drilldown_key
  140. cell = KpiMatrixCell(row, subcol, val, val_rendered, val_comment)
  141. cell_tuple.append(cell)
  142. col._set_cell_tuple(row, cell_tuple)
  143. def iter_rows(self):
  144. for kpi_row in self._kpi_rows.values():
  145. yield kpi_row
  146. detail_rows = self._detail_rows[kpi_row.kpi].values()
  147. detail_rows = sorted(detail_rows, key=lambda r: r.description)
  148. for detail_row in detail_rows:
  149. yield detail_row
  150. def iter_cols(self):
  151. return self._cols.values()
  152. def iter_subcols(self):
  153. for col in self.iter_cols():
  154. for subcol in col.iter_subcols():
  155. yield subcol
  156. def _load_account_names(self):
  157. account_ids = set()
  158. for detail_rows in self._detail_rows.values():
  159. account_ids.update(detail_rows.keys())
  160. account_ids = list(account_ids)
  161. accounts = self._account_model.search([('id', 'in', account_ids)])
  162. self._account_names = {a.id: u'{} {}'.format(a.code, a.name)
  163. for a in accounts}
  164. def get_account_name(self, account_id):
  165. if account_id not in self._account_names:
  166. self._load_account_names()
  167. return self._account_names[account_id]
  168. def _get_selection_label(selection, value):
  169. for v, l in selection:
  170. if v == value:
  171. return l
  172. return ''
  173. def _utc_midnight(d, tz_name, add_day=0):
  174. d = fields.Datetime.from_string(d) + datetime.timedelta(days=add_day)
  175. utc_tz = pytz.timezone('UTC')
  176. context_tz = pytz.timezone(tz_name)
  177. local_timestamp = context_tz.localize(d, is_dst=False)
  178. return fields.Datetime.to_string(local_timestamp.astimezone(utc_tz))
  179. def _python_var(var_str):
  180. return re.sub(r'\W|^(?=\d)', '_', var_str).lower()
  181. def _is_valid_python_var(name):
  182. return re.match("[_A-Za-z][_a-zA-Z0-9]*$", name)
  183. class MisReportKpi(models.Model):
  184. """ A KPI is an element (ie a line) of a MIS report.
  185. In addition to a name and description, it has an expression
  186. to compute it based on queries defined in the MIS report.
  187. It also has various informations defining how to render it
  188. (numeric or percentage or a string, a prefix, a suffix, divider) and
  189. how to render comparison of two values of the KPI.
  190. KPI's have a sequence and are ordered inside the MIS report.
  191. """
  192. _name = 'mis.report.kpi'
  193. name = fields.Char(size=32, required=True,
  194. string='Name')
  195. description = fields.Char(required=True,
  196. string='Description',
  197. translate=True)
  198. multi = fields.Boolean()
  199. expression = fields.Char(
  200. compute='_compute_expression',
  201. inverse='_inverse_expression')
  202. expression_ids = fields.One2many('mis.report.kpi.expression', 'kpi_id')
  203. auto_expand_accounts = fields.Boolean(string='Display details by account')
  204. style = fields.Many2one(
  205. string="Default style for KPI",
  206. comodel_name="mis.report.kpi.style",
  207. required=False
  208. )
  209. style_expression = fields.Char(
  210. string='Style expression',
  211. help='An expression that returns a style name for the kpi style')
  212. type = fields.Selection([('num', _('Numeric')),
  213. ('pct', _('Percentage')),
  214. ('str', _('String'))],
  215. required=True,
  216. string='Type',
  217. default='num')
  218. divider = fields.Selection([('1e-6', _('µ')),
  219. ('1e-3', _('m')),
  220. ('1', _('1')),
  221. ('1e3', _('k')),
  222. ('1e6', _('M'))],
  223. string='Factor',
  224. default='1')
  225. dp = fields.Integer(string='Rounding', default=0)
  226. prefix = fields.Char(size=16, string='Prefix')
  227. suffix = fields.Char(size=16, string='Suffix')
  228. compare_method = fields.Selection([('diff', _('Difference')),
  229. ('pct', _('Percentage')),
  230. ('none', _('None'))],
  231. required=True,
  232. string='Comparison Method',
  233. default='pct')
  234. sequence = fields.Integer(string='Sequence', default=100)
  235. report_id = fields.Many2one('mis.report',
  236. string='Report',
  237. ondelete='cascade')
  238. _order = 'sequence, id'
  239. @api.one
  240. @api.constrains('name')
  241. def _check_name(self):
  242. if not _is_valid_python_var(self.name):
  243. raise exceptions.Warning(_('The name must be a valid '
  244. 'python identifier'))
  245. @api.onchange('name')
  246. def _onchange_name(self):
  247. if self.name and not _is_valid_python_var(self.name):
  248. return {
  249. 'warning': {
  250. 'title': 'Invalid name %s' % self.name,
  251. 'message': 'The name must be a valid python identifier'
  252. }
  253. }
  254. @api.multi
  255. def _compute_expression(self):
  256. for kpi in self:
  257. l = []
  258. for expression in kpi.expression_ids:
  259. if expression.subkpi_id:
  260. l.append('{}={}'.format(
  261. expression.subkpi_id.name, expression.name))
  262. else:
  263. l.append(
  264. expression.name or 'AccountingNone')
  265. kpi.expression = ',\n'.join(l)
  266. @api.multi
  267. def _inverse_expression(self):
  268. for kpi in self:
  269. if kpi.multi:
  270. raise UserError('Can not update a multi kpi from the kpi line')
  271. if kpi.expression_ids:
  272. kpi.expression_ids[0].write({
  273. 'name': kpi.expression,
  274. 'subkpi_id': None})
  275. for expression in kpi.expression_ids[1:]:
  276. expression.unlink()
  277. else:
  278. kpi.write({
  279. 'expression_ids': [(0, 0, {
  280. 'name': kpi.expression
  281. })]
  282. })
  283. @api.onchange('multi')
  284. def _onchange_multi(self):
  285. for kpi in self:
  286. if not kpi.multi:
  287. if kpi.expression_ids:
  288. kpi.expression = kpi.expression_ids[0].name
  289. else:
  290. kpi.expression = None
  291. else:
  292. expressions = []
  293. for subkpi in kpi.report_id.subkpi_ids:
  294. expressions.append((0, 0, {
  295. 'name': kpi.expression,
  296. 'subkpi_id': subkpi.id,
  297. }))
  298. kpi.expression_ids = expressions
  299. @api.onchange('description')
  300. def _onchange_description(self):
  301. """ construct name from description """
  302. if self.description and not self.name:
  303. self.name = _python_var(self.description)
  304. @api.onchange('type')
  305. def _onchange_type(self):
  306. if self.type == 'num':
  307. self.compare_method = 'pct'
  308. self.divider = '1'
  309. self.dp = 0
  310. elif self.type == 'pct':
  311. self.compare_method = 'diff'
  312. self.divider = '1'
  313. self.dp = 0
  314. elif self.type == 'str':
  315. self.compare_method = 'none'
  316. self.divider = ''
  317. self.dp = 0
  318. def render(self, lang, value):
  319. """ render a KPI value as a unicode string, ready for display """
  320. assert len(self) == 1
  321. if value is None or value is AccountingNone:
  322. return ''
  323. elif self.type == 'num':
  324. return self._render_num(lang, value, self.divider,
  325. self.dp, self.prefix, self.suffix)
  326. elif self.type == 'pct':
  327. return self._render_num(lang, value, 0.01,
  328. self.dp, '', '%')
  329. else:
  330. return unicode(value)
  331. def render_comparison(self, lang, value, base_value,
  332. average_value, average_base_value):
  333. """ render the comparison of two KPI values, ready for display
  334. If the difference is 0, an empty string is returned.
  335. """
  336. assert len(self) == 1
  337. if value is None:
  338. value = AccountingNone
  339. if base_value is None:
  340. base_value = AccountingNone
  341. if self.type == 'pct':
  342. delta = value - base_value
  343. if delta and round(delta, self.dp) != 0:
  344. return self._render_num(
  345. lang,
  346. delta,
  347. 0.01, self.dp, '', _('pp'),
  348. sign='+')
  349. elif self.type == 'num':
  350. if value and average_value:
  351. value = value / float(average_value)
  352. if base_value and average_base_value:
  353. base_value = base_value / float(average_base_value)
  354. if self.compare_method == 'diff':
  355. delta = value - base_value
  356. if delta and round(delta, self.dp) != 0:
  357. return self._render_num(
  358. lang,
  359. delta,
  360. self.divider, self.dp, self.prefix, self.suffix,
  361. sign='+')
  362. elif self.compare_method == 'pct':
  363. if base_value and round(base_value, self.dp) != 0:
  364. delta = (value - base_value) / abs(base_value)
  365. if delta and round(delta, self.dp) != 0:
  366. return self._render_num(
  367. lang,
  368. delta,
  369. 0.01, self.dp, '', '%',
  370. sign='+')
  371. return ''
  372. def _render_num(self, lang, value, divider,
  373. dp, prefix, suffix, sign='-'):
  374. divider_label = _get_selection_label(
  375. self._columns['divider'].selection, divider)
  376. if divider_label == '1':
  377. divider_label = ''
  378. # format number following user language
  379. value = round(value / float(divider or 1), dp) or 0
  380. value = lang.format(
  381. '%%%s.%df' % (sign, dp),
  382. value,
  383. grouping=True)
  384. value = u'%s\N{NO-BREAK SPACE}%s\N{NO-BREAK SPACE}%s%s' % \
  385. (prefix or '', value, divider_label, suffix or '')
  386. value = value.replace('-', u'\N{NON-BREAKING HYPHEN}')
  387. return value
  388. class MisReportSubkpi(models.Model):
  389. _name = 'mis.report.subkpi'
  390. _order = 'sequence'
  391. sequence = fields.Integer()
  392. report_id = fields.Many2one('mis.report')
  393. name = fields.Char(size=32, required=True,
  394. string='Name')
  395. description = fields.Char(required=True,
  396. string='Description',
  397. translate=True)
  398. expression_ids = fields.One2many('mis.report.kpi.expression', 'subkpi_id')
  399. @api.one
  400. @api.constrains('name')
  401. def _check_name(self):
  402. if not _is_valid_python_var(self.name):
  403. raise exceptions.Warning(_('The name must be a valid '
  404. 'python identifier'))
  405. @api.onchange('name')
  406. def _onchange_name(self):
  407. if self.name and not _is_valid_python_var(self.name):
  408. return {
  409. 'warning': {
  410. 'title': 'Invalid name %s' % self.name,
  411. 'message': 'The name must be a valid python identifier'
  412. }
  413. }
  414. @api.onchange('description')
  415. def _onchange_description(self):
  416. """ construct name from description """
  417. if self.description and not self.name:
  418. self.name = _python_var(self.description)
  419. @api.multi
  420. def unlink(self):
  421. for subkpi in self:
  422. subkpi.expression_ids.unlink()
  423. return super(MisReportSubkpi, self).unlink()
  424. class MisReportKpiExpression(models.Model):
  425. """ A KPI Expression is an expression of a line of a MIS report Kpi.
  426. It's used to compute the kpi value.
  427. """
  428. _name = 'mis.report.kpi.expression'
  429. _order = 'sequence, name'
  430. sequence = fields.Integer(
  431. related='subkpi_id.sequence',
  432. store=True,
  433. readonly=True)
  434. name = fields.Char(string='Expression')
  435. kpi_id = fields.Many2one('mis.report.kpi')
  436. # TODO FIXME set readonly=True when onchange('subkpi_ids') below works
  437. subkpi_id = fields.Many2one(
  438. 'mis.report.subkpi',
  439. readonly=False)
  440. _sql_constraints = [
  441. ('subkpi_kpi_unique', 'unique(subkpi_id, kpi_id)',
  442. 'Sub KPI must be used once and only once for each KPI'),
  443. ]
  444. class MisReportQuery(models.Model):
  445. """ A query to fetch arbitrary data for a MIS report.
  446. A query works on a model and has a domain and list of fields to fetch.
  447. At runtime, the domain is expanded with a "and" on the date/datetime field.
  448. """
  449. _name = 'mis.report.query'
  450. @api.one
  451. @api.depends('field_ids')
  452. def _compute_field_names(self):
  453. field_names = [field.name for field in self.field_ids]
  454. self.field_names = ', '.join(field_names)
  455. name = fields.Char(size=32, required=True,
  456. string='Name')
  457. model_id = fields.Many2one('ir.model', required=True,
  458. string='Model')
  459. field_ids = fields.Many2many('ir.model.fields', required=True,
  460. string='Fields to fetch')
  461. field_names = fields.Char(compute='_compute_field_names',
  462. string='Fetched fields name')
  463. aggregate = fields.Selection([('sum', _('Sum')),
  464. ('avg', _('Average')),
  465. ('min', _('Min')),
  466. ('max', _('Max'))],
  467. string='Aggregate')
  468. date_field = fields.Many2one('ir.model.fields', required=True,
  469. string='Date field',
  470. domain=[('ttype', 'in',
  471. ('date', 'datetime'))])
  472. domain = fields.Char(string='Domain')
  473. report_id = fields.Many2one('mis.report', string='Report',
  474. ondelete='cascade')
  475. _order = 'name'
  476. @api.one
  477. @api.constrains('name')
  478. def _check_name(self):
  479. if not _is_valid_python_var(self.name):
  480. raise exceptions.Warning(_('The name must be a valid '
  481. 'python identifier'))
  482. class MisReport(models.Model):
  483. """ A MIS report template (without period information)
  484. The MIS report holds:
  485. * a list of explicit queries; the result of each query is
  486. stored in a variable with same name as a query, containing as list
  487. of data structures populated with attributes for each fields to fetch;
  488. when queries have an aggregate method and no fields to group, it returns
  489. a data structure with the aggregated fields
  490. * a list of KPI to be evaluated based on the variables resulting
  491. from the accounting data and queries (KPI expressions can references
  492. queries and accounting expression - see AccoutingExpressionProcessor)
  493. """
  494. _name = 'mis.report'
  495. name = fields.Char(required=True,
  496. string='Name', translate=True)
  497. description = fields.Char(required=False,
  498. string='Description', translate=True)
  499. query_ids = fields.One2many('mis.report.query', 'report_id',
  500. string='Queries',
  501. copy=True)
  502. kpi_ids = fields.One2many('mis.report.kpi', 'report_id',
  503. string='KPI\'s',
  504. copy=True)
  505. subkpi_ids = fields.One2many('mis.report.subkpi', 'report_id',
  506. string="Sub KPI",
  507. copy=True)
  508. @api.onchange('subkpi_ids')
  509. def _on_change_subkpi_ids(self):
  510. """ Update kpi expressions when subkpis change on the report,
  511. so the list of kpi expressions is always up-to-date """
  512. for kpi in self.kpi_ids:
  513. if not kpi.multi:
  514. continue
  515. new_subkpis = set([subkpi for subkpi in self.subkpi_ids])
  516. expressions = []
  517. for expression in kpi.expression_ids:
  518. assert expression.subkpi_id # must be true if kpi is multi
  519. if expression.subkpi_id not in self.subkpi_ids:
  520. expressions.append((2, expression.id, None)) # remove
  521. else:
  522. new_subkpis.remove(expression.subkpi_id) # no change
  523. for subkpi in new_subkpis:
  524. # TODO FIXME this does not work, while the remove above works
  525. expressions.append((0, None, {
  526. 'name': False,
  527. 'subkpi_id': subkpi.id,
  528. })) # add empty expressions for new subkpis
  529. if expressions:
  530. kpi.expressions_ids = expressions
  531. @api.multi
  532. def get_wizard_report_action(self):
  533. action = self.env.ref('mis_builder.mis_report_instance_view_action')
  534. res = action.read()[0]
  535. view = self.env.ref('mis_builder.wizard_mis_report_instance_view_form')
  536. res.update({
  537. 'view_id': view.id,
  538. 'views': [(view.id, 'form')],
  539. 'target': 'new',
  540. 'context': {
  541. 'default_report_id': self.id,
  542. 'default_name': self.name,
  543. 'default_temporary': True,
  544. }
  545. })
  546. return res
  547. @api.one
  548. def copy(self, default=None):
  549. default = dict(default or {})
  550. default['name'] = _('%s (copy)') % self.name
  551. return super(MisReport, self).copy(default)
  552. # TODO: kpi name cannot be start with query name
  553. @api.multi
  554. def _prepare_kpi_matrix(self):
  555. self.ensure_one()
  556. kpi_matrix = KpiMatrix(self.env)
  557. for kpi in self.kpi_ids:
  558. kpi_matrix.declare_kpi(kpi)
  559. return kpi_matrix
  560. @api.multi
  561. def _prepare_aep(self, company):
  562. self.ensure_one()
  563. aep = AEP(self.env)
  564. for kpi in self.kpi_ids:
  565. for expression in kpi.expression_ids:
  566. aep.parse_expr(expression.name)
  567. aep.done_parsing(company)
  568. return aep
  569. @api.multi
  570. def _fetch_queries(self, date_from, date_to,
  571. get_additional_query_filter=None):
  572. self.ensure_one()
  573. res = {}
  574. for query in self.query_ids:
  575. model = self.env[query.model_id.model]
  576. eval_context = {
  577. 'env': self.env,
  578. 'time': time,
  579. 'datetime': datetime,
  580. 'dateutil': dateutil,
  581. # deprecated
  582. 'uid': self.env.uid,
  583. 'context': self.env.context,
  584. }
  585. domain = query.domain and \
  586. safe_eval(query.domain, eval_context) or []
  587. if get_additional_query_filter:
  588. domain.extend(get_additional_query_filter(query))
  589. if query.date_field.ttype == 'date':
  590. domain.extend([(query.date_field.name, '>=', date_from),
  591. (query.date_field.name, '<=', date_to)])
  592. else:
  593. datetime_from = _utc_midnight(
  594. date_from, self._context.get('tz', 'UTC'))
  595. datetime_to = _utc_midnight(
  596. date_to, self._context.get('tz', 'UTC'), add_day=1)
  597. domain.extend([(query.date_field.name, '>=', datetime_from),
  598. (query.date_field.name, '<', datetime_to)])
  599. field_names = [f.name for f in query.field_ids]
  600. if not query.aggregate:
  601. data = model.search_read(domain, field_names)
  602. res[query.name] = [AutoStruct(**d) for d in data]
  603. elif query.aggregate == 'sum':
  604. data = model.read_group(
  605. domain, field_names, [])
  606. s = AutoStruct(count=data[0]['__count'])
  607. for field_name in field_names:
  608. v = data[0][field_name]
  609. setattr(s, field_name, v)
  610. res[query.name] = s
  611. else:
  612. data = model.search_read(domain, field_names)
  613. s = AutoStruct(count=len(data))
  614. if query.aggregate == 'min':
  615. agg = _min
  616. elif query.aggregate == 'max':
  617. agg = _max
  618. elif query.aggregate == 'avg':
  619. agg = _avg
  620. for field_name in field_names:
  621. setattr(s, field_name,
  622. agg([d[field_name] for d in data]))
  623. res[query.name] = s
  624. return res
  625. @api.multi
  626. def _compute_period(self, kpi_matrix,
  627. period_key, period_description, period_comment,
  628. aep,
  629. date_from, date_to,
  630. target_move,
  631. company,
  632. subkpis_filter=None,
  633. get_additional_move_line_filter=None,
  634. get_additional_query_filter=None):
  635. """ Evaluate a report for a given period, populating a KpiMatrix.
  636. :param kpi_matrix: the KpiMatrix object to be populated
  637. :param period_key: the period key to use when populating the KpiMatrix
  638. :param aep: an AccountingExpressionProcessor instance created
  639. using _prepare_aep()
  640. :param date_from, date_to: the starting and ending date
  641. :param target_move: all|posted
  642. :param company:
  643. :param get_additional_move_line_filter: a bound method that takes
  644. no arguments and returns
  645. a domain compatible with
  646. account.move.line
  647. :param get_additional_query_filter: a bound method that takes a single
  648. query argument and returns a
  649. domain compatible with the query
  650. underlying model
  651. """
  652. self.ensure_one()
  653. locals_dict = {
  654. 'sum': _sum,
  655. 'min': _min,
  656. 'max': _max,
  657. 'len': len,
  658. 'avg': _avg,
  659. 'AccountingNone': AccountingNone,
  660. 'SimpleArray': SimpleArray,
  661. }
  662. # fetch non-accounting queries
  663. locals_dict.update(self._fetch_queries(
  664. date_from, date_to, get_additional_query_filter))
  665. # use AEP to do the accounting queries
  666. additional_move_line_filter = None
  667. if get_additional_move_line_filter:
  668. additional_move_line_filter = get_additional_move_line_filter()
  669. aep.do_queries(company,
  670. date_from, date_to,
  671. target_move,
  672. additional_move_line_filter)
  673. if subkpis_filter:
  674. subkpis = [subkpi for subkpi in self.subkpi_ids
  675. if subkpi in subkpis_filter]
  676. else:
  677. subkpis = self.subkpi_ids
  678. kpi_matrix.declare_period(period_key,
  679. period_description, period_comment,
  680. locals_dict, subkpis)
  681. compute_queue = self.kpi_ids
  682. recompute_queue = []
  683. while True:
  684. for kpi in compute_queue:
  685. # build the list of expressions for this kpi
  686. expressions = []
  687. for expression in kpi.expression_ids:
  688. if expression.subkpi_id and \
  689. subkpis_filter and \
  690. expression.subkpi_id not in subkpis_filter:
  691. continue
  692. expressions.append(expression.name)
  693. vals = []
  694. try:
  695. for expression in expressions:
  696. replaced_expr = aep.replace_expr(expression)
  697. vals.append(
  698. mis_safe_eval(replaced_expr, locals_dict))
  699. except NameError:
  700. recompute_queue.append(kpi)
  701. break
  702. else:
  703. # no error, set it in locals_dict so it can be used
  704. # in computing other kpis
  705. if len(expressions) == 1:
  706. locals_dict[kpi.name] = vals[0]
  707. else:
  708. locals_dict[kpi.name] = SimpleArray(vals)
  709. kpi_matrix.set_values(kpi, period_key, vals)
  710. if not kpi.auto_expand_accounts:
  711. continue
  712. for account_id, replaced_exprs in \
  713. aep.replace_exprs_by_account_id(expressions):
  714. account_id_vals = []
  715. for replaced_expr in replaced_exprs:
  716. account_id_vals.append(
  717. mis_safe_eval(replaced_expr, locals_dict))
  718. kpi_matrix.set_values_detail_account(
  719. kpi, period_key, account_id, account_id_vals)
  720. if len(recompute_queue) == 0:
  721. # nothing to recompute, we are done
  722. break
  723. if len(recompute_queue) == len(compute_queue):
  724. # could not compute anything in this iteration
  725. # (ie real Name errors or cyclic dependency)
  726. # so we stop trying
  727. break
  728. # try again
  729. compute_queue = recompute_queue
  730. recompute_queue = []
  731. class MisReportInstancePeriod(models.Model):
  732. """ A MIS report instance has the logic to compute
  733. a report template for a given date period.
  734. Periods have a duration (day, week, fiscal period) and
  735. are defined as an offset relative to a pivot date.
  736. """
  737. @api.one
  738. @api.depends('report_instance_id.pivot_date',
  739. 'report_instance_id.comparison_mode',
  740. 'type', 'offset', 'duration', 'mode')
  741. def _compute_dates(self):
  742. self.date_from = False
  743. self.date_to = False
  744. self.valid = False
  745. report = self.report_instance_id
  746. d = fields.Date.from_string(report.pivot_date)
  747. if not report.comparison_mode:
  748. self.date_from = report.date_from
  749. self.date_to = report.date_to
  750. self.valid = True
  751. elif self.mode == 'fix':
  752. self.date_from = self.manual_date_from
  753. self.date_to = self.manual_date_to
  754. self.valid = True
  755. elif self.type == 'd':
  756. date_from = d + datetime.timedelta(days=self.offset)
  757. date_to = date_from + \
  758. datetime.timedelta(days=self.duration - 1)
  759. self.date_from = fields.Date.to_string(date_from)
  760. self.date_to = fields.Date.to_string(date_to)
  761. self.valid = True
  762. elif self.type == 'w':
  763. date_from = d - datetime.timedelta(d.weekday())
  764. date_from = date_from + datetime.timedelta(days=self.offset * 7)
  765. date_to = date_from + \
  766. datetime.timedelta(days=(7 * self.duration) - 1)
  767. self.date_from = fields.Date.to_string(date_from)
  768. self.date_to = fields.Date.to_string(date_to)
  769. self.valid = True
  770. elif self.type == 'date_range':
  771. date_range_obj = self.env['date.range']
  772. current_periods = date_range_obj.search(
  773. [('type_id', '=', self.date_range_type_id.id),
  774. ('date_start', '<=', d),
  775. ('date_end', '>=', d),
  776. ('company_id', '=', self.report_instance_id.company_id.id)])
  777. if current_periods:
  778. all_periods = date_range_obj.search(
  779. [('type_id', '=', self.date_range_type_id.id),
  780. ('company_id', '=',
  781. self.report_instance_id.company_id.id)],
  782. order='date_start')
  783. all_period_ids = [p.id for p in all_periods]
  784. p = all_period_ids.index(current_periods[0].id) + self.offset
  785. if p >= 0 and p + self.duration <= len(all_period_ids):
  786. periods = all_periods[p:p + self.duration]
  787. self.date_from = periods[0].date_start
  788. self.date_to = periods[-1].date_end
  789. self.valid = True
  790. _name = 'mis.report.instance.period'
  791. name = fields.Char(size=32, required=True,
  792. string='Description', translate=True)
  793. mode = fields.Selection([('fix', 'Fix'),
  794. ('relative', 'Relative'),
  795. ], required=True,
  796. default='fix')
  797. type = fields.Selection([('d', _('Day')),
  798. ('w', _('Week')),
  799. ('date_range', _('Date Range'))
  800. ],
  801. string='Period type')
  802. date_range_type_id = fields.Many2one(
  803. comodel_name='date.range.type', string='Date Range Type')
  804. offset = fields.Integer(string='Offset',
  805. help='Offset from current period',
  806. default=-1)
  807. duration = fields.Integer(string='Duration',
  808. help='Number of periods',
  809. default=1)
  810. date_from = fields.Date(compute='_compute_dates', string="From")
  811. date_to = fields.Date(compute='_compute_dates', string="To")
  812. manual_date_from = fields.Date(string="From")
  813. manual_date_to = fields.Date(string="To")
  814. date_range_id = fields.Many2one(
  815. comodel_name='date.range',
  816. string='Date Range')
  817. valid = fields.Boolean(compute='_compute_dates',
  818. type='boolean',
  819. string='Valid')
  820. sequence = fields.Integer(string='Sequence', default=100)
  821. report_instance_id = fields.Many2one('mis.report.instance',
  822. string='Report Instance',
  823. ondelete='cascade')
  824. comparison_column_ids = fields.Many2many(
  825. comodel_name='mis.report.instance.period',
  826. relation='mis_report_instance_period_rel',
  827. column1='period_id',
  828. column2='compare_period_id',
  829. string='Compare with')
  830. normalize_factor = fields.Integer(
  831. string='Factor',
  832. help='Factor to use to normalize the period (used in comparison',
  833. default=1)
  834. subkpi_ids = fields.Many2many(
  835. 'mis.report.subkpi',
  836. string="Sub KPI Filter")
  837. _order = 'sequence, id'
  838. _sql_constraints = [
  839. ('duration', 'CHECK (duration>0)',
  840. 'Wrong duration, it must be positive!'),
  841. ('normalize_factor', 'CHECK (normalize_factor>0)',
  842. 'Wrong normalize factor, it must be positive!'),
  843. ('name_unique', 'unique(name, report_instance_id)',
  844. 'Period name should be unique by report'),
  845. ]
  846. @api.onchange('date_range_id')
  847. def onchange_date_range(self):
  848. for record in self:
  849. record.manual_date_from = record.date_range_id.date_start
  850. record.manual_date_to = record.date_range_id.date_end
  851. record.name = record.date_range_id.name
  852. @api.multi
  853. def _get_additional_move_line_filter(self):
  854. """ Prepare a filter to apply on all move lines
  855. This filter is applied with a AND operator on all
  856. accounting expression domains. This hook is intended
  857. to be inherited, and is useful to implement filtering
  858. on analytic dimensions or operational units.
  859. Returns an Odoo domain expression (a python list)
  860. compatible with account.move.line."""
  861. self.ensure_one()
  862. return []
  863. @api.multi
  864. def _get_additional_query_filter(self, query):
  865. """ Prepare an additional filter to apply on the query
  866. This filter is combined to the query domain with a AND
  867. operator. This hook is intended
  868. to be inherited, and is useful to implement filtering
  869. on analytic dimensions or operational units.
  870. Returns an Odoo domain expression (a python list)
  871. compatible with the model of the query."""
  872. self.ensure_one()
  873. return []
  874. @api.multi
  875. def drilldown(self, expr):
  876. self.ensure_one()
  877. # TODO FIXME: drilldown by account
  878. if AEP.has_account_var(expr):
  879. aep = AEP(self.env)
  880. aep.parse_expr(expr)
  881. aep.done_parsing(self.report_instance_id.company_id)
  882. domain = aep.get_aml_domain_for_expr(
  883. expr,
  884. self.date_from, self.date_to,
  885. self.report_instance_id.target_move,
  886. self.report_instance_id.company_id)
  887. domain.extend(self._get_additional_move_line_filter())
  888. return {
  889. 'name': expr + ' - ' + self.name,
  890. 'domain': domain,
  891. 'type': 'ir.actions.act_window',
  892. 'res_model': 'account.move.line',
  893. 'views': [[False, 'list'], [False, 'form']],
  894. 'view_type': 'list',
  895. 'view_mode': 'list',
  896. 'target': 'current',
  897. }
  898. else:
  899. return False
  900. class MisReportInstance(models.Model):
  901. """The MIS report instance combines everything to compute
  902. a MIS report template for a set of periods."""
  903. @api.one
  904. @api.depends('date')
  905. def _compute_pivot_date(self):
  906. if self.date:
  907. self.pivot_date = self.date
  908. else:
  909. self.pivot_date = fields.Date.context_today(self)
  910. @api.model
  911. def _default_company(self):
  912. return self.env['res.company'].\
  913. _company_default_get('mis.report.instance')
  914. _name = 'mis.report.instance'
  915. name = fields.Char(required=True,
  916. string='Name', translate=True)
  917. description = fields.Char(related='report_id.description',
  918. readonly=True)
  919. date = fields.Date(string='Base date',
  920. help='Report base date '
  921. '(leave empty to use current date)')
  922. pivot_date = fields.Date(compute='_compute_pivot_date',
  923. string="Pivot date")
  924. report_id = fields.Many2one('mis.report',
  925. required=True,
  926. string='Report')
  927. period_ids = fields.One2many('mis.report.instance.period',
  928. 'report_instance_id',
  929. required=True,
  930. string='Periods',
  931. copy=True)
  932. target_move = fields.Selection([('posted', 'All Posted Entries'),
  933. ('all', 'All Entries')],
  934. string='Target Moves',
  935. required=True,
  936. default='posted')
  937. company_id = fields.Many2one(comodel_name='res.company',
  938. string='Company',
  939. default=_default_company,
  940. required=True)
  941. landscape_pdf = fields.Boolean(string='Landscape PDF')
  942. comparison_mode = fields.Boolean(
  943. compute="_compute_comparison_mode",
  944. inverse="_inverse_comparison_mode")
  945. date_range_id = fields.Many2one(
  946. comodel_name='date.range',
  947. string='Date Range')
  948. date_from = fields.Date(string="From")
  949. date_to = fields.Date(string="To")
  950. temporary = fields.Boolean(default=False)
  951. @api.multi
  952. def save_report(self):
  953. self.ensure_one()
  954. self.write({'temporary': False})
  955. action = self.env.ref('mis_builder.mis_report_instance_view_action')
  956. res = action.read()[0]
  957. view = self.env.ref('mis_builder.mis_report_instance_view_form')
  958. res.update({
  959. 'views': [(view.id, 'form')],
  960. 'res_id': self.id,
  961. })
  962. return res
  963. @api.model
  964. def _vacuum_report(self, hours=24):
  965. clear_date = fields.Datetime.to_string(
  966. datetime.datetime.now() - datetime.timedelta(hours=hours))
  967. reports = self.search([
  968. ('write_date', '<', clear_date),
  969. ('temporary', '=', True),
  970. ])
  971. _logger.debug('Vacuum %s Temporary MIS Builder Report', len(reports))
  972. return reports.unlink()
  973. @api.one
  974. def copy(self, default=None):
  975. default = dict(default or {})
  976. default['name'] = _('%s (copy)') % self.name
  977. return super(MisReportInstance, self).copy(default)
  978. def _format_date(self, date):
  979. # format date following user language
  980. lang_model = self.env['res.lang']
  981. lang_id = lang_model._lang_get(self.env.user.lang)
  982. date_format = lang_model.browse(lang_id).date_format
  983. return datetime.datetime.strftime(
  984. fields.Date.from_string(date), date_format)
  985. @api.multi
  986. @api.depends('date_from')
  987. def _compute_comparison_mode(self):
  988. for instance in self:
  989. instance.comparison_mode = bool(instance.period_ids) and\
  990. not bool(instance.date_from)
  991. @api.multi
  992. def _inverse_comparison_mode(self):
  993. for record in self:
  994. if not record.comparison_mode:
  995. if not record.date_from:
  996. record.date_from = datetime.now()
  997. if not record.date_to:
  998. record.date_to = datetime.now()
  999. record.period_ids.unlink()
  1000. record.write({'period_ids': [
  1001. (0, 0, {
  1002. 'name': 'Default',
  1003. 'type': 'd',
  1004. })
  1005. ]})
  1006. else:
  1007. record.date_from = None
  1008. record.date_to = None
  1009. @api.onchange('date_range_id')
  1010. def onchange_date_range(self):
  1011. for record in self:
  1012. record.date_from = record.date_range_id.date_start
  1013. record.date_to = record.date_range_id.date_end
  1014. @api.multi
  1015. def preview(self):
  1016. assert len(self) == 1
  1017. view_id = self.env.ref('mis_builder.'
  1018. 'mis_report_instance_result_view_form')
  1019. return {
  1020. 'type': 'ir.actions.act_window',
  1021. 'res_model': 'mis.report.instance',
  1022. 'res_id': self.id,
  1023. 'view_mode': 'form',
  1024. 'view_type': 'form',
  1025. 'view_id': view_id.id,
  1026. 'target': 'current',
  1027. }
  1028. @api.multi
  1029. def print_pdf(self):
  1030. self.ensure_one()
  1031. return {
  1032. 'name': 'MIS report instance QWEB PDF report',
  1033. 'model': 'mis.report.instance',
  1034. 'type': 'ir.actions.report.xml',
  1035. 'report_name': 'mis_builder.report_mis_report_instance',
  1036. 'report_type': 'qweb-pdf',
  1037. 'context': self.env.context,
  1038. }
  1039. @api.multi
  1040. def export_xls(self):
  1041. self.ensure_one()
  1042. return {
  1043. 'name': 'MIS report instance XLSX report',
  1044. 'model': 'mis.report.instance',
  1045. 'type': 'ir.actions.report.xml',
  1046. 'report_name': 'mis.report.instance.xlsx',
  1047. 'report_type': 'xlsx',
  1048. 'context': self.env.context,
  1049. }
  1050. @api.multi
  1051. def display_settings(self):
  1052. assert len(self.ids) <= 1
  1053. view_id = self.env.ref('mis_builder.mis_report_instance_view_form')
  1054. return {
  1055. 'type': 'ir.actions.act_window',
  1056. 'res_model': 'mis.report.instance',
  1057. 'res_id': self.id if self.id else False,
  1058. 'view_mode': 'form',
  1059. 'view_type': 'form',
  1060. 'views': [(view_id.id, 'form')],
  1061. 'view_id': view_id.id,
  1062. 'target': 'current',
  1063. }
  1064. @api.multi
  1065. def compute(self):
  1066. self.ensure_one()
  1067. aep = self.report_id._prepare_aep(self.company_id)
  1068. kpi_matrix = self.report_id._prepare_kpi_matrix()
  1069. for period in self.period_ids:
  1070. # add the column header
  1071. if period.date_from == period.date_to:
  1072. comment = self._format_date(period.date_from)
  1073. else:
  1074. # from, to
  1075. date_from = self._format_date(period.date_from)
  1076. date_to = self._format_date(period.date_to)
  1077. comment = _('from %s to %s') % (date_from, date_to)
  1078. self.report_id._compute_period(
  1079. kpi_matrix,
  1080. period.id,
  1081. period.name,
  1082. comment,
  1083. aep,
  1084. period.date_from,
  1085. period.date_to,
  1086. self.target_move,
  1087. self.company_id,
  1088. period.subkpi_ids,
  1089. period._get_additional_move_line_filter,
  1090. period._get_additional_query_filter)
  1091. # TODO FIXME comparison columns
  1092. header = [{'cols': []}, {'cols': []}]
  1093. for col in kpi_matrix.iter_cols():
  1094. header[0]['cols'].append({
  1095. 'description': col.description,
  1096. 'comment': col.comment,
  1097. 'colspan': col.colspan,
  1098. })
  1099. for subcol in col.iter_subcols():
  1100. header[1]['cols'].append({
  1101. 'description': subcol.description,
  1102. 'comment': subcol.comment,
  1103. 'colspan': 1,
  1104. })
  1105. content = []
  1106. for row in kpi_matrix.iter_rows():
  1107. row_data = {
  1108. 'row_id': id(row),
  1109. 'parent_row_id': row.parent_row and id(row.parent_row) or None,
  1110. 'description': row.description,
  1111. 'comment': row.comment,
  1112. 'style': row.style and row.style.to_css_style() or '',
  1113. 'cols': []
  1114. }
  1115. for cell in row.iter_cells(kpi_matrix.iter_subcols()):
  1116. if cell is None:
  1117. row_data['cols'].append({})
  1118. else:
  1119. row_data['cols'].append({
  1120. 'val': (cell.val
  1121. if cell.val is not AccountingNone else None),
  1122. 'val_r': cell.val_rendered,
  1123. 'val_c': cell.val_comment,
  1124. # TODO FIXME style
  1125. # TODO FIXME drilldown
  1126. })
  1127. content.append(row_data)
  1128. return {
  1129. 'header': header,
  1130. 'content': content,
  1131. }