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.

829 lines
35 KiB

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