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.

650 lines
29 KiB

10 years ago
  1. # vim: set fileencoding=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 datetime import datetime, timedelta
  25. from dateutil import parser
  26. import traceback
  27. import re
  28. import pytz
  29. from openerp.osv import orm, fields
  30. from openerp.tools.safe_eval import safe_eval
  31. from openerp.tools.translate import _
  32. from openerp import tools
  33. from collections import OrderedDict
  34. class AutoStruct(object):
  35. def __init__(self, **kwargs):
  36. for k, v in kwargs.items():
  37. setattr(self, k, v)
  38. def _get_selection_label(selection, value):
  39. for v, l in selection:
  40. if v == value:
  41. return l
  42. return ''
  43. def _utc_midnight(d, tz_name, add_day=0):
  44. d = datetime.strptime(d, tools.DEFAULT_SERVER_DATE_FORMAT)
  45. if add_day:
  46. d = d + timedelta(days=add_day)
  47. utc_tz = pytz.timezone('UTC')
  48. context_tz = pytz.timezone(tz_name)
  49. local_timestamp = context_tz.localize(d, is_dst=False)
  50. return datetime.strftime(local_timestamp.astimezone(utc_tz), tools.DEFAULT_SERVER_DATETIME_FORMAT)
  51. def _clean(varStr):
  52. return re.sub('\W|^(?=\d)', '_', varStr).lower()
  53. class mis_report_kpi(orm.Model):
  54. """ A KPI is an element of a MIS report.
  55. In addition to a name and description, it has an expression
  56. to compute it based on queries defined in the MIS report.
  57. It also has various informations defining how to render it
  58. (numeric or percentage or a string, a suffix, divider) and
  59. how to render comparison of two values of the KPI.
  60. KPI are ordered inside the MIS report, as some KPI expressions
  61. can depend on other KPI that need to be computed before.
  62. """
  63. _name = 'mis.report.kpi'
  64. _columns = {
  65. 'name': fields.char(size=32, required=True,
  66. string='Name'),
  67. 'description': fields.char(required=True,
  68. string='Description',
  69. translate=True),
  70. 'expression': fields.char(required=True,
  71. string='Expression'),
  72. 'css_style': fields.char(string='CSS style'),
  73. 'type': fields.selection([('num', _('Numeric')),
  74. ('pct', _('Percentage')),
  75. ('str', _('String'))],
  76. required=True,
  77. string='Type'),
  78. 'divider': fields.selection([('1e-6', _('µ')),
  79. ('1e-3', _('m')),
  80. ('1', _('1')),
  81. ('1e3', _('k')),
  82. ('1e6', _('M'))],
  83. string='Factor'),
  84. 'dp': fields.integer(string='Rounding'),
  85. 'suffix': fields.char(size=16, string='Suffix'),
  86. 'compare_method': fields.selection([('diff', _('Difference')),
  87. ('pct', _('Percentage')),
  88. ('none', _('None'))],
  89. required=True,
  90. string='Comparison Method'),
  91. 'sequence': fields.integer(string='Sequence'),
  92. 'report_id': fields.many2one('mis.report', string='Report'),
  93. }
  94. _defaults = {
  95. 'type': 'num',
  96. 'divider': '1',
  97. 'dp': 0,
  98. 'compare_method': 'pct',
  99. 'sequence': 100,
  100. }
  101. _order = 'sequence'
  102. def _check_name(self, cr, uid, ids, context=None):
  103. for record_name in self.read(cr, uid, ids, ['name']):
  104. if not re.match("[_A-Za-z][_a-zA-Z0-9]*$", record_name['name']):
  105. return False
  106. return True
  107. _constraints = [
  108. (_check_name, 'The name must be a valid python identifier', ['name']),
  109. ]
  110. def onchange_name(self, cr, uid, ids, name, context=None):
  111. # check it is a valid python identifier
  112. res = {}
  113. if name and not re.match("[_A-Za-z][_a-zA-Z0-9]*$", name):
  114. res['warning'] = {'title': 'Invalid name', 'message': 'The name must be a valid python identifier'}
  115. return res
  116. def onchange_description(self, cr, uid, ids, description, name, context=None):
  117. # construct name from description
  118. res = {}
  119. if description and not name:
  120. res = {'value': {'name': _clean(description)}}
  121. return res
  122. def onchange_type(self, cr, uid, ids, kpi_type, context=None):
  123. res = {}
  124. if kpi_type == 'pct':
  125. res['value'] = {'compare_method': 'diff'}
  126. elif kpi_type == 'str':
  127. res['value'] = {'compare_method': 'none',
  128. 'divider': '',
  129. 'dp': 0}
  130. return res
  131. def _render(self, cr, uid, kpi, value, context=None):
  132. """ render a KPI value as a unicode string, ready for display """
  133. if kpi.type == 'num':
  134. return self._render_num(cr, uid, value, kpi.divider, kpi.dp, kpi.suffix, context=context)
  135. elif kpi.type == 'pct':
  136. return self._render_num(cr, uid, value, 0.01, kpi.dp, '%', context=context)
  137. else:
  138. return unicode(value)
  139. def _render_comparison(self, cr, uid, kpi, value, base_value, average_value, average_base_value, context=None):
  140. """ render the comparison of two KPI values, ready for display """
  141. if value is None or base_value is None:
  142. return ''
  143. if kpi.type == 'pct':
  144. return self._render_num(cr, uid, value - base_value, 0.01, kpi.dp, _('pp'), sign='+', context=context)
  145. elif kpi.type == 'num':
  146. if average_value:
  147. value = value / float(average_value)
  148. if average_base_value:
  149. base_value = base_value / float(average_base_value)
  150. if kpi.compare_method == 'diff':
  151. return self._render_num(cr, uid, value - base_value, kpi.divider,
  152. kpi.dp, kpi.suffix, sign='+', context=context)
  153. elif kpi.compare_method == 'pct' and base_value != 0:
  154. return self._render_num(cr, uid, value / base_value - 1,
  155. 0.01, kpi.dp, '%',
  156. sign='+', context=context)
  157. return ''
  158. def _render_num(self, cr, uid, value, divider, dp, suffix, sign='-', context=None):
  159. divider_label = _get_selection_label(self._columns['divider'].selection, divider)
  160. if divider_label == '1':
  161. divider_label = ''
  162. # format number following user language
  163. lang = self.pool['res.users'].read(cr, uid, uid, ['lang'], context=context)['lang']
  164. language_id = self.pool['res.lang'].search(cr, uid, [('code', '=', lang)], context=context)
  165. value = round(value / float(divider or 1), dp) or 0
  166. return '%s %s%s' % (self.pool['res.lang'].format(cr, uid, language_id,
  167. '%%%s.%df' % (sign, dp),
  168. value, context=context),
  169. divider_label, suffix or '')
  170. class mis_report_query(orm.Model):
  171. """ A query to fetch data for a MIS report.
  172. A query works on a model and has a domain and list of fields to fetch.
  173. At runtime, the domain is expanded with a "and" on the date/datetime field.
  174. """
  175. _name = 'mis.report.query'
  176. def _get_field_names(self, cr, uid, ids, name, args, context=None):
  177. res = {}
  178. for query in self.browse(cr, uid, ids, context=context):
  179. field_name = []
  180. for field in query.field_ids:
  181. field_name.append(field.name)
  182. res[query.id] = ', '.join(field_name)
  183. return res
  184. def onchange_field_ids(self, cr, uid, ids, field_ids, context=None):
  185. # compute field_names
  186. field_name = []
  187. for field in self.pool.get('ir.model.fields').read(cr, uid, field_ids[0][2], ['name'], context=context):
  188. field_name.append(field['name'])
  189. return {'value': {'field_name': ', '.join(field_name)}}
  190. _columns = {
  191. 'name': fields.char(size=32, required=True,
  192. string='Name'),
  193. 'model_id': fields.many2one('ir.model', required=True,
  194. string='Model'),
  195. 'field_ids': fields.many2many('ir.model.fields', required=True,
  196. string='Fields to fetch'),
  197. 'field_name': fields.function(_get_field_names, type='char', string='Fetched fields name',
  198. store={'mis.report.query':
  199. (lambda self, cr, uid, ids, c={}: ids, ['field_ids'], 20), }),
  200. 'date_field': fields.many2one('ir.model.fields', required=True,
  201. string='Date field',
  202. domain=[('ttype', 'in', ('date', 'datetime'))]),
  203. 'domain': fields.char(string='Domain'),
  204. 'report_id': fields.many2one('mis.report', string='Report'),
  205. }
  206. _order = 'name'
  207. def _check_name(self, cr, uid, ids, context=None):
  208. for record_name in self.read(cr, uid, ids, ['name']):
  209. if not re.match("[_A-Za-z][_a-zA-Z0-9]*$", record_name['name']):
  210. return False
  211. return True
  212. _constraints = [
  213. (_check_name, 'The name must be a valid python identifier', ['name']),
  214. ]
  215. class mis_report(orm.Model):
  216. """ A MIS report template (without period information)
  217. The MIS report holds:
  218. * an implicit query fetching allow the account balances;
  219. for each account, the balance is stored in a variable named
  220. bal_{code} where {code} is the account code
  221. * a list of explicit queries; the result of each query is
  222. stored in a variable with same name as a query, containing as list
  223. of data structures populated with attributes for each fields to fetch
  224. * a list of KPI to be evaluated based on the variables resulting
  225. from the balance and queries
  226. """
  227. _name = 'mis.report'
  228. _columns = {
  229. 'name': fields.char(size=32, required=True,
  230. string='Name', translate=True),
  231. 'description': fields.char(required=False,
  232. string='Description', translate=True),
  233. 'query_ids': fields.one2many('mis.report.query', 'report_id',
  234. string='Queries'),
  235. 'kpi_ids': fields.one2many('mis.report.kpi', 'report_id',
  236. string='KPI\'s'),
  237. }
  238. def create(self, cr, uid, vals, context=None):
  239. if 'kpi_ids' in vals:
  240. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  241. for idx, line in enumerate(vals['kpi_ids']):
  242. if line[0] == 0:
  243. line[2]['sequence'] = idx + 1
  244. else:
  245. mis_report_kpi_obj.write(cr, uid, [line[1]], {'sequence': idx + 1}, context=context)
  246. return super(mis_report, self).create(cr, uid, vals, context=context)
  247. def write(self, cr, uid, ids, vals, context=None):
  248. res = super(mis_report, self).write(cr, uid, ids, vals, context=context)
  249. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  250. for report in self.browse(cr, uid, ids, context):
  251. for idx, kpi in enumerate(report.kpi_ids):
  252. mis_report_kpi_obj.write(cr, uid, [kpi.id], {'sequence': idx + 1}, context=context)
  253. return res
  254. class mis_report_instance_period(orm.Model):
  255. """ A MIS report instance has the logic to compute
  256. a report template for a give date period.
  257. Periods have a duration (day, week, fiscal period) and
  258. are defined as an offset relative to a pivot date.
  259. """
  260. def _get_dates(self, cr, uid, ids, field_names, arg, context=None):
  261. if isinstance(ids, (int, long)):
  262. ids = [ids]
  263. res = {}
  264. for c in self.browse(cr, uid, ids, context=context):
  265. d = parser.parse(c.report_instance_id.pivot_date)
  266. if c.type == 'd':
  267. date_from = d + timedelta(days=c.offset)
  268. date_to = date_from + timedelta(days=c.duration - 1)
  269. date_from = date_from.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  270. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  271. period_ids = None
  272. elif c.type == 'w':
  273. date_from = d - timedelta(d.weekday())
  274. date_from = date_from + timedelta(days=c.offset * 7)
  275. date_to = date_from + timedelta(days=(7 * c.duration) - 1)
  276. date_from = date_from.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  277. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  278. period_ids = None
  279. elif c.type == 'fp':
  280. period_obj = self.pool['account.period']
  281. all_period_ids = period_obj.search(cr, uid,
  282. [('special', '=', False),
  283. '|', ('company_id', '=', False),
  284. ('company_id', '=', c.company_id.id)],
  285. order='date_start',
  286. context=context)
  287. current_period_ids = period_obj.search(cr, uid,
  288. [('special', '=', False),
  289. ('date_start', '<=', d),
  290. ('date_stop', '>=', d),
  291. '|', ('company_id', '=', False),
  292. ('company_id', '=', c.company_id.id)],
  293. context=context)
  294. if not current_period_ids:
  295. raise orm.except_orm(_("Error!"),
  296. _("No current fiscal period for %s") % d)
  297. p = all_period_ids.index(current_period_ids[0]) + c.offset
  298. if p < 0 or p >= len(all_period_ids):
  299. raise orm.except_orm(_("Error!"),
  300. _("No such fiscal period for %s "
  301. "with offset %d") % (d, c.offset))
  302. period_ids = all_period_ids[p:p + c.duration]
  303. periods = period_obj.browse(cr, uid, period_ids,
  304. context=context)
  305. date_from = periods[0].date_start
  306. date_to = periods[-1].date_stop
  307. else:
  308. raise orm.except_orm(_("Error!"),
  309. _("Unimplemented period type %s") %
  310. (c.type,))
  311. res[c.id] = {
  312. 'date_from': date_from,
  313. 'date_to': date_to,
  314. 'period_from': period_ids and period_ids[0],
  315. 'period_to': period_ids and period_ids[-1],
  316. }
  317. return res
  318. _name = 'mis.report.instance.period'
  319. _columns = {
  320. 'name': fields.char(size=32, required=True,
  321. string='Description', translate=True),
  322. 'type': fields.selection([('d', _('Day')),
  323. ('w', _('Week')),
  324. ('fp', _('Fiscal Period')),
  325. # ('fy', _('Fiscal Year'))
  326. ],
  327. required=True,
  328. string='Period type'),
  329. 'offset': fields.integer(string='Offset',
  330. help='Offset from current period'),
  331. 'duration': fields.integer(string='Duration',
  332. help='Number of periods'),
  333. 'date_from': fields.function(_get_dates,
  334. type='date',
  335. multi="dates",
  336. string="From"),
  337. 'date_to': fields.function(_get_dates,
  338. type='date',
  339. multi="dates",
  340. string="To"),
  341. 'period_from': fields.function(_get_dates,
  342. type='many2one', obj='account.period',
  343. multi="dates", string="From period"),
  344. 'period_to': fields.function(_get_dates,
  345. type='many2one', obj='account.period',
  346. multi="dates", string="To period"),
  347. 'sequence': fields.integer(string='Sequence'),
  348. 'report_instance_id': fields.many2one('mis.report.instance',
  349. string='Report Instance'),
  350. 'comparison_column_ids': fields.many2many('mis.report.instance.period', 'mis_report_instance_period_rel',
  351. 'period_id', 'compare_period_id', string='Compare with'),
  352. 'company_id': fields.many2one('res.company', 'Company', required=True),
  353. 'normalize_factor': fields.integer(string='Factor',
  354. help='Factor to use to normalize the period (used in comparison'),
  355. }
  356. _defaults = {
  357. 'offset': -1,
  358. 'duration': 1,
  359. 'sequence': 100,
  360. 'normalize_factor': 1,
  361. 'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid,
  362. 'mis.report.instance.period',
  363. context=c)
  364. }
  365. _order = 'sequence'
  366. _sql_constraints = [
  367. ('duration', 'CHECK (duration>0)', 'Wrong duration, it must be positive!'),
  368. ('normalize_factor', 'CHECK (normalize_factor>0)', 'Wrong normalize factor, it must be positive!'),
  369. ('name_unique', 'unique(name, report_instance_id)', 'Period name should be unique by report'),
  370. ]
  371. def _fetch_balances(self, cr, uid, c, context=None):
  372. """ fetch the general account balances for the given period
  373. returns a dictionary {bal_<account.code>: account.balance}
  374. """
  375. if context is None:
  376. context = {}
  377. account_obj = self.pool['account.account']
  378. search_ctx = dict(context)
  379. if c.period_from:
  380. search_ctx.update({'period_from': c.period_from.id,
  381. 'period_to': c.period_to.id})
  382. else:
  383. search_ctx.update({'date_from': c.date_from,
  384. 'date_to': c.date_to})
  385. # TODO: initial balance?
  386. account_ids = account_obj.search(cr, uid, ['|', ('company_id', '=', False), ('company_id', '=', c.company_id.id)], context=context)
  387. account_datas = account_obj.read(cr, uid, account_ids, ['code', 'balance'], context=search_ctx)
  388. balances = {}
  389. for account_data in account_datas:
  390. key = 'bal' + _clean(account_data['code'])
  391. assert key not in balances
  392. balances[key] = account_data['balance']
  393. return balances
  394. def _fetch_queries(self, cr, uid, c, context):
  395. res = {}
  396. report = c.report_instance_id.report_id
  397. for query in report.query_ids:
  398. obj = self.pool[query.model_id.model]
  399. domain = query.domain and safe_eval(query.domain) or []
  400. if query.date_field.ttype == 'date':
  401. domain.extend([(query.date_field.name, '>=', c.date_from),
  402. (query.date_field.name, '<=', c.date_to)])
  403. else:
  404. datetime_from = _utc_midnight(c.date_from, context.get('tz', 'UTC'))
  405. datetime_to = _utc_midnight(c.date_to, context.get('tz', 'UTC'), add_day=1)
  406. domain.extend([(query.date_field.name, '>=', datetime_from),
  407. (query.date_field.name, '<', datetime_to)])
  408. if obj._columns.get('company_id', False):
  409. domain.extend(['|', ('company_id', '=', False), ('company_id', '=', c.company_id.id)])
  410. field_names = [field.name for field in query.field_ids]
  411. obj_ids = obj.search(cr, uid, domain, context=context)
  412. obj_datas = obj.read(cr, uid, obj_ids, field_names, context=context)
  413. res[query.name] = [AutoStruct(**d) for d in obj_datas]
  414. return res
  415. def _compute(self, cr, uid, c, context=None):
  416. if context is None:
  417. context = {}
  418. kpi_obj = self.pool['mis.report.kpi']
  419. res = {}
  420. localdict = {
  421. 'registry': self.pool,
  422. 'sum': sum,
  423. 'min': min,
  424. 'max': max,
  425. 'len': len,
  426. 'avg': lambda l: sum(l) / float(len(l)),
  427. }
  428. localdict.update(self._fetch_balances(cr, uid, c, context=context))
  429. localdict.update(self._fetch_queries(cr, uid, c, context=context))
  430. for kpi in c.report_instance_id.report_id.kpi_ids:
  431. try:
  432. kpi_val = safe_eval(kpi.expression, localdict)
  433. except ZeroDivisionError:
  434. kpi_val = None
  435. kpi_val_rendered = '#DIV/0'
  436. kpi_val_comment = traceback.format_exc()
  437. except:
  438. kpi_val = None
  439. kpi_val_rendered = '#ERR'
  440. kpi_val_comment = traceback.format_exc()
  441. else:
  442. kpi_val_rendered = kpi_obj._render(cr, uid, kpi, kpi_val, context=context)
  443. kpi_val_comment = None
  444. localdict[kpi.name] = kpi_val
  445. try:
  446. kpi_style = None
  447. if kpi.css_style:
  448. kpi_style = safe_eval(kpi.css_style, localdict)
  449. except:
  450. kpi_style = None
  451. res[kpi.name] = {
  452. 'val': kpi_val,
  453. 'val_r': kpi_val_rendered,
  454. 'val_c': kpi_val_comment,
  455. 'style': kpi_style,
  456. 'suffix': kpi.suffix,
  457. 'dp': kpi.dp,
  458. 'is_percentage': kpi.type == 'pct',
  459. }
  460. return res
  461. class mis_report_instance(orm.Model):
  462. """ The MIS report instance combines compute and
  463. display a MIS report template for a set of periods """
  464. def _get_pivot_date(self, cr, uid, ids, field_name, arg, context=None):
  465. res = {}
  466. for r in self.browse(cr, uid, ids, context=context):
  467. if r.date:
  468. res[r.id] = r.date
  469. else:
  470. res[r.id] = fields.date.context_today(self, cr, uid,
  471. context=context)
  472. return res
  473. _name = 'mis.report.instance'
  474. _columns = {
  475. 'name': fields.char(size=32, required=True,
  476. string='Name', translate=True),
  477. 'description': fields.char(required=False,
  478. string='Description', translate=True),
  479. 'date': fields.date(string='Base date',
  480. help='Report base date '
  481. '(leave empty to use current date)'),
  482. 'pivot_date': fields.function(_get_pivot_date,
  483. type='date',
  484. string="Pivot date"),
  485. 'report_id': fields.many2one('mis.report',
  486. required=True,
  487. string='Report'),
  488. 'period_ids': fields.one2many('mis.report.instance.period',
  489. 'report_instance_id',
  490. required=True,
  491. string='Periods'),
  492. 'target_move': fields.selection([('posted', 'All Posted Entries'),
  493. ('all', 'All Entries'),
  494. ], 'Target Moves', required=True),
  495. }
  496. _defaults = {
  497. 'target_move': 'posted',
  498. }
  499. def create(self, cr, uid, vals, context=None):
  500. if 'period_ids' in vals:
  501. mis_report_instance_period_obj = self.pool.get('mis.report.instance.period')
  502. for idx, line in enumerate(vals['period_ids']):
  503. if line[0] == 0:
  504. line[2]['sequence'] = idx + 1
  505. else:
  506. mis_report_instance_period_obj.write(cr, uid, [line[1]], {'sequence': idx + 1}, context=context)
  507. return super(mis_report_instance, self).create(cr, uid, vals, context=context)
  508. def write(self, cr, uid, ids, vals, context=None):
  509. res = super(mis_report_instance, self).write(cr, uid, ids, vals, context=context)
  510. mis_report_instance_period_obj = self.pool.get('mis.report.instance.period')
  511. for instance in self.browse(cr, uid, ids, context):
  512. for idx, period in enumerate(instance.period_ids):
  513. mis_report_instance_period_obj.write(cr, uid, [period.id], {'sequence': idx + 1}, context=context)
  514. return res
  515. def _format_date(self, cr, uid, date, context=None):
  516. # format date following user language
  517. lang = self.pool['res.users'].read(cr, uid, uid, ['lang'], context=context)['lang']
  518. language_id = self.pool['res.lang'].search(cr, uid, [('code', '=', lang)], context=context)[0]
  519. tformat = self.pool['res.lang'].read(cr, uid, language_id, ['date_format'])['date_format']
  520. return datetime.strftime(datetime.strptime(date, tools.DEFAULT_SERVER_DATE_FORMAT), tformat)
  521. def compute(self, cr, uid, _ids, context=None):
  522. assert isinstance(_ids, (int, long))
  523. if context is None:
  524. context = {}
  525. r = self.browse(cr, uid, _ids, context=context)
  526. context['state'] = r.target_move
  527. content = OrderedDict()
  528. #empty line name for header
  529. header = OrderedDict()
  530. header[''] = {'kpi_name': '', 'cols': []}
  531. #initialize lines with kpi
  532. for kpi in r.report_id.kpi_ids:
  533. content[kpi.name] = {'kpi_name': kpi.description, 'cols': []}
  534. report_instance_period_obj = self.pool.get('mis.report.instance.period')
  535. kpi_obj = self.pool.get('mis.report.kpi')
  536. period_values = {}
  537. for period in r.period_ids:
  538. # add the column header
  539. header['']['cols'].append(dict(name=period.name,
  540. date=(period.duration > 1 or period.type == 'w') and
  541. _('from %s to %s' %
  542. (period.period_from and period.period_from.name
  543. or self._format_date(cr, uid, period.date_from, context=context),
  544. period.period_to and period.period_to.name
  545. or self._format_date(cr, uid, period.date_to, context=context)))
  546. or period.period_from and period.period_from.name or period.date_from))
  547. # compute kpi values
  548. values = report_instance_period_obj._compute(cr, uid, period, context=context)
  549. period_values[period.name] = values
  550. for key in values:
  551. content[key]['cols'].append(values[key])
  552. # add comparison column
  553. for period in r.period_ids:
  554. for compare_col in period.comparison_column_ids:
  555. # add the column header
  556. header['']['cols'].append(dict(name='%s - %s' % (period.name, compare_col.name), date=''))
  557. column1_values = period_values[period.name]
  558. column2_values = period_values[compare_col.name]
  559. for kpi in r.report_id.kpi_ids:
  560. content[kpi.name]['cols'].append({'val_r': kpi_obj._render_comparison(cr, uid, kpi,
  561. column1_values[kpi.name]['val'],
  562. column2_values[kpi.name]['val'],
  563. period.normalize_factor, compare_col.normalize_factor, context=context)})
  564. return {'header': header,
  565. 'content': content}