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.

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