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