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.

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