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.

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