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.

1009 lines
38 KiB

9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
  1. # -*- coding: utf-8 -*-
  2. # © 2014-2015 ACSONE SA/NV (<http://acsone.eu>)
  3. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html).
  4. import datetime
  5. import dateutil
  6. import logging
  7. import re
  8. import time
  9. import traceback
  10. import pytz
  11. from openerp import api, exceptions, fields, models, _
  12. from openerp.tools.safe_eval import safe_eval
  13. from .aep import AccountingExpressionProcessor as AEP
  14. from .aggregate import _sum, _avg, _min, _max
  15. from .accounting_none import AccountingNone
  16. from openerp.exceptions import UserError
  17. from .simple_array import SimpleArray
  18. _logger = logging.getLogger(__name__)
  19. class DataError(Exception):
  20. def __init__(self, name, msg):
  21. self.name = name
  22. self.msg = msg
  23. class AutoStruct(object):
  24. def __init__(self, **kwargs):
  25. for k, v in kwargs.items():
  26. setattr(self, k, v)
  27. def _get_selection_label(selection, value):
  28. for v, l in selection:
  29. if v == value:
  30. return l
  31. return ''
  32. def _utc_midnight(d, tz_name, add_day=0):
  33. d = fields.Datetime.from_string(d) + datetime.timedelta(days=add_day)
  34. utc_tz = pytz.timezone('UTC')
  35. context_tz = pytz.timezone(tz_name)
  36. local_timestamp = context_tz.localize(d, is_dst=False)
  37. return fields.Datetime.to_string(local_timestamp.astimezone(utc_tz))
  38. def _python_var(var_str):
  39. return re.sub(r'\W|^(?=\d)', '_', var_str).lower()
  40. def _is_valid_python_var(name):
  41. return re.match("[_A-Za-z][_a-zA-Z0-9]*$", name)
  42. class MisReportKpi(models.Model):
  43. """ A KPI is an element (ie a line) of a MIS report.
  44. In addition to a name and description, it has an expression
  45. to compute it based on queries defined in the MIS report.
  46. It also has various informations defining how to render it
  47. (numeric or percentage or a string, a prefix, a suffix, divider) and
  48. how to render comparison of two values of the KPI.
  49. KPI's have a sequence and are ordered inside the MIS report.
  50. """
  51. _name = 'mis.report.kpi'
  52. name = fields.Char(size=32, required=True,
  53. string='Name')
  54. description = fields.Char(required=True,
  55. string='Description',
  56. translate=True)
  57. multi = fields.Boolean()
  58. expression = fields.Char(
  59. compute='_compute_expression',
  60. inverse='_inverse_expression')
  61. expression_ids = fields.One2many('mis.report.kpi.expression', 'kpi_id')
  62. default_css_style = fields.Char(string='Default CSS style')
  63. css_style = fields.Char(string='CSS style expression')
  64. type = fields.Selection([('num', _('Numeric')),
  65. ('pct', _('Percentage')),
  66. ('str', _('String'))],
  67. required=True,
  68. string='Type',
  69. default='num')
  70. divider = fields.Selection([('1e-6', _('µ')),
  71. ('1e-3', _('m')),
  72. ('1', _('1')),
  73. ('1e3', _('k')),
  74. ('1e6', _('M'))],
  75. string='Factor',
  76. default='1')
  77. dp = fields.Integer(string='Rounding', default=0)
  78. prefix = fields.Char(size=16, string='Prefix')
  79. suffix = fields.Char(size=16, string='Suffix')
  80. compare_method = fields.Selection([('diff', _('Difference')),
  81. ('pct', _('Percentage')),
  82. ('none', _('None'))],
  83. required=True,
  84. string='Comparison Method',
  85. default='pct')
  86. sequence = fields.Integer(string='Sequence', default=100)
  87. report_id = fields.Many2one('mis.report',
  88. string='Report',
  89. ondelete='cascade')
  90. _order = 'sequence, id'
  91. @api.one
  92. @api.constrains('name')
  93. def _check_name(self):
  94. if not _is_valid_python_var(self.name):
  95. raise exceptions.Warning(_('The name must be a valid '
  96. 'python identifier'))
  97. @api.onchange('name')
  98. def _onchange_name(self):
  99. if self.name and not _is_valid_python_var(self.name):
  100. return {
  101. 'warning': {
  102. 'title': 'Invalid name %s' % self.name,
  103. 'message': 'The name must be a valid python identifier'
  104. }
  105. }
  106. @api.multi
  107. def _compute_expression(self):
  108. for kpi in self:
  109. kpi.expression = ''
  110. for expression in kpi.expression_ids:
  111. if expression.subkpi_id:
  112. kpi.expression += '%s :\n' % expression.subkpi_id.name
  113. kpi.expression += '%s\n' % expression.name
  114. @api.multi
  115. def _inverse_expression(self):
  116. for kpi in self:
  117. if kpi.multi:
  118. raise UserError('Can not update a multi kpi from the kpi line')
  119. if kpi.expression_ids:
  120. kpi.expression_ids[0].write({
  121. 'name': kpi.expression,
  122. 'subkpi_id': None})
  123. for expression in kpi.expression_ids[1:]:
  124. expression.unlink()
  125. else:
  126. kpi.write({
  127. 'expression_ids': [(0, 0, {
  128. 'name': kpi.expression
  129. })]
  130. })
  131. @api.onchange('multi')
  132. def _onchange_multi(self):
  133. for kpi in self:
  134. if not kpi.multi:
  135. if kpi.expression_ids:
  136. kpi.expression = kpi.expression_ids[0].name
  137. else:
  138. kpi.expression = None
  139. else:
  140. expressions = []
  141. for subkpi in kpi.report_id.subkpi_ids:
  142. expressions.append((0, 0, {
  143. 'name': kpi.expression,
  144. 'subkpi_id': subkpi.id,
  145. }))
  146. kpi.expression_ids = expressions
  147. @api.onchange('description')
  148. def _onchange_description(self):
  149. """ construct name from description """
  150. if self.description and not self.name:
  151. self.name = _python_var(self.description)
  152. @api.onchange('type')
  153. def _onchange_type(self):
  154. if self.type == 'num':
  155. self.compare_method = 'pct'
  156. self.divider = '1'
  157. self.dp = 0
  158. elif self.type == 'pct':
  159. self.compare_method = 'diff'
  160. self.divider = '1'
  161. self.dp = 0
  162. elif self.type == 'str':
  163. self.compare_method = 'none'
  164. self.divider = ''
  165. self.dp = 0
  166. def render(self, lang_id, value):
  167. """ render a KPI value as a unicode string, ready for display """
  168. assert len(self) == 1
  169. if value is None or value == AccountingNone:
  170. return ''
  171. elif self.type == 'num':
  172. return self._render_num(lang_id, value, self.divider,
  173. self.dp, self.prefix, self.suffix)
  174. elif self.type == 'pct':
  175. return self._render_num(lang_id, value, 0.01,
  176. self.dp, '', '%')
  177. else:
  178. return unicode(value)
  179. def render_comparison(self, lang_id, value, base_value,
  180. average_value, average_base_value):
  181. """ render the comparison of two KPI values, ready for display
  182. If the difference is 0, an empty string is returned.
  183. """
  184. assert len(self) == 1
  185. if value is None:
  186. value = AccountingNone
  187. if base_value is None:
  188. base_value = AccountingNone
  189. if self.type == 'pct':
  190. delta = value - base_value
  191. if delta and round(delta, self.dp) != 0:
  192. return self._render_num(
  193. lang_id,
  194. delta,
  195. 0.01, self.dp, '', _('pp'),
  196. sign='+')
  197. elif self.type == 'num':
  198. if value and average_value:
  199. value = value / float(average_value)
  200. if base_value and average_base_value:
  201. base_value = base_value / float(average_base_value)
  202. if self.compare_method == 'diff':
  203. delta = value - base_value
  204. if delta and round(delta, self.dp) != 0:
  205. return self._render_num(
  206. lang_id,
  207. delta,
  208. self.divider, self.dp, self.prefix, self.suffix,
  209. sign='+')
  210. elif self.compare_method == 'pct':
  211. if base_value and round(base_value, self.dp) != 0:
  212. delta = (value - base_value) / abs(base_value)
  213. if delta and round(delta, self.dp) != 0:
  214. return self._render_num(
  215. lang_id,
  216. delta,
  217. 0.01, self.dp, '', '%',
  218. sign='+')
  219. return ''
  220. def _render_num(self, lang_id, value, divider,
  221. dp, prefix, suffix, sign='-'):
  222. divider_label = _get_selection_label(
  223. self._columns['divider'].selection, divider)
  224. if divider_label == '1':
  225. divider_label = ''
  226. # format number following user language
  227. value = round(value / float(divider or 1), dp) or 0
  228. value = self.env['res.lang'].browse(lang_id).format(
  229. '%%%s.%df' % (sign, dp),
  230. value,
  231. grouping=True)
  232. value = u'%s\N{NARROW NO-BREAK SPACE}%s\N{NO-BREAK SPACE}%s%s' % \
  233. (prefix or '', value, divider_label, suffix or '')
  234. value = value.replace('-', u'\N{NON-BREAKING HYPHEN}')
  235. return value
  236. class MisReportSubkpi(models.Model):
  237. _name = 'mis.report.subkpi'
  238. _order = 'sequence'
  239. sequence = fields.Integer()
  240. report_id = fields.Many2one('mis.report')
  241. name = fields.Char(required=True)
  242. expression_ids = fields.One2many('mis.report.kpi.expression', 'subkpi_id')
  243. @api.multi
  244. def unlink(self):
  245. for subkpi in self:
  246. subkpi.expression_ids.unlink()
  247. return super(MisReportSubkpi, self).unlink()
  248. class MisReportKpiExpression(models.Model):
  249. """ A KPI Expression is an expression of a line of a MIS report Kpi.
  250. It's used to compute the kpi value.
  251. """
  252. _name = 'mis.report.kpi.expression'
  253. _order = 'sequence, name'
  254. sequence = fields.Integer(
  255. related='subkpi_id.sequence',
  256. store=True,
  257. readonly=True)
  258. name = fields.Char(string='Expression')
  259. kpi_id = fields.Many2one('mis.report.kpi')
  260. subkpi_id = fields.Many2one(
  261. 'mis.report.subkpi',
  262. readonly=True)
  263. class MisReportQuery(models.Model):
  264. """ A query to fetch arbitrary data for a MIS report.
  265. A query works on a model and has a domain and list of fields to fetch.
  266. At runtime, the domain is expanded with a "and" on the date/datetime field.
  267. """
  268. _name = 'mis.report.query'
  269. @api.one
  270. @api.depends('field_ids')
  271. def _compute_field_names(self):
  272. field_names = [field.name for field in self.field_ids]
  273. self.field_names = ', '.join(field_names)
  274. name = fields.Char(size=32, required=True,
  275. string='Name')
  276. model_id = fields.Many2one('ir.model', required=True,
  277. string='Model')
  278. field_ids = fields.Many2many('ir.model.fields', required=True,
  279. string='Fields to fetch')
  280. field_names = fields.Char(compute='_compute_field_names',
  281. string='Fetched fields name')
  282. aggregate = fields.Selection([('sum', _('Sum')),
  283. ('avg', _('Average')),
  284. ('min', _('Min')),
  285. ('max', _('Max'))],
  286. string='Aggregate')
  287. date_field = fields.Many2one('ir.model.fields', required=True,
  288. string='Date field',
  289. domain=[('ttype', 'in',
  290. ('date', 'datetime'))])
  291. domain = fields.Char(string='Domain')
  292. report_id = fields.Many2one('mis.report', string='Report',
  293. ondelete='cascade')
  294. _order = 'name'
  295. @api.one
  296. @api.constrains('name')
  297. def _check_name(self):
  298. if not _is_valid_python_var(self.name):
  299. raise exceptions.Warning(_('The name must be a valid '
  300. 'python identifier'))
  301. class MisReport(models.Model):
  302. """ A MIS report template (without period information)
  303. The MIS report holds:
  304. * a list of explicit queries; the result of each query is
  305. stored in a variable with same name as a query, containing as list
  306. of data structures populated with attributes for each fields to fetch;
  307. when queries have an aggregate method and no fields to group, it returns
  308. a data structure with the aggregated fields
  309. * a list of KPI to be evaluated based on the variables resulting
  310. from the accounting data and queries (KPI expressions can references
  311. queries and accounting expression - see AccoutingExpressionProcessor)
  312. """
  313. _name = 'mis.report'
  314. name = fields.Char(required=True,
  315. string='Name', translate=True)
  316. description = fields.Char(required=False,
  317. string='Description', translate=True)
  318. query_ids = fields.One2many('mis.report.query', 'report_id',
  319. string='Queries',
  320. copy=True)
  321. kpi_ids = fields.One2many('mis.report.kpi', 'report_id',
  322. string='KPI\'s',
  323. copy=True)
  324. subkpi_ids = fields.One2many(
  325. 'mis.report.subkpi',
  326. 'report_id',
  327. string="Sub KPI")
  328. @api.one
  329. def copy(self, default=None):
  330. default = dict(default or {})
  331. default['name'] = _('%s (copy)') % self.name
  332. return super(MisReport, self).copy(default)
  333. # TODO: kpi name cannot be start with query name
  334. @api.multi
  335. def _prepare_aep(self, company):
  336. self.ensure_one()
  337. aep = AEP(self.env)
  338. for kpi in self.kpi_ids:
  339. aep.parse_expr(kpi.expression)
  340. aep.done_parsing(company)
  341. return aep
  342. @api.multi
  343. def _fetch_queries(self, date_from, date_to,
  344. get_additional_query_filter=None):
  345. self.ensure_one()
  346. res = {}
  347. for query in self.query_ids:
  348. model = self.env[query.model_id.model]
  349. eval_context = {
  350. 'env': self.env,
  351. 'time': time,
  352. 'datetime': datetime,
  353. 'dateutil': dateutil,
  354. # deprecated
  355. 'uid': self.env.uid,
  356. 'context': self.env.context,
  357. }
  358. domain = query.domain and \
  359. safe_eval(query.domain, eval_context) or []
  360. if get_additional_query_filter:
  361. domain.extend(get_additional_query_filter(query))
  362. if query.date_field.ttype == 'date':
  363. domain.extend([(query.date_field.name, '>=', date_from),
  364. (query.date_field.name, '<=', date_to)])
  365. else:
  366. datetime_from = _utc_midnight(
  367. date_from, self._context.get('tz', 'UTC'))
  368. datetime_to = _utc_midnight(
  369. date_to, self._context.get('tz', 'UTC'), add_day=1)
  370. domain.extend([(query.date_field.name, '>=', datetime_from),
  371. (query.date_field.name, '<', datetime_to)])
  372. field_names = [f.name for f in query.field_ids]
  373. if not query.aggregate:
  374. data = model.search_read(domain, field_names)
  375. res[query.name] = [AutoStruct(**d) for d in data]
  376. elif query.aggregate == 'sum':
  377. data = model.read_group(
  378. domain, field_names, [])
  379. s = AutoStruct(count=data[0]['__count'])
  380. for field_name in field_names:
  381. v = data[0][field_name]
  382. setattr(s, field_name, v)
  383. res[query.name] = s
  384. else:
  385. data = model.search_read(domain, field_names)
  386. s = AutoStruct(count=len(data))
  387. if query.aggregate == 'min':
  388. agg = _min
  389. elif query.aggregate == 'max':
  390. agg = _max
  391. elif query.aggregate == 'avg':
  392. agg = _avg
  393. for field_name in field_names:
  394. setattr(s, field_name,
  395. agg([d[field_name] for d in data]))
  396. res[query.name] = s
  397. return res
  398. @api.multi
  399. def _compute(self, lang_id, aep,
  400. date_from, date_to,
  401. target_move,
  402. company,
  403. subkpi_ids,
  404. get_additional_move_line_filter=None,
  405. get_additional_query_filter=None):
  406. """ Compute
  407. :param lang_id: id of a res.lang object
  408. :param aep: an AccountingExpressionProcessor instance created
  409. using _prepare_aep()
  410. :param date_from, date_to: the starting and ending date
  411. :param target_move: all|posted
  412. :param company:
  413. :param get_additional_move_line_filter: a bound method that takes
  414. no arguments and returns
  415. a domain compatible with
  416. account.move.line
  417. :param get_additional_query_filter: a bound method that takes a single
  418. query argument and returns a
  419. domain compatible with the query
  420. underlying model
  421. """
  422. self.ensure_one()
  423. res = {}
  424. localdict = {
  425. 'registry': self.pool,
  426. 'sum': _sum,
  427. 'min': _min,
  428. 'max': _max,
  429. 'len': len,
  430. 'avg': _avg,
  431. 'AccountingNone': AccountingNone,
  432. }
  433. localdict.update(self._fetch_queries(
  434. date_from, date_to, get_additional_query_filter))
  435. additional_move_line_filter = None
  436. if get_additional_move_line_filter:
  437. additional_move_line_filter = get_additional_move_line_filter()
  438. aep.do_queries(date_from, date_to,
  439. target_move,
  440. company,
  441. additional_move_line_filter)
  442. compute_queue = self.kpi_ids
  443. recompute_queue = []
  444. while True:
  445. for kpi in compute_queue:
  446. vals = []
  447. has_error = False
  448. for expression in kpi.expression_ids:
  449. if expression.subkpi_id \
  450. and expression.subkpi_id not in subkpi_ids:
  451. continue
  452. try:
  453. kpi_eval_expression = aep.replace_expr(expression.name)
  454. vals.append(safe_eval(kpi_eval_expression, localdict))
  455. except ZeroDivisionError:
  456. has_error = True
  457. vals.append(DataError(
  458. '#DIV/0',
  459. '\n\n%s' % (traceback.format_exc(),)))
  460. except (NameError, ValueError):
  461. has_error = True
  462. recompute_queue.append(kpi)
  463. vals.append(DataError(
  464. '#ERR',
  465. '\n\n%s' % (traceback.format_exc(),)))
  466. except:
  467. has_error = True
  468. vals.append(DataError(
  469. '#ERR',
  470. '\n\n%s' % (traceback.format_exc(),)))
  471. if len(vals) == 1 and isinstance(vals[0], SimpleArray):
  472. vals = vals[0]
  473. else:
  474. vals = SimpleArray(vals)
  475. if not has_error:
  476. localdict[kpi.name] = vals
  477. res[kpi] = vals
  478. if len(recompute_queue) == 0:
  479. # nothing to recompute, we are done
  480. break
  481. if len(recompute_queue) == len(compute_queue):
  482. # could not compute anything in this iteration
  483. # (ie real Value errors or cyclic dependency)
  484. # so we stop trying
  485. break
  486. # try again
  487. compute_queue = recompute_queue
  488. recompute_queue = []
  489. return res, localdict
  490. class MisReportInstancePeriod(models.Model):
  491. """ A MIS report instance has the logic to compute
  492. a report template for a given date period.
  493. Periods have a duration (day, week, fiscal period) and
  494. are defined as an offset relative to a pivot date.
  495. """
  496. @api.one
  497. @api.depends('report_instance_id.pivot_date', 'type', 'offset', 'duration')
  498. def _compute_dates(self):
  499. self.date_from = False
  500. self.date_to = False
  501. self.valid = False
  502. d = fields.Date.from_string(self.report_instance_id.pivot_date)
  503. if self.type == 'd':
  504. date_from = d + datetime.timedelta(days=self.offset)
  505. date_to = date_from + \
  506. datetime.timedelta(days=self.duration - 1)
  507. self.date_from = fields.Date.to_string(date_from)
  508. self.date_to = fields.Date.to_string(date_to)
  509. self.valid = True
  510. elif self.type == 'w':
  511. date_from = d - datetime.timedelta(d.weekday())
  512. date_from = date_from + datetime.timedelta(days=self.offset * 7)
  513. date_to = date_from + \
  514. datetime.timedelta(days=(7 * self.duration) - 1)
  515. self.date_from = fields.Date.to_string(date_from)
  516. self.date_to = fields.Date.to_string(date_to)
  517. self.valid = True
  518. elif self.type == 'date_range':
  519. date_range_obj = self.env['date.range']
  520. current_periods = date_range_obj.search(
  521. [('type_id', '=', self.date_range_type_id.id),
  522. ('date_start', '<=', d),
  523. ('date_end', '>=', d),
  524. ('company_id', '=', self.report_instance_id.company_id.id)])
  525. if current_periods:
  526. all_periods = date_range_obj.search(
  527. [('type_id', '=', self.date_range_type_id.id),
  528. ('company_id', '=',
  529. self.report_instance_id.company_id.id)],
  530. order='date_start')
  531. all_period_ids = [p.id for p in all_periods]
  532. p = all_period_ids.index(current_periods[0].id) + self.offset
  533. if p >= 0 and p + self.duration <= len(all_period_ids):
  534. periods = all_periods[p:p + self.duration]
  535. self.date_from = periods[0].date_start
  536. self.date_to = periods[-1].date_end
  537. self.valid = True
  538. _name = 'mis.report.instance.period'
  539. name = fields.Char(size=32, required=True,
  540. string='Description', translate=True)
  541. type = fields.Selection([('d', _('Day')),
  542. ('w', _('Week')),
  543. ('date_range', _('Date Range'))
  544. ],
  545. required=True,
  546. string='Period type')
  547. date_range_type_id = fields.Many2one(
  548. comodel_name='date.range.type', string='Date Range Type')
  549. offset = fields.Integer(string='Offset',
  550. help='Offset from current period',
  551. default=-1)
  552. duration = fields.Integer(string='Duration',
  553. help='Number of periods',
  554. default=1)
  555. date_from = fields.Date(compute='_compute_dates', string="From")
  556. date_to = fields.Date(compute='_compute_dates', string="To")
  557. valid = fields.Boolean(compute='_compute_dates',
  558. type='boolean',
  559. string='Valid')
  560. sequence = fields.Integer(string='Sequence', default=100)
  561. report_instance_id = fields.Many2one('mis.report.instance',
  562. string='Report Instance',
  563. ondelete='cascade')
  564. comparison_column_ids = fields.Many2many(
  565. comodel_name='mis.report.instance.period',
  566. relation='mis_report_instance_period_rel',
  567. column1='period_id',
  568. column2='compare_period_id',
  569. string='Compare with')
  570. normalize_factor = fields.Integer(
  571. string='Factor',
  572. help='Factor to use to normalize the period (used in comparison',
  573. default=1)
  574. subkpi_ids = fields.Many2many(
  575. 'mis.report.subkpi',
  576. string="Sub KPI")
  577. _order = 'sequence, id'
  578. _sql_constraints = [
  579. ('duration', 'CHECK (duration>0)',
  580. 'Wrong duration, it must be positive!'),
  581. ('normalize_factor', 'CHECK (normalize_factor>0)',
  582. 'Wrong normalize factor, it must be positive!'),
  583. ('name_unique', 'unique(name, report_instance_id)',
  584. 'Period name should be unique by report'),
  585. ]
  586. @api.multi
  587. def _get_additional_move_line_filter(self):
  588. """ Prepare a filter to apply on all move lines
  589. This filter is applied with a AND operator on all
  590. accounting expression domains. This hook is intended
  591. to be inherited, and is useful to implement filtering
  592. on analytic dimensions or operational units.
  593. Returns an Odoo domain expression (a python list)
  594. compatible with account.move.line."""
  595. self.ensure_one()
  596. return []
  597. @api.multi
  598. def _get_additional_query_filter(self, query):
  599. """ Prepare an additional filter to apply on the query
  600. This filter is combined to the query domain with a AND
  601. operator. This hook is intended
  602. to be inherited, and is useful to implement filtering
  603. on analytic dimensions or operational units.
  604. Returns an Odoo domain expression (a python list)
  605. compatible with the model of the query."""
  606. self.ensure_one()
  607. return []
  608. @api.multi
  609. def drilldown(self, expr):
  610. self.ensure_one()
  611. if AEP.has_account_var(expr):
  612. aep = AEP(self.env)
  613. aep.parse_expr(expr)
  614. aep.done_parsing(self.report_instance_id.company_id)
  615. domain = aep.get_aml_domain_for_expr(
  616. expr,
  617. self.date_from, self.date_to,
  618. self.report_instance_id.target_move,
  619. self.report_instance_id.company_id)
  620. domain.extend(self._get_additional_move_line_filter())
  621. return {
  622. 'name': expr + ' - ' + self.name,
  623. 'domain': domain,
  624. 'type': 'ir.actions.act_window',
  625. 'res_model': 'account.move.line',
  626. 'views': [[False, 'list'], [False, 'form']],
  627. 'view_type': 'list',
  628. 'view_mode': 'list',
  629. 'target': 'current',
  630. }
  631. else:
  632. return False
  633. @api.multi
  634. def _compute(self, lang_id, aep):
  635. """ Compute and render a mis report instance period
  636. It returns a dictionary keyed on kpi.name with a list of dictionaries
  637. with the following values (one item in the list for each subkpi):
  638. * val: the evaluated kpi, or None if there is no data or an error
  639. * val_r: the rendered kpi as a string, or #ERR, #DIV
  640. * val_c: a comment (explaining the error, typically)
  641. * style: the css style of the kpi
  642. (may change in the future!)
  643. * prefix: a prefix to display in front of the rendered value
  644. * suffix: a prefix to display after rendered value
  645. * dp: the decimal precision of the kpi
  646. * is_percentage: true if the kpi is of percentage type
  647. (may change in the future!)
  648. * expr: the kpi expression
  649. * drilldown: true if the drilldown method of
  650. mis.report.instance.period is going to do something
  651. useful in this kpi
  652. """
  653. self.ensure_one()
  654. # first invoke the compute method on the mis report template
  655. # passing it all the information regarding period and filters
  656. data, localdict = self.report_instance_id.report_id._compute(
  657. lang_id, aep,
  658. self.date_from, self.date_to,
  659. self.report_instance_id.target_move,
  660. self.report_instance_id.company_id,
  661. self.subkpi_ids,
  662. self._get_additional_move_line_filter,
  663. self._get_additional_query_filter,
  664. )
  665. # second, render it to something that can be used by the widget
  666. res = {}
  667. for kpi, vals in data.items():
  668. res[kpi.name] = []
  669. try:
  670. kpi_style = None
  671. if kpi.css_style:
  672. kpi_style = safe_eval(kpi.css_style, localdict)
  673. except:
  674. _logger.warning("error evaluating css stype expression %s",
  675. kpi.css_style, exc_info=True)
  676. kpi_style = None
  677. default_vals = {
  678. 'style': kpi_style,
  679. 'prefix': kpi.prefix,
  680. 'suffix': kpi.suffix,
  681. 'dp': kpi.dp,
  682. 'is_percentage': kpi.type == 'pct',
  683. 'period_id': self.id,
  684. 'expr': kpi.expression,
  685. }
  686. for idx, subkpi_val in enumerate(vals):
  687. vals = default_vals.copy()
  688. if isinstance(subkpi_val, DataError):
  689. vals.update({
  690. 'val': subkpi_val.name,
  691. 'val_r': subkpi_val.name,
  692. 'val_c': subkpi_val.msg,
  693. 'drilldown': False,
  694. })
  695. else:
  696. # TODO FIXME: has_account_var on each subkpi expression?
  697. drilldown = (subkpi_val is not AccountingNone and
  698. AEP.has_account_var(kpi.expression))
  699. if kpi.multi:
  700. expression = kpi.expression_ids[idx].name
  701. else:
  702. expression = kpi.expression
  703. comment = kpi.name + " = " + expression
  704. vals.update({
  705. 'val': (None
  706. if subkpi_val is AccountingNone
  707. else subkpi_val),
  708. 'val_r': kpi.render(lang_id, subkpi_val),
  709. 'val_c': comment,
  710. 'drilldown': drilldown,
  711. })
  712. res[kpi.name].append(vals)
  713. return res
  714. class MisReportInstance(models.Model):
  715. """The MIS report instance combines everything to compute
  716. a MIS report template for a set of periods."""
  717. @api.one
  718. @api.depends('date')
  719. def _compute_pivot_date(self):
  720. if self.date:
  721. self.pivot_date = self.date
  722. else:
  723. self.pivot_date = fields.Date.context_today(self)
  724. @api.model
  725. def _default_company(self):
  726. return self.env['res.company'].\
  727. _company_default_get('mis.report.instance')
  728. _name = 'mis.report.instance'
  729. name = fields.Char(required=True,
  730. string='Name', translate=True)
  731. description = fields.Char(required=False,
  732. string='Description', translate=True)
  733. date = fields.Date(string='Base date',
  734. help='Report base date '
  735. '(leave empty to use current date)')
  736. pivot_date = fields.Date(compute='_compute_pivot_date',
  737. string="Pivot date")
  738. report_id = fields.Many2one('mis.report',
  739. required=True,
  740. string='Report')
  741. period_ids = fields.One2many('mis.report.instance.period',
  742. 'report_instance_id',
  743. required=True,
  744. string='Periods',
  745. copy=True)
  746. target_move = fields.Selection([('posted', 'All Posted Entries'),
  747. ('all', 'All Entries')],
  748. string='Target Moves',
  749. required=True,
  750. default='posted')
  751. company_id = fields.Many2one(comodel_name='res.company',
  752. string='Company',
  753. default=_default_company,
  754. required=True)
  755. landscape_pdf = fields.Boolean(string='Landscape PDF')
  756. @api.one
  757. def copy(self, default=None):
  758. default = dict(default or {})
  759. default['name'] = _('%s (copy)') % self.name
  760. return super(MisReportInstance, self).copy(default)
  761. def _format_date(self, lang_id, date):
  762. # format date following user language
  763. date_format = self.env['res.lang'].browse(lang_id).date_format
  764. return datetime.datetime.strftime(
  765. fields.Date.from_string(date), date_format)
  766. @api.multi
  767. def preview(self):
  768. assert len(self) == 1
  769. view_id = self.env.ref('mis_builder.'
  770. 'mis_report_instance_result_view_form')
  771. return {
  772. 'type': 'ir.actions.act_window',
  773. 'res_model': 'mis.report.instance',
  774. 'res_id': self.id,
  775. 'view_mode': 'form',
  776. 'view_type': 'form',
  777. 'view_id': view_id.id,
  778. 'target': 'current',
  779. }
  780. @api.multi
  781. def print_pdf(self):
  782. self.ensure_one()
  783. return {
  784. 'name': 'MIS report instance QWEB PDF report',
  785. 'model': 'mis.report.instance',
  786. 'type': 'ir.actions.report.xml',
  787. 'report_name': 'mis_builder.report_mis_report_instance',
  788. 'report_type': 'qweb-pdf',
  789. 'context': self.env.context,
  790. }
  791. @api.multi
  792. def export_xls(self):
  793. self.ensure_one()
  794. return {
  795. 'name': 'MIS report instance XLSX report',
  796. 'model': 'mis.report.instance',
  797. 'type': 'ir.actions.report.xml',
  798. 'report_name': 'mis.report.instance.xlsx',
  799. 'report_type': 'xlsx',
  800. 'context': self.env.context,
  801. }
  802. @api.multi
  803. def display_settings(self):
  804. assert len(self.ids) <= 1
  805. view_id = self.env.ref('mis_builder.mis_report_instance_view_form')
  806. return {
  807. 'type': 'ir.actions.act_window',
  808. 'res_model': 'mis.report.instance',
  809. 'res_id': self.id if self.id else False,
  810. 'view_mode': 'form',
  811. 'view_type': 'form',
  812. 'views': [(view_id.id, 'form')],
  813. 'view_id': view_id.id,
  814. 'target': 'current',
  815. }
  816. @api.multi
  817. def compute(self):
  818. self.ensure_one()
  819. aep = self.report_id._prepare_aep(self.company_id)
  820. # fetch user language only once
  821. # TODO: is this necessary?
  822. lang = self.env.user.lang
  823. if not lang:
  824. lang = 'en_US'
  825. lang_id = self.env['res.lang'].search([('code', '=', lang)]).id
  826. # compute kpi values for each period
  827. kpi_values_by_period_ids = {}
  828. for period in self.period_ids:
  829. if not period.valid:
  830. continue
  831. kpi_values = period._compute(lang_id, aep)
  832. kpi_values_by_period_ids[period.id] = kpi_values
  833. # prepare header and content
  834. header = [{
  835. 'kpi_name': '',
  836. 'cols': []
  837. }, {
  838. 'kpi_name': '',
  839. 'cols': []
  840. }]
  841. content = []
  842. rows_by_kpi_name = {}
  843. for kpi in self.report_id.kpi_ids:
  844. rows_by_kpi_name[kpi.name] = {
  845. 'kpi_name': kpi.description,
  846. 'cols': [],
  847. 'default_style': kpi.default_css_style
  848. }
  849. content.append(rows_by_kpi_name[kpi.name])
  850. # populate header and content
  851. for period in self.period_ids:
  852. if not period.valid:
  853. continue
  854. # add the column header
  855. if period.duration > 1 or period.type == 'w':
  856. # from, to
  857. date_from = self._format_date(lang_id, period.date_from)
  858. date_to = self._format_date(lang_id, period.date_to)
  859. header_date = _('from %s to %s') % (date_from, date_to)
  860. else:
  861. header_date = self._format_date(lang_id, period.date_from)
  862. header[0]['cols'].append(dict(
  863. name=period.name,
  864. date=header_date,
  865. colspan=len(period.subkpi_ids) or 1,
  866. ))
  867. for subkpi in period.subkpi_ids:
  868. header[1]['cols'].append(dict(
  869. name=subkpi.name,
  870. colspan=1,
  871. ))
  872. if not period.subkpi_ids:
  873. header[1]['cols'].append(dict(
  874. name="",
  875. colspan=1,
  876. ))
  877. # add kpi values
  878. kpi_values = kpi_values_by_period_ids[period.id]
  879. for kpi_name in kpi_values:
  880. rows_by_kpi_name[kpi_name]['cols'] += kpi_values[kpi_name]
  881. # add comparison columns
  882. for compare_col in period.comparison_column_ids:
  883. compare_kpi_values = \
  884. kpi_values_by_period_ids.get(compare_col.id)
  885. if compare_kpi_values:
  886. # add the comparison column header
  887. header[0]['cols'].append(
  888. dict(name=_('%s vs %s') % (period.name,
  889. compare_col.name),
  890. date=''))
  891. # add comparison values
  892. for kpi in self.report_id.kpi_ids:
  893. rows_by_kpi_name[kpi.name]['cols'].append({
  894. 'val_r': kpi.render_comparison(
  895. lang_id,
  896. kpi_values[kpi.name]['val'],
  897. compare_kpi_values[kpi.name]['val'],
  898. period.normalize_factor,
  899. compare_col.normalize_factor)
  900. })
  901. return {
  902. 'header': header,
  903. 'content': content,
  904. }