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.

687 lines
26 KiB

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