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.

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