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.

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