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.

1032 lines
39 KiB

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