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.

822 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. additional_move_line_filter = None
  371. if get_additional_move_line_filter:
  372. additional_move_line_filter = get_additional_move_line_filter()
  373. aep.do_queries(date_from, date_to,
  374. target_move,
  375. additional_move_line_filter)
  376. compute_queue = self.kpi_ids
  377. recompute_queue = []
  378. while True:
  379. for kpi in compute_queue:
  380. try:
  381. kpi_val_comment = kpi.name + " = " + kpi.expression
  382. kpi_eval_expression = aep.replace_expr(kpi.expression)
  383. kpi_val = safe_eval(kpi_eval_expression, localdict)
  384. localdict[kpi.name] = kpi_val
  385. except ZeroDivisionError:
  386. kpi_val = None
  387. kpi_val_rendered = '#DIV/0'
  388. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  389. except (NameError, ValueError):
  390. recompute_queue.append(kpi)
  391. kpi_val = None
  392. kpi_val_rendered = '#ERR'
  393. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  394. except:
  395. kpi_val = None
  396. kpi_val_rendered = '#ERR'
  397. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  398. else:
  399. kpi_val_rendered = kpi.render(lang_id, kpi_val)
  400. try:
  401. kpi_style = None
  402. if kpi.css_style:
  403. kpi_style = safe_eval(kpi.css_style, localdict)
  404. except:
  405. _logger.warning("error evaluating css stype expression %s",
  406. kpi.css_style, exc_info=True)
  407. kpi_style = None
  408. drilldown = (kpi_val is not None and
  409. AEP.has_account_var(kpi.expression))
  410. res[kpi.name] = {
  411. 'val': None if kpi_val is AccountingNone else kpi_val,
  412. 'val_r': kpi_val_rendered,
  413. 'val_c': kpi_val_comment,
  414. 'style': kpi_style,
  415. 'prefix': kpi.prefix,
  416. 'suffix': kpi.suffix,
  417. 'dp': kpi.dp,
  418. 'is_percentage': kpi.type == 'pct',
  419. 'period_id': period_id,
  420. 'expr': kpi.expression,
  421. 'drilldown': drilldown,
  422. }
  423. if len(recompute_queue) == 0:
  424. # nothing to recompute, we are done
  425. break
  426. if len(recompute_queue) == len(compute_queue):
  427. # could not compute anything in this iteration
  428. # (ie real Value errors or cyclic dependency)
  429. # so we stop trying
  430. break
  431. # try again
  432. compute_queue = recompute_queue
  433. recompute_queue = []
  434. return res
  435. class MisReportInstancePeriod(models.Model):
  436. """ A MIS report instance has the logic to compute
  437. a report template for a given date period.
  438. Periods have a duration (day, week, fiscal period) and
  439. are defined as an offset relative to a pivot date.
  440. """
  441. @api.one
  442. @api.depends('report_instance_id.pivot_date', 'type', 'offset', 'duration')
  443. def _compute_dates(self):
  444. self.date_from = False
  445. self.date_to = False
  446. self.valid = False
  447. d = fields.Date.from_string(self.report_instance_id.pivot_date)
  448. if self.type == 'd':
  449. date_from = d + datetime.timedelta(days=self.offset)
  450. date_to = date_from + \
  451. datetime.timedelta(days=self.duration - 1)
  452. self.date_from = fields.Date.to_string(date_from)
  453. self.date_to = fields.Date.to_string(date_to)
  454. self.valid = True
  455. elif self.type == 'w':
  456. date_from = d - datetime.timedelta(d.weekday())
  457. date_from = date_from + datetime.timedelta(days=self.offset * 7)
  458. date_to = date_from + \
  459. datetime.timedelta(days=(7 * self.duration) - 1)
  460. self.date_from = fields.Date.to_string(date_from)
  461. self.date_to = fields.Date.to_string(date_to)
  462. self.valid = True
  463. _name = 'mis.report.instance.period'
  464. name = fields.Char(size=32, required=True,
  465. string='Description', translate=True)
  466. type = fields.Selection([('d', _('Day')),
  467. ('w', _('Week')),
  468. # ('fy', _('Fiscal Year'))
  469. ],
  470. required=True,
  471. string='Period type')
  472. offset = fields.Integer(string='Offset',
  473. help='Offset from current period',
  474. default=-1)
  475. duration = fields.Integer(string='Duration',
  476. help='Number of periods',
  477. default=1)
  478. date_from = fields.Date(compute='_compute_dates', string="From")
  479. date_to = fields.Date(compute='_compute_dates', string="To")
  480. valid = fields.Boolean(compute='_compute_dates',
  481. type='boolean',
  482. string='Valid')
  483. sequence = fields.Integer(string='Sequence', default=100)
  484. report_instance_id = fields.Many2one('mis.report.instance',
  485. string='Report Instance',
  486. ondelete='cascade')
  487. comparison_column_ids = fields.Many2many(
  488. comodel_name='mis.report.instance.period',
  489. relation='mis_report_instance_period_rel',
  490. column1='period_id',
  491. column2='compare_period_id',
  492. string='Compare with')
  493. normalize_factor = fields.Integer(
  494. string='Factor',
  495. help='Factor to use to normalize the period (used in comparison',
  496. default=1)
  497. _order = 'sequence, id'
  498. _sql_constraints = [
  499. ('duration', 'CHECK (duration>0)',
  500. 'Wrong duration, it must be positive!'),
  501. ('normalize_factor', 'CHECK (normalize_factor>0)',
  502. 'Wrong normalize factor, it must be positive!'),
  503. ('name_unique', 'unique(name, report_instance_id)',
  504. 'Period name should be unique by report'),
  505. ]
  506. @api.multi
  507. def _get_additional_move_line_filter(self):
  508. """ Prepare a filter to apply on all move lines
  509. This filter is applied with a AND operator on all
  510. accounting expression domains. This hook is intended
  511. to be inherited, and is useful to implement filtering
  512. on analytic dimensions or operational units.
  513. Returns an Odoo domain expression (a python list)
  514. compatible with account.move.line."""
  515. self.ensure_one()
  516. return []
  517. @api.multi
  518. def _get_additional_query_filter(self, query):
  519. """ Prepare an additional filter to apply on the query
  520. This filter is combined to the query domain with a AND
  521. operator. This hook is intended
  522. to be inherited, and is useful to implement filtering
  523. on analytic dimensions or operational units.
  524. Returns an Odoo domain expression (a python list)
  525. compatible with the model of the query."""
  526. self.ensure_one()
  527. return []
  528. @api.multi
  529. def drilldown(self, expr):
  530. self.ensure_one()
  531. if AEP.has_account_var(expr):
  532. aep = AEP(self.env)
  533. aep.parse_expr(expr)
  534. aep.done_parsing()
  535. domain = aep.get_aml_domain_for_expr(
  536. expr,
  537. self.date_from, self.date_to,
  538. self.report_instance_id.target_move)
  539. domain.extend(self._get_additional_move_line_filter())
  540. return {
  541. 'name': expr + ' - ' + self.name,
  542. 'domain': domain,
  543. 'type': 'ir.actions.act_window',
  544. 'res_model': 'account.move.line',
  545. 'views': [[False, 'list'], [False, 'form']],
  546. 'view_type': 'list',
  547. 'view_mode': 'list',
  548. 'target': 'current',
  549. }
  550. else:
  551. return False
  552. @api.multi
  553. def _compute(self, lang_id, aep):
  554. self.ensure_one()
  555. return self.report_instance_id.report_id._compute(
  556. lang_id, aep,
  557. self.date_from, self.date_to,
  558. self.report_instance_id.target_move,
  559. self._get_additional_move_line_filter,
  560. self._get_additional_query_filter,
  561. period_id=self.id,
  562. )
  563. class MisReportInstance(models.Model):
  564. """The MIS report instance combines everything to compute
  565. a MIS report template for a set of periods."""
  566. @api.one
  567. @api.depends('date')
  568. def _compute_pivot_date(self):
  569. if self.date:
  570. self.pivot_date = self.date
  571. else:
  572. self.pivot_date = fields.Date.context_today(self)
  573. _name = 'mis.report.instance'
  574. name = fields.Char(required=True,
  575. string='Name', translate=True)
  576. description = fields.Char(required=False,
  577. string='Description', translate=True)
  578. date = fields.Date(string='Base date',
  579. help='Report base date '
  580. '(leave empty to use current date)')
  581. pivot_date = fields.Date(compute='_compute_pivot_date',
  582. string="Pivot date")
  583. report_id = fields.Many2one('mis.report',
  584. required=True,
  585. string='Report')
  586. period_ids = fields.One2many('mis.report.instance.period',
  587. 'report_instance_id',
  588. required=True,
  589. string='Periods',
  590. copy=True)
  591. target_move = fields.Selection([('posted', 'All Posted Entries'),
  592. ('all', 'All Entries')],
  593. string='Target Moves',
  594. required=True,
  595. default='posted')
  596. company_id = fields.Many2one(comodel_name='res.company',
  597. string='Company')
  598. landscape_pdf = fields.Boolean(string='Landscape PDF')
  599. @api.one
  600. def copy(self, default=None):
  601. default = dict(default or {})
  602. default['name'] = _('%s (copy)') % self.name
  603. return super(MisReportInstance, self).copy(default)
  604. def _format_date(self, lang_id, date):
  605. # format date following user language
  606. date_format = self.env['res.lang'].browse(lang_id).date_format
  607. return datetime.datetime.strftime(
  608. fields.Date.from_string(date), date_format)
  609. @api.multi
  610. def preview(self):
  611. assert len(self) == 1
  612. view_id = self.env.ref('mis_builder.'
  613. 'mis_report_instance_result_view_form')
  614. return {
  615. 'type': 'ir.actions.act_window',
  616. 'res_model': 'mis.report.instance',
  617. 'res_id': self.id,
  618. 'view_mode': 'form',
  619. 'view_type': 'form',
  620. 'view_id': view_id.id,
  621. 'target': 'current',
  622. }
  623. @api.multi
  624. def print_pdf(self):
  625. self.ensure_one()
  626. return {
  627. 'name': 'MIS report instance QWEB PDF report',
  628. 'model': 'mis.report.instance',
  629. 'type': 'ir.actions.report.xml',
  630. 'report_name': 'mis_builder.report_mis_report_instance',
  631. 'report_type': 'qweb-pdf',
  632. 'context': self.env.context,
  633. }
  634. @api.multi
  635. def export_xls(self):
  636. self.ensure_one()
  637. return {
  638. 'name': 'MIS report instance XLSX report',
  639. 'model': 'mis.report.instance',
  640. 'type': 'ir.actions.report.xml',
  641. 'report_name': 'mis.report.instance.xlsx',
  642. 'report_type': 'xlsx',
  643. 'context': self.env.context,
  644. }
  645. @api.multi
  646. def display_settings(self):
  647. assert len(self.ids) <= 1
  648. view_id = self.env.ref('mis_builder.mis_report_instance_view_form')
  649. return {
  650. 'type': 'ir.actions.act_window',
  651. 'res_model': 'mis.report.instance',
  652. 'res_id': self.id if self.id else False,
  653. 'view_mode': 'form',
  654. 'view_type': 'form',
  655. 'views': [(view_id.id, 'form')],
  656. 'view_id': view_id.id,
  657. 'target': 'current',
  658. }
  659. @api.multi
  660. def compute(self):
  661. self.ensure_one()
  662. aep = self.report_id._prepare_aep()
  663. # fetch user language only once
  664. # TODO: is this necessary?
  665. lang = self.env.user.lang
  666. if not lang:
  667. lang = 'en_US'
  668. lang_id = self.env['res.lang'].search([('code', '=', lang)]).id
  669. # compute kpi values for each period
  670. kpi_values_by_period_ids = {}
  671. for period in self.period_ids:
  672. if not period.valid:
  673. continue
  674. kpi_values = period._compute(lang_id, aep)
  675. kpi_values_by_period_ids[period.id] = kpi_values
  676. # prepare header and content
  677. header = []
  678. header.append({
  679. 'kpi_name': '',
  680. 'cols': []
  681. })
  682. content = []
  683. rows_by_kpi_name = {}
  684. for kpi in self.report_id.kpi_ids:
  685. rows_by_kpi_name[kpi.name] = {
  686. 'kpi_name': kpi.description,
  687. 'cols': [],
  688. 'default_style': kpi.default_css_style
  689. }
  690. content.append(rows_by_kpi_name[kpi.name])
  691. # populate header and content
  692. for period in self.period_ids:
  693. if not period.valid:
  694. continue
  695. # add the column header
  696. if period.duration > 1 or period.type == 'w':
  697. # from, to
  698. date_from = self._format_date(lang_id, period.date_from)
  699. date_to = self._format_date(lang_id, period.date_to)
  700. header_date = _('from %s to %s') % (date_from, date_to)
  701. else:
  702. header_date = self._format_date(lang_id, period.date_from)
  703. header[0]['cols'].append(dict(name=period.name, date=header_date))
  704. # add kpi values
  705. kpi_values = kpi_values_by_period_ids[period.id]
  706. for kpi_name in kpi_values:
  707. rows_by_kpi_name[kpi_name]['cols'].append(kpi_values[kpi_name])
  708. # add comparison columns
  709. for compare_col in period.comparison_column_ids:
  710. compare_kpi_values = \
  711. kpi_values_by_period_ids.get(compare_col.id)
  712. if compare_kpi_values:
  713. # add the comparison column header
  714. header[0]['cols'].append(
  715. dict(name=_('%s vs %s') % (period.name,
  716. compare_col.name),
  717. date=''))
  718. # add comparison values
  719. for kpi in self.report_id.kpi_ids:
  720. rows_by_kpi_name[kpi.name]['cols'].append({
  721. 'val_r': kpi.render_comparison(
  722. lang_id,
  723. kpi_values[kpi.name]['val'],
  724. compare_kpi_values[kpi.name]['val'],
  725. period.normalize_factor,
  726. compare_col.normalize_factor)
  727. })
  728. return {'header': header,
  729. 'content': content}