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.

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