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.

1240 lines
47 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.one
  424. def copy(self, default=None):
  425. default = dict(default or {})
  426. default['name'] = _('%s (copy)') % self.name
  427. return super(MisReport, self).copy(default)
  428. # TODO: kpi name cannot be start with query name
  429. @api.multi
  430. def _prepare_aep(self, company):
  431. self.ensure_one()
  432. aep = AEP(self.env)
  433. for kpi in self.kpi_ids:
  434. aep.parse_expr(kpi.expression)
  435. aep.done_parsing(company)
  436. return aep
  437. @api.multi
  438. def _fetch_queries(self, date_from, date_to,
  439. get_additional_query_filter=None):
  440. self.ensure_one()
  441. res = {}
  442. for query in self.query_ids:
  443. model = self.env[query.model_id.model]
  444. eval_context = {
  445. 'env': self.env,
  446. 'time': time,
  447. 'datetime': datetime,
  448. 'dateutil': dateutil,
  449. # deprecated
  450. 'uid': self.env.uid,
  451. 'context': self.env.context,
  452. }
  453. domain = query.domain and \
  454. safe_eval(query.domain, eval_context) or []
  455. if get_additional_query_filter:
  456. domain.extend(get_additional_query_filter(query))
  457. if query.date_field.ttype == 'date':
  458. domain.extend([(query.date_field.name, '>=', date_from),
  459. (query.date_field.name, '<=', date_to)])
  460. else:
  461. datetime_from = _utc_midnight(
  462. date_from, self._context.get('tz', 'UTC'))
  463. datetime_to = _utc_midnight(
  464. date_to, self._context.get('tz', 'UTC'), add_day=1)
  465. domain.extend([(query.date_field.name, '>=', datetime_from),
  466. (query.date_field.name, '<', datetime_to)])
  467. field_names = [f.name for f in query.field_ids]
  468. if not query.aggregate:
  469. data = model.search_read(domain, field_names)
  470. res[query.name] = [AutoStruct(**d) for d in data]
  471. elif query.aggregate == 'sum':
  472. data = model.read_group(
  473. domain, field_names, [])
  474. s = AutoStruct(count=data[0]['__count'])
  475. for field_name in field_names:
  476. v = data[0][field_name]
  477. setattr(s, field_name, v)
  478. res[query.name] = s
  479. else:
  480. data = model.search_read(domain, field_names)
  481. s = AutoStruct(count=len(data))
  482. if query.aggregate == 'min':
  483. agg = _min
  484. elif query.aggregate == 'max':
  485. agg = _max
  486. elif query.aggregate == 'avg':
  487. agg = _avg
  488. for field_name in field_names:
  489. setattr(s, field_name,
  490. agg([d[field_name] for d in data]))
  491. res[query.name] = s
  492. return res
  493. @api.multi
  494. def _compute(self, kpi_matrix, kpi_matrix_period,
  495. lang_id, aep,
  496. date_from, date_to,
  497. target_move,
  498. company,
  499. subkpis_filter,
  500. get_additional_move_line_filter=None,
  501. get_additional_query_filter=None):
  502. """ Evaluate a report for a given period, populating a KpiMatrix.
  503. :param kpi_matrix: the KpiMatrix object to be populated
  504. :param kpi_matrix_period: the period key to use when populating
  505. the KpiMatrix
  506. :param lang_id: id of a res.lang object
  507. :param aep: an AccountingExpressionProcessor instance created
  508. using _prepare_aep()
  509. :param date_from, date_to: the starting and ending date
  510. :param target_move: all|posted
  511. :param company:
  512. :param get_additional_move_line_filter: a bound method that takes
  513. no arguments and returns
  514. a domain compatible with
  515. account.move.line
  516. :param get_additional_query_filter: a bound method that takes a single
  517. query argument and returns a
  518. domain compatible with the query
  519. underlying model
  520. For each kpi, it calls set_kpi_vals and set_kpi_exploded_vals
  521. with vals being a tuple with the evaluation
  522. result for sub-kpis, or a DataError object if the evaluation failed.
  523. When done, it also calls set_localdict to store the local values
  524. that served for the computation of the period.
  525. """
  526. self.ensure_one()
  527. localdict = {
  528. 'registry': self.pool,
  529. 'sum': _sum,
  530. 'min': _min,
  531. 'max': _max,
  532. 'len': len,
  533. 'avg': _avg,
  534. 'AccountingNone': AccountingNone,
  535. }
  536. localdict.update(self._fetch_queries(
  537. date_from, date_to, get_additional_query_filter))
  538. additional_move_line_filter = None
  539. if get_additional_move_line_filter:
  540. additional_move_line_filter = get_additional_move_line_filter()
  541. aep.do_queries(date_from, date_to,
  542. target_move,
  543. company,
  544. additional_move_line_filter)
  545. compute_queue = self.kpi_ids
  546. recompute_queue = []
  547. while True:
  548. for kpi in compute_queue:
  549. vals = []
  550. has_error = False
  551. for expression in kpi.expression_ids:
  552. if expression.subkpi_id and \
  553. subkpis_filter and \
  554. expression.subkpi_id not in subkpis_filter:
  555. continue
  556. try:
  557. kpi_eval_expression = aep.replace_expr(expression.name)
  558. vals.append(safe_eval(kpi_eval_expression, localdict))
  559. except ZeroDivisionError:
  560. has_error = True
  561. vals.append(DataError(
  562. '#DIV/0',
  563. '\n\n%s' % (traceback.format_exc(),)))
  564. except (NameError, ValueError):
  565. has_error = True
  566. recompute_queue.append(kpi)
  567. vals.append(DataError(
  568. '#ERR',
  569. '\n\n%s' % (traceback.format_exc(),)))
  570. except:
  571. has_error = True
  572. vals.append(DataError(
  573. '#ERR',
  574. '\n\n%s' % (traceback.format_exc(),)))
  575. if len(vals) == 1 and isinstance(vals[0], SimpleArray):
  576. vals = vals[0]
  577. else:
  578. vals = SimpleArray(vals)
  579. kpi_matrix.set_kpi_vals(kpi_matrix_period, kpi, vals)
  580. if has_error:
  581. continue
  582. # no error, set it in localdict so it can be used
  583. # in computing other kpis
  584. localdict[kpi.name] = vals
  585. # let's compute the exploded values by account
  586. # we assume there will be no errors, because it is a
  587. # the same as the kpi, just filtered on one account;
  588. # I'd say if we have an exception in this part, it's bug...
  589. if not kpi.auto_expand_accounts:
  590. continue
  591. for account_id in aep.get_accounts_in_expr(kpi.expression):
  592. account_id_vals = []
  593. for expression in kpi.expression_ids:
  594. if expression.subkpi_id and \
  595. subkpis_filter and \
  596. expression.subkpi_id not in subkpis_filter:
  597. continue
  598. kpi_eval_expression = \
  599. aep.replace_expr(expression.name,
  600. account_ids_filter=[account_id])
  601. account_id_vals.\
  602. append(safe_eval(kpi_eval_expression, localdict))
  603. kpi_matrix.set_kpi_exploded_vals(kpi_matrix_period, kpi,
  604. account_id,
  605. account_id_vals)
  606. if len(recompute_queue) == 0:
  607. # nothing to recompute, we are done
  608. break
  609. if len(recompute_queue) == len(compute_queue):
  610. # could not compute anything in this iteration
  611. # (ie real Value errors or cyclic dependency)
  612. # so we stop trying
  613. break
  614. # try again
  615. compute_queue = recompute_queue
  616. recompute_queue = []
  617. kpi_matrix.set_localdict(kpi_matrix_period, localdict)
  618. class MisReportInstancePeriod(models.Model):
  619. """ A MIS report instance has the logic to compute
  620. a report template for a given date period.
  621. Periods have a duration (day, week, fiscal period) and
  622. are defined as an offset relative to a pivot date.
  623. """
  624. @api.one
  625. @api.depends('report_instance_id.pivot_date', 'type', 'offset',
  626. 'duration', 'report_instance_id.comparison_mode')
  627. def _compute_dates(self):
  628. self.date_from = False
  629. self.date_to = False
  630. self.valid = False
  631. report = self.report_instance_id
  632. d = fields.Date.from_string(report.pivot_date)
  633. if not report.comparison_mode:
  634. self.date_from = report.date_from
  635. self.date_to = report.date_to
  636. self.valid = True
  637. elif self.mode == 'fix':
  638. self.date_from = self.manual_date_from
  639. self.date_to = self.manual_date_to
  640. self.valid = True
  641. elif self.type == 'd':
  642. date_from = d + datetime.timedelta(days=self.offset)
  643. date_to = date_from + \
  644. datetime.timedelta(days=self.duration - 1)
  645. self.date_from = fields.Date.to_string(date_from)
  646. self.date_to = fields.Date.to_string(date_to)
  647. self.valid = True
  648. elif self.type == 'w':
  649. date_from = d - datetime.timedelta(d.weekday())
  650. date_from = date_from + datetime.timedelta(days=self.offset * 7)
  651. date_to = date_from + \
  652. datetime.timedelta(days=(7 * self.duration) - 1)
  653. self.date_from = fields.Date.to_string(date_from)
  654. self.date_to = fields.Date.to_string(date_to)
  655. self.valid = True
  656. elif self.type == 'date_range':
  657. date_range_obj = self.env['date.range']
  658. current_periods = date_range_obj.search(
  659. [('type_id', '=', self.date_range_type_id.id),
  660. ('date_start', '<=', d),
  661. ('date_end', '>=', d),
  662. ('company_id', '=', self.report_instance_id.company_id.id)])
  663. if current_periods:
  664. all_periods = date_range_obj.search(
  665. [('type_id', '=', self.date_range_type_id.id),
  666. ('company_id', '=',
  667. self.report_instance_id.company_id.id)],
  668. order='date_start')
  669. all_period_ids = [p.id for p in all_periods]
  670. p = all_period_ids.index(current_periods[0].id) + self.offset
  671. if p >= 0 and p + self.duration <= len(all_period_ids):
  672. periods = all_periods[p:p + self.duration]
  673. self.date_from = periods[0].date_start
  674. self.date_to = periods[-1].date_end
  675. self.valid = True
  676. _name = 'mis.report.instance.period'
  677. name = fields.Char(size=32, required=True,
  678. string='Description', translate=True)
  679. mode = fields.Selection([('fix', 'Fix'),
  680. ('relative', 'Relative'),
  681. ], required=True,
  682. default='fix')
  683. type = fields.Selection([('d', _('Day')),
  684. ('w', _('Week')),
  685. ('date_range', _('Date Range'))
  686. ],
  687. required=True,
  688. string='Period type')
  689. date_range_type_id = fields.Many2one(
  690. comodel_name='date.range.type', string='Date Range Type')
  691. offset = fields.Integer(string='Offset',
  692. help='Offset from current period',
  693. default=-1)
  694. duration = fields.Integer(string='Duration',
  695. help='Number of periods',
  696. default=1)
  697. date_from = fields.Date(compute='_compute_dates', string="From")
  698. date_to = fields.Date(compute='_compute_dates', string="To")
  699. manual_date_from = fields.Date(string="From")
  700. manual_date_to = fields.Date(string="To")
  701. date_range_id = fields.Many2one(
  702. comodel_name='date.range',
  703. string='Date Range')
  704. valid = fields.Boolean(compute='_compute_dates',
  705. type='boolean',
  706. string='Valid')
  707. sequence = fields.Integer(string='Sequence', default=100)
  708. report_instance_id = fields.Many2one('mis.report.instance',
  709. string='Report Instance',
  710. ondelete='cascade')
  711. comparison_column_ids = fields.Many2many(
  712. comodel_name='mis.report.instance.period',
  713. relation='mis_report_instance_period_rel',
  714. column1='period_id',
  715. column2='compare_period_id',
  716. string='Compare with')
  717. normalize_factor = fields.Integer(
  718. string='Factor',
  719. help='Factor to use to normalize the period (used in comparison',
  720. default=1)
  721. subkpi_ids = fields.Many2many(
  722. 'mis.report.subkpi',
  723. string="Sub KPI Filter")
  724. _order = 'sequence, id'
  725. _sql_constraints = [
  726. ('duration', 'CHECK (duration>0)',
  727. 'Wrong duration, it must be positive!'),
  728. ('normalize_factor', 'CHECK (normalize_factor>0)',
  729. 'Wrong normalize factor, it must be positive!'),
  730. ('name_unique', 'unique(name, report_instance_id)',
  731. 'Period name should be unique by report'),
  732. ]
  733. @api.onchange('date_range_id')
  734. def onchange_date_range(self):
  735. for record in self:
  736. record.manual_date_from = record.date_range_id.date_start
  737. record.manual_date_to = record.date_range_id.date_end
  738. @api.multi
  739. def _get_additional_move_line_filter(self):
  740. """ Prepare a filter to apply on all move lines
  741. This filter is applied with a AND operator on all
  742. accounting expression domains. This hook is intended
  743. to be inherited, and is useful to implement filtering
  744. on analytic dimensions or operational units.
  745. Returns an Odoo domain expression (a python list)
  746. compatible with account.move.line."""
  747. self.ensure_one()
  748. return []
  749. @api.multi
  750. def _get_additional_query_filter(self, query):
  751. """ Prepare an additional filter to apply on the query
  752. This filter is combined to the query domain with a AND
  753. operator. This hook is intended
  754. to be inherited, and is useful to implement filtering
  755. on analytic dimensions or operational units.
  756. Returns an Odoo domain expression (a python list)
  757. compatible with the model of the query."""
  758. self.ensure_one()
  759. return []
  760. @api.multi
  761. def drilldown(self, expr):
  762. self.ensure_one()
  763. # TODO FIXME: drilldown by account
  764. if AEP.has_account_var(expr):
  765. aep = AEP(self.env)
  766. aep.parse_expr(expr)
  767. aep.done_parsing(self.report_instance_id.company_id)
  768. domain = aep.get_aml_domain_for_expr(
  769. expr,
  770. self.date_from, self.date_to,
  771. self.report_instance_id.target_move,
  772. self.report_instance_id.company_id)
  773. domain.extend(self._get_additional_move_line_filter())
  774. return {
  775. 'name': expr + ' - ' + self.name,
  776. 'domain': domain,
  777. 'type': 'ir.actions.act_window',
  778. 'res_model': 'account.move.line',
  779. 'views': [[False, 'list'], [False, 'form']],
  780. 'view_type': 'list',
  781. 'view_mode': 'list',
  782. 'target': 'current',
  783. }
  784. else:
  785. return False
  786. @api.multi
  787. def _compute(self, kpi_matrix, lang_id, aep):
  788. """ Compute and render a mis report instance period
  789. It returns a dictionary keyed on kpi.name with a list of dictionaries
  790. with the following values (one item in the list for each subkpi):
  791. * val: the evaluated kpi, or None if there is no data or an error
  792. * val_r: the rendered kpi as a string, or #ERR, #DIV
  793. * val_c: a comment (explaining the error, typically)
  794. * style: the css style of the kpi
  795. (may change in the future!)
  796. * prefix: a prefix to display in front of the rendered value
  797. * suffix: a prefix to display after rendered value
  798. * dp: the decimal precision of the kpi
  799. * is_percentage: true if the kpi is of percentage type
  800. (may change in the future!)
  801. * expr: the kpi expression
  802. * drilldown: true if the drilldown method of
  803. mis.report.instance.period is going to do something
  804. useful in this kpi
  805. """
  806. self.ensure_one()
  807. # first invoke the compute method on the mis report template
  808. # passing it all the information regarding period and filters
  809. self.report_instance_id.report_id._compute(
  810. kpi_matrix, self,
  811. lang_id, aep,
  812. self.date_from, self.date_to,
  813. self.report_instance_id.target_move,
  814. self.report_instance_id.company_id,
  815. self.subkpi_ids,
  816. self._get_additional_move_line_filter,
  817. self._get_additional_query_filter,
  818. )
  819. # second, render it to something that can be used by the widget
  820. res = {}
  821. for kpi_name, kpi, vals in kpi_matrix.iter_kpi_vals(self):
  822. res[kpi_name] = []
  823. try:
  824. # TODO FIXME check css_style evaluation wrt subkpis
  825. kpi_style = None
  826. if kpi.css_style:
  827. kpi_style = safe_eval(kpi.css_style,
  828. kpi_matrix.get_localdict(self))
  829. except:
  830. _logger.warning("error evaluating css stype expression %s",
  831. kpi.css_style, exc_info=True)
  832. kpi_style = None
  833. default_vals = {
  834. 'style': kpi_style,
  835. 'prefix': kpi.prefix,
  836. 'suffix': kpi.suffix,
  837. 'dp': kpi.dp,
  838. 'is_percentage': kpi.type == 'pct',
  839. 'period_id': self.id,
  840. 'expr': kpi.expression, # TODO FIXME
  841. }
  842. for idx, subkpi_val in enumerate(vals):
  843. vals = default_vals.copy()
  844. if isinstance(subkpi_val, DataError):
  845. vals.update({
  846. 'val': subkpi_val.name,
  847. 'val_r': subkpi_val.name,
  848. 'val_c': subkpi_val.msg,
  849. 'drilldown': False,
  850. })
  851. else:
  852. # TODO FIXME: has_account_var on each subkpi expression?
  853. drilldown = (subkpi_val is not AccountingNone and
  854. AEP.has_account_var(kpi.expression))
  855. if kpi.multi:
  856. expression = kpi.expression_ids[idx].name
  857. else:
  858. expression = kpi.expression
  859. # TODO FIXME: check we have meaningfulname for exploded
  860. # kpis
  861. comment = kpi.name + " = " + expression
  862. vals.update({
  863. 'val': (None
  864. if subkpi_val is AccountingNone
  865. else subkpi_val),
  866. 'val_r': kpi.render(lang_id, subkpi_val),
  867. 'val_c': comment,
  868. 'drilldown': drilldown,
  869. })
  870. res[kpi_name].append(vals)
  871. return res
  872. class MisReportInstance(models.Model):
  873. """The MIS report instance combines everything to compute
  874. a MIS report template for a set of periods."""
  875. @api.one
  876. @api.depends('date')
  877. def _compute_pivot_date(self):
  878. if self.date:
  879. self.pivot_date = self.date
  880. else:
  881. self.pivot_date = fields.Date.context_today(self)
  882. @api.model
  883. def _default_company(self):
  884. return self.env['res.company'].\
  885. _company_default_get('mis.report.instance')
  886. _name = 'mis.report.instance'
  887. name = fields.Char(required=True,
  888. string='Name', translate=True)
  889. description = fields.Char(required=False,
  890. string='Description', translate=True)
  891. date = fields.Date(string='Base date',
  892. help='Report base date '
  893. '(leave empty to use current date)')
  894. pivot_date = fields.Date(compute='_compute_pivot_date',
  895. string="Pivot date")
  896. report_id = fields.Many2one('mis.report',
  897. required=True,
  898. string='Report')
  899. period_ids = fields.One2many('mis.report.instance.period',
  900. 'report_instance_id',
  901. required=True,
  902. string='Periods',
  903. copy=True)
  904. target_move = fields.Selection([('posted', 'All Posted Entries'),
  905. ('all', 'All Entries')],
  906. string='Target Moves',
  907. required=True,
  908. default='posted')
  909. company_id = fields.Many2one(comodel_name='res.company',
  910. string='Company',
  911. default=_default_company,
  912. required=True)
  913. landscape_pdf = fields.Boolean(string='Landscape PDF')
  914. comparison_mode = fields.Boolean(
  915. compute="_compute_comparison_mode",
  916. inverse="_inverse_comparison_mode")
  917. date_range_id = fields.Many2one(
  918. comodel_name='date.range',
  919. string='Date Range')
  920. date_from = fields.Date(string="From")
  921. date_to = fields.Date(string="To")
  922. @api.one
  923. def copy(self, default=None):
  924. default = dict(default or {})
  925. default['name'] = _('%s (copy)') % self.name
  926. return super(MisReportInstance, self).copy(default)
  927. def _format_date(self, lang_id, date):
  928. # format date following user language
  929. date_format = self.env['res.lang'].browse(lang_id).date_format
  930. return datetime.datetime.strftime(
  931. fields.Date.from_string(date), date_format)
  932. @api.multi
  933. @api.depends('date_from')
  934. def _compute_comparison_mode(self):
  935. for instance in self:
  936. instance.advanced_mode = not bool(instance.date_from)
  937. @api.multi
  938. def _inverse_comparison_mode(self):
  939. for record in self:
  940. if not record.comparison_mode:
  941. if not record.date_from:
  942. record.date_from = datetime.now()
  943. if not record.date_to:
  944. record.date_to = datetime.now()
  945. record.period_ids.unlink()
  946. record.write({'period_ids': [
  947. (0, 0, {
  948. 'name': 'Default',
  949. 'type': 'd',
  950. })
  951. ]})
  952. else:
  953. record.date_from = None
  954. record.date_to = None
  955. @api.onchange('date_range_id')
  956. def onchange_date_range(self):
  957. for record in self:
  958. record.date_from = record.date_range_id.date_start
  959. record.date_to = record.date_range_id.date_end
  960. @api.multi
  961. def preview(self):
  962. assert len(self) == 1
  963. view_id = self.env.ref('mis_builder.'
  964. 'mis_report_instance_result_view_form')
  965. return {
  966. 'type': 'ir.actions.act_window',
  967. 'res_model': 'mis.report.instance',
  968. 'res_id': self.id,
  969. 'view_mode': 'form',
  970. 'view_type': 'form',
  971. 'view_id': view_id.id,
  972. 'target': 'current',
  973. }
  974. @api.multi
  975. def print_pdf(self):
  976. self.ensure_one()
  977. return {
  978. 'name': 'MIS report instance QWEB PDF report',
  979. 'model': 'mis.report.instance',
  980. 'type': 'ir.actions.report.xml',
  981. 'report_name': 'mis_builder.report_mis_report_instance',
  982. 'report_type': 'qweb-pdf',
  983. 'context': self.env.context,
  984. }
  985. @api.multi
  986. def export_xls(self):
  987. self.ensure_one()
  988. return {
  989. 'name': 'MIS report instance XLSX report',
  990. 'model': 'mis.report.instance',
  991. 'type': 'ir.actions.report.xml',
  992. 'report_name': 'mis.report.instance.xlsx',
  993. 'report_type': 'xlsx',
  994. 'context': self.env.context,
  995. }
  996. @api.multi
  997. def display_settings(self):
  998. assert len(self.ids) <= 1
  999. view_id = self.env.ref('mis_builder.mis_report_instance_view_form')
  1000. return {
  1001. 'type': 'ir.actions.act_window',
  1002. 'res_model': 'mis.report.instance',
  1003. 'res_id': self.id if self.id else False,
  1004. 'view_mode': 'form',
  1005. 'view_type': 'form',
  1006. 'views': [(view_id.id, 'form')],
  1007. 'view_id': view_id.id,
  1008. 'target': 'current',
  1009. }
  1010. @api.multi
  1011. def compute(self):
  1012. self.ensure_one()
  1013. aep = self.report_id._prepare_aep(self.company_id)
  1014. # fetch user language only once
  1015. # TODO: is this necessary?
  1016. lang = self.env.user.lang
  1017. if not lang:
  1018. lang = 'en_US'
  1019. lang_id = self.env['res.lang'].search([('code', '=', lang)]).id
  1020. # compute kpi values for each period
  1021. kpi_values_by_period_ids = {}
  1022. kpi_matrix = KpiMatrix()
  1023. for period in self.period_ids:
  1024. if not period.valid:
  1025. continue
  1026. kpi_values = period._compute(kpi_matrix, lang_id, aep)
  1027. kpi_values_by_period_ids[period.id] = kpi_values
  1028. kpi_matrix.load_account_names(self.env['account.account'])
  1029. # prepare header and content
  1030. header = [{
  1031. 'kpi_name': '',
  1032. 'cols': []
  1033. }, {
  1034. 'kpi_name': '',
  1035. 'cols': []
  1036. }]
  1037. content = []
  1038. rows_by_kpi_name = {}
  1039. for kpi_name, kpi_description, kpi in kpi_matrix.iter_kpis():
  1040. rows_by_kpi_name[kpi_name] = {
  1041. 'kpi_name': kpi_description,
  1042. 'cols': [],
  1043. 'default_style': kpi.default_css_style
  1044. }
  1045. content.append(rows_by_kpi_name[kpi_name])
  1046. # populate header and content
  1047. for period in self.period_ids:
  1048. if not period.valid:
  1049. continue
  1050. # add the column header
  1051. if period.duration > 1 or period.type == 'w':
  1052. # from, to
  1053. date_from = self._format_date(lang_id, period.date_from)
  1054. date_to = self._format_date(lang_id, period.date_to)
  1055. header_date = _('from %s to %s') % (date_from, date_to)
  1056. else:
  1057. header_date = self._format_date(lang_id, period.date_from)
  1058. subkpis = period.subkpi_ids or \
  1059. period.report_instance_id.report_id.subkpi_ids
  1060. header[0]['cols'].append(dict(
  1061. name=period.name,
  1062. date=header_date,
  1063. colspan=len(subkpis) or 1,
  1064. ))
  1065. if subkpis:
  1066. for subkpi in subkpis:
  1067. header[1]['cols'].append(dict(
  1068. name=subkpi.name,
  1069. colspan=1,
  1070. ))
  1071. else:
  1072. header[1]['cols'].append(dict(
  1073. name="",
  1074. colspan=1,
  1075. ))
  1076. # add kpi values
  1077. kpi_values = kpi_values_by_period_ids[period.id]
  1078. for kpi_name in kpi_values:
  1079. rows_by_kpi_name[kpi_name]['cols'] += kpi_values[kpi_name]
  1080. # add comparison columns
  1081. for compare_col in period.comparison_column_ids:
  1082. compare_kpi_values = \
  1083. kpi_values_by_period_ids.get(compare_col.id)
  1084. if compare_kpi_values:
  1085. # add the comparison column header
  1086. header[0]['cols'].append(
  1087. dict(name=_('%s vs %s') % (period.name,
  1088. compare_col.name),
  1089. date=''))
  1090. # add comparison values
  1091. for kpi in self.report_id.kpi_ids:
  1092. rows_by_kpi_name[kpi.name]['cols'].append({
  1093. 'val_r': kpi.render_comparison(
  1094. lang_id,
  1095. kpi_values[kpi.name]['val'],
  1096. compare_kpi_values[kpi.name]['val'],
  1097. period.normalize_factor,
  1098. compare_col.normalize_factor)
  1099. })
  1100. return {
  1101. 'header': header,
  1102. 'content': content,
  1103. }