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.

1019 lines
38 KiB

9 years ago
9 years ago
9 years ago
11 years ago
9 years ago
11 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. get_additional_move_line_filter=None,
  404. get_additional_query_filter=None,
  405. period_id=None):
  406. """ Evaluate a report for a given period.
  407. It returns a dictionary keyed on kpi.name with the following values:
  408. * val: the evaluated kpi, or None if there is no data or an error
  409. * val_r: the rendered kpi as a string, or #ERR, #DIV
  410. * val_c: a comment (explaining the error, typically)
  411. * style: the css style of the kpi
  412. (may change in the future!)
  413. * prefix: a prefix to display in front of the rendered value
  414. * suffix: a prefix to display after rendered value
  415. * dp: the decimal precision of the kpi
  416. * is_percentage: true if the kpi is of percentage type
  417. (may change in the future!)
  418. * expr: the kpi expression
  419. * drilldown: true if the drilldown method of
  420. mis.report.instance.period is going to do something
  421. useful in this kpi
  422. :param lang_id: id of a res.lang object
  423. :param aep: an AccountingExpressionProcessor instance created
  424. using _prepare_aep()
  425. :param date_from, date_to: the starting and ending date
  426. :param target_move: all|posted
  427. :param get_additional_move_line_filter: a bound method that takes
  428. no arguments and returns
  429. a domain compatible with
  430. account.move.line
  431. :param get_additional_query_filter: a bound method that takes a single
  432. query argument and returns a
  433. domain compatible with the query
  434. underlying model
  435. :param period_id: an optional opaque value that is returned as
  436. query_id field in the result (may change in the
  437. future!)
  438. """
  439. self.ensure_one()
  440. res = {}
  441. localdict = {
  442. 'registry': self.pool,
  443. 'sum': _sum,
  444. 'min': _min,
  445. 'max': _max,
  446. 'len': len,
  447. 'avg': _avg,
  448. 'AccountingNone': AccountingNone,
  449. }
  450. localdict.update(self._fetch_queries(
  451. date_from, date_to, get_additional_query_filter))
  452. additional_move_line_filter = None
  453. if get_additional_move_line_filter:
  454. additional_move_line_filter = get_additional_move_line_filter()
  455. aep.do_queries(date_from, date_to,
  456. target_move,
  457. company,
  458. additional_move_line_filter)
  459. compute_queue = self.kpi_ids
  460. recompute_queue = []
  461. period = self.env['mis.report.instance.period'].browse(period_id)
  462. while True:
  463. for kpi in compute_queue:
  464. vals = []
  465. has_error = False
  466. for expression in kpi.expression_ids:
  467. if expression.subkpi_id \
  468. and expression.subkpi_id not in period.subkpi_ids:
  469. continue
  470. try:
  471. kpi_eval_expression = aep.replace_expr(expression.name)
  472. vals.append(safe_eval(kpi_eval_expression, localdict))
  473. except ZeroDivisionError:
  474. has_error = True
  475. vals.append(DataError(
  476. '#DIV/0',
  477. '\n\n%s' % (traceback.format_exc(),)))
  478. except (NameError, ValueError):
  479. has_error = True
  480. recompute_queue.append(kpi)
  481. vals.append(DataError(
  482. '#ERR',
  483. '\n\n%s' % (traceback.format_exc(),)))
  484. except:
  485. has_error = True
  486. vals.append(DataError(
  487. '#ERR',
  488. '\n\n%s' % (traceback.format_exc(),)))
  489. if len(vals) == 1 and isinstance(vals[0], SimpleArray):
  490. vals = vals[0]
  491. else:
  492. vals = SimpleArray(vals)
  493. if not has_error:
  494. localdict[kpi.name] = vals
  495. res[kpi] = vals
  496. if len(recompute_queue) == 0:
  497. # nothing to recompute, we are done
  498. break
  499. if len(recompute_queue) == len(compute_queue):
  500. # could not compute anything in this iteration
  501. # (ie real Value errors or cyclic dependency)
  502. # so we stop trying
  503. break
  504. # try again
  505. compute_queue = recompute_queue
  506. recompute_queue = []
  507. return res
  508. class MisReportInstancePeriod(models.Model):
  509. """ A MIS report instance has the logic to compute
  510. a report template for a given date period.
  511. Periods have a duration (day, week, fiscal period) and
  512. are defined as an offset relative to a pivot date.
  513. """
  514. @api.one
  515. @api.depends('report_instance_id.pivot_date', 'type', 'offset', 'duration')
  516. def _compute_dates(self):
  517. self.date_from = False
  518. self.date_to = False
  519. self.valid = False
  520. d = fields.Date.from_string(self.report_instance_id.pivot_date)
  521. if self.type == 'd':
  522. date_from = d + datetime.timedelta(days=self.offset)
  523. date_to = date_from + \
  524. datetime.timedelta(days=self.duration - 1)
  525. self.date_from = fields.Date.to_string(date_from)
  526. self.date_to = fields.Date.to_string(date_to)
  527. self.valid = True
  528. elif self.type == 'w':
  529. date_from = d - datetime.timedelta(d.weekday())
  530. date_from = date_from + datetime.timedelta(days=self.offset * 7)
  531. date_to = date_from + \
  532. datetime.timedelta(days=(7 * self.duration) - 1)
  533. self.date_from = fields.Date.to_string(date_from)
  534. self.date_to = fields.Date.to_string(date_to)
  535. self.valid = True
  536. elif self.type == 'date_range':
  537. date_range_obj = self.env['date.range']
  538. current_periods = date_range_obj.search(
  539. [('type_id', '=', self.date_range_type_id.id),
  540. ('date_start', '<=', d),
  541. ('date_end', '>=', d),
  542. ('company_id', '=', self.report_instance_id.company_id.id)])
  543. if current_periods:
  544. all_periods = date_range_obj.search(
  545. [('type_id', '=', self.date_range_type_id.id),
  546. ('company_id', '=',
  547. self.report_instance_id.company_id.id)],
  548. order='date_start')
  549. all_period_ids = [p.id for p in all_periods]
  550. p = all_period_ids.index(current_periods[0].id) + self.offset
  551. if p >= 0 and p + self.duration <= len(all_period_ids):
  552. periods = all_periods[p:p + self.duration]
  553. self.date_from = periods[0].date_start
  554. self.date_to = periods[-1].date_end
  555. self.valid = True
  556. _name = 'mis.report.instance.period'
  557. name = fields.Char(size=32, required=True,
  558. string='Description', translate=True)
  559. type = fields.Selection([('d', _('Day')),
  560. ('w', _('Week')),
  561. ('date_range', _('Date Range'))
  562. ],
  563. required=True,
  564. string='Period type')
  565. date_range_type_id = fields.Many2one(
  566. comodel_name='date.range.type', string='Date Range Type')
  567. offset = fields.Integer(string='Offset',
  568. help='Offset from current period',
  569. default=-1)
  570. duration = fields.Integer(string='Duration',
  571. help='Number of periods',
  572. default=1)
  573. date_from = fields.Date(compute='_compute_dates', string="From")
  574. date_to = fields.Date(compute='_compute_dates', string="To")
  575. valid = fields.Boolean(compute='_compute_dates',
  576. type='boolean',
  577. string='Valid')
  578. sequence = fields.Integer(string='Sequence', default=100)
  579. report_instance_id = fields.Many2one('mis.report.instance',
  580. string='Report Instance',
  581. ondelete='cascade')
  582. comparison_column_ids = fields.Many2many(
  583. comodel_name='mis.report.instance.period',
  584. relation='mis_report_instance_period_rel',
  585. column1='period_id',
  586. column2='compare_period_id',
  587. string='Compare with')
  588. normalize_factor = fields.Integer(
  589. string='Factor',
  590. help='Factor to use to normalize the period (used in comparison',
  591. default=1)
  592. subkpi_ids = fields.Many2many(
  593. 'mis.report.subkpi',
  594. string="Sub KPI")
  595. _order = 'sequence, id'
  596. _sql_constraints = [
  597. ('duration', 'CHECK (duration>0)',
  598. 'Wrong duration, it must be positive!'),
  599. ('normalize_factor', 'CHECK (normalize_factor>0)',
  600. 'Wrong normalize factor, it must be positive!'),
  601. ('name_unique', 'unique(name, report_instance_id)',
  602. 'Period name should be unique by report'),
  603. ]
  604. @api.multi
  605. def _get_additional_move_line_filter(self):
  606. """ Prepare a filter to apply on all move lines
  607. This filter is applied with a AND operator on all
  608. accounting expression domains. This hook is intended
  609. to be inherited, and is useful to implement filtering
  610. on analytic dimensions or operational units.
  611. Returns an Odoo domain expression (a python list)
  612. compatible with account.move.line."""
  613. self.ensure_one()
  614. return []
  615. @api.multi
  616. def _get_additional_query_filter(self, query):
  617. """ Prepare an additional filter to apply on the query
  618. This filter is combined to the query domain with a AND
  619. operator. This hook is intended
  620. to be inherited, and is useful to implement filtering
  621. on analytic dimensions or operational units.
  622. Returns an Odoo domain expression (a python list)
  623. compatible with the model of the query."""
  624. self.ensure_one()
  625. return []
  626. @api.multi
  627. def drilldown(self, expr):
  628. self.ensure_one()
  629. if AEP.has_account_var(expr):
  630. aep = AEP(self.env)
  631. aep.parse_expr(expr)
  632. aep.done_parsing(self.report_instance_id.company_id)
  633. domain = aep.get_aml_domain_for_expr(
  634. expr,
  635. self.date_from, self.date_to,
  636. self.report_instance_id.target_move,
  637. self.report_instance_id.company_id)
  638. domain.extend(self._get_additional_move_line_filter())
  639. return {
  640. 'name': expr + ' - ' + self.name,
  641. 'domain': domain,
  642. 'type': 'ir.actions.act_window',
  643. 'res_model': 'account.move.line',
  644. 'views': [[False, 'list'], [False, 'form']],
  645. 'view_type': 'list',
  646. 'view_mode': 'list',
  647. 'target': 'current',
  648. }
  649. else:
  650. return False
  651. @api.multi
  652. def _render(self, data, lang_id):
  653. self.ensure_one()
  654. res = {}
  655. if self.subkpi_ids:
  656. index2subkpi = {
  657. idx: subkpi.name
  658. for idx, subkpi in enumerate(self.subkpi_ids)
  659. }
  660. else:
  661. index2subkpi = {0: 'default'}
  662. for kpi, vals in data.items():
  663. res[kpi.name] = []
  664. # TODO FIXME localdict
  665. try:
  666. kpi_style = None
  667. if kpi.css_style:
  668. kpi_style = safe_eval(kpi.css_style, localdict)
  669. except:
  670. _logger.warning("error evaluating css stype expression %s",
  671. kpi.css_style, exc_info=True)
  672. kpi_style = None
  673. default_vals = {
  674. 'style': kpi_style,
  675. 'prefix': kpi.prefix,
  676. 'suffix': kpi.suffix,
  677. 'dp': kpi.dp,
  678. 'is_percentage': kpi.type == 'pct',
  679. 'period_id': self.id,
  680. 'expr': kpi.expression,
  681. }
  682. for idx, subkpi_val in enumerate(vals):
  683. vals = default_vals.copy()
  684. if isinstance(subkpi_val, DataError):
  685. vals.update({
  686. 'val': subkpi_val.name,
  687. 'val_r': subkpi_val.name,
  688. 'val_c': subkpi_val.msg,
  689. 'drilldown': None,
  690. })
  691. else:
  692. drilldown = (subkpi_val is not None and
  693. AEP.has_account_var(kpi.expression))
  694. if kpi.multi:
  695. expression = kpi.expression_ids[idx].name
  696. else:
  697. expression = kpi.expression
  698. comment = kpi.name + " = " + expression
  699. vals.update({
  700. 'val': None if subkpi_val is AccountingNone
  701. else subkpi_val,
  702. 'val_r': kpi.render(lang_id, subkpi_val),
  703. 'val_c': comment,
  704. 'drilldown': drilldown,
  705. })
  706. res[kpi.name].append(vals)
  707. return res
  708. @api.multi
  709. def _compute(self, lang_id, aep):
  710. self.ensure_one()
  711. data = self.report_instance_id.report_id._compute(
  712. lang_id, aep,
  713. self.date_from, self.date_to,
  714. self.report_instance_id.target_move,
  715. self.report_instance_id.company_id,
  716. self._get_additional_move_line_filter,
  717. self._get_additional_query_filter,
  718. period_id=self.id,
  719. )
  720. return self._render(data, lang_id)
  721. class MisReportInstance(models.Model):
  722. """The MIS report instance combines everything to compute
  723. a MIS report template for a set of periods."""
  724. @api.one
  725. @api.depends('date')
  726. def _compute_pivot_date(self):
  727. if self.date:
  728. self.pivot_date = self.date
  729. else:
  730. self.pivot_date = fields.Date.context_today(self)
  731. @api.model
  732. def _default_company(self):
  733. return self.env['res.company'].\
  734. _company_default_get('mis.report.instance')
  735. _name = 'mis.report.instance'
  736. name = fields.Char(required=True,
  737. string='Name', translate=True)
  738. description = fields.Char(required=False,
  739. string='Description', translate=True)
  740. date = fields.Date(string='Base date',
  741. help='Report base date '
  742. '(leave empty to use current date)')
  743. pivot_date = fields.Date(compute='_compute_pivot_date',
  744. string="Pivot date")
  745. report_id = fields.Many2one('mis.report',
  746. required=True,
  747. string='Report')
  748. period_ids = fields.One2many('mis.report.instance.period',
  749. 'report_instance_id',
  750. required=True,
  751. string='Periods',
  752. copy=True)
  753. target_move = fields.Selection([('posted', 'All Posted Entries'),
  754. ('all', 'All Entries')],
  755. string='Target Moves',
  756. required=True,
  757. default='posted')
  758. company_id = fields.Many2one(comodel_name='res.company',
  759. string='Company',
  760. default=_default_company,
  761. required=True)
  762. landscape_pdf = fields.Boolean(string='Landscape PDF')
  763. @api.one
  764. def copy(self, default=None):
  765. default = dict(default or {})
  766. default['name'] = _('%s (copy)') % self.name
  767. return super(MisReportInstance, self).copy(default)
  768. def _format_date(self, lang_id, date):
  769. # format date following user language
  770. date_format = self.env['res.lang'].browse(lang_id).date_format
  771. return datetime.datetime.strftime(
  772. fields.Date.from_string(date), date_format)
  773. @api.multi
  774. def preview(self):
  775. assert len(self) == 1
  776. view_id = self.env.ref('mis_builder.'
  777. 'mis_report_instance_result_view_form')
  778. return {
  779. 'type': 'ir.actions.act_window',
  780. 'res_model': 'mis.report.instance',
  781. 'res_id': self.id,
  782. 'view_mode': 'form',
  783. 'view_type': 'form',
  784. 'view_id': view_id.id,
  785. 'target': 'current',
  786. }
  787. @api.multi
  788. def print_pdf(self):
  789. self.ensure_one()
  790. return {
  791. 'name': 'MIS report instance QWEB PDF report',
  792. 'model': 'mis.report.instance',
  793. 'type': 'ir.actions.report.xml',
  794. 'report_name': 'mis_builder.report_mis_report_instance',
  795. 'report_type': 'qweb-pdf',
  796. 'context': self.env.context,
  797. }
  798. @api.multi
  799. def export_xls(self):
  800. self.ensure_one()
  801. return {
  802. 'name': 'MIS report instance XLSX report',
  803. 'model': 'mis.report.instance',
  804. 'type': 'ir.actions.report.xml',
  805. 'report_name': 'mis.report.instance.xlsx',
  806. 'report_type': 'xlsx',
  807. 'context': self.env.context,
  808. }
  809. @api.multi
  810. def display_settings(self):
  811. assert len(self.ids) <= 1
  812. view_id = self.env.ref('mis_builder.mis_report_instance_view_form')
  813. return {
  814. 'type': 'ir.actions.act_window',
  815. 'res_model': 'mis.report.instance',
  816. 'res_id': self.id if self.id else False,
  817. 'view_mode': 'form',
  818. 'view_type': 'form',
  819. 'views': [(view_id.id, 'form')],
  820. 'view_id': view_id.id,
  821. 'target': 'current',
  822. }
  823. @api.multi
  824. def compute(self):
  825. self.ensure_one()
  826. aep = self.report_id._prepare_aep(self.company_id)
  827. # fetch user language only once
  828. # TODO: is this necessary?
  829. lang = self.env.user.lang
  830. if not lang:
  831. lang = 'en_US'
  832. lang_id = self.env['res.lang'].search([('code', '=', lang)]).id
  833. # compute kpi values for each period
  834. kpi_values_by_period_ids = {}
  835. for period in self.period_ids:
  836. if not period.valid:
  837. continue
  838. kpi_values = period._compute(lang_id, aep)
  839. kpi_values_by_period_ids[period.id] = kpi_values
  840. # prepare header and content
  841. header = [{
  842. 'kpi_name': '',
  843. 'cols': []
  844. },{
  845. 'kpi_name': '',
  846. 'cols': []
  847. }]
  848. content = []
  849. rows_by_kpi_name = {}
  850. for kpi in self.report_id.kpi_ids:
  851. rows_by_kpi_name[kpi.name] = {
  852. 'kpi_name': kpi.description,
  853. 'cols': [],
  854. 'default_style': kpi.default_css_style
  855. }
  856. content.append(rows_by_kpi_name[kpi.name])
  857. # populate header and content
  858. for period in self.period_ids:
  859. if not period.valid:
  860. continue
  861. # add the column header
  862. if period.duration > 1 or period.type == 'w':
  863. # from, to
  864. date_from = self._format_date(lang_id, period.date_from)
  865. date_to = self._format_date(lang_id, period.date_to)
  866. header_date = _('from %s to %s') % (date_from, date_to)
  867. else:
  868. header_date = self._format_date(lang_id, period.date_from)
  869. header[0]['cols'].append(dict(
  870. name=period.name,
  871. date=header_date,
  872. colspan = len(period.subkpi_ids) or 1,
  873. ))
  874. for subkpi in period.subkpi_ids:
  875. header[1]['cols'].append(dict(
  876. name=subkpi.name,
  877. colspan = 1,
  878. ))
  879. if not period.subkpi_ids:
  880. header[1]['cols'].append(dict(
  881. name="",
  882. colspan = 1,
  883. ))
  884. # add kpi values
  885. kpi_values = kpi_values_by_period_ids[period.id]
  886. for kpi_name in kpi_values:
  887. rows_by_kpi_name[kpi_name]['cols'] += kpi_values[kpi_name]
  888. # add comparison columns
  889. for compare_col in period.comparison_column_ids:
  890. compare_kpi_values = \
  891. kpi_values_by_period_ids.get(compare_col.id)
  892. if compare_kpi_values:
  893. # add the comparison column header
  894. header[0]['cols'].append(
  895. dict(name=_('%s vs %s') % (period.name,
  896. compare_col.name),
  897. date=''))
  898. # add comparison values
  899. for kpi in self.report_id.kpi_ids:
  900. rows_by_kpi_name[kpi.name]['cols'].append({
  901. 'val_r': kpi.render_comparison(
  902. lang_id,
  903. kpi_values[kpi.name]['val'],
  904. compare_kpi_values[kpi.name]['val'],
  905. period.normalize_factor,
  906. compare_col.normalize_factor)
  907. })
  908. return {
  909. 'header': header,
  910. 'content': content,
  911. }