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.

884 lines
35 KiB

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