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.

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