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.

1408 lines
53 KiB

9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
8 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. from collections import defaultdict, OrderedDict
  5. import datetime
  6. import dateutil
  7. import logging
  8. import re
  9. import time
  10. import traceback
  11. import pytz
  12. from openerp import api, exceptions, fields, models, _
  13. from openerp.tools.safe_eval import safe_eval
  14. from .aep import AccountingExpressionProcessor as AEP
  15. from .aggregate import _sum, _avg, _min, _max
  16. from .accounting_none import AccountingNone
  17. from openerp.exceptions import UserError
  18. from .simple_array import SimpleArray
  19. _logger = logging.getLogger(__name__)
  20. class DataError(Exception):
  21. def __init__(self, name, msg):
  22. self.name = name
  23. self.msg = msg
  24. class AutoStruct(object):
  25. def __init__(self, **kwargs):
  26. for k, v in kwargs.items():
  27. setattr(self, k, v)
  28. class KpiMatrix(object):
  29. """ This object holds the computation results in a way
  30. that can be browsed easily for rendering """
  31. def __init__(self, env):
  32. self.env = env
  33. # { period: {kpi: vals}
  34. self._kpi_vals = defaultdict(dict)
  35. # { period: {kpi: {account_id: vals}}}
  36. self._kpi_exploded_vals = defaultdict(dict)
  37. # { period: localdict }
  38. self._localdict = {}
  39. # { kpi: set(account_ids) }
  40. self._kpis = OrderedDict()
  41. # { account_id: account name }
  42. self._account_names_by_id = {}
  43. def _get_row_id(self, kpi, account_id=None):
  44. r = kpi.name
  45. if account_id:
  46. r += ':' + str(account_id)
  47. return r
  48. def declare_kpi(self, kpi):
  49. raise RuntimeError("not implemented")
  50. def declare_period(self, period_key, localdict, subkpis,
  51. description, comment):
  52. raise RuntimeError("not implemented")
  53. def set_values(self, kpi, period_key, vals):
  54. raise RuntimeError("not implemented")
  55. def set_values_detail_account(self, kpi, period_key, account_id, vals):
  56. raise RuntimeError("not implemented")
  57. def add_comparison(self, period_key_1, period_key_2,
  58. description, comment,
  59. after_period_key):
  60. raise RuntimeError("not implemented")
  61. def iter_row_headers(self):
  62. """ Iterate rows headers, top down
  63. yields row_id, parent_row_id=None, row_description, row_comment, \
  64. row_style, kpi
  65. """
  66. raise RuntimeError("not implemented")
  67. def iter_col_headers(self):
  68. """ Iterate column headers, left to right
  69. yields col_id, col_description, col_comment, col_span, period_key
  70. """
  71. raise RuntimeError("not implemented")
  72. def iter_subcol_headers(self):
  73. """ Iterate sub columns headers, left to right
  74. yields subcol_id, col_id, subcol_description, subcol_comment
  75. """
  76. raise RuntimeError("not implemented")
  77. def iter_row_values(self):
  78. """ Iterate row values, left to right
  79. yields row_id, col_id, val, val_rendered, val_comment,
  80. val_style, subkpi, period_key
  81. """
  82. raise RuntimeError("not implemented")
  83. def iter_kpi_values(self, period_key):
  84. """
  85. yields kpi, kpi_values
  86. """
  87. raise RuntimeError("not implemented")
  88. # TODO FIXME old methods to be removed
  89. def set_kpi_vals(self, period, kpi, vals):
  90. """ Set the values for a kpi in a period
  91. vals is a list of sub-kpi values.
  92. """
  93. self._kpi_vals[period][kpi] = vals
  94. if kpi not in self._kpis:
  95. self._kpis[kpi] = set()
  96. def set_kpi_exploded_vals(self, period, kpi, account_id, vals):
  97. """ Set the detail values for a kpi in a period for a GL account
  98. This is used by the automatic details mechanism.
  99. vals is a list of sub-kpi values.
  100. """
  101. exploded_vals = self._kpi_exploded_vals[period]
  102. if kpi not in exploded_vals:
  103. exploded_vals[kpi] = {}
  104. exploded_vals[kpi][account_id] = vals
  105. self._kpis[kpi].add(account_id)
  106. def set_localdict(self, period, localdict):
  107. # TODO FIXME to be removed when we have styles
  108. self._localdict[period] = localdict
  109. def get_localdict(self, period):
  110. # TODO FIXME to be removed when we have styles
  111. return self._localdict[period]
  112. def iter_kpi_vals(self, period):
  113. """ Iterate kpi values, including auto-expanded details by account
  114. It yields, in no specific order:
  115. * kpi technical name
  116. * kpi object
  117. * subkpi values tuple
  118. """
  119. for kpi, vals in self._kpi_vals[period].iteritems():
  120. yield kpi.name, kpi, vals
  121. kpi_exploded_vals = self._kpi_exploded_vals[period]
  122. if kpi not in kpi_exploded_vals:
  123. continue
  124. for account_id, account_id_vals in \
  125. kpi_exploded_vals[kpi].iteritems():
  126. yield "%s:%s" % (kpi.name, account_id), kpi, account_id_vals
  127. def iter_kpis(self):
  128. """ Iterate kpis, including auto-expanded details by accounts
  129. It yields, in display order:
  130. * kpi technical name
  131. * kpi display name
  132. * kpi object
  133. """
  134. for kpi, account_ids in self._kpis.iteritems():
  135. yield kpi.name, kpi.description, kpi
  136. for account_id in sorted(account_ids, key=self.get_account_name):
  137. yield "%s:%s" % (kpi.name, account_id), \
  138. self.get_account_name(account_id), kpi
  139. def get_exploded_account_ids(self):
  140. """ Get the list of auto-expanded account ids
  141. It returns the complete list, across all periods and kpis.
  142. This method must be called after setting all kpi values
  143. using set_kpi_vals and set_exploded_kpi_vals.
  144. """
  145. res = set()
  146. for kpi, account_ids in self._kpis.iteritems():
  147. res.update(account_ids)
  148. return list(res)
  149. def load_account_names(self, account_obj):
  150. """ Load account names for all exploded account ids
  151. This method must be called after setting all kpi values
  152. using set_kpi_vals and set_exploded_kpi_vals, and before
  153. calling get_account_name().
  154. """
  155. account_data = account_obj.browse(self.get_exploded_account_ids())
  156. self._account_names_by_id = {a.id: u"{} {}".format(a.code, a.name)
  157. for a in account_data}
  158. def get_account_name(self, account_id):
  159. """ Get account display name from it's id
  160. This method must be called after loading account names with
  161. load_account_names().
  162. """
  163. return self._account_names_by_id.get(account_id, account_id)
  164. def _get_selection_label(selection, value):
  165. for v, l in selection:
  166. if v == value:
  167. return l
  168. return ''
  169. def _utc_midnight(d, tz_name, add_day=0):
  170. d = fields.Datetime.from_string(d) + datetime.timedelta(days=add_day)
  171. utc_tz = pytz.timezone('UTC')
  172. context_tz = pytz.timezone(tz_name)
  173. local_timestamp = context_tz.localize(d, is_dst=False)
  174. return fields.Datetime.to_string(local_timestamp.astimezone(utc_tz))
  175. def _python_var(var_str):
  176. return re.sub(r'\W|^(?=\d)', '_', var_str).lower()
  177. def _is_valid_python_var(name):
  178. return re.match("[_A-Za-z][_a-zA-Z0-9]*$", name)
  179. class MisReportKpi(models.Model):
  180. """ A KPI is an element (ie a line) of a MIS report.
  181. In addition to a name and description, it has an expression
  182. to compute it based on queries defined in the MIS report.
  183. It also has various informations defining how to render it
  184. (numeric or percentage or a string, a prefix, a suffix, divider) and
  185. how to render comparison of two values of the KPI.
  186. KPI's have a sequence and are ordered inside the MIS report.
  187. """
  188. _name = 'mis.report.kpi'
  189. name = fields.Char(size=32, required=True,
  190. string='Name')
  191. description = fields.Char(required=True,
  192. string='Description',
  193. translate=True)
  194. multi = fields.Boolean()
  195. expression = fields.Char(
  196. compute='_compute_expression',
  197. inverse='_inverse_expression')
  198. expression_ids = fields.One2many('mis.report.kpi.expression', 'kpi_id')
  199. auto_expand_accounts = fields.Boolean(string='Display details by account')
  200. style = fields.Many2one(
  201. string="Default style for KPI",
  202. comodel_name="mis.report.kpi.style",
  203. required=False
  204. )
  205. style_expression = fields.Char(
  206. string='Style expression',
  207. help='An expression that returns a style name for the kpi style')
  208. type = fields.Selection([('num', _('Numeric')),
  209. ('pct', _('Percentage')),
  210. ('str', _('String'))],
  211. required=True,
  212. string='Type',
  213. default='num')
  214. divider = fields.Selection([('1e-6', _('µ')),
  215. ('1e-3', _('m')),
  216. ('1', _('1')),
  217. ('1e3', _('k')),
  218. ('1e6', _('M'))],
  219. string='Factor',
  220. default='1')
  221. dp = fields.Integer(string='Rounding', default=0)
  222. prefix = fields.Char(size=16, string='Prefix')
  223. suffix = fields.Char(size=16, string='Suffix')
  224. compare_method = fields.Selection([('diff', _('Difference')),
  225. ('pct', _('Percentage')),
  226. ('none', _('None'))],
  227. required=True,
  228. string='Comparison Method',
  229. default='pct')
  230. sequence = fields.Integer(string='Sequence', default=100)
  231. report_id = fields.Many2one('mis.report',
  232. string='Report',
  233. ondelete='cascade')
  234. _order = 'sequence, id'
  235. @api.one
  236. @api.constrains('name')
  237. def _check_name(self):
  238. if not _is_valid_python_var(self.name):
  239. raise exceptions.Warning(_('The name must be a valid '
  240. 'python identifier'))
  241. @api.onchange('name')
  242. def _onchange_name(self):
  243. if self.name and not _is_valid_python_var(self.name):
  244. return {
  245. 'warning': {
  246. 'title': 'Invalid name %s' % self.name,
  247. 'message': 'The name must be a valid python identifier'
  248. }
  249. }
  250. @api.multi
  251. def _compute_expression(self):
  252. for kpi in self:
  253. l = []
  254. for expression in kpi.expression_ids:
  255. if expression.subkpi_id:
  256. l.append('{}={}'.format(
  257. expression.subkpi_id.name, expression.name))
  258. else:
  259. l.append(
  260. expression.name)
  261. kpi.expression = ',\n'.join(l)
  262. @api.multi
  263. def _inverse_expression(self):
  264. for kpi in self:
  265. if kpi.multi:
  266. raise UserError('Can not update a multi kpi from the kpi line')
  267. if kpi.expression_ids:
  268. kpi.expression_ids[0].write({
  269. 'name': kpi.expression,
  270. 'subkpi_id': None})
  271. for expression in kpi.expression_ids[1:]:
  272. expression.unlink()
  273. else:
  274. kpi.write({
  275. 'expression_ids': [(0, 0, {
  276. 'name': kpi.expression
  277. })]
  278. })
  279. @api.onchange('multi')
  280. def _onchange_multi(self):
  281. for kpi in self:
  282. if not kpi.multi:
  283. if kpi.expression_ids:
  284. kpi.expression = kpi.expression_ids[0].name
  285. else:
  286. kpi.expression = None
  287. else:
  288. expressions = []
  289. for subkpi in kpi.report_id.subkpi_ids:
  290. expressions.append((0, 0, {
  291. 'name': kpi.expression,
  292. 'subkpi_id': subkpi.id,
  293. }))
  294. kpi.expression_ids = expressions
  295. @api.onchange('description')
  296. def _onchange_description(self):
  297. """ construct name from description """
  298. if self.description and not self.name:
  299. self.name = _python_var(self.description)
  300. @api.onchange('type')
  301. def _onchange_type(self):
  302. if self.type == 'num':
  303. self.compare_method = 'pct'
  304. self.divider = '1'
  305. self.dp = 0
  306. elif self.type == 'pct':
  307. self.compare_method = 'diff'
  308. self.divider = '1'
  309. self.dp = 0
  310. elif self.type == 'str':
  311. self.compare_method = 'none'
  312. self.divider = ''
  313. self.dp = 0
  314. def render(self, lang_id, value):
  315. """ render a KPI value as a unicode string, ready for display """
  316. assert len(self) == 1
  317. if value is None or value is AccountingNone:
  318. return ''
  319. elif self.type == 'num':
  320. return self._render_num(lang_id, value, self.divider,
  321. self.dp, self.prefix, self.suffix)
  322. elif self.type == 'pct':
  323. return self._render_num(lang_id, value, 0.01,
  324. self.dp, '', '%')
  325. else:
  326. return unicode(value) # noqa - silence python3 error
  327. def render_comparison(self, lang_id, value, base_value,
  328. average_value, average_base_value):
  329. """ render the comparison of two KPI values, ready for display
  330. If the difference is 0, an empty string is returned.
  331. """
  332. assert len(self) == 1
  333. if value is None:
  334. value = AccountingNone
  335. if base_value is None:
  336. base_value = AccountingNone
  337. if self.type == 'pct':
  338. delta = value - base_value
  339. if delta and round(delta, self.dp) != 0:
  340. return self._render_num(
  341. lang_id,
  342. delta,
  343. 0.01, self.dp, '', _('pp'),
  344. sign='+')
  345. elif self.type == 'num':
  346. if value and average_value:
  347. value = value / float(average_value)
  348. if base_value and average_base_value:
  349. base_value = base_value / float(average_base_value)
  350. if self.compare_method == 'diff':
  351. delta = value - base_value
  352. if delta and round(delta, self.dp) != 0:
  353. return self._render_num(
  354. lang_id,
  355. delta,
  356. self.divider, self.dp, self.prefix, self.suffix,
  357. sign='+')
  358. elif self.compare_method == 'pct':
  359. if base_value and round(base_value, self.dp) != 0:
  360. delta = (value - base_value) / abs(base_value)
  361. if delta and round(delta, self.dp) != 0:
  362. return self._render_num(
  363. lang_id,
  364. delta,
  365. 0.01, self.dp, '', '%',
  366. sign='+')
  367. return ''
  368. def _render_num(self, lang_id, value, divider,
  369. dp, prefix, suffix, sign='-'):
  370. divider_label = _get_selection_label(
  371. self._columns['divider'].selection, divider)
  372. if divider_label == '1':
  373. divider_label = ''
  374. # format number following user language
  375. value = round(value / float(divider or 1), dp) or 0
  376. value = self.env['res.lang'].browse(lang_id).format(
  377. '%%%s.%df' % (sign, dp),
  378. value,
  379. grouping=True)
  380. value = u'%s\N{NARROW NO-BREAK SPACE}%s\N{NO-BREAK SPACE}%s%s' % \
  381. (prefix or '', value, divider_label, suffix or '')
  382. value = value.replace('-', u'\N{NON-BREAKING HYPHEN}')
  383. return value
  384. class MisReportSubkpi(models.Model):
  385. _name = 'mis.report.subkpi'
  386. _order = 'sequence'
  387. sequence = fields.Integer()
  388. report_id = fields.Many2one('mis.report')
  389. name = fields.Char(size=32, required=True,
  390. string='Name')
  391. description = fields.Char(required=True,
  392. string='Description',
  393. translate=True)
  394. expression_ids = fields.One2many('mis.report.kpi.expression', 'subkpi_id')
  395. @api.one
  396. @api.constrains('name')
  397. def _check_name(self):
  398. if not _is_valid_python_var(self.name):
  399. raise exceptions.Warning(_('The name must be a valid '
  400. 'python identifier'))
  401. @api.onchange('name')
  402. def _onchange_name(self):
  403. if self.name and not _is_valid_python_var(self.name):
  404. return {
  405. 'warning': {
  406. 'title': 'Invalid name %s' % self.name,
  407. 'message': 'The name must be a valid python identifier'
  408. }
  409. }
  410. @api.onchange('description')
  411. def _onchange_description(self):
  412. """ construct name from description """
  413. if self.description and not self.name:
  414. self.name = _python_var(self.description)
  415. @api.multi
  416. def unlink(self):
  417. for subkpi in self:
  418. subkpi.expression_ids.unlink()
  419. return super(MisReportSubkpi, self).unlink()
  420. class MisReportKpiExpression(models.Model):
  421. """ A KPI Expression is an expression of a line of a MIS report Kpi.
  422. It's used to compute the kpi value.
  423. """
  424. _name = 'mis.report.kpi.expression'
  425. _order = 'sequence, name'
  426. sequence = fields.Integer(
  427. related='subkpi_id.sequence',
  428. store=True,
  429. readonly=True)
  430. name = fields.Char(string='Expression')
  431. kpi_id = fields.Many2one('mis.report.kpi')
  432. subkpi_id = fields.Many2one(
  433. 'mis.report.subkpi',
  434. readonly=True)
  435. class MisReportQuery(models.Model):
  436. """ A query to fetch arbitrary data for a MIS report.
  437. A query works on a model and has a domain and list of fields to fetch.
  438. At runtime, the domain is expanded with a "and" on the date/datetime field.
  439. """
  440. _name = 'mis.report.query'
  441. @api.one
  442. @api.depends('field_ids')
  443. def _compute_field_names(self):
  444. field_names = [field.name for field in self.field_ids]
  445. self.field_names = ', '.join(field_names)
  446. name = fields.Char(size=32, required=True,
  447. string='Name')
  448. model_id = fields.Many2one('ir.model', required=True,
  449. string='Model')
  450. field_ids = fields.Many2many('ir.model.fields', required=True,
  451. string='Fields to fetch')
  452. field_names = fields.Char(compute='_compute_field_names',
  453. string='Fetched fields name')
  454. aggregate = fields.Selection([('sum', _('Sum')),
  455. ('avg', _('Average')),
  456. ('min', _('Min')),
  457. ('max', _('Max'))],
  458. string='Aggregate')
  459. date_field = fields.Many2one('ir.model.fields', required=True,
  460. string='Date field',
  461. domain=[('ttype', 'in',
  462. ('date', 'datetime'))])
  463. domain = fields.Char(string='Domain')
  464. report_id = fields.Many2one('mis.report', string='Report',
  465. ondelete='cascade')
  466. _order = 'name'
  467. @api.one
  468. @api.constrains('name')
  469. def _check_name(self):
  470. if not _is_valid_python_var(self.name):
  471. raise exceptions.Warning(_('The name must be a valid '
  472. 'python identifier'))
  473. class MisReport(models.Model):
  474. """ A MIS report template (without period information)
  475. The MIS report holds:
  476. * a list of explicit queries; the result of each query is
  477. stored in a variable with same name as a query, containing as list
  478. of data structures populated with attributes for each fields to fetch;
  479. when queries have an aggregate method and no fields to group, it returns
  480. a data structure with the aggregated fields
  481. * a list of KPI to be evaluated based on the variables resulting
  482. from the accounting data and queries (KPI expressions can references
  483. queries and accounting expression - see AccoutingExpressionProcessor)
  484. """
  485. _name = 'mis.report'
  486. name = fields.Char(required=True,
  487. string='Name', translate=True)
  488. description = fields.Char(required=False,
  489. string='Description', translate=True)
  490. query_ids = fields.One2many('mis.report.query', 'report_id',
  491. string='Queries',
  492. copy=True)
  493. kpi_ids = fields.One2many('mis.report.kpi', 'report_id',
  494. string='KPI\'s',
  495. copy=True)
  496. subkpi_ids = fields.One2many(
  497. 'mis.report.subkpi',
  498. 'report_id',
  499. string="Sub KPI")
  500. @api.multi
  501. def get_wizard_report_action(self):
  502. action = self.env.ref('mis_builder.mis_report_instance_view_action')
  503. res = action.read()[0]
  504. view = self.env.ref('mis_builder.wizard_mis_report_instance_view_form')
  505. res.update({
  506. 'view_id': view.id,
  507. 'views': [(view.id, 'form')],
  508. 'target': 'new',
  509. 'context': {
  510. 'default_report_id': self.id,
  511. 'default_name': self.name,
  512. 'default_temporary': True,
  513. }
  514. })
  515. return res
  516. @api.one
  517. def copy(self, default=None):
  518. default = dict(default or {})
  519. default['name'] = _('%s (copy)') % self.name
  520. return super(MisReport, self).copy(default)
  521. # TODO: kpi name cannot be start with query name
  522. @api.multi
  523. def _prepare_kpi_matrix(self):
  524. self.ensure_one()
  525. kpi_matrix = KpiMatrix(self.env)
  526. for kpi in self.kpi_ids:
  527. kpi_matrix.declare_kpi(kpi)
  528. return kpi_matrix
  529. @api.multi
  530. def _prepare_aep(self, company):
  531. self.ensure_one()
  532. aep = AEP(self.env)
  533. for kpi in self.kpi_ids:
  534. aep.parse_expr(kpi.expression)
  535. aep.done_parsing(company)
  536. return aep
  537. @api.multi
  538. def _fetch_queries(self, date_from, date_to,
  539. get_additional_query_filter=None):
  540. self.ensure_one()
  541. res = {}
  542. for query in self.query_ids:
  543. model = self.env[query.model_id.model]
  544. eval_context = {
  545. 'env': self.env,
  546. 'time': time,
  547. 'datetime': datetime,
  548. 'dateutil': dateutil,
  549. # deprecated
  550. 'uid': self.env.uid,
  551. 'context': self.env.context,
  552. }
  553. domain = query.domain and \
  554. safe_eval(query.domain, eval_context) or []
  555. if get_additional_query_filter:
  556. domain.extend(get_additional_query_filter(query))
  557. if query.date_field.ttype == 'date':
  558. domain.extend([(query.date_field.name, '>=', date_from),
  559. (query.date_field.name, '<=', date_to)])
  560. else:
  561. datetime_from = _utc_midnight(
  562. date_from, self._context.get('tz', 'UTC'))
  563. datetime_to = _utc_midnight(
  564. date_to, self._context.get('tz', 'UTC'), add_day=1)
  565. domain.extend([(query.date_field.name, '>=', datetime_from),
  566. (query.date_field.name, '<', datetime_to)])
  567. field_names = [f.name for f in query.field_ids]
  568. if not query.aggregate:
  569. data = model.search_read(domain, field_names)
  570. res[query.name] = [AutoStruct(**d) for d in data]
  571. elif query.aggregate == 'sum':
  572. data = model.read_group(
  573. domain, field_names, [])
  574. s = AutoStruct(count=data[0]['__count'])
  575. for field_name in field_names:
  576. v = data[0][field_name]
  577. setattr(s, field_name, v)
  578. res[query.name] = s
  579. else:
  580. data = model.search_read(domain, field_names)
  581. s = AutoStruct(count=len(data))
  582. if query.aggregate == 'min':
  583. agg = _min
  584. elif query.aggregate == 'max':
  585. agg = _max
  586. elif query.aggregate == 'avg':
  587. agg = _avg
  588. for field_name in field_names:
  589. setattr(s, field_name,
  590. agg([d[field_name] for d in data]))
  591. res[query.name] = s
  592. return res
  593. @api.multi
  594. def _compute_period(self, kpi_matrix, period_key,
  595. lang_id, aep,
  596. date_from, date_to,
  597. target_move,
  598. company,
  599. subkpis_filter=None,
  600. get_additional_move_line_filter=None,
  601. get_additional_query_filter=None):
  602. """ Evaluate a report for a given period, populating a KpiMatrix.
  603. :param kpi_matrix: the KpiMatrix object to be populated
  604. :param period_key: the period key to use when populating the KpiMatrix
  605. :param lang_id: id of a res.lang object
  606. :param aep: an AccountingExpressionProcessor instance created
  607. using _prepare_aep()
  608. :param date_from, date_to: the starting and ending date
  609. :param target_move: all|posted
  610. :param company:
  611. :param get_additional_move_line_filter: a bound method that takes
  612. no arguments and returns
  613. a domain compatible with
  614. account.move.line
  615. :param get_additional_query_filter: a bound method that takes a single
  616. query argument and returns a
  617. domain compatible with the query
  618. underlying model
  619. For each kpi, it calls set_kpi_vals and set_kpi_exploded_vals
  620. with vals being a tuple with the evaluation
  621. result for sub-kpis, or a DataError object if the evaluation failed.
  622. When done, it also calls set_localdict to store the local values
  623. that served for the computation of the period.
  624. """
  625. self.ensure_one()
  626. localdict = {
  627. 'sum': _sum,
  628. 'min': _min,
  629. 'max': _max,
  630. 'len': len,
  631. 'avg': _avg,
  632. 'AccountingNone': AccountingNone,
  633. }
  634. # fetch non-accounting queries
  635. localdict.update(self._fetch_queries(
  636. date_from, date_to, get_additional_query_filter))
  637. # prepare the period in the kpi matrix
  638. kpi_matrix.declare_period(period_key, localdict)
  639. # use AEP to do the accounting queries
  640. additional_move_line_filter = None
  641. if get_additional_move_line_filter:
  642. additional_move_line_filter = get_additional_move_line_filter()
  643. aep.do_queries(company,
  644. date_from, date_to,
  645. target_move,
  646. additional_move_line_filter)
  647. compute_queue = self.kpi_ids
  648. recompute_queue = []
  649. while True:
  650. for kpi in compute_queue:
  651. vals = []
  652. has_error = False
  653. for expression in kpi.expression_ids:
  654. if expression.subkpi_id and \
  655. subkpis_filter and \
  656. expression.subkpi_id not in subkpis_filter:
  657. continue
  658. try:
  659. kpi_eval_expression = aep.replace_expr(expression.name)
  660. vals.append(safe_eval(kpi_eval_expression, localdict))
  661. except ZeroDivisionError:
  662. has_error = True
  663. vals.append(DataError(
  664. '#DIV/0',
  665. '\n\n%s' % (traceback.format_exc(),)))
  666. except (NameError, ValueError):
  667. has_error = True
  668. recompute_queue.append(kpi)
  669. vals.append(DataError(
  670. '#ERR',
  671. '\n\n%s' % (traceback.format_exc(),)))
  672. except:
  673. has_error = True
  674. vals.append(DataError(
  675. '#ERR',
  676. '\n\n%s' % (traceback.format_exc(),)))
  677. if len(vals) == 1 and isinstance(vals[0], SimpleArray):
  678. vals = vals[0]
  679. else:
  680. vals = SimpleArray(vals)
  681. kpi_matrix.set_kpi_vals(period_key, kpi, vals)
  682. if has_error:
  683. continue
  684. # no error, set it in localdict so it can be used
  685. # in computing other kpis
  686. localdict[kpi.name] = vals
  687. # TODO FIXME handle exceptions
  688. if not kpi.auto_expand_accounts:
  689. continue
  690. expr = []
  691. for expression in kpi.expression_ids:
  692. if expression.subkpi_id and \
  693. subkpis_filter and \
  694. expression.subkpi_id not in subkpis_filter:
  695. continue
  696. expr.append(expression.name)
  697. expr = ', '.join(expr) # tuple
  698. for account_id, replaced_expr in \
  699. aep.replace_expr_by_account_id(expr):
  700. account_id_vals = safe_eval(replaced_expr, localdict)
  701. kpi_matrix.set_kpi_exploded_vals(kpi_matrix_period, kpi,
  702. account_id,
  703. account_id_vals)
  704. if len(recompute_queue) == 0:
  705. # nothing to recompute, we are done
  706. break
  707. if len(recompute_queue) == len(compute_queue):
  708. # could not compute anything in this iteration
  709. # (ie real Value errors or cyclic dependency)
  710. # so we stop trying
  711. break
  712. # try again
  713. compute_queue = recompute_queue
  714. recompute_queue = []
  715. kpi_matrix.set_localdict(period_key, localdict)
  716. class MisReportInstancePeriod(models.Model):
  717. """ A MIS report instance has the logic to compute
  718. a report template for a given date period.
  719. Periods have a duration (day, week, fiscal period) and
  720. are defined as an offset relative to a pivot date.
  721. """
  722. @api.one
  723. @api.depends('report_instance_id.pivot_date', 'type', 'offset',
  724. 'duration', 'report_instance_id.comparison_mode')
  725. def _compute_dates(self):
  726. self.date_from = False
  727. self.date_to = False
  728. self.valid = False
  729. report = self.report_instance_id
  730. d = fields.Date.from_string(report.pivot_date)
  731. if not report.comparison_mode:
  732. self.date_from = report.date_from
  733. self.date_to = report.date_to
  734. self.valid = True
  735. elif self.mode == 'fix':
  736. self.date_from = self.manual_date_from
  737. self.date_to = self.manual_date_to
  738. self.valid = True
  739. elif self.type == 'd':
  740. date_from = d + datetime.timedelta(days=self.offset)
  741. date_to = date_from + \
  742. datetime.timedelta(days=self.duration - 1)
  743. self.date_from = fields.Date.to_string(date_from)
  744. self.date_to = fields.Date.to_string(date_to)
  745. self.valid = True
  746. elif self.type == 'w':
  747. date_from = d - datetime.timedelta(d.weekday())
  748. date_from = date_from + datetime.timedelta(days=self.offset * 7)
  749. date_to = date_from + \
  750. datetime.timedelta(days=(7 * self.duration) - 1)
  751. self.date_from = fields.Date.to_string(date_from)
  752. self.date_to = fields.Date.to_string(date_to)
  753. self.valid = True
  754. elif self.type == 'date_range':
  755. date_range_obj = self.env['date.range']
  756. current_periods = date_range_obj.search(
  757. [('type_id', '=', self.date_range_type_id.id),
  758. ('date_start', '<=', d),
  759. ('date_end', '>=', d),
  760. ('company_id', '=', self.report_instance_id.company_id.id)])
  761. if current_periods:
  762. all_periods = date_range_obj.search(
  763. [('type_id', '=', self.date_range_type_id.id),
  764. ('company_id', '=',
  765. self.report_instance_id.company_id.id)],
  766. order='date_start')
  767. all_period_ids = [p.id for p in all_periods]
  768. p = all_period_ids.index(current_periods[0].id) + self.offset
  769. if p >= 0 and p + self.duration <= len(all_period_ids):
  770. periods = all_periods[p:p + self.duration]
  771. self.date_from = periods[0].date_start
  772. self.date_to = periods[-1].date_end
  773. self.valid = True
  774. _name = 'mis.report.instance.period'
  775. name = fields.Char(size=32, required=True,
  776. string='Description', translate=True)
  777. mode = fields.Selection([('fix', 'Fix'),
  778. ('relative', 'Relative'),
  779. ], required=True,
  780. default='fix')
  781. type = fields.Selection([('d', _('Day')),
  782. ('w', _('Week')),
  783. ('date_range', _('Date Range'))
  784. ],
  785. string='Period type')
  786. date_range_type_id = fields.Many2one(
  787. comodel_name='date.range.type', string='Date Range Type')
  788. offset = fields.Integer(string='Offset',
  789. help='Offset from current period',
  790. default=-1)
  791. duration = fields.Integer(string='Duration',
  792. help='Number of periods',
  793. default=1)
  794. date_from = fields.Date(compute='_compute_dates', string="From")
  795. date_to = fields.Date(compute='_compute_dates', string="To")
  796. manual_date_from = fields.Date(string="From")
  797. manual_date_to = fields.Date(string="To")
  798. date_range_id = fields.Many2one(
  799. comodel_name='date.range',
  800. string='Date Range')
  801. valid = fields.Boolean(compute='_compute_dates',
  802. type='boolean',
  803. string='Valid')
  804. sequence = fields.Integer(string='Sequence', default=100)
  805. report_instance_id = fields.Many2one('mis.report.instance',
  806. string='Report Instance',
  807. ondelete='cascade')
  808. comparison_column_ids = fields.Many2many(
  809. comodel_name='mis.report.instance.period',
  810. relation='mis_report_instance_period_rel',
  811. column1='period_id',
  812. column2='compare_period_id',
  813. string='Compare with')
  814. normalize_factor = fields.Integer(
  815. string='Factor',
  816. help='Factor to use to normalize the period (used in comparison',
  817. default=1)
  818. subkpi_ids = fields.Many2many(
  819. 'mis.report.subkpi',
  820. string="Sub KPI Filter")
  821. _order = 'sequence, id'
  822. _sql_constraints = [
  823. ('duration', 'CHECK (duration>0)',
  824. 'Wrong duration, it must be positive!'),
  825. ('normalize_factor', 'CHECK (normalize_factor>0)',
  826. 'Wrong normalize factor, it must be positive!'),
  827. ('name_unique', 'unique(name, report_instance_id)',
  828. 'Period name should be unique by report'),
  829. ]
  830. @api.onchange('date_range_id')
  831. def onchange_date_range(self):
  832. for record in self:
  833. record.manual_date_from = record.date_range_id.date_start
  834. record.manual_date_to = record.date_range_id.date_end
  835. record.name = record.date_range_id.name
  836. @api.multi
  837. def _get_additional_move_line_filter(self):
  838. """ Prepare a filter to apply on all move lines
  839. This filter is applied with a AND operator on all
  840. accounting expression domains. This hook is intended
  841. to be inherited, and is useful to implement filtering
  842. on analytic dimensions or operational units.
  843. Returns an Odoo domain expression (a python list)
  844. compatible with account.move.line."""
  845. self.ensure_one()
  846. return []
  847. @api.multi
  848. def _get_additional_query_filter(self, query):
  849. """ Prepare an additional filter to apply on the query
  850. This filter is combined to the query domain with a AND
  851. operator. This hook is intended
  852. to be inherited, and is useful to implement filtering
  853. on analytic dimensions or operational units.
  854. Returns an Odoo domain expression (a python list)
  855. compatible with the model of the query."""
  856. self.ensure_one()
  857. return []
  858. @api.multi
  859. def drilldown(self, expr):
  860. self.ensure_one()
  861. # TODO FIXME: drilldown by account
  862. if AEP.has_account_var(expr):
  863. aep = AEP(self.env)
  864. aep.parse_expr(expr)
  865. aep.done_parsing(self.report_instance_id.company_id)
  866. domain = aep.get_aml_domain_for_expr(
  867. expr,
  868. self.date_from, self.date_to,
  869. self.report_instance_id.target_move,
  870. self.report_instance_id.company_id)
  871. domain.extend(self._get_additional_move_line_filter())
  872. return {
  873. 'name': expr + ' - ' + self.name,
  874. 'domain': domain,
  875. 'type': 'ir.actions.act_window',
  876. 'res_model': 'account.move.line',
  877. 'views': [[False, 'list'], [False, 'form']],
  878. 'view_type': 'list',
  879. 'view_mode': 'list',
  880. 'target': 'current',
  881. }
  882. else:
  883. return False
  884. @api.multi
  885. def _render_period(self, kpi_matrix, lang_id, aep):
  886. """ Compute and render a mis report instance period
  887. It returns a dictionary keyed on kpi.name with a list of dictionaries
  888. with the following values (one item in the list for each subkpi):
  889. * val: the evaluated kpi, or None if there is no data or an error
  890. * val_r: the rendered kpi as a string, or #ERR, #DIV
  891. * val_c: a comment (explaining the error, typically)
  892. * style: the css style of the kpi
  893. (may change in the future!)
  894. * prefix: a prefix to display in front of the rendered value
  895. * suffix: a prefix to display after rendered value
  896. * dp: the decimal precision of the kpi
  897. * is_percentage: true if the kpi is of percentage type
  898. (may change in the future!)
  899. * expr: the kpi expression
  900. * drilldown: true if the drilldown method of
  901. mis.report.instance.period is going to do something
  902. useful in this kpi
  903. """
  904. self.ensure_one()
  905. # first invoke the compute method on the mis report template
  906. # passing it all the information regarding period and filters
  907. self.report_instance_id.report_id._compute_period(
  908. kpi_matrix, self,
  909. lang_id, aep,
  910. self.date_from, self.date_to,
  911. self.report_instance_id.target_move,
  912. self.report_instance_id.company_id,
  913. self.subkpi_ids,
  914. self._get_additional_move_line_filter,
  915. self._get_additional_query_filter,
  916. )
  917. # second, render it to something that can be used by the widget
  918. res = {}
  919. mis_report_kpi_style = self.env['mis.report.kpi.style']
  920. for kpi_name, kpi, vals in kpi_matrix.iter_kpi_vals(self):
  921. res[kpi_name] = []
  922. try:
  923. # TODO FIXME check style_expression evaluation wrt subkpis
  924. kpi_style = None
  925. if kpi.style_expression:
  926. style_name = safe_eval(kpi.style_expression,
  927. kpi_matrix.get_localdict(self))
  928. styles = mis_report_kpi_style.search(
  929. [('name', '=', style_name)])
  930. kpi_style = styles and styles[0]
  931. except:
  932. _logger.warning("error evaluating css stype expression %s",
  933. kpi.style, exc_info=True)
  934. default_vals = {
  935. 'prefix': kpi.prefix,
  936. 'suffix': kpi.suffix,
  937. 'dp': kpi.dp,
  938. 'is_percentage': kpi.type == 'pct',
  939. 'period_id': self.id,
  940. 'style': '',
  941. 'xlsx_style': {},
  942. }
  943. if kpi_style:
  944. default_vals.update({
  945. 'style': kpi_style.to_css_style(),
  946. 'xlsx_style': kpi_style.to_xlsx_forma_properties(),
  947. })
  948. for idx, subkpi_val in enumerate(vals):
  949. vals = default_vals.copy()
  950. if isinstance(subkpi_val, DataError):
  951. vals.update({
  952. 'val': subkpi_val.name,
  953. 'val_r': subkpi_val.name,
  954. 'val_c': subkpi_val.msg,
  955. 'drilldown': False,
  956. })
  957. else:
  958. if kpi.multi:
  959. expression = kpi.expression_ids[idx].name
  960. comment = '{}.{} = {}'.format(
  961. kpi.name,
  962. kpi.expression_ids[idx].subkpi_id.name,
  963. expression)
  964. else:
  965. expression = kpi.expression
  966. comment = '{} = {}'.format(
  967. kpi.name,
  968. expression)
  969. drilldown = (subkpi_val is not AccountingNone and
  970. AEP.has_account_var(expression))
  971. vals.update({
  972. 'val': (None
  973. if subkpi_val is AccountingNone
  974. else subkpi_val),
  975. 'val_r': kpi.render(lang_id, subkpi_val),
  976. 'val_c': comment,
  977. 'expr': expression,
  978. 'drilldown': drilldown,
  979. })
  980. res[kpi_name].append(vals)
  981. return res
  982. class MisReportInstance(models.Model):
  983. """The MIS report instance combines everything to compute
  984. a MIS report template for a set of periods."""
  985. @api.one
  986. @api.depends('date')
  987. def _compute_pivot_date(self):
  988. if self.date:
  989. self.pivot_date = self.date
  990. else:
  991. self.pivot_date = fields.Date.context_today(self)
  992. @api.model
  993. def _default_company(self):
  994. return self.env['res.company'].\
  995. _company_default_get('mis.report.instance')
  996. _name = 'mis.report.instance'
  997. name = fields.Char(required=True,
  998. string='Name', translate=True)
  999. description = fields.Char(related='report_id.description',
  1000. readonly=True)
  1001. date = fields.Date(string='Base date',
  1002. help='Report base date '
  1003. '(leave empty to use current date)')
  1004. pivot_date = fields.Date(compute='_compute_pivot_date',
  1005. string="Pivot date")
  1006. report_id = fields.Many2one('mis.report',
  1007. required=True,
  1008. string='Report')
  1009. period_ids = fields.One2many('mis.report.instance.period',
  1010. 'report_instance_id',
  1011. required=True,
  1012. string='Periods',
  1013. copy=True)
  1014. target_move = fields.Selection([('posted', 'All Posted Entries'),
  1015. ('all', 'All Entries')],
  1016. string='Target Moves',
  1017. required=True,
  1018. default='posted')
  1019. company_id = fields.Many2one(comodel_name='res.company',
  1020. string='Company',
  1021. default=_default_company,
  1022. required=True)
  1023. landscape_pdf = fields.Boolean(string='Landscape PDF')
  1024. comparison_mode = fields.Boolean(
  1025. compute="_compute_comparison_mode",
  1026. inverse="_inverse_comparison_mode")
  1027. date_range_id = fields.Many2one(
  1028. comodel_name='date.range',
  1029. string='Date Range')
  1030. date_from = fields.Date(string="From")
  1031. date_to = fields.Date(string="To")
  1032. temporary = fields.Boolean(default=False)
  1033. @api.multi
  1034. def save_report(self):
  1035. self.ensure_one()
  1036. self.write({'temporary': False})
  1037. action = self.env.ref('mis_builder.mis_report_instance_view_action')
  1038. res = action.read()[0]
  1039. view = self.env.ref('mis_builder.mis_report_instance_view_form')
  1040. res.update({
  1041. 'views': [(view.id, 'form')],
  1042. 'res_id': self.id,
  1043. })
  1044. return res
  1045. @api.model
  1046. def _vacuum_report(self, hours=24):
  1047. clear_date = fields.Datetime.to_string(
  1048. datetime.datetime.now() - datetime.timedelta(hours=hours))
  1049. reports = self.search([
  1050. ('write_date', '<', clear_date),
  1051. ('temporary', '=', True),
  1052. ])
  1053. _logger.debug('Vacuum %s Temporary MIS Builder Report', len(reports))
  1054. return reports.unlink()
  1055. @api.one
  1056. def copy(self, default=None):
  1057. default = dict(default or {})
  1058. default['name'] = _('%s (copy)') % self.name
  1059. return super(MisReportInstance, self).copy(default)
  1060. def _format_date(self, lang_id, date):
  1061. # format date following user language
  1062. date_format = self.env['res.lang'].browse(lang_id).date_format
  1063. return datetime.datetime.strftime(
  1064. fields.Date.from_string(date), date_format)
  1065. @api.multi
  1066. @api.depends('date_from')
  1067. def _compute_comparison_mode(self):
  1068. for instance in self:
  1069. instance.comparison_mode = bool(instance.period_ids) and\
  1070. not bool(instance.date_from)
  1071. @api.multi
  1072. def _inverse_comparison_mode(self):
  1073. for record in self:
  1074. if not record.comparison_mode:
  1075. if not record.date_from:
  1076. record.date_from = datetime.now()
  1077. if not record.date_to:
  1078. record.date_to = datetime.now()
  1079. record.period_ids.unlink()
  1080. record.write({'period_ids': [
  1081. (0, 0, {
  1082. 'name': 'Default',
  1083. 'type': 'd',
  1084. })
  1085. ]})
  1086. else:
  1087. record.date_from = None
  1088. record.date_to = None
  1089. @api.onchange('date_range_id')
  1090. def onchange_date_range(self):
  1091. for record in self:
  1092. record.date_from = record.date_range_id.date_start
  1093. record.date_to = record.date_range_id.date_end
  1094. @api.multi
  1095. def preview(self):
  1096. assert len(self) == 1
  1097. view_id = self.env.ref('mis_builder.'
  1098. 'mis_report_instance_result_view_form')
  1099. return {
  1100. 'type': 'ir.actions.act_window',
  1101. 'res_model': 'mis.report.instance',
  1102. 'res_id': self.id,
  1103. 'view_mode': 'form',
  1104. 'view_type': 'form',
  1105. 'view_id': view_id.id,
  1106. 'target': 'current',
  1107. }
  1108. @api.multi
  1109. def print_pdf(self):
  1110. self.ensure_one()
  1111. return {
  1112. 'name': 'MIS report instance QWEB PDF report',
  1113. 'model': 'mis.report.instance',
  1114. 'type': 'ir.actions.report.xml',
  1115. 'report_name': 'mis_builder.report_mis_report_instance',
  1116. 'report_type': 'qweb-pdf',
  1117. 'context': self.env.context,
  1118. }
  1119. @api.multi
  1120. def export_xls(self):
  1121. self.ensure_one()
  1122. return {
  1123. 'name': 'MIS report instance XLSX report',
  1124. 'model': 'mis.report.instance',
  1125. 'type': 'ir.actions.report.xml',
  1126. 'report_name': 'mis.report.instance.xlsx',
  1127. 'report_type': 'xlsx',
  1128. 'context': self.env.context,
  1129. }
  1130. @api.multi
  1131. def display_settings(self):
  1132. assert len(self.ids) <= 1
  1133. view_id = self.env.ref('mis_builder.mis_report_instance_view_form')
  1134. return {
  1135. 'type': 'ir.actions.act_window',
  1136. 'res_model': 'mis.report.instance',
  1137. 'res_id': self.id if self.id else False,
  1138. 'view_mode': 'form',
  1139. 'view_type': 'form',
  1140. 'views': [(view_id.id, 'form')],
  1141. 'view_id': view_id.id,
  1142. 'target': 'current',
  1143. }
  1144. @api.multi
  1145. def compute(self):
  1146. self.ensure_one()
  1147. aep = self.report_id._prepare_aep(self.company_id)
  1148. # fetch user language only once
  1149. # TODO: is this necessary?
  1150. lang = self.env.user.lang
  1151. if not lang:
  1152. lang = 'en_US'
  1153. lang_id = self.env['res.lang'].search([('code', '=', lang)]).id
  1154. # compute kpi values for each period
  1155. kpi_values_by_period_ids = {}
  1156. kpi_matrix = KpiMatrix(lang_id)
  1157. for period in self.period_ids:
  1158. if not period.valid:
  1159. continue
  1160. kpi_values = period._render_period(kpi_matrix, lang_id, aep)
  1161. kpi_values_by_period_ids[period.id] = kpi_values
  1162. kpi_matrix.load_account_names(self.env['account.account'])
  1163. # prepare header and content
  1164. header = [{
  1165. 'kpi_name': '',
  1166. 'cols': []
  1167. }, {
  1168. 'kpi_name': '',
  1169. 'cols': []
  1170. }]
  1171. content = []
  1172. rows_by_kpi_name = {}
  1173. for kpi_name, kpi_description, kpi in kpi_matrix.iter_kpis():
  1174. props = {
  1175. 'kpi_name': kpi_description,
  1176. 'cols': [],
  1177. 'default_style': '',
  1178. 'default_xlsx_style': {},
  1179. }
  1180. rows_by_kpi_name[kpi_name] = props
  1181. if kpi.style:
  1182. props.update({
  1183. 'default_style': kpi.style.to_css_style(),
  1184. 'default_xlsx_style': kpi.style.to_xlsx_format_properties()
  1185. })
  1186. content.append(rows_by_kpi_name[kpi_name])
  1187. # populate header and content
  1188. for period in self.period_ids:
  1189. if not period.valid:
  1190. continue
  1191. # add the column header
  1192. if period.duration > 1 or period.type in ('w', 'date_range'):
  1193. # from, to
  1194. date_from = self._format_date(lang_id, period.date_from)
  1195. date_to = self._format_date(lang_id, period.date_to)
  1196. header_date = _('from %s to %s') % (date_from, date_to)
  1197. else:
  1198. header_date = self._format_date(lang_id, period.date_from)
  1199. subkpis = period.subkpi_ids or \
  1200. period.report_instance_id.report_id.subkpi_ids
  1201. header[0]['cols'].append(dict(
  1202. name=period.name,
  1203. date=header_date,
  1204. colspan=len(subkpis) or 1,
  1205. ))
  1206. if subkpis:
  1207. for subkpi in subkpis:
  1208. header[1]['cols'].append(dict(
  1209. name=subkpi.description,
  1210. colspan=1,
  1211. ))
  1212. else:
  1213. header[1]['cols'].append(dict(
  1214. name="",
  1215. colspan=1,
  1216. ))
  1217. # add kpi values
  1218. kpi_values = kpi_values_by_period_ids[period.id]
  1219. for kpi_name in kpi_values:
  1220. rows_by_kpi_name[kpi_name]['cols'] += kpi_values[kpi_name]
  1221. # add comparison columns
  1222. for compare_col in period.comparison_column_ids:
  1223. compare_kpi_values = \
  1224. kpi_values_by_period_ids.get(compare_col.id)
  1225. if compare_kpi_values:
  1226. # add the comparison column header
  1227. header[0]['cols'].append(
  1228. dict(name=_('%s vs %s') % (period.name,
  1229. compare_col.name),
  1230. date=''))
  1231. # add comparison values
  1232. for kpi in self.report_id.kpi_ids:
  1233. rows_by_kpi_name[kpi.name]['cols'].append({
  1234. 'val_r': kpi.render_comparison(
  1235. lang_id,
  1236. kpi_values[kpi.name]['val'],
  1237. compare_kpi_values[kpi.name]['val'],
  1238. period.normalize_factor,
  1239. compare_col.normalize_factor)
  1240. })
  1241. return {
  1242. 'report_name': self.name,
  1243. 'header': header,
  1244. 'content': content,
  1245. }