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.

913 lines
37 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # mis_builder module for Odoo, Management Information System Builder
  5. # Copyright (C) 2014-2015 ACSONE SA/NV (<http://acsone.eu>)
  6. #
  7. # This file is a part of mis_builder
  8. #
  9. # mis_builder is free software: you can redistribute it and/or modify
  10. # it under the terms of the GNU Affero General Public License v3 or later
  11. # as published by the Free Software Foundation, either version 3 of the
  12. # License, or (at your option) any later version.
  13. #
  14. # mis_builder is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU Affero General Public License v3 or later for more details.
  18. #
  19. # You should have received a copy of the GNU Affero General Public License
  20. # v3 or later along with this program.
  21. # If not, see <http://www.gnu.org/licenses/>.
  22. #
  23. ##############################################################################
  24. import datetime
  25. import dateutil
  26. from dateutil import parser
  27. import logging
  28. import re
  29. import time
  30. import traceback
  31. import pytz
  32. from openerp.osv import orm, fields
  33. from openerp import tools
  34. from openerp.tools.safe_eval import safe_eval
  35. from openerp.tools.translate import _
  36. from .aep import AccountingExpressionProcessor as AEP
  37. from .aggregate import _sum, _avg, _min, _max
  38. _logger = logging.getLogger(__name__)
  39. class AutoStruct(object):
  40. def __init__(self, **kwargs):
  41. for k, v in kwargs.items():
  42. setattr(self, k, v)
  43. def _get_selection_label(selection, value):
  44. for v, l in selection:
  45. if v == value:
  46. return l
  47. return ''
  48. def _utc_midnight(d, tz_name, add_day=0):
  49. d = datetime.datetime.strptime(d, tools.DEFAULT_SERVER_DATE_FORMAT)
  50. utc_tz = pytz.timezone('UTC')
  51. if add_day:
  52. d = d + datetime.timedelta(days=add_day)
  53. context_tz = pytz.timezone(tz_name)
  54. local_timestamp = context_tz.localize(d, is_dst=False)
  55. return local_timestamp.astimezone(utc_tz).strftime(
  56. tools.DEFAULT_SERVER_DATE_FORMAT)
  57. def _python_var(var_str):
  58. return re.sub(r'\W|^(?=\d)', '_', var_str).lower()
  59. def _is_valid_python_var(name):
  60. return re.match("[_A-Za-z][_a-zA-Z0-9]*$", name)
  61. class MisReportKpi(orm.Model):
  62. """ A KPI is an element (ie a line) of a MIS report.
  63. In addition to a name and description, it has an expression
  64. to compute it based on queries defined in the MIS report.
  65. It also has various informations defining how to render it
  66. (numeric or percentage or a string, a suffix, divider) and
  67. how to render comparison of two values of the KPI.
  68. KPI's have a sequence and are ordered inside the MIS report.
  69. """
  70. _name = 'mis.report.kpi'
  71. _columns = {
  72. 'name': fields.char(size=32, required=True,
  73. string='Name'),
  74. 'description': fields.char(required=True,
  75. string='Description',
  76. translate=True),
  77. 'expression': fields.char(required=True,
  78. string='Expression'),
  79. 'default_css_style': fields.char(
  80. string='Default CSS style'),
  81. 'css_style': fields.char(string='CSS style expression'),
  82. 'type': fields.selection([('num', _('Numeric')),
  83. ('pct', _('Percentage')),
  84. ('str', _('String'))],
  85. required=True,
  86. string='Type'),
  87. 'divider': fields.selection([('1e-6', _('µ')),
  88. ('1e-3', _('m')),
  89. ('1', _('1')),
  90. ('1e3', _('k')),
  91. ('1e6', _('M'))],
  92. string='Factor'),
  93. 'dp': fields.integer(string='Rounding'),
  94. 'suffix': fields.char(size=16, string='Suffix'),
  95. 'compare_method': fields.selection([('diff', _('Difference')),
  96. ('pct', _('Percentage')),
  97. ('none', _('None'))],
  98. required=True,
  99. string='Comparison Method'),
  100. 'sequence': fields.integer(string='Sequence'),
  101. 'report_id': fields.many2one('mis.report', string='Report'),
  102. }
  103. _defaults = {
  104. 'type': 'num',
  105. 'divider': '1',
  106. 'dp': 0,
  107. 'compare_method': 'pct',
  108. 'sequence': 100,
  109. }
  110. _order = 'sequence, id'
  111. def _check_name(self, cr, uid, ids, context=None):
  112. for record_name in self.read(cr, uid, ids, ['name']):
  113. if not _is_valid_python_var(record_name['name']):
  114. return False
  115. return True
  116. _constraints = [
  117. (_check_name, 'The name must be a valid python identifier', ['name']),
  118. ]
  119. def onchange_name(self, cr, uid, ids, name, context=None):
  120. res = {}
  121. if name and not _is_valid_python_var(name):
  122. res['warning'] = {
  123. 'title': 'Invalid name %s' % name,
  124. 'message': 'The name must be a valid python identifier'}
  125. return res
  126. def onchange_description(self, cr, uid, ids, description, name,
  127. context=None):
  128. """ construct name from description """
  129. res = {}
  130. if description and not name:
  131. res = {'value': {'name': _python_var(description)}}
  132. return res
  133. def onchange_type(self, cr, uid, ids, kpi_type, context=None):
  134. res = {}
  135. if kpi_type == 'num':
  136. res['value'] = {
  137. 'compare_method': 'pct',
  138. 'divider': '1',
  139. 'dp': 0
  140. }
  141. elif kpi_type == 'pct':
  142. res['value'] = {
  143. 'compare_method': 'diff',
  144. 'divider': '1',
  145. 'dp': 0
  146. }
  147. elif kpi_type == 'str':
  148. res['value'] = {
  149. 'compare_method': 'none',
  150. 'divider': '',
  151. 'dp': 0
  152. }
  153. return res
  154. def render(self, cr, uid, lang_id, kpi, value, context=None):
  155. if value is None:
  156. return '#N/A'
  157. if kpi.type == 'num':
  158. return self._render_num(cr, uid, lang_id, value, kpi.divider,
  159. kpi.dp, kpi.suffix, context=context)
  160. elif kpi.type == 'pct':
  161. return self._render_num(cr, uid, lang_id, value, 0.01,
  162. kpi.dp, '%', context=context)
  163. else:
  164. return unicode(value)
  165. def _render_comparison(self, cr, uid, lang_id, kpi, value, base_value,
  166. average_value, average_base_value, context=None):
  167. """ render the comparison of two KPI values, ready for display """
  168. if value is None or base_value is None:
  169. return ''
  170. if kpi.type == 'pct':
  171. return self._render_num(cr, uid, lang_id, value - base_value, 0.01,
  172. kpi.dp, _('pp'), sign='+', context=context)
  173. elif kpi.type == 'num':
  174. if average_value:
  175. value = value / float(average_value)
  176. if average_base_value:
  177. base_value = base_value / float(average_base_value)
  178. if kpi.compare_method == 'diff':
  179. return self._render_num(cr, uid, lang_id, value - base_value,
  180. kpi.divider,
  181. kpi.dp, kpi.suffix, sign='+',
  182. context=context)
  183. elif kpi.compare_method == 'pct':
  184. if round(base_value, kpi.dp) != 0:
  185. return self._render_num(
  186. cr, uid, lang_id,
  187. (value - base_value) / abs(base_value),
  188. 0.01, kpi.dp, '%', sign='+', context=context)
  189. return ''
  190. def _render_num(self, cr, uid, lang_id, value, divider,
  191. dp, suffix, sign='-', context=None):
  192. divider_label = _get_selection_label(
  193. self._columns['divider'].selection, divider)
  194. if divider_label == '1':
  195. divider_label = ''
  196. # format number following user language
  197. value = round(value / float(divider or 1), dp) or 0
  198. value = self.pool['res.lang'].format(
  199. cr, uid, lang_id,
  200. '%%%s.%df' % (sign, dp),
  201. value,
  202. grouping=True,
  203. context=context)
  204. value = u'%s\N{NO-BREAK SPACE}%s%s' % \
  205. (value, divider_label, suffix or '')
  206. value = value.replace('-', u'\N{NON-BREAKING HYPHEN}')
  207. return value
  208. class MisReportQuery(orm.Model):
  209. """ A query to fetch arbitrary data for a MIS report.
  210. A query works on a model and has a domain and list of fields to fetch.
  211. At runtime, the domain is expanded with a "and" on the date/datetime field.
  212. """
  213. _name = 'mis.report.query'
  214. def _get_field_names(self, cr, uid, ids, name, args, context=None):
  215. res = {}
  216. for query in self.browse(cr, uid, ids, context=context):
  217. field_names = []
  218. for field in query.field_ids:
  219. field_names.append(field.name)
  220. res[query.id] = ', '.join(field_names)
  221. return res
  222. def onchange_field_ids(self, cr, uid, ids, field_ids, context=None):
  223. # compute field_names
  224. field_names = []
  225. for field in self.pool.get('ir.model.fields').read(
  226. cr, uid,
  227. field_ids[0][2],
  228. ['name'],
  229. context=context):
  230. field_names.append(field['name'])
  231. return {'value': {'field_names': ', '.join(field_names)}}
  232. _columns = {
  233. 'name': fields.char(size=32, required=True,
  234. string='Name'),
  235. 'model_id': fields.many2one('ir.model', required=True,
  236. string='Model'),
  237. 'field_ids': fields.many2many('ir.model.fields', required=True,
  238. string='Fields to fetch'),
  239. 'field_names': fields.function(_get_field_names, type='char',
  240. string='Fetched fields name',
  241. store={'mis.report.query':
  242. (lambda self, cr, uid, ids, c={}:
  243. ids, ['field_ids'], 20), }),
  244. 'aggregate': fields.selection([('sum', _('Sum')),
  245. ('avg', _('Average')),
  246. ('min', _('Min')),
  247. ('max', _('Max'))],
  248. string='Aggregate'),
  249. 'date_field': fields.many2one('ir.model.fields', required=True,
  250. string='Date field',
  251. domain=[('ttype', 'in',
  252. ('date', 'datetime'))]),
  253. 'domain': fields.char(string='Domain'),
  254. 'report_id': fields.many2one('mis.report', string='Report',
  255. ondelete='cascade'),
  256. }
  257. _order = 'name'
  258. def _check_name(self, cr, uid, ids, context=None):
  259. for record_name in self.read(cr, uid, ids, ['name']):
  260. if not _is_valid_python_var(record_name['name']):
  261. return False
  262. return True
  263. _constraints = [
  264. (_check_name, 'The name must be a valid python identifier', ['name']),
  265. ]
  266. class MisReport(orm.Model):
  267. """ A MIS report template (without period information)
  268. The MIS report holds:
  269. * a list of explicit queries; the result of each query is
  270. stored in a variable with same name as a query, containing as list
  271. of data structures populated with attributes for each fields to fetch;
  272. when queries have an aggregate method and no fields to group, it returns
  273. a data structure with the aggregated fields
  274. * a list of KPI to be evaluated based on the variables resulting
  275. from the accounting data and queries (KPI expressions can references
  276. queries and accounting expression - see AccoutingExpressionProcessor)
  277. """
  278. _name = 'mis.report'
  279. _columns = {
  280. 'name': fields.char(size=32, required=True,
  281. string='Name', translate=True),
  282. 'description': fields.char(required=False,
  283. string='Description', translate=True),
  284. 'query_ids': fields.one2many('mis.report.query', 'report_id',
  285. string='Queries'),
  286. 'kpi_ids': fields.one2many('mis.report.kpi', 'report_id',
  287. string='KPI\'s'),
  288. }
  289. # TODO: kpi name cannot be start with query name
  290. def create(self, cr, uid, vals, context=None):
  291. # TODO: explain this
  292. if 'kpi_ids' in vals:
  293. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  294. for idx, line in enumerate(vals['kpi_ids']):
  295. if line[0] == 0:
  296. line[2]['sequence'] = idx + 1
  297. else:
  298. mis_report_kpi_obj.write(
  299. cr, uid, [line[1]], {'sequence': idx + 1},
  300. context=context)
  301. return super(MisReport, self).create(cr, uid, vals, context=context)
  302. def write(self, cr, uid, ids, vals, context=None):
  303. # TODO: explain this
  304. res = super(MisReport, self).write(
  305. cr, uid, ids, vals, context=context)
  306. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  307. for report in self.browse(cr, uid, ids, context):
  308. for idx, kpi in enumerate(report.kpi_ids):
  309. mis_report_kpi_obj.write(
  310. cr, uid, [kpi.id], {'sequence': idx + 1}, context=context)
  311. return res
  312. class MisReportInstancePeriod(orm.Model):
  313. """ A MIS report instance has the logic to compute
  314. a report template for a given date period.
  315. Periods have a duration (day, week, fiscal period) and
  316. are defined as an offset relative to a pivot date.
  317. """
  318. def _get_dates(self, cr, uid, ids, field_names, arg, context=None):
  319. if isinstance(ids, (int, long)):
  320. ids = [ids]
  321. res = {}
  322. for c in self.browse(cr, uid, ids, context=context):
  323. period_ids = None
  324. valid = True
  325. date_from = False
  326. date_to = False
  327. d = parser.parse(c.report_instance_id.pivot_date)
  328. if c.type == 'd':
  329. date_from = d + datetime.timedelta(days=c.offset)
  330. date_to = date_from + datetime.timedelta(days=c.duration - 1)
  331. date_from = date_from.strftime(
  332. tools.DEFAULT_SERVER_DATE_FORMAT)
  333. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  334. elif c.type == 'w':
  335. date_from = d - datetime.timedelta(d.weekday())
  336. date_from = date_from + datetime.timedelta(days=c.offset * 7)
  337. date_to = date_from + datetime.timedelta(
  338. days=(7 * c.duration) - 1)
  339. date_from = date_from.strftime(
  340. tools.DEFAULT_SERVER_DATE_FORMAT)
  341. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  342. elif c.type == 'fp':
  343. period_obj = self.pool['account.period']
  344. current_period_ids = period_obj.search(
  345. cr, uid,
  346. [('special', '=', False),
  347. ('date_start', '<=', d),
  348. ('date_stop', '>=', d),
  349. ('company_id', '=', c.company_id.id)],
  350. context=context)
  351. if current_period_ids:
  352. all_period_ids = period_obj.search(
  353. cr, uid,
  354. [('special', '=', False),
  355. ('company_id', '=', c.company_id.id)],
  356. order='date_start',
  357. context=context)
  358. p = all_period_ids.index(current_period_ids[0]) + \
  359. c.offset
  360. if p >= 0 and p + c.duration <= len(all_period_ids):
  361. period_ids = all_period_ids[p:p + c.duration]
  362. periods = period_obj.browse(cr, uid, period_ids,
  363. context=context)
  364. date_from = periods[0].date_start
  365. date_to = periods[-1].date_stop
  366. res[c.id] = {
  367. 'date_from': date_from,
  368. 'date_to': date_to,
  369. 'period_from': period_ids and period_ids[0] or False,
  370. 'period_to': period_ids and period_ids[-1] or False,
  371. 'valid': valid,
  372. }
  373. return res
  374. _name = 'mis.report.instance.period'
  375. _columns = {
  376. 'name': fields.char(size=32, required=True,
  377. string='Description', translate=True),
  378. 'type': fields.selection([('d', _('Day')),
  379. ('w', _('Week')),
  380. ('fp', _('Fiscal Period')),
  381. # ('fy', _('Fiscal Year'))
  382. ],
  383. required=True,
  384. string='Period type'),
  385. 'offset': fields.integer(string='Offset',
  386. help='Offset from current period'),
  387. 'duration': fields.integer(string='Duration',
  388. help='Number of periods'),
  389. 'date_from': fields.function(_get_dates,
  390. type='date',
  391. multi="dates",
  392. string="From"),
  393. 'date_to': fields.function(_get_dates,
  394. type='date',
  395. multi="dates",
  396. string="To"),
  397. 'period_from': fields.function(_get_dates,
  398. type='many2one', obj='account.period',
  399. multi="dates", string="From period"),
  400. 'period_to': fields.function(_get_dates,
  401. type='many2one', obj='account.period',
  402. multi="dates", string="To period"),
  403. 'valid': fields.function(_get_dates,
  404. type='boolean',
  405. multi="dates",
  406. string='Valid'),
  407. 'sequence': fields.integer(string='Sequence'),
  408. 'report_instance_id': fields.many2one('mis.report.instance',
  409. string='Report Instance',
  410. ondelete='cascade'),
  411. 'comparison_column_ids': fields.many2many(
  412. 'mis.report.instance.period',
  413. 'mis_report_instance_period_rel',
  414. 'period_id',
  415. 'compare_period_id',
  416. string='Compare with'),
  417. 'company_id': fields.related('report_instance_id', 'company_id',
  418. type="many2one", relation="res.company",
  419. string="Company", readonly=True),
  420. 'normalize_factor': fields.integer(
  421. string='Factor',
  422. help='Factor to use to normalize the period (used in comparison'),
  423. }
  424. _defaults = {
  425. 'offset': -1,
  426. 'duration': 1,
  427. 'sequence': 100,
  428. 'normalize_factor': 1,
  429. }
  430. _order = 'sequence, id'
  431. _sql_constraints = [
  432. ('duration', 'CHECK (duration>0)',
  433. 'Wrong duration, it must be positive!'),
  434. ('normalize_factor', 'CHECK (normalize_factor>0)',
  435. 'Wrong normalize factor, it must be positive!'),
  436. ('name_unique', 'unique(name, report_instance_id)',
  437. 'Period name should be unique by report'),
  438. ]
  439. def _get_additional_move_line_filter(self, cr, uid, _id, context=None):
  440. """ Prepare a filter to apply on all move lines
  441. This filter is applied with a AND operator on all
  442. accounting expression domains. This hook is intended
  443. to be inherited, and is useful to implement filtering
  444. on analytic dimensions or operational units.
  445. Returns an Odoo domain expression (a python list)
  446. compatible with account.move.line."""
  447. return []
  448. def _get_additional_query_filter(self, cr, uid, _id, query, context=None):
  449. """ Prepare an additional filter to apply on the query
  450. This filter is combined to the query domain with a AND
  451. operator. This hook is intended
  452. to be inherited, and is useful to implement filtering
  453. on analytic dimensions or operational units.
  454. Returns an Odoo domain expression (a python list)
  455. compatible with the model of the query."""
  456. return []
  457. def drilldown(self, cr, uid, _id, expr, context=None):
  458. this = self.browse(cr, uid, _id, context=context)
  459. if AEP.has_account_var(expr):
  460. aep = AEP(cr)
  461. aep.parse_expr(expr)
  462. aep.done_parsing(cr, uid, this.report_instance_id.root_account,
  463. context=context)
  464. domain = aep.get_aml_domain_for_expr(
  465. cr, uid, expr,
  466. this.date_from, this.date_to,
  467. this.period_from, this.period_to,
  468. this.report_instance_id.target_move,
  469. context=context)
  470. domain.extend(self._get_additional_move_line_filter(
  471. cr, uid, _id, context=context))
  472. return {
  473. 'name': expr + ' - ' + this.name,
  474. 'domain': domain,
  475. 'type': 'ir.actions.act_window',
  476. 'res_model': 'account.move.line',
  477. 'views': [[False, 'list'], [False, 'form']],
  478. 'view_type': 'list',
  479. 'view_mode': 'list',
  480. 'target': 'current',
  481. }
  482. else:
  483. return False
  484. def _fetch_queries(self, cr, uid, c, context):
  485. res = {}
  486. report = c.report_instance_id.report_id
  487. for query in report.query_ids:
  488. obj = self.pool[query.model_id.model]
  489. eval_context = {
  490. 'time': time,
  491. 'datetime': datetime,
  492. 'dateutil': dateutil,
  493. # deprecated
  494. 'uid': uid,
  495. 'context': context,
  496. }
  497. if not c.date_from or not c.date_to:
  498. raise orm.except_orm(_('Error!'),
  499. _('Please define From and To dates for '
  500. 'period %s.') % c.name)
  501. domain = query.domain and \
  502. safe_eval(query.domain, eval_context) or []
  503. domain.extend(self._get_additional_query_filter(
  504. cr, uid, c.id, query, context=context))
  505. if query.date_field.ttype == 'date':
  506. domain.extend([(query.date_field.name, '>=', c.date_from),
  507. (query.date_field.name, '<=', c.date_to)])
  508. else:
  509. tz = context.get('tz', False) or 'UTC'
  510. datetime_from = _utc_midnight(
  511. c.date_from, tz)
  512. datetime_to = _utc_midnight(
  513. c.date_to, tz, add_day=1)
  514. domain.extend([(query.date_field.name, '>=', datetime_from),
  515. (query.date_field.name, '<', datetime_to)])
  516. if obj._columns.get('company_id', False):
  517. domain.extend(['|', ('company_id', '=', False),
  518. ('company_id', '=', c.company_id.id)])
  519. field_names = [f.name for f in query.field_ids]
  520. if not query.aggregate:
  521. obj_ids = obj.search(cr, uid, domain, context=context)
  522. data = obj.read(
  523. cr, uid, obj_ids, field_names, context=context)
  524. res[query.name] = [AutoStruct(**d) for d in data]
  525. elif query.aggregate == 'sum':
  526. data = obj.read_group(
  527. cr, uid, domain, field_names, '', context=context)
  528. s = AutoStruct(count=data[0]['_count'])
  529. for field_name in field_names:
  530. v = data[0][field_name]
  531. setattr(s, field_name, v)
  532. res[query.name] = s
  533. else:
  534. obj_ids = obj.search(cr, uid, domain, context=context)
  535. data = obj.read(
  536. cr, uid, obj_ids, field_names, context=context)
  537. s = AutoStruct(count=len(data))
  538. if query.aggregate == 'min':
  539. agg = _min
  540. elif query.aggregate == 'max':
  541. agg = _max
  542. elif query.aggregate == 'avg':
  543. agg = _avg
  544. for field_name in field_names:
  545. setattr(s, field_name,
  546. agg([d[field_name] for d in data]))
  547. res[query.name] = s
  548. return res
  549. def _compute(self, cr, uid, lang_id, c, aep, context=None):
  550. if context is None:
  551. context = {}
  552. kpi_obj = self.pool['mis.report.kpi']
  553. res = {}
  554. localdict = {
  555. 'registry': self.pool,
  556. 'sum': _sum,
  557. 'min': _min,
  558. 'max': _max,
  559. 'len': len,
  560. 'avg': _avg,
  561. }
  562. localdict.update(self._fetch_queries(cr, uid, c, context=context))
  563. aep.do_queries(cr, uid, c.date_from, c.date_to,
  564. c.period_from, c.period_to,
  565. c.report_instance_id.target_move,
  566. self._get_additional_move_line_filter(cr, uid, c.id,
  567. context=context),
  568. context=context)
  569. compute_queue = c.report_instance_id.report_id.kpi_ids
  570. recompute_queue = []
  571. while True:
  572. for kpi in compute_queue:
  573. try:
  574. kpi_val_comment = kpi.name + " = " + kpi.expression
  575. kpi_eval_expression = aep.replace_expr(kpi.expression)
  576. kpi_val = safe_eval(kpi_eval_expression, localdict)
  577. except ZeroDivisionError:
  578. kpi_val = None
  579. kpi_val_rendered = '#DIV/0'
  580. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  581. except (NameError, ValueError):
  582. recompute_queue.append(kpi)
  583. kpi_val = None
  584. kpi_val_rendered = '#ERR'
  585. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  586. except:
  587. kpi_val = None
  588. kpi_val_rendered = '#ERR'
  589. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  590. else:
  591. kpi_val_rendered = kpi_obj.render(
  592. cr, uid, lang_id, kpi, kpi_val, context=context)
  593. localdict[kpi.name] = kpi_val
  594. try:
  595. kpi_style = None
  596. if kpi.css_style:
  597. kpi_style = safe_eval(kpi.css_style, localdict)
  598. except:
  599. _logger.warning("error evaluating css stype expression %s",
  600. kpi.css_style, exc_info=True)
  601. kpi_style = None
  602. drilldown = (kpi_val is not None and
  603. AEP.has_account_var(kpi.expression))
  604. res[kpi.name] = {
  605. 'val': kpi_val,
  606. 'val_r': kpi_val_rendered,
  607. 'val_c': kpi_val_comment,
  608. 'style': kpi_style,
  609. 'default_style': kpi.default_css_style or None,
  610. 'suffix': kpi.suffix,
  611. 'dp': kpi.dp,
  612. 'is_percentage': kpi.type == 'pct',
  613. 'period_id': c.id,
  614. 'expr': kpi.expression,
  615. 'drilldown': drilldown,
  616. }
  617. if len(recompute_queue) == 0:
  618. # nothing to recompute, we are done
  619. break
  620. if len(recompute_queue) == len(compute_queue):
  621. # could not compute anything in this iteration
  622. # (ie real Value errors or cyclic dependency)
  623. # so we stop trying
  624. break
  625. # try again
  626. compute_queue = recompute_queue
  627. recompute_queue = []
  628. return res
  629. class MisReportInstance(orm.Model):
  630. """The MIS report instance combines everything to compute
  631. a MIS report template for a set of periods."""
  632. def _compute_pivot_date(self, cr, uid, ids, field_name, arg, context=None):
  633. res = {}
  634. for r in self.browse(cr, uid, ids, context=context):
  635. if r.date:
  636. res[r.id] = r.date
  637. else:
  638. res[r.id] = fields.date.context_today(self, cr, uid,
  639. context=context)
  640. return res
  641. _name = 'mis.report.instance'
  642. _columns = {
  643. 'name': fields.char(size=32, required=True,
  644. string='Name', translate=True),
  645. 'description': fields.char(required=False,
  646. string='Description', translate=True),
  647. 'date': fields.date(string='Base date',
  648. help='Report base date '
  649. '(leave empty to use current date)'),
  650. 'pivot_date': fields.function(_compute_pivot_date,
  651. type='date',
  652. string="Pivot date"),
  653. 'report_id': fields.many2one('mis.report',
  654. required=True,
  655. string='Report'),
  656. 'period_ids': fields.one2many('mis.report.instance.period',
  657. 'report_instance_id',
  658. required=True,
  659. string='Periods'),
  660. 'target_move': fields.selection([('posted', 'All Posted Entries'),
  661. ('all', 'All Entries'),
  662. ], 'Target Moves', required=True),
  663. 'company_id': fields.related('root_account', 'company_id',
  664. type='many2one', relation='res.company',
  665. string='Company', readonly=True,
  666. store=True),
  667. 'root_account': fields.many2one('account.account',
  668. domain='[("parent_id", "=", False)]',
  669. string="Account chart",
  670. required=True)
  671. }
  672. _defaults = {
  673. 'target_move': 'posted',
  674. }
  675. def create(self, cr, uid, vals, context=None):
  676. if not vals:
  677. return context.get('active_id', None)
  678. # TODO: explain this
  679. if 'period_ids' in vals:
  680. mis_report_instance_period_obj = self.pool.get(
  681. 'mis.report.instance.period')
  682. for idx, line in enumerate(vals['period_ids']):
  683. if line[0] == 0:
  684. line[2]['sequence'] = idx + 1
  685. else:
  686. mis_report_instance_period_obj.write(
  687. cr, uid, [line[1]], {'sequence': idx + 1},
  688. context=context)
  689. return super(MisReportInstance, self).create(cr, uid, vals,
  690. context=context)
  691. def write(self, cr, uid, ids, vals, context=None):
  692. # TODO: explain this
  693. res = super(MisReportInstance, self).write(
  694. cr, uid, ids, vals, context=context)
  695. mis_report_instance_period_obj = self.pool.get(
  696. 'mis.report.instance.period')
  697. for instance in self.browse(cr, uid, ids, context):
  698. for idx, period in enumerate(instance.period_ids):
  699. mis_report_instance_period_obj.write(
  700. cr, uid, [period.id], {'sequence': idx + 1},
  701. context=context)
  702. return res
  703. def preview(self, cr, uid, ids, context=None):
  704. assert len(ids) == 1
  705. view_id = self.pool['ir.model.data'].get_object_reference(
  706. cr, uid, 'mis_builder',
  707. 'mis_report_instance_result_view_form')[1]
  708. return {
  709. 'type': 'ir.actions.act_window',
  710. 'res_model': 'mis.report.instance',
  711. 'res_id': ids[0],
  712. 'view_mode': 'form',
  713. 'view_type': 'form',
  714. 'view_id': view_id,
  715. 'target': 'new',
  716. }
  717. def _format_date(self, cr, uid, lang_id, date, context=None):
  718. # format date following user language
  719. tformat = self.pool['res.lang'].read(
  720. cr, uid, lang_id, ['date_format'])[0]['date_format']
  721. date = datetime.datetime.strptime(date,
  722. tools.DEFAULT_SERVER_DATE_FORMAT)
  723. return date.strftime(tformat)
  724. def compute(self, cr, uid, _id, context=None):
  725. assert isinstance(_id, (int, long))
  726. if context is None:
  727. context = {}
  728. r = self.browse(cr, uid, _id, context=context)
  729. # prepare AccountingExpressionProcessor
  730. aep = AEP(cr)
  731. for kpi in r.report_id.kpi_ids:
  732. aep.parse_expr(kpi.expression)
  733. aep.done_parsing(cr, uid, r.root_account, context=context)
  734. report_instance_period_obj = self.pool['mis.report.instance.period']
  735. kpi_obj = self.pool.get('mis.report.kpi')
  736. # fetch user language only once
  737. # TODO: is this necessary?
  738. lang = self.pool['res.users'].read(
  739. cr, uid, uid, ['lang'], context=context)['lang']
  740. if not lang:
  741. lang = 'en_US'
  742. lang_id = self.pool['res.lang'].search(
  743. cr, uid, [('code', '=', lang)], context=context)
  744. # compute kpi values for each period
  745. kpi_values_by_period_ids = {}
  746. for period in r.period_ids:
  747. if not period.valid:
  748. continue
  749. kpi_values = report_instance_period_obj._compute(
  750. cr, uid, lang_id, period, aep, context=context)
  751. kpi_values_by_period_ids[period.id] = kpi_values
  752. # prepare header and content
  753. header = []
  754. header.append({
  755. 'kpi_name': '',
  756. 'cols': []
  757. })
  758. content = []
  759. rows_by_kpi_name = {}
  760. for kpi in r.report_id.kpi_ids:
  761. rows_by_kpi_name[kpi.name] = {
  762. 'kpi_name': kpi.description,
  763. 'cols': [],
  764. 'default_style': kpi.default_css_style
  765. }
  766. content.append(rows_by_kpi_name[kpi.name])
  767. # populate header and content
  768. for period in r.period_ids:
  769. if not period.valid:
  770. continue
  771. # add the column header
  772. if period.duration > 1 or period.type == 'w':
  773. # from, to
  774. if period.period_from and period.period_to:
  775. date_from = period.period_from.name
  776. date_to = period.period_to.name
  777. else:
  778. date_from = self._format_date(
  779. cr, uid, lang_id, period.date_from)
  780. date_to = self._format_date(
  781. cr, uid, lang_id, period.date_to)
  782. header_date = _('from %s to %s') % (date_from, date_to)
  783. else:
  784. # one period or one day
  785. if period.period_from and period.period_to:
  786. header_date = period.period_from.name
  787. else:
  788. header_date = self._format_date(
  789. cr, uid, lang_id, period.date_from)
  790. header[0]['cols'].append(dict(name=period.name, date=header_date))
  791. # add kpi values
  792. kpi_values = kpi_values_by_period_ids[period.id]
  793. for kpi_name in kpi_values:
  794. rows_by_kpi_name[kpi_name]['cols'].append(kpi_values[kpi_name])
  795. # add comparison columns
  796. for compare_col in period.comparison_column_ids:
  797. compare_kpi_values = \
  798. kpi_values_by_period_ids.get(compare_col.id)
  799. if compare_kpi_values:
  800. # add the comparison column header
  801. header[0]['cols'].append(
  802. dict(name=_('%s vs %s') % (period.name,
  803. compare_col.name),
  804. date=''))
  805. # add comparison values
  806. for kpi in r.report_id.kpi_ids:
  807. rows_by_kpi_name[kpi.name]['cols'].append({
  808. 'val_r': kpi_obj._render_comparison(
  809. cr,
  810. uid,
  811. lang_id,
  812. kpi,
  813. kpi_values[kpi.name]['val'],
  814. compare_kpi_values[kpi.name]['val'],
  815. period.normalize_factor,
  816. compare_col.normalize_factor,
  817. context=context)
  818. })
  819. return {'header': header,
  820. 'content': content}