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.

834 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
  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. from .aep import MODE_VARIATION
  37. from .aep import MODE_END
  38. from .aep import MODE_INITIAL
  39. class AutoStruct(object):
  40. def __init__(self, **kwargs):
  41. for k, v in kwargs.items():
  42. setattr(self, k, v)
  43. def _get_selection_label(selection, value):
  44. for v, l in selection:
  45. if v == value:
  46. return l
  47. return ''
  48. def _utc_midnight(d, tz_name, add_day=0):
  49. d = datetime.strptime(d, tools.DEFAULT_SERVER_DATE_FORMAT)
  50. if add_day:
  51. d = d + timedelta(days=add_day)
  52. utc_tz = pytz.timezone('UTC')
  53. context_tz = pytz.timezone(tz_name)
  54. local_timestamp = context_tz.localize(d, is_dst=False)
  55. return datetime.strftime(local_timestamp.astimezone(utc_tz),
  56. tools.DEFAULT_SERVER_DATETIME_FORMAT)
  57. def _python_var(var_str):
  58. return re.sub(r'\W|^(?=\d)', '_', var_str).lower()
  59. def _is_valid_python_var(name):
  60. return re.match("[_A-Za-z][_a-zA-Z0-9]*$", name)
  61. class mis_report_kpi(orm.Model):
  62. """ A KPI is an element of a MIS report.
  63. In addition to a name and description, it has an expression
  64. to compute it based on queries defined in the MIS report.
  65. It also has various informations defining how to render it
  66. (numeric or percentage or a string, a suffix, divider) and
  67. how to render comparison of two values of the KPI.
  68. KPI are ordered inside the MIS report, as some KPI expressions
  69. can depend on other KPI that need to be computed before.
  70. """
  71. _name = 'mis.report.kpi'
  72. _columns = {
  73. 'name': fields.char(size=32, required=True,
  74. string='Name'),
  75. 'description': fields.char(required=True,
  76. string='Description',
  77. translate=True),
  78. 'expression': fields.char(required=True,
  79. string='Expression'),
  80. 'default_css_style': fields.char(
  81. string='Default CSS style'),
  82. 'css_style': fields.char(string='CSS style expression'),
  83. 'type': fields.selection([('num', _('Numeric')),
  84. ('pct', _('Percentage')),
  85. ('str', _('String'))],
  86. required=True,
  87. string='Type'),
  88. 'divider': fields.selection([('1e-6', _('µ')),
  89. ('1e-3', _('m')),
  90. ('1', _('1')),
  91. ('1e3', _('k')),
  92. ('1e6', _('M'))],
  93. string='Factor'),
  94. 'dp': fields.integer(string='Rounding'),
  95. 'suffix': fields.char(size=16, string='Suffix'),
  96. 'compare_method': fields.selection([('diff', _('Difference')),
  97. ('pct', _('Percentage')),
  98. ('none', _('None'))],
  99. required=True,
  100. string='Comparison Method'),
  101. 'sequence': fields.integer(string='Sequence'),
  102. 'report_id': fields.many2one('mis.report', string='Report'),
  103. }
  104. _defaults = {
  105. 'type': 'num',
  106. 'divider': '1',
  107. 'dp': 0,
  108. 'compare_method': 'pct',
  109. 'sequence': 100,
  110. }
  111. _order = 'sequence'
  112. def _check_name(self, cr, uid, ids, context=None):
  113. for record_name in self.read(cr, uid, ids, ['name']):
  114. if not _is_valid_python_var(record_name['name']):
  115. return False
  116. return True
  117. _constraints = [
  118. (_check_name, 'The name must be a valid python identifier', ['name']),
  119. ]
  120. def onchange_name(self, cr, uid, ids, name, context=None):
  121. res = {}
  122. if name and not _is_valid_python_var(name):
  123. res['warning'] = {
  124. 'title': 'Invalid name',
  125. 'message': 'The name must be a valid python identifier'}
  126. return res
  127. def onchange_description(self, cr, uid, ids, description, name,
  128. context=None):
  129. """ construct name from description """
  130. res = {}
  131. if description and not name:
  132. res = {'value': {'name': _python_var(description)}}
  133. return res
  134. def onchange_type(self, cr, uid, ids, kpi_type, context=None):
  135. res = {}
  136. if kpi_type == 'pct':
  137. res['value'] = {'compare_method': 'diff'}
  138. elif kpi_type == 'str':
  139. res['value'] = {'compare_method': 'none',
  140. 'divider': '',
  141. 'dp': 0}
  142. return res
  143. def _render(self, cr, uid, lang_id, kpi, value, context=None):
  144. """ render a KPI value as a unicode string, ready for display """
  145. if kpi.type == 'num':
  146. return self._render_num(cr, uid, lang_id, value, kpi.divider,
  147. kpi.dp, kpi.suffix, context=context)
  148. elif kpi.type == 'pct':
  149. return self._render_num(cr, uid, lang_id, value, 0.01,
  150. kpi.dp, '%', context=context)
  151. else:
  152. return unicode(value)
  153. def _render_comparison(self, cr, uid, lang_id, kpi, value, base_value,
  154. average_value, average_base_value, context=None):
  155. """ render the comparison of two KPI values, ready for display """
  156. if value is None or base_value is None:
  157. return ''
  158. if kpi.type == 'pct':
  159. return self._render_num(cr, uid, lang_id, value - base_value, 0.01,
  160. kpi.dp, _('pp'), sign='+', context=context)
  161. elif kpi.type == 'num':
  162. if average_value:
  163. value = value / float(average_value)
  164. if average_base_value:
  165. base_value = base_value / float(average_base_value)
  166. if kpi.compare_method == 'diff':
  167. return self._render_num(cr, uid, lang_id, value - base_value,
  168. kpi.divider,
  169. kpi.dp, kpi.suffix, sign='+',
  170. context=context)
  171. elif kpi.compare_method == 'pct' and base_value != 0:
  172. return self._render_num(cr, uid, lang_id,
  173. value / base_value - 1, 0.01,
  174. kpi.dp, '%', sign='+', context=context)
  175. return ''
  176. def _render_num(self, cr, uid, lang_id, value, divider,
  177. dp, suffix, sign='-', context=None):
  178. divider_label = _get_selection_label(
  179. self._columns['divider'].selection, divider)
  180. if divider_label == '1':
  181. divider_label = ''
  182. # format number following user language
  183. value = round(value / float(divider or 1), dp) or 0
  184. return u'%s\xA0%s%s' % (self.pool['res.lang'].format(
  185. cr, uid, lang_id,
  186. '%%%s.%df' % (
  187. sign, dp),
  188. value,
  189. grouping=True,
  190. context=context),
  191. divider_label, suffix or '')
  192. class mis_report_query(orm.Model):
  193. """ A query to fetch data for a MIS report.
  194. A query works on a model and has a domain and list of fields to fetch.
  195. At runtime, the domain is expanded with a "and" on the date/datetime field.
  196. """
  197. _name = 'mis.report.query'
  198. def _get_field_names(self, cr, uid, ids, name, args, context=None):
  199. res = {}
  200. for query in self.browse(cr, uid, ids, context=context):
  201. field_names = []
  202. for field in query.field_ids:
  203. field_names.append(field.name)
  204. res[query.id] = ', '.join(field_names)
  205. return res
  206. def onchange_field_ids(self, cr, uid, ids, field_ids, context=None):
  207. # compute field_names
  208. field_names = []
  209. for field in self.pool.get('ir.model.fields').read(
  210. cr, uid,
  211. field_ids[0][2],
  212. ['name'],
  213. context=context):
  214. field_names.append(field['name'])
  215. return {'value': {'field_names': ', '.join(field_names)}}
  216. _columns = {
  217. 'name': fields.char(size=32, required=True,
  218. string='Name'),
  219. 'model_id': fields.many2one('ir.model', required=True,
  220. string='Model'),
  221. 'field_ids': fields.many2many('ir.model.fields', required=True,
  222. string='Fields to fetch'),
  223. 'field_names': fields.function(_get_field_names, type='char',
  224. string='Fetched fields name',
  225. store={'mis.report.query':
  226. (lambda self, cr, uid, ids, c={}:
  227. ids, ['field_ids'], 20), }),
  228. 'date_field': fields.many2one('ir.model.fields', required=True,
  229. string='Date field',
  230. domain=[('ttype', 'in',
  231. ('date', 'datetime'))]),
  232. 'domain': fields.char(string='Domain'),
  233. 'report_id': fields.many2one('mis.report', string='Report',
  234. ondelete='cascade'),
  235. }
  236. _order = 'name'
  237. def _check_name(self, cr, uid, ids, context=None):
  238. for record_name in self.read(cr, uid, ids, ['name']):
  239. if not _is_valid_python_var(record_name['name']):
  240. return False
  241. return True
  242. _constraints = [
  243. (_check_name, 'The name must be a valid python identifier', ['name']),
  244. ]
  245. class mis_report(orm.Model):
  246. """ A MIS report template (without period information)
  247. The MIS report holds:
  248. * an implicit query fetching all the account balances;
  249. for each account, the balance is stored in a variable named
  250. bal_{code} where {code} is the account code
  251. * an implicit query fetching all the account balances solde;
  252. for each account, the balance solde is stored in a variable named
  253. bals_{code} where {code} is the account code
  254. * a list of explicit queries; the result of each query is
  255. stored in a variable with same name as a query, containing as list
  256. of data structures populated with attributes for each fields to fetch
  257. * a list of KPI to be evaluated based on the variables resulting
  258. from the balance and queries
  259. """
  260. _name = 'mis.report'
  261. _columns = {
  262. 'name': fields.char(size=32, required=True,
  263. string='Name', translate=True),
  264. 'description': fields.char(required=False,
  265. string='Description', translate=True),
  266. 'query_ids': fields.one2many('mis.report.query', 'report_id',
  267. string='Queries'),
  268. 'kpi_ids': fields.one2many('mis.report.kpi', 'report_id',
  269. string='KPI\'s'),
  270. }
  271. # TODO: kpi name cannot be start with query name
  272. def create(self, cr, uid, vals, context=None):
  273. # TODO: explain this
  274. if 'kpi_ids' in vals:
  275. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  276. for idx, line in enumerate(vals['kpi_ids']):
  277. if line[0] == 0:
  278. line[2]['sequence'] = idx + 1
  279. else:
  280. mis_report_kpi_obj.write(
  281. cr, uid, [line[1]], {'sequence': idx + 1},
  282. context=context)
  283. return super(mis_report, self).create(cr, uid, vals, context=context)
  284. def write(self, cr, uid, ids, vals, context=None):
  285. # TODO: explain this
  286. res = super(mis_report, self).write(
  287. cr, uid, ids, vals, context=context)
  288. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  289. for report in self.browse(cr, uid, ids, context):
  290. for idx, kpi in enumerate(report.kpi_ids):
  291. mis_report_kpi_obj.write(
  292. cr, uid, [kpi.id], {'sequence': idx + 1}, context=context)
  293. return res
  294. class mis_report_instance_period(orm.Model):
  295. """ A MIS report instance has the logic to compute
  296. a report template for a given date period.
  297. Periods have a duration (day, week, fiscal period) and
  298. are defined as an offset relative to a pivot date.
  299. """
  300. def _get_dates(self, cr, uid, ids, field_names, arg, context=None):
  301. if isinstance(ids, (int, long)):
  302. ids = [ids]
  303. res = {}
  304. for c in self.browse(cr, uid, ids, context=context):
  305. d = parser.parse(c.report_instance_id.pivot_date)
  306. if c.type == 'd':
  307. date_from = d + timedelta(days=c.offset)
  308. date_to = date_from + timedelta(days=c.duration - 1)
  309. date_from = date_from.strftime(
  310. tools.DEFAULT_SERVER_DATE_FORMAT)
  311. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  312. period_ids = None
  313. elif c.type == 'w':
  314. date_from = d - timedelta(d.weekday())
  315. date_from = date_from + timedelta(days=c.offset * 7)
  316. date_to = date_from + timedelta(days=(7 * c.duration) - 1)
  317. date_from = date_from.strftime(
  318. tools.DEFAULT_SERVER_DATE_FORMAT)
  319. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  320. period_ids = None
  321. elif c.type == 'fp':
  322. period_obj = self.pool['account.period']
  323. all_period_ids = period_obj.search(
  324. cr, uid,
  325. [('special', '=', False),
  326. '|', ('company_id', '=', False),
  327. ('company_id', '=', c.company_id.id)],
  328. order='date_start',
  329. context=context)
  330. current_period_ids = period_obj.search(
  331. cr, uid,
  332. [('special', '=', False),
  333. ('date_start', '<=', d),
  334. ('date_stop', '>=', d),
  335. '|', ('company_id', '=', False),
  336. ('company_id', '=', c.company_id.id)],
  337. context=context)
  338. if not current_period_ids:
  339. raise orm.except_orm(_("Error!"),
  340. _("No current fiscal period for %s")
  341. % d)
  342. p = all_period_ids.index(current_period_ids[0]) + c.offset
  343. if p < 0 or p >= len(all_period_ids):
  344. raise orm.except_orm(_("Error!"),
  345. _("No such fiscal period for %s "
  346. "with offset %d") % (d, c.offset))
  347. period_ids = all_period_ids[p:p + c.duration]
  348. periods = period_obj.browse(cr, uid, period_ids,
  349. context=context)
  350. date_from = periods[0].date_start
  351. date_to = periods[-1].date_stop
  352. else:
  353. raise orm.except_orm(_("Error!"),
  354. _("Unimplemented period type %s") %
  355. (c.type,))
  356. res[c.id] = {
  357. 'date_from': date_from,
  358. 'date_to': date_to,
  359. 'period_from': period_ids and period_ids[0] or False,
  360. 'period_to': period_ids and period_ids[-1] or False,
  361. }
  362. return res
  363. _name = 'mis.report.instance.period'
  364. _columns = {
  365. 'name': fields.char(size=32, required=True,
  366. string='Description', translate=True),
  367. 'type': fields.selection([('d', _('Day')),
  368. ('w', _('Week')),
  369. ('fp', _('Fiscal Period')),
  370. # ('fy', _('Fiscal Year'))
  371. ],
  372. required=True,
  373. string='Period type'),
  374. 'offset': fields.integer(string='Offset',
  375. help='Offset from current period'),
  376. 'duration': fields.integer(string='Duration',
  377. help='Number of periods'),
  378. 'date_from': fields.function(_get_dates,
  379. type='date',
  380. multi="dates",
  381. string="From"),
  382. 'date_to': fields.function(_get_dates,
  383. type='date',
  384. multi="dates",
  385. string="To"),
  386. 'period_from': fields.function(_get_dates,
  387. type='many2one', obj='account.period',
  388. multi="dates", string="From period"),
  389. 'period_to': fields.function(_get_dates,
  390. type='many2one', obj='account.period',
  391. multi="dates", string="To period"),
  392. 'sequence': fields.integer(string='Sequence'),
  393. 'report_instance_id': fields.many2one('mis.report.instance',
  394. string='Report Instance',
  395. ondelete='cascade'),
  396. 'comparison_column_ids': fields.many2many(
  397. 'mis.report.instance.period',
  398. 'mis_report_instance_period_rel',
  399. 'period_id',
  400. 'compare_period_id',
  401. string='Compare with'),
  402. 'company_id': fields.related('report_instance_id', 'company_id',
  403. type="many2one", relation="res.company",
  404. string="Company", readonly=True),
  405. 'normalize_factor': fields.integer(
  406. string='Factor',
  407. help='Factor to use to normalize the period (used in comparison'),
  408. }
  409. _defaults = {
  410. 'offset': -1,
  411. 'duration': 1,
  412. 'sequence': 100,
  413. 'normalize_factor': 1,
  414. }
  415. _order = 'sequence'
  416. _sql_constraints = [
  417. ('duration', 'CHECK (duration>0)',
  418. 'Wrong duration, it must be positive!'),
  419. ('normalize_factor', 'CHECK (normalize_factor>0)',
  420. 'Wrong normalize factor, it must be positive!'),
  421. ('name_unique', 'unique(name, report_instance_id)',
  422. 'Period name should be unique by report'),
  423. ]
  424. def drilldown(self, cr, uid, id, expr, context=None):
  425. this = self.browse(cr, uid, id, context=context)[0]
  426. env = Environment(cr, uid, {})
  427. aep = AccountingExpressionProcessor(env)
  428. aep.parse_expr(expr)
  429. aep.done_parsing([('company_id', '=',
  430. this.report_instance_id.company_id.id)])
  431. domain = aep.get_aml_domain_for_expr(expr)
  432. if domain:
  433. # TODO: reuse compute_period_domain
  434. # compute date/period
  435. period_ids = []
  436. date_from = None
  437. date_to = None
  438. period_obj = self.pool['account.period']
  439. target_move = this.report_instance_id.target_move
  440. if target_move == 'posted':
  441. domain.append(('move_id.state', '=', target_move))
  442. if this.period_from:
  443. compute_period_ids = period_obj.build_ctx_periods(
  444. cr, uid, this.period_from.id, this.period_to.id)
  445. period_ids.extend(compute_period_ids)
  446. else:
  447. date_from = this.date_from
  448. date_to = this.date_to
  449. if period_ids:
  450. if date_from:
  451. domain.append('|')
  452. domain.append(('period_id', 'in', period_ids))
  453. if date_from:
  454. domain.extend([('date', '>=', date_from),
  455. ('date', '<=', date_to)])
  456. return {
  457. 'name': expr + ' - ' + this.name,
  458. 'domain': domain,
  459. 'type': 'ir.actions.act_window',
  460. 'res_model': 'account.move.line',
  461. 'views': [[False, 'list'], [False, 'form']],
  462. 'view_type': 'list',
  463. 'view_mode': 'list',
  464. 'target': 'current',
  465. }
  466. else:
  467. return False
  468. def compute_period_domain(self, cr, uid, period_report, aep, mode,
  469. context=None):
  470. domain = []
  471. target_move = period_report.report_instance_id.target_move
  472. if target_move == 'posted':
  473. domain.append(('move_id.state', '=', target_move))
  474. if not period_report.period_from.id or not period_report.period_to.id:
  475. aml_domain = aep\
  476. .get_aml_domain_for_periods(period_report.date_from,
  477. period_report.date_to,
  478. mode)
  479. domain.extend(aml_domain)
  480. elif period_report.period_from.id and period_report.period_to.id:
  481. aml_domain = aep\
  482. .get_aml_domain_for_periods(period_report.period_from,
  483. period_report.period_to,
  484. mode)
  485. domain.extend(aml_domain)
  486. return domain
  487. def _fetch_queries(self, cr, uid, c, context):
  488. res = {}
  489. report = c.report_instance_id.report_id
  490. for query in report.query_ids:
  491. obj = self.pool[query.model_id.model]
  492. domain = query.domain and safe_eval(query.domain) or []
  493. if query.date_field.ttype == 'date':
  494. domain.extend([(query.date_field.name, '>=', c.date_from),
  495. (query.date_field.name, '<=', c.date_to)])
  496. else:
  497. datetime_from = _utc_midnight(
  498. c.date_from, context.get('tz', 'UTC'))
  499. datetime_to = _utc_midnight(
  500. c.date_to, context.get('tz', 'UTC'), add_day=1)
  501. domain.extend([(query.date_field.name, '>=', datetime_from),
  502. (query.date_field.name, '<', datetime_to)])
  503. if obj._columns.get('company_id', False):
  504. domain.extend(['|', ('company_id', '=', False),
  505. ('company_id', '=', c.company_id.id)])
  506. field_names = [field.name for field in query.field_ids]
  507. obj_ids = obj.search(cr, uid, domain, context=context)
  508. obj_datas = obj.read(
  509. cr, uid, obj_ids, field_names, context=context)
  510. res[query.name] = [AutoStruct(**d) for d in obj_datas]
  511. return res
  512. def _compute(self, cr, uid, lang_id, c, aep, context=None):
  513. if context is None:
  514. context = {}
  515. kpi_obj = self.pool['mis.report.kpi']
  516. res = {}
  517. localdict = {
  518. 'registry': self.pool,
  519. 'sum': sum,
  520. 'min': min,
  521. 'max': max,
  522. 'len': len,
  523. 'avg': lambda l: sum(l) / float(len(l)),
  524. }
  525. domain_p = self.compute_period_domain(cr, uid, c, aep, MODE_VARIATION,
  526. context=context)
  527. domain_e = self.compute_period_domain(cr, uid, c, aep, MODE_END,
  528. context=context)
  529. domain_i = self.compute_period_domain(cr, uid, c, aep, MODE_INITIAL,
  530. context=context)
  531. aep.do_queries(domain_p, domain_i, domain_e)
  532. localdict.update(self._fetch_queries(cr, uid, c,
  533. context=context))
  534. compute_queue = c.report_instance_id.report_id.kpi_ids
  535. recompute_queue = []
  536. while True:
  537. for kpi in compute_queue:
  538. try:
  539. kpi_val_comment = kpi.name + " = " + kpi.expression
  540. kpi_eval_expression = aep.replace_expr(kpi.expression)
  541. kpi_val = safe_eval(kpi_eval_expression, localdict)
  542. except ZeroDivisionError:
  543. kpi_val = None
  544. kpi_val_rendered = '#DIV/0'
  545. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  546. except ValueError:
  547. recompute_queue.append(kpi)
  548. kpi_val = None
  549. kpi_val_rendered = '#ERR'
  550. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  551. except:
  552. kpi_val = None
  553. kpi_val_rendered = '#ERR'
  554. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  555. else:
  556. kpi_val_rendered = kpi_obj._render(
  557. cr, uid, lang_id, kpi, kpi_val, context=context)
  558. localdict[kpi.name] = kpi_val
  559. try:
  560. kpi_style = None
  561. if kpi.css_style:
  562. kpi_style = safe_eval(kpi.css_style, localdict)
  563. except:
  564. kpi_style = None
  565. drilldown = (kpi_val is not None and
  566. bool(aep.get_aml_domain_for_expr(kpi.expression)))
  567. res[kpi.name] = {
  568. 'val': kpi_val,
  569. 'val_r': kpi_val_rendered,
  570. 'val_c': kpi_val_comment,
  571. 'style': kpi_style,
  572. 'default_style': kpi.default_css_style or None,
  573. 'suffix': kpi.suffix,
  574. 'dp': kpi.dp,
  575. 'is_percentage': kpi.type == 'pct',
  576. 'period_id': c.id,
  577. 'expr': kpi.expression,
  578. 'drilldown': drilldown,
  579. }
  580. if len(recompute_queue) == 0:
  581. # nothing to recompute, we are done
  582. break
  583. if len(recompute_queue) == len(compute_queue):
  584. # could not compute anything in this iteration
  585. # (ie real Value errors or cyclic dependency)
  586. # so we stop trying
  587. break
  588. # try again
  589. compute_queue = recompute_queue
  590. recompute_queue = []
  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}