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.

1334 lines
50 KiB

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