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.

639 lines
28 KiB

11 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. for idx, line in enumerate(vals['kpi_ids']):
  241. line[2]['sequence'] = idx + 1
  242. return super(mis_report, self).create(cr, uid, vals, context=context)
  243. def write(self, cr, uid, ids, vals, context=None):
  244. res = super(mis_report, self).write(cr, uid, ids, vals, context=context)
  245. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  246. for report in self.browse(cr, uid, ids, context):
  247. for idx, kpi in enumerate(report.kpi_ids):
  248. mis_report_kpi_obj.write(cr, uid, [kpi.id], {'sequence': idx + 1}, context=context)
  249. return res
  250. class mis_report_instance_period(orm.Model):
  251. """ A MIS report instance has the logic to compute
  252. a report template for a give date period.
  253. Periods have a duration (day, week, fiscal period) and
  254. are defined as an offset relative to a pivot date.
  255. """
  256. def _get_dates(self, cr, uid, ids, field_names, arg, context=None):
  257. if isinstance(ids, (int, long)):
  258. ids = [ids]
  259. res = {}
  260. for c in self.browse(cr, uid, ids, context=context):
  261. d = parser.parse(c.report_instance_id.pivot_date)
  262. if c.type == 'd':
  263. date_from = d + timedelta(days=c.offset)
  264. date_to = date_from + timedelta(days=c.duration - 1)
  265. date_from = date_from.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  266. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  267. period_ids = None
  268. elif c.type == 'w':
  269. date_from = d - timedelta(d.weekday())
  270. date_from = date_from + timedelta(days=c.offset * 7)
  271. date_to = date_from + timedelta(days=(7 * c.duration) - 1)
  272. date_from = date_from.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  273. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  274. period_ids = None
  275. elif c.type == 'fp':
  276. period_obj = self.pool['account.period']
  277. all_period_ids = period_obj.search(cr, uid,
  278. [('special', '=', False), ('company_id', '=', c.company_id.id)],
  279. order='date_start',
  280. context=context)
  281. current_period_ids = period_obj.search(cr, uid,
  282. [('special', '=', False),
  283. ('date_start', '<=', d),
  284. ('date_stop', '>=', d),
  285. ('company_id', '=', c.company_id.id)],
  286. context=context)
  287. if not current_period_ids:
  288. raise orm.except_orm(_("Error!"),
  289. _("No current fiscal period for %s") % d)
  290. p = all_period_ids.index(current_period_ids[0]) + c.offset
  291. if p < 0 or p >= len(all_period_ids):
  292. raise orm.except_orm(_("Error!"),
  293. _("No such fiscal period for %s "
  294. "with offset %d") % (d, c.offset))
  295. period_ids = all_period_ids[p:p + c.duration]
  296. periods = period_obj.browse(cr, uid, period_ids,
  297. context=context)
  298. date_from = periods[0].date_start
  299. date_to = periods[-1].date_stop
  300. else:
  301. raise orm.except_orm(_("Error!"),
  302. _("Unimplemented period type %s") %
  303. (c.type,))
  304. res[c.id] = {
  305. 'date_from': date_from,
  306. 'date_to': date_to,
  307. 'period_from': period_ids and period_ids[0],
  308. 'period_to': period_ids and period_ids[-1],
  309. }
  310. return res
  311. _name = 'mis.report.instance.period'
  312. _columns = {
  313. 'name': fields.char(size=32, required=True,
  314. string='Description', translate=True),
  315. 'type': fields.selection([('d', _('Day')),
  316. ('w', _('Week')),
  317. ('fp', _('Fiscal Period')),
  318. # ('fy', _('Fiscal Year'))
  319. ],
  320. required=True,
  321. string='Period type'),
  322. 'offset': fields.integer(string='Offset',
  323. help='Offset from current period'),
  324. 'duration': fields.integer(string='Duration',
  325. help='Number of periods'),
  326. 'date_from': fields.function(_get_dates,
  327. type='date',
  328. multi="dates",
  329. string="From"),
  330. 'date_to': fields.function(_get_dates,
  331. type='date',
  332. multi="dates",
  333. string="To"),
  334. 'period_from': fields.function(_get_dates,
  335. type='many2one', obj='account.period',
  336. multi="dates", string="From period"),
  337. 'period_to': fields.function(_get_dates,
  338. type='many2one', obj='account.period',
  339. multi="dates", string="To period"),
  340. 'sequence': fields.integer(string='Sequence'),
  341. 'report_instance_id': fields.many2one('mis.report.instance',
  342. string='Report Instance'),
  343. 'comparison_column_ids': fields.many2many('mis.report.instance.period', 'mis_report_instance_period_rel',
  344. 'period_id', 'compare_period_id', string='Compare with'),
  345. 'company_id': fields.many2one('res.company', 'Company', required=True),
  346. 'normalize_factor': fields.integer(string='Factor',
  347. help='Factor to use to normalize the period (used in comparison'),
  348. }
  349. _defaults = {
  350. 'offset': -1,
  351. 'duration': 1,
  352. 'sequence': 100,
  353. 'normalize_factor': 1,
  354. 'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid,
  355. 'mis.report.instance.period',
  356. context=c)
  357. }
  358. _order = 'sequence'
  359. _sql_constraints = [
  360. ('duration', 'CHECK (duration>0)', 'Wrong duration, it must be positive!'),
  361. ('normalize_factor', 'CHECK (normalize_factor>0)', 'Wrong normalize factor, it must be positive!'),
  362. ('name_unique', 'unique(name, report_instance_id)', 'Period name should be unique by report'),
  363. ]
  364. def _fetch_balances(self, cr, uid, c, context=None):
  365. """ fetch the general account balances for the given period
  366. returns a dictionary {bal_<account.code>: account.balance}
  367. """
  368. if context is None:
  369. context = {}
  370. account_obj = self.pool['account.account']
  371. search_ctx = dict(context)
  372. if c.period_from:
  373. search_ctx.update({'period_from': c.period_from.id,
  374. 'period_to': c.period_to.id})
  375. else:
  376. search_ctx.update({'date_from': c.date_from,
  377. 'date_to': c.date_to})
  378. # TODO: initial balance?
  379. account_ids = account_obj.search(cr, uid, [('company_id', '=', c.company_id.id)], context=context)
  380. account_datas = account_obj.read(cr, uid, account_ids, ['code', 'balance'], context=search_ctx)
  381. balances = {}
  382. for account_data in account_datas:
  383. key = 'bal' + _clean(account_data['code'])
  384. assert key not in balances
  385. balances[key] = account_data['balance']
  386. return balances
  387. def _fetch_queries(self, cr, uid, c, context):
  388. res = {}
  389. report = c.report_instance_id.report_id
  390. for query in report.query_ids:
  391. obj = self.pool[query.model_id.model]
  392. domain = query.domain and safe_eval(query.domain) or []
  393. if query.date_field.ttype == 'date':
  394. domain.extend([(query.date_field.name, '>=', c.date_from),
  395. (query.date_field.name, '<=', c.date_to)])
  396. else:
  397. datetime_from = _utc_midnight(c.date_from, context.get('tz', 'UTC'))
  398. datetime_to = _utc_midnight(c.date_to, context.get('tz', 'UTC'), add_day=1)
  399. domain.extend([(query.date_field.name, '>=', datetime_from),
  400. (query.date_field.name, '<', datetime_to)])
  401. if obj._columns.get('company_id', False):
  402. domain.extend([('company_id', '=', c.company_id.id)])
  403. field_names = [field.name for field in query.field_ids]
  404. obj_ids = obj.search(cr, uid, domain, context=context)
  405. obj_datas = obj.read(cr, uid, obj_ids, field_names, context=context)
  406. res[query.name] = [AutoStruct(**d) for d in obj_datas]
  407. return res
  408. def _compute(self, cr, uid, c, context=None):
  409. if context is None:
  410. context = {}
  411. kpi_obj = self.pool['mis.report.kpi']
  412. res = {}
  413. localdict = {
  414. 'registry': self.pool,
  415. 'sum': sum,
  416. 'min': min,
  417. 'max': max,
  418. 'len': len,
  419. 'avg': lambda l: sum(l) / float(len(l)),
  420. }
  421. localdict.update(self._fetch_balances(cr, uid, c, context=context))
  422. localdict.update(self._fetch_queries(cr, uid, c, context=context))
  423. for kpi in c.report_instance_id.report_id.kpi_ids:
  424. try:
  425. kpi_val = safe_eval(kpi.expression, localdict)
  426. except ZeroDivisionError:
  427. kpi_val = None
  428. kpi_val_rendered = '#DIV/0'
  429. kpi_val_comment = traceback.format_exc()
  430. except:
  431. kpi_val = None
  432. kpi_val_rendered = '#ERR'
  433. kpi_val_comment = traceback.format_exc()
  434. else:
  435. kpi_val_rendered = kpi_obj._render(cr, uid, kpi, kpi_val, context=context)
  436. kpi_val_comment = None
  437. localdict[kpi.name] = kpi_val
  438. try:
  439. kpi_style = None
  440. if kpi.css_style:
  441. kpi_style = safe_eval(kpi.css_style, localdict)
  442. except:
  443. kpi_style = None
  444. res[kpi.name] = {
  445. 'val': kpi_val,
  446. 'val_r': kpi_val_rendered,
  447. 'val_c': kpi_val_comment,
  448. 'style': kpi_style,
  449. 'suffix': kpi.suffix,
  450. 'dp': kpi.dp,
  451. 'is_percentage': kpi.type == 'pct',
  452. }
  453. return res
  454. class mis_report_instance(orm.Model):
  455. """ The MIS report instance combines compute and
  456. display a MIS report template for a set of periods """
  457. def _get_pivot_date(self, cr, uid, ids, field_name, arg, context=None):
  458. res = {}
  459. for r in self.browse(cr, uid, ids, context=context):
  460. if r.date:
  461. res[r.id] = r.date
  462. else:
  463. res[r.id] = fields.date.context_today(self, cr, uid,
  464. context=context)
  465. return res
  466. _name = 'mis.report.instance'
  467. _columns = {
  468. 'name': fields.char(size=32, required=True,
  469. string='Name', translate=True),
  470. 'description': fields.char(required=False,
  471. string='Description', translate=True),
  472. 'date': fields.date(string='Base date',
  473. help='Report base date '
  474. '(leave empty to use current date)'),
  475. 'pivot_date': fields.function(_get_pivot_date,
  476. type='date',
  477. string="Pivot date"),
  478. 'report_id': fields.many2one('mis.report',
  479. required=True,
  480. string='Report'),
  481. 'period_ids': fields.one2many('mis.report.instance.period',
  482. 'report_instance_id',
  483. required=True,
  484. string='Periods'),
  485. 'target_move': fields.selection([('posted', 'All Posted Entries'),
  486. ('all', 'All Entries'),
  487. ], 'Target Moves', required=True),
  488. }
  489. _defaults = {
  490. 'target_move': 'posted',
  491. }
  492. def create(self, cr, uid, vals, context=None):
  493. if 'period_ids' in vals:
  494. for idx, line in enumerate(vals['period_ids']):
  495. line[2]['sequence'] = idx + 1
  496. return super(mis_report_instance, self).create(cr, uid, vals, context=context)
  497. def write(self, cr, uid, ids, vals, context=None):
  498. res = super(mis_report_instance, self).write(cr, uid, ids, vals, context=context)
  499. mis_report_instance_period_obj = self.pool.get('mis.report.instance.period')
  500. for instance in self.browse(cr, uid, ids, context):
  501. for idx, period in enumerate(instance.period_ids):
  502. mis_report_instance_period_obj.write(cr, uid, [period.id], {'sequence': idx + 1}, context=context)
  503. return res
  504. def _format_date(self, cr, uid, date, context=None):
  505. # format date following user language
  506. lang = self.pool['res.users'].read(cr, uid, uid, ['lang'], context=context)['lang']
  507. language_id = self.pool['res.lang'].search(cr, uid, [('code', '=', lang)], context=context)[0]
  508. tformat = self.pool['res.lang'].read(cr, uid, language_id, ['date_format'])['date_format']
  509. return datetime.strftime(datetime.strptime(date, tools.DEFAULT_SERVER_DATE_FORMAT), tformat)
  510. def compute(self, cr, uid, _ids, context=None):
  511. assert isinstance(_ids, (int, long))
  512. if context is None:
  513. context = {}
  514. r = self.browse(cr, uid, _ids, context=context)
  515. context['state'] = r.target_move
  516. content = OrderedDict()
  517. #empty line name for header
  518. header = OrderedDict()
  519. header[''] = {'kpi_name': '', 'cols': []}
  520. #initialize lines with kpi
  521. for kpi in r.report_id.kpi_ids:
  522. content[kpi.name] = {'kpi_name': kpi.description, 'cols': []}
  523. report_instance_period_obj = self.pool.get('mis.report.instance.period')
  524. kpi_obj = self.pool.get('mis.report.kpi')
  525. period_values = {}
  526. for period in r.period_ids:
  527. # add the column header
  528. header['']['cols'].append(dict(name=period.name,
  529. date=(period.duration > 1 or period.type == 'w') and
  530. _('from %s to %s' %
  531. (period.period_from and period.period_from.name
  532. or self._format_date(cr, uid, period.date_from, context=context),
  533. period.period_to and period.period_to.name
  534. or self._format_date(cr, uid, period.date_to, context=context)))
  535. or period.period_from and period.period_from.name or period.date_from))
  536. # compute kpi values
  537. values = report_instance_period_obj._compute(cr, uid, period, context=context)
  538. period_values[period.name] = values
  539. for key in values:
  540. content[key]['cols'].append(values[key])
  541. # add comparison column
  542. for period in r.period_ids:
  543. for compare_col in period.comparison_column_ids:
  544. # add the column header
  545. header['']['cols'].append(dict(name='%s - %s' % (period.name, compare_col.name), date=''))
  546. column1_values = period_values[period.name]
  547. column2_values = period_values[compare_col.name]
  548. for kpi in r.report_id.kpi_ids:
  549. content[kpi.name]['cols'].append({'val_r': kpi_obj._render_comparison(cr, uid, kpi,
  550. column1_values[kpi.name]['val'],
  551. column2_values[kpi.name]['val'],
  552. period.normalize_factor, compare_col.normalize_factor, context=context)})
  553. return {'header': header,
  554. 'content': content}