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.

1401 lines
53 KiB

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