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.

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