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.

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