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.

703 lines
27 KiB

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