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.

857 lines
36 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
  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 collections import OrderedDict
  25. from datetime import datetime, timedelta
  26. from dateutil import parser
  27. import re
  28. import traceback
  29. import pytz
  30. from openerp.api import Environment
  31. from openerp.osv import orm, fields
  32. from openerp import tools
  33. from openerp.tools.safe_eval import safe_eval
  34. from openerp.tools.translate import _
  35. from .aep import AccountingExpressionProcessor
  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 u'%s\xA0%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. ondelete='cascade'),
  232. }
  233. _order = 'name'
  234. def _check_name(self, cr, uid, ids, context=None):
  235. for record_name in self.read(cr, uid, ids, ['name']):
  236. if not _is_valid_python_var(record_name['name']):
  237. return False
  238. return True
  239. _constraints = [
  240. (_check_name, 'The name must be a valid python identifier', ['name']),
  241. ]
  242. class mis_report(orm.Model):
  243. """ A MIS report template (without period information)
  244. The MIS report holds:
  245. * an implicit query fetching all the account balances;
  246. for each account, the balance is stored in a variable named
  247. bal_{code} where {code} is the account code
  248. * an implicit query fetching all the account balances solde;
  249. for each account, the balance solde is stored in a variable named
  250. bals_{code} where {code} is the account code
  251. * a list of explicit queries; the result of each query is
  252. stored in a variable with same name as a query, containing as list
  253. of data structures populated with attributes for each fields to fetch
  254. * a list of KPI to be evaluated based on the variables resulting
  255. from the balance and queries
  256. """
  257. _name = 'mis.report'
  258. _columns = {
  259. 'name': fields.char(size=32, required=True,
  260. string='Name', translate=True),
  261. 'description': fields.char(required=False,
  262. string='Description', translate=True),
  263. 'query_ids': fields.one2many('mis.report.query', 'report_id',
  264. string='Queries'),
  265. 'kpi_ids': fields.one2many('mis.report.kpi', 'report_id',
  266. string='KPI\'s'),
  267. }
  268. # TODO: kpi name cannot be start with query name
  269. def create(self, cr, uid, vals, context=None):
  270. # TODO: explain this
  271. if 'kpi_ids' in vals:
  272. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  273. for idx, line in enumerate(vals['kpi_ids']):
  274. if line[0] == 0:
  275. line[2]['sequence'] = idx + 1
  276. else:
  277. mis_report_kpi_obj.write(
  278. cr, uid, [line[1]], {'sequence': idx + 1},
  279. context=context)
  280. return super(mis_report, self).create(cr, uid, vals, context=context)
  281. def write(self, cr, uid, ids, vals, context=None):
  282. # TODO: explain this
  283. res = super(mis_report, self).write(
  284. cr, uid, ids, vals, context=context)
  285. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  286. for report in self.browse(cr, uid, ids, context):
  287. for idx, kpi in enumerate(report.kpi_ids):
  288. mis_report_kpi_obj.write(
  289. cr, uid, [kpi.id], {'sequence': idx + 1}, context=context)
  290. return res
  291. class mis_report_instance_period(orm.Model):
  292. """ A MIS report instance has the logic to compute
  293. a report template for a given date period.
  294. Periods have a duration (day, week, fiscal period) and
  295. are defined as an offset relative to a pivot date.
  296. """
  297. def _get_dates(self, cr, uid, ids, field_names, arg, context=None):
  298. if isinstance(ids, (int, long)):
  299. ids = [ids]
  300. res = {}
  301. for c in self.browse(cr, uid, ids, context=context):
  302. d = parser.parse(c.report_instance_id.pivot_date)
  303. if c.type == 'd':
  304. date_from = d + timedelta(days=c.offset)
  305. date_to = date_from + timedelta(days=c.duration - 1)
  306. date_from = date_from.strftime(
  307. tools.DEFAULT_SERVER_DATE_FORMAT)
  308. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  309. period_ids = None
  310. elif c.type == 'w':
  311. date_from = d - timedelta(d.weekday())
  312. date_from = date_from + timedelta(days=c.offset * 7)
  313. date_to = date_from + timedelta(days=(7 * c.duration) - 1)
  314. date_from = date_from.strftime(
  315. tools.DEFAULT_SERVER_DATE_FORMAT)
  316. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  317. period_ids = None
  318. elif c.type == 'fp':
  319. period_obj = self.pool['account.period']
  320. all_period_ids = period_obj.search(
  321. cr, uid,
  322. [('special', '=', False),
  323. '|', ('company_id', '=', False),
  324. ('company_id', '=', c.company_id.id)],
  325. order='date_start',
  326. context=context)
  327. current_period_ids = period_obj.search(
  328. cr, uid,
  329. [('special', '=', False),
  330. ('date_start', '<=', d),
  331. ('date_stop', '>=', d),
  332. '|', ('company_id', '=', False),
  333. ('company_id', '=', c.company_id.id)],
  334. context=context)
  335. if not current_period_ids:
  336. raise orm.except_orm(_("Error!"),
  337. _("No current fiscal period for %s")
  338. % d)
  339. p = all_period_ids.index(current_period_ids[0]) + c.offset
  340. if p < 0 or p >= len(all_period_ids):
  341. raise orm.except_orm(_("Error!"),
  342. _("No such fiscal period for %s "
  343. "with offset %d") % (d, c.offset))
  344. period_ids = all_period_ids[p:p + c.duration]
  345. periods = period_obj.browse(cr, uid, period_ids,
  346. context=context)
  347. date_from = periods[0].date_start
  348. date_to = periods[-1].date_stop
  349. else:
  350. raise orm.except_orm(_("Error!"),
  351. _("Unimplemented period type %s") %
  352. (c.type,))
  353. res[c.id] = {
  354. 'date_from': date_from,
  355. 'date_to': date_to,
  356. 'period_from': period_ids and period_ids[0],
  357. 'period_to': period_ids and period_ids[-1],
  358. }
  359. return res
  360. _name = 'mis.report.instance.period'
  361. _columns = {
  362. 'name': fields.char(size=32, required=True,
  363. string='Description', translate=True),
  364. 'type': fields.selection([('d', _('Day')),
  365. ('w', _('Week')),
  366. ('fp', _('Fiscal Period')),
  367. # ('fy', _('Fiscal Year'))
  368. ],
  369. required=True,
  370. string='Period type'),
  371. 'offset': fields.integer(string='Offset',
  372. help='Offset from current period'),
  373. 'duration': fields.integer(string='Duration',
  374. help='Number of periods'),
  375. 'date_from': fields.function(_get_dates,
  376. type='date',
  377. multi="dates",
  378. string="From"),
  379. 'date_to': fields.function(_get_dates,
  380. type='date',
  381. multi="dates",
  382. string="To"),
  383. 'period_from': fields.function(_get_dates,
  384. type='many2one', obj='account.period',
  385. multi="dates", string="From period"),
  386. 'period_to': fields.function(_get_dates,
  387. type='many2one', obj='account.period',
  388. multi="dates", string="To period"),
  389. 'sequence': fields.integer(string='Sequence'),
  390. 'report_instance_id': fields.many2one('mis.report.instance',
  391. string='Report Instance',
  392. ondelete='cascade'),
  393. 'comparison_column_ids': fields.many2many(
  394. 'mis.report.instance.period',
  395. 'mis_report_instance_period_rel',
  396. 'period_id',
  397. 'compare_period_id',
  398. string='Compare with'),
  399. 'company_id': fields.related('report_instance_id', 'company_id',
  400. type="many2one", relation="res.company",
  401. string="Company", readonly=True),
  402. 'normalize_factor': fields.integer(
  403. string='Factor',
  404. help='Factor to use to normalize the period (used in comparison'),
  405. }
  406. _defaults = {
  407. 'offset': -1,
  408. 'duration': 1,
  409. 'sequence': 100,
  410. 'normalize_factor': 1,
  411. }
  412. _order = 'sequence'
  413. _sql_constraints = [
  414. ('duration', 'CHECK (duration>0)',
  415. 'Wrong duration, it must be positive!'),
  416. ('normalize_factor', 'CHECK (normalize_factor>0)',
  417. 'Wrong normalize factor, it must be positive!'),
  418. ('name_unique', 'unique(name, report_instance_id)',
  419. 'Period name should be unique by report'),
  420. ]
  421. def compute_domain(self, cr, uid, ids, account_, context=None):
  422. if isinstance(ids, (int, long)):
  423. ids = [ids]
  424. domain = []
  425. this = self.browse(cr, uid, ids, context=context)[0]
  426. env = Environment(cr, uid, {})
  427. aep = AccountingExpressionProcessor(env)
  428. aep.parse_expr(account_)
  429. aep.done_parsing([('company_id', '=',
  430. this.report_instance_id.company_id.id)])
  431. domain.extend(aep.get_aml_domain_for_expr(account_))
  432. if domain != []:
  433. # compute date/period
  434. period_ids = []
  435. date_from = None
  436. date_to = None
  437. period_obj = self.pool['account.period']
  438. target_move = this.report_instance_id.target_move
  439. if target_move == 'posted':
  440. domain.append(('move_id.state', '=', target_move))
  441. if this.period_from:
  442. compute_period_ids = period_obj.build_ctx_periods(
  443. cr, uid, this.period_from.id, this.period_to.id)
  444. period_ids.extend(compute_period_ids)
  445. else:
  446. date_from = this.date_from
  447. date_to = this.date_to
  448. if period_ids:
  449. if date_from:
  450. domain.append('|')
  451. domain.append(('period_id', 'in', period_ids))
  452. if date_from:
  453. domain.extend([('date', '>=', date_from),
  454. ('date', '<=', date_to)])
  455. else:
  456. domain = False
  457. return domain
  458. def compute_period_domain(self, cr, uid, period_report, is_end,
  459. is_initial, context=None):
  460. period_obj = self.pool['account.period']
  461. move_obj = self.pool['account.move']
  462. domain_list = []
  463. target_move = period_report.report_instance_id.target_move
  464. if target_move == 'posted':
  465. domain_list.append(('move_id.state', '=', target_move))
  466. if not is_end and not is_initial:
  467. if period_report.period_from:
  468. compute_period_ids = period_obj.build_ctx_periods(
  469. cr, uid, period_report.period_from.id,
  470. period_report.period_to.id)
  471. domain_list.extend([('period_id', 'in', compute_period_ids)])
  472. else:
  473. domain_list.extend([('date', '>=', period_report.date_from),
  474. ('date', '<=', period_report.date_to)])
  475. elif period_report.period_from and period_report.period_to:
  476. period_to = period_report.period_to
  477. if is_initial:
  478. move_id = move_obj.search(
  479. cr, uid, [('period_id.special', '=', False),
  480. ('period_id.date_start', '<',
  481. period_to.date_start)],
  482. order="period_id desc", limit=1, context=context)
  483. if move_id:
  484. computed_period_to = move_obj.browse(
  485. cr, uid, move_id[0], context=context).period_id.id
  486. else:
  487. computed_period_to = self.pool['account.period'].search(
  488. cr, uid, [('company_id', '=',
  489. period_report.company_id.id)],
  490. order='date_start desc', limit=1)[0]
  491. # Change start period to search correctly period from
  492. period_to = period_obj.browse(cr, uid, [computed_period_to],
  493. context=context)[0]
  494. move_id = move_obj.search(
  495. cr, uid, [('period_id.special', '=', True),
  496. ('period_id.date_start', '<=',
  497. period_to.date_start)],
  498. order="period_id desc", limit=1, context=context)
  499. if move_id:
  500. computed_period_from = move_obj.browse(
  501. cr, uid, move_id[0], context=context).period_id.id
  502. else:
  503. computed_period_from = self.pool['account.period'].search(
  504. cr, uid, [('company_id', '=',
  505. period_report.company_id.id)],
  506. order='date_start', limit=1)[0]
  507. compute_period_ids = period_obj.build_ctx_periods(
  508. cr, uid, computed_period_from, period_to.id)
  509. domain_list.extend([('period_id', 'in', compute_period_ids)])
  510. return domain_list
  511. def _fetch_queries(self, cr, uid, c, context):
  512. res = {}
  513. report = c.report_instance_id.report_id
  514. for query in report.query_ids:
  515. obj = self.pool[query.model_id.model]
  516. domain = query.domain and safe_eval(query.domain) or []
  517. if query.date_field.ttype == 'date':
  518. domain.extend([(query.date_field.name, '>=', c.date_from),
  519. (query.date_field.name, '<=', c.date_to)])
  520. else:
  521. datetime_from = _utc_midnight(
  522. c.date_from, context.get('tz', 'UTC'))
  523. datetime_to = _utc_midnight(
  524. c.date_to, context.get('tz', 'UTC'), add_day=1)
  525. domain.extend([(query.date_field.name, '>=', datetime_from),
  526. (query.date_field.name, '<', datetime_to)])
  527. if obj._columns.get('company_id', False):
  528. domain.extend(['|', ('company_id', '=', False),
  529. ('company_id', '=', c.company_id.id)])
  530. field_names = [field.name for field in query.field_ids]
  531. obj_ids = obj.search(cr, uid, domain, context=context)
  532. obj_datas = obj.read(
  533. cr, uid, obj_ids, field_names, context=context)
  534. res[query.name] = [AutoStruct(**d) for d in obj_datas]
  535. return res
  536. def _compute(self, cr, uid, lang_id, c, aep, context=None):
  537. if context is None:
  538. context = {}
  539. kpi_obj = self.pool['mis.report.kpi']
  540. res = {}
  541. localdict = {
  542. 'registry': self.pool,
  543. 'sum': sum,
  544. 'min': min,
  545. 'max': max,
  546. 'len': len,
  547. 'avg': lambda l: sum(l) / float(len(l)),
  548. }
  549. domain_p = self.compute_period_domain(cr, uid, c, False, False,
  550. context=context)
  551. domain_e = self.compute_period_domain(cr, uid, c, True, False,
  552. context=context)
  553. domain_i = self.compute_period_domain(cr, uid, c, False, True,
  554. context=context)
  555. aep.do_queries(domain_p, domain_i, domain_e)
  556. localdict.update(self._fetch_queries(cr, uid, c,
  557. context=context))
  558. compute_queue = c.report_instance_id.report_id.kpi_ids
  559. recompute_queue = []
  560. while True:
  561. for kpi in compute_queue:
  562. try:
  563. kpi_val_comment = kpi.expression
  564. kpi_eval_expression = aep.replace_expr(kpi.expression)
  565. kpi_val = safe_eval(kpi_eval_expression, localdict)
  566. except ZeroDivisionError:
  567. kpi_val = None
  568. kpi_val_rendered = '#DIV/0'
  569. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  570. except ValueError:
  571. recompute_queue.append(kpi)
  572. kpi_val = None
  573. kpi_val_rendered = '#ERR'
  574. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  575. except:
  576. kpi_val = None
  577. kpi_val_rendered = '#ERR'
  578. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  579. else:
  580. kpi_val_rendered = kpi_obj._render(
  581. cr, uid, lang_id, kpi, kpi_val, context=context)
  582. localdict[kpi.name] = kpi_val
  583. try:
  584. kpi_style = None
  585. if kpi.css_style:
  586. kpi_style = safe_eval(kpi.css_style, localdict)
  587. except:
  588. kpi_style = None
  589. drilldown = bool(aep.get_aml_domain_for_expr(kpi.expression))
  590. res[kpi.name] = {
  591. 'val': kpi_val,
  592. 'val_r': kpi_val_rendered,
  593. 'val_c': kpi_val_comment,
  594. 'style': kpi_style,
  595. 'default_style': kpi.default_css_style or None,
  596. 'suffix': kpi.suffix,
  597. 'dp': kpi.dp,
  598. 'is_percentage': kpi.type == 'pct',
  599. 'period_id': c.id,
  600. 'period_name': c.name,
  601. 'drilldown': drilldown,
  602. }
  603. if len(recompute_queue) == 0:
  604. # nothing to recompute, we are done
  605. break
  606. if len(recompute_queue) == len(compute_queue):
  607. # could not compute anything in this iteration
  608. # (ie real Value errors or cyclic dependency)
  609. # so we stop trying
  610. break
  611. # try again
  612. compute_queue = recompute_queue
  613. recompute_queue = []
  614. return res
  615. class mis_report_instance(orm.Model):
  616. """ The MIS report instance combines compute and
  617. display a MIS report template for a set of periods """
  618. def _get_pivot_date(self, cr, uid, ids, field_name, arg, context=None):
  619. res = {}
  620. for r in self.browse(cr, uid, ids, context=context):
  621. if r.date:
  622. res[r.id] = r.date
  623. else:
  624. res[r.id] = fields.date.context_today(self, cr, uid,
  625. context=context)
  626. return res
  627. _name = 'mis.report.instance'
  628. _columns = {
  629. 'name': fields.char(size=32, required=True,
  630. string='Name', translate=True),
  631. 'description': fields.char(required=False,
  632. string='Description', translate=True),
  633. 'date': fields.date(string='Base date',
  634. help='Report base date '
  635. '(leave empty to use current date)'),
  636. 'pivot_date': fields.function(_get_pivot_date,
  637. type='date',
  638. string="Pivot date"),
  639. 'report_id': fields.many2one('mis.report',
  640. required=True,
  641. string='Report'),
  642. 'period_ids': fields.one2many('mis.report.instance.period',
  643. 'report_instance_id',
  644. required=True,
  645. string='Periods'),
  646. 'target_move': fields.selection([('posted', 'All Posted Entries'),
  647. ('all', 'All Entries'),
  648. ], 'Target Moves', required=True),
  649. 'company_id': fields.many2one('res.company', 'Company', required=True),
  650. }
  651. _defaults = {
  652. 'target_move': 'posted',
  653. 'company_id': lambda s, cr, uid, c:
  654. s.pool.get('res.company')._company_default_get(
  655. cr, uid,
  656. 'mis.report.instance',
  657. context=c)
  658. }
  659. def create(self, cr, uid, vals, context=None):
  660. if not vals:
  661. return context.get('active_id', None)
  662. # TODO: explain this
  663. if 'period_ids' in vals:
  664. mis_report_instance_period_obj = self.pool.get(
  665. 'mis.report.instance.period')
  666. for idx, line in enumerate(vals['period_ids']):
  667. if line[0] == 0:
  668. line[2]['sequence'] = idx + 1
  669. else:
  670. mis_report_instance_period_obj.write(
  671. cr, uid, [line[1]], {'sequence': idx + 1},
  672. context=context)
  673. return super(mis_report_instance, self).create(cr, uid, vals,
  674. context=context)
  675. def write(self, cr, uid, ids, vals, context=None):
  676. # TODO: explain this
  677. res = super(mis_report_instance, self).write(
  678. cr, uid, ids, vals, context=context)
  679. mis_report_instance_period_obj = self.pool.get(
  680. 'mis.report.instance.period')
  681. for instance in self.browse(cr, uid, ids, context):
  682. for idx, period in enumerate(instance.period_ids):
  683. mis_report_instance_period_obj.write(
  684. cr, uid, [period.id], {'sequence': idx + 1},
  685. context=context)
  686. return res
  687. def _format_date(self, cr, uid, lang_id, date, context=None):
  688. # format date following user language
  689. tformat = self.pool['res.lang'].read(
  690. cr, uid, lang_id, ['date_format'])[0]['date_format']
  691. return datetime.strftime(datetime.strptime(
  692. date,
  693. tools.DEFAULT_SERVER_DATE_FORMAT),
  694. tformat)
  695. def compute(self, cr, uid, _ids, context=None):
  696. assert isinstance(_ids, (int, long))
  697. if context is None:
  698. context = {}
  699. r = self.browse(cr, uid, _ids, context=context)
  700. context['state'] = r.target_move
  701. content = OrderedDict()
  702. # empty line name for header
  703. header = OrderedDict()
  704. header[''] = {'kpi_name': '', 'cols': [], 'default_style': ''}
  705. env = Environment(cr, uid, {})
  706. aep = AccountingExpressionProcessor(env)
  707. # initialize lines with kpi
  708. for kpi in r.report_id.kpi_ids:
  709. aep.parse_expr(kpi.expression)
  710. content[kpi.name] = {'kpi_name': kpi.description,
  711. 'cols': [],
  712. 'default_style': ''}
  713. aep.done_parsing([('company_id', '=', r.company_id.id)])
  714. report_instance_period_obj = self.pool.get(
  715. 'mis.report.instance.period')
  716. kpi_obj = self.pool.get('mis.report.kpi')
  717. period_values = {}
  718. lang = self.pool['res.users'].read(
  719. cr, uid, uid, ['lang'], context=context)['lang']
  720. if not lang:
  721. lang = 'en_US'
  722. lang_id = self.pool['res.lang'].search(
  723. cr, uid, [('code', '=', lang)], context=context)
  724. for period in r.period_ids:
  725. # add the column header
  726. header['']['cols'].append(dict(
  727. name=period.name,
  728. date=(period.duration > 1 or period.type == 'w') and
  729. _('from %s to %s' %
  730. (period.period_from and period.period_from.name
  731. or self._format_date(cr, uid, lang_id, period.date_from,
  732. context=context),
  733. period.period_to and period.period_to.name
  734. or self._format_date(cr, uid, lang_id, period.date_to,
  735. context=context)))
  736. or period.period_from and period.period_from.name or
  737. period.date_from))
  738. # compute kpi values
  739. values = report_instance_period_obj._compute(
  740. cr, uid, lang_id, period, aep, context=context)
  741. period_values[period.name] = values
  742. for key in values:
  743. content[key]['default_style'] = values[key]['default_style']
  744. content[key]['cols'].append(values[key])
  745. # add comparison column
  746. for period in r.period_ids:
  747. for compare_col in period.comparison_column_ids:
  748. # add the column header
  749. header['']['cols'].append(
  750. dict(name='%s - %s' % (period.name, compare_col.name),
  751. date=''))
  752. column1_values = period_values[period.name]
  753. column2_values = period_values[compare_col.name]
  754. for kpi in r.report_id.kpi_ids:
  755. content[kpi.name]['cols'].append(
  756. {'val_r': kpi_obj._render_comparison(
  757. cr,
  758. uid,
  759. lang_id,
  760. kpi,
  761. column1_values[kpi.name]['val'],
  762. column2_values[kpi.name]['val'],
  763. period.normalize_factor,
  764. compare_col.normalize_factor,
  765. context=context)})
  766. return {'header': header,
  767. 'content': content}