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.

912 lines
36 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
  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # mis_builder module for Odoo, Management Information System Builder
  5. # Copyright (C) 2014-2015 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. import datetime
  25. import dateutil
  26. from dateutil import parser
  27. import logging
  28. import re
  29. import time
  30. import traceback
  31. import pytz
  32. from openerp.osv import orm, fields
  33. from openerp import tools
  34. from openerp.tools.safe_eval import safe_eval
  35. from openerp.tools.translate import _
  36. from .aep import AccountingExpressionProcessor as AEP
  37. _logger = logging.getLogger(__name__)
  38. class AutoStruct(object):
  39. def __init__(self, **kwargs):
  40. for k, v in kwargs.items():
  41. setattr(self, k, v)
  42. def _get_selection_label(selection, value):
  43. for v, l in selection:
  44. if v == value:
  45. return l
  46. return ''
  47. def _utc_midnight(d, tz_name, add_day=0):
  48. d = datetime.datetime.strptime(d, tools.DEFAULT_SERVER_DATE_FORMAT)
  49. utc_tz = pytz.timezone('UTC')
  50. if add_day:
  51. d = d + datetime.timedelta(days=add_day)
  52. context_tz = pytz.timezone(tz_name)
  53. local_timestamp = context_tz.localize(d, is_dst=False)
  54. return datetime.datetime.strftime(local_timestamp.astimezone(utc_tz))
  55. def _python_var(var_str):
  56. return re.sub(r'\W|^(?=\d)', '_', var_str).lower()
  57. def _is_valid_python_var(name):
  58. return re.match("[_A-Za-z][_a-zA-Z0-9]*$", name)
  59. def _sum(l):
  60. if not l:
  61. return None
  62. return sum(l)
  63. def _avg(l):
  64. if not l:
  65. return None
  66. return sum(l) / float(len(l))
  67. def _min(l):
  68. if not l:
  69. return None
  70. return min(l)
  71. def _max(l):
  72. if not l:
  73. return None
  74. return max(l)
  75. class MisReportKpi(orm.Model):
  76. """ A KPI is an element (ie a line) of a MIS report.
  77. In addition to a name and description, it has an expression
  78. to compute it based on queries defined in the MIS report.
  79. It also has various informations defining how to render it
  80. (numeric or percentage or a string, a suffix, divider) and
  81. how to render comparison of two values of the KPI.
  82. KPI's have a sequence and are ordered inside the MIS report.
  83. """
  84. _name = 'mis.report.kpi'
  85. _columns = {
  86. 'name': fields.char(size=32, required=True,
  87. string='Name'),
  88. 'description': fields.char(required=True,
  89. string='Description',
  90. translate=True),
  91. 'expression': fields.char(required=True,
  92. string='Expression'),
  93. 'default_css_style': fields.char(
  94. string='Default CSS style'),
  95. 'css_style': fields.char(string='CSS style expression'),
  96. 'type': fields.selection([('num', _('Numeric')),
  97. ('pct', _('Percentage')),
  98. ('str', _('String'))],
  99. required=True,
  100. string='Type'),
  101. 'divider': fields.selection([('1e-6', _('µ')),
  102. ('1e-3', _('m')),
  103. ('1', _('1')),
  104. ('1e3', _('k')),
  105. ('1e6', _('M'))],
  106. string='Factor'),
  107. 'dp': fields.integer(string='Rounding'),
  108. 'suffix': fields.char(size=16, string='Suffix'),
  109. 'compare_method': fields.selection([('diff', _('Difference')),
  110. ('pct', _('Percentage')),
  111. ('none', _('None'))],
  112. required=True,
  113. string='Comparison Method'),
  114. 'sequence': fields.integer(string='Sequence'),
  115. 'report_id': fields.many2one('mis.report', string='Report'),
  116. }
  117. _defaults = {
  118. 'type': 'num',
  119. 'divider': '1',
  120. 'dp': 0,
  121. 'compare_method': 'pct',
  122. 'sequence': 100,
  123. }
  124. _order = 'sequence, id'
  125. def _check_name(self, cr, uid, ids, context=None):
  126. for record_name in self.read(cr, uid, ids, ['name']):
  127. if not _is_valid_python_var(record_name['name']):
  128. return False
  129. return True
  130. _constraints = [
  131. (_check_name, 'The name must be a valid python identifier', ['name']),
  132. ]
  133. def onchange_name(self, cr, uid, ids, name, context=None):
  134. res = {}
  135. if name and not _is_valid_python_var(name):
  136. res['warning'] = {
  137. 'title': 'Invalid name %s' % name,
  138. 'message': 'The name must be a valid python identifier'}
  139. return res
  140. def onchange_description(self, cr, uid, ids, description, name,
  141. context=None):
  142. """ construct name from description """
  143. res = {}
  144. if description and not name:
  145. res = {'value': {'name': _python_var(description)}}
  146. return res
  147. def onchange_type(self, cr, uid, ids, kpi_type, context=None):
  148. res = {}
  149. if kpi_type == 'num':
  150. res['value'] = {
  151. 'compare_method': 'pct',
  152. 'divider': '1',
  153. 'dp': 0
  154. }
  155. elif kpi_type == 'pct':
  156. res['value'] = {
  157. 'compare_method': 'diff',
  158. 'divider': '1',
  159. 'dp': 0
  160. }
  161. elif kpi_type == 'str':
  162. res['value'] = {
  163. 'compare_method': 'none',
  164. 'divider': '',
  165. 'dp': 0
  166. }
  167. return res
  168. def render(self, cr, uid, lang_id, kpi, value, context=None):
  169. if value is None:
  170. return '#N/A'
  171. if kpi.type == 'num':
  172. return self._render_num(cr, uid, lang_id, value, kpi.divider,
  173. kpi.dp, kpi.suffix, context=context)
  174. elif kpi.type == 'pct':
  175. return self._render_num(cr, uid, lang_id, value, 0.01,
  176. kpi.dp, '%', context=context)
  177. else:
  178. return unicode(value)
  179. def _render_comparison(self, cr, uid, lang_id, kpi, value, base_value,
  180. average_value, average_base_value, context=None):
  181. """ render the comparison of two KPI values, ready for display """
  182. if value is None or base_value is None:
  183. return ''
  184. if kpi.type == 'pct':
  185. return self._render_num(cr, uid, lang_id, value - base_value, 0.01,
  186. kpi.dp, _('pp'), sign='+', context=context)
  187. elif kpi.type == 'num':
  188. if average_value:
  189. value = value / float(average_value)
  190. if average_base_value:
  191. base_value = base_value / float(average_base_value)
  192. if kpi.compare_method == 'diff':
  193. return self._render_num(cr, uid, lang_id, value - base_value,
  194. kpi.divider,
  195. kpi.dp, kpi.suffix, sign='+',
  196. context=context)
  197. elif kpi.compare_method == 'pct':
  198. if round(base_value, kpi.dp) != 0:
  199. return self._render_num(
  200. cr, uid, lang_id,
  201. (value - base_value) / abs(base_value),
  202. 0.01, kpi.dp, '%', sign='+', context=context)
  203. return ''
  204. def _render_num(self, cr, uid, lang_id, value, divider,
  205. dp, suffix, sign='-', context=None):
  206. divider_label = _get_selection_label(
  207. self._columns['divider'].selection, divider)
  208. if divider_label == '1':
  209. divider_label = ''
  210. # format number following user language
  211. value = round(value / float(divider or 1), dp) or 0
  212. value = self.pool['res.lang'].format(
  213. cr, uid, lang_id,
  214. '%%%s.%df' % (sign, dp),
  215. value,
  216. grouping=True,
  217. context=context)
  218. value = u'%s\N{NO-BREAK SPACE}%s%s' % \
  219. (value, divider_label, suffix or '')
  220. value = value.replace('-', u'\N{NON-BREAKING HYPHEN}')
  221. return value
  222. class MisReportQuery(orm.Model):
  223. """ A query to fetch arbitrary data for a MIS report.
  224. A query works on a model and has a domain and list of fields to fetch.
  225. At runtime, the domain is expanded with a "and" on the date/datetime field.
  226. """
  227. _name = 'mis.report.query'
  228. def _get_field_names(self, cr, uid, ids, name, args, context=None):
  229. res = {}
  230. for query in self.browse(cr, uid, ids, context=context):
  231. field_names = []
  232. for field in query.field_ids:
  233. field_names.append(field.name)
  234. res[query.id] = ', '.join(field_names)
  235. return res
  236. def onchange_field_ids(self, cr, uid, ids, field_ids, context=None):
  237. # compute field_names
  238. field_names = []
  239. for field in self.pool.get('ir.model.fields').read(
  240. cr, uid,
  241. field_ids[0][2],
  242. ['name'],
  243. context=context):
  244. field_names.append(field['name'])
  245. return {'value': {'field_names': ', '.join(field_names)}}
  246. _columns = {
  247. 'name': fields.char(size=32, required=True,
  248. string='Name'),
  249. 'model_id': fields.many2one('ir.model', required=True,
  250. string='Model'),
  251. 'field_ids': fields.many2many('ir.model.fields', required=True,
  252. string='Fields to fetch'),
  253. 'field_names': fields.function(_get_field_names, type='char',
  254. string='Fetched fields name',
  255. store={'mis.report.query':
  256. (lambda self, cr, uid, ids, c={}:
  257. ids, ['field_ids'], 20), }),
  258. 'aggregate': fields.selection([('sum', _('Sum')),
  259. ('avg', _('Average')),
  260. ('min', _('Min')),
  261. ('max', _('Max'))],
  262. string='Aggregate'),
  263. 'date_field': fields.many2one('ir.model.fields', required=True,
  264. string='Date field',
  265. domain=[('ttype', 'in',
  266. ('date', 'datetime'))]),
  267. 'domain': fields.char(string='Domain'),
  268. 'report_id': fields.many2one('mis.report', string='Report',
  269. ondelete='cascade'),
  270. }
  271. _order = 'name'
  272. def _check_name(self, cr, uid, ids, context=None):
  273. for record_name in self.read(cr, uid, ids, ['name']):
  274. if not _is_valid_python_var(record_name['name']):
  275. return False
  276. return True
  277. _constraints = [
  278. (_check_name, 'The name must be a valid python identifier', ['name']),
  279. ]
  280. class MisReport(orm.Model):
  281. """ A MIS report template (without period information)
  282. The MIS report holds:
  283. * a list of explicit queries; the result of each query is
  284. stored in a variable with same name as a query, containing as list
  285. of data structures populated with attributes for each fields to fetch;
  286. when queries have an aggregate method and no fields to group, it returns
  287. a data structure with the aggregated fields
  288. * a list of KPI to be evaluated based on the variables resulting
  289. from the accounting data and queries (KPI expressions can references
  290. queries and accounting expression - see AccoutingExpressionProcessor)
  291. """
  292. _name = 'mis.report'
  293. _columns = {
  294. 'name': fields.char(size=32, required=True,
  295. string='Name', translate=True),
  296. 'description': fields.char(required=False,
  297. string='Description', translate=True),
  298. 'query_ids': fields.one2many('mis.report.query', 'report_id',
  299. string='Queries'),
  300. 'kpi_ids': fields.one2many('mis.report.kpi', 'report_id',
  301. string='KPI\'s'),
  302. }
  303. # TODO: kpi name cannot be start with query name
  304. def create(self, cr, uid, vals, context=None):
  305. # TODO: explain this
  306. if 'kpi_ids' in vals:
  307. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  308. for idx, line in enumerate(vals['kpi_ids']):
  309. if line[0] == 0:
  310. line[2]['sequence'] = idx + 1
  311. else:
  312. mis_report_kpi_obj.write(
  313. cr, uid, [line[1]], {'sequence': idx + 1},
  314. context=context)
  315. return super(MisReport, self).create(cr, uid, vals, context=context)
  316. def write(self, cr, uid, ids, vals, context=None):
  317. # TODO: explain this
  318. res = super(MisReport, self).write(
  319. cr, uid, ids, vals, context=context)
  320. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  321. for report in self.browse(cr, uid, ids, context):
  322. for idx, kpi in enumerate(report.kpi_ids):
  323. mis_report_kpi_obj.write(
  324. cr, uid, [kpi.id], {'sequence': idx + 1}, context=context)
  325. return res
  326. class MisReportInstancePeriod(orm.Model):
  327. """ A MIS report instance has the logic to compute
  328. a report template for a given date period.
  329. Periods have a duration (day, week, fiscal period) and
  330. are defined as an offset relative to a pivot date.
  331. """
  332. def _get_dates(self, cr, uid, ids, field_names, arg, context=None):
  333. if isinstance(ids, (int, long)):
  334. ids = [ids]
  335. res = {}
  336. for c in self.browse(cr, uid, ids, context=context):
  337. period_ids = None
  338. valid = True
  339. date_from = False
  340. date_to = False
  341. d = parser.parse(c.report_instance_id.pivot_date)
  342. if c.type == 'd':
  343. date_from = d + datetime.timedelta(days=c.offset)
  344. date_to = date_from + datetime.timedelta(days=c.duration - 1)
  345. date_from = date_from.strftime(
  346. tools.DEFAULT_SERVER_DATE_FORMAT)
  347. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  348. elif c.type == 'w':
  349. date_from = d - datetime.timedelta(d.weekday())
  350. date_from = date_from + datetime.timedelta(days=c.offset * 7)
  351. date_to = date_from + datetime.timedelta(
  352. days=(7 * c.duration) - 1)
  353. date_from = date_from.strftime(
  354. tools.DEFAULT_SERVER_DATE_FORMAT)
  355. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  356. elif c.type == 'fp':
  357. period_obj = self.pool['account.period']
  358. current_period_ids = period_obj.search(
  359. cr, uid,
  360. [('special', '=', False),
  361. ('date_start', '<=', d),
  362. ('date_stop', '>=', d),
  363. ('company_id', '=', c.company_id.id)],
  364. context=context)
  365. if current_period_ids:
  366. all_period_ids = period_obj.search(
  367. cr, uid,
  368. [('special', '=', False),
  369. ('company_id', '=', c.company_id.id)],
  370. order='date_start',
  371. context=context)
  372. p = all_period_ids.index(current_period_ids[0]) + \
  373. c.offset
  374. if p >= 0 and p + c.duration <= len(all_period_ids):
  375. period_ids = all_period_ids[p:p + c.duration]
  376. periods = period_obj.browse(cr, uid, period_ids,
  377. context=context)
  378. date_from = periods[0].date_start
  379. date_to = periods[-1].date_stop
  380. res[c.id] = {
  381. 'date_from': date_from,
  382. 'date_to': date_to,
  383. 'period_from': period_ids and period_ids[0] or False,
  384. 'period_to': period_ids and period_ids[-1] or False,
  385. 'valid': valid,
  386. }
  387. return res
  388. _name = 'mis.report.instance.period'
  389. _columns = {
  390. 'name': fields.char(size=32, required=True,
  391. string='Description', translate=True),
  392. 'type': fields.selection([('d', _('Day')),
  393. ('w', _('Week')),
  394. ('fp', _('Fiscal Period')),
  395. # ('fy', _('Fiscal Year'))
  396. ],
  397. required=True,
  398. string='Period type'),
  399. 'offset': fields.integer(string='Offset',
  400. help='Offset from current period'),
  401. 'duration': fields.integer(string='Duration',
  402. help='Number of periods'),
  403. 'date_from': fields.function(_get_dates,
  404. type='date',
  405. multi="dates",
  406. string="From"),
  407. 'date_to': fields.function(_get_dates,
  408. type='date',
  409. multi="dates",
  410. string="To"),
  411. 'period_from': fields.function(_get_dates,
  412. type='many2one', obj='account.period',
  413. multi="dates", string="From period"),
  414. 'period_to': fields.function(_get_dates,
  415. type='many2one', obj='account.period',
  416. multi="dates", string="To period"),
  417. 'valid': fields.function(_get_dates,
  418. type='boolean',
  419. multi="dates",
  420. string='Valid'),
  421. 'sequence': fields.integer(string='Sequence'),
  422. 'report_instance_id': fields.many2one('mis.report.instance',
  423. string='Report Instance',
  424. ondelete='cascade'),
  425. 'comparison_column_ids': fields.many2many(
  426. 'mis.report.instance.period',
  427. 'mis_report_instance_period_rel',
  428. 'period_id',
  429. 'compare_period_id',
  430. string='Compare with'),
  431. 'company_id': fields.related('report_instance_id', 'company_id',
  432. type="many2one", relation="res.company",
  433. string="Company", readonly=True),
  434. 'normalize_factor': fields.integer(
  435. string='Factor',
  436. help='Factor to use to normalize the period (used in comparison'),
  437. }
  438. _defaults = {
  439. 'offset': -1,
  440. 'duration': 1,
  441. 'sequence': 100,
  442. 'normalize_factor': 1,
  443. }
  444. _order = 'sequence, id'
  445. _sql_constraints = [
  446. ('duration', 'CHECK (duration>0)',
  447. 'Wrong duration, it must be positive!'),
  448. ('normalize_factor', 'CHECK (normalize_factor>0)',
  449. 'Wrong normalize factor, it must be positive!'),
  450. ('name_unique', 'unique(name, report_instance_id)',
  451. 'Period name should be unique by report'),
  452. ]
  453. def drilldown(self, cr, uid, _id, expr, context=None):
  454. this = self.browse(cr, uid, _id, context=context)
  455. if AEP.has_account_var(expr):
  456. aep = AEP(cr)
  457. aep.parse_expr(expr)
  458. aep.done_parsing(cr, uid, this.report_instance_id.root_account,
  459. context=context)
  460. domain = aep.get_aml_domain_for_expr(
  461. cr, uid, expr,
  462. this.date_from, this.date_to,
  463. this.period_from, this.period_to,
  464. this.report_instance_id.target_move,
  465. context=context)
  466. return {
  467. 'name': expr + ' - ' + this.name,
  468. 'domain': domain,
  469. 'type': 'ir.actions.act_window',
  470. 'res_model': 'account.move.line',
  471. 'views': [[False, 'list'], [False, 'form']],
  472. 'view_type': 'list',
  473. 'view_mode': 'list',
  474. 'target': 'current',
  475. }
  476. else:
  477. return False
  478. def _fetch_queries(self, cr, uid, c, context):
  479. res = {}
  480. report = c.report_instance_id.report_id
  481. query_obj = self.pool['mis.report.query']
  482. for query in report.query_ids:
  483. obj = self.pool[query.model_id.model]
  484. eval_context = {
  485. 'time': time,
  486. 'datetime': datetime,
  487. 'dateutil': dateutil,
  488. # deprecated
  489. 'uid': uid,
  490. 'context': context,
  491. }
  492. if not c.date_from or not c.date_to:
  493. raise orm.except_orm(_('Error!'),
  494. _('Please define From and To dates for '
  495. 'period %s.') % c.name)
  496. domain = query.domain and \
  497. safe_eval(query.domain, eval_context) or []
  498. domain.extend(query_obj._get_additional_filter(cr, uid,
  499. query.id,
  500. context=context))
  501. if query.date_field.ttype == 'date':
  502. domain.extend([(query.date_field.name, '>=', c.date_from),
  503. (query.date_field.name, '<=', c.date_to)])
  504. else:
  505. tz = context.get('tz', False) or 'UTC'
  506. datetime_from = _utc_midnight(
  507. c.date_from, tz)
  508. datetime_to = _utc_midnight(
  509. c.date_to, tz, add_day=1)
  510. domain.extend([(query.date_field.name, '>=', datetime_from),
  511. (query.date_field.name, '<', datetime_to)])
  512. if obj._columns.get('company_id', False):
  513. domain.extend(['|', ('company_id', '=', False),
  514. ('company_id', '=', c.company_id.id)])
  515. field_names = [f.name for f in query.field_ids]
  516. if not query.aggregate:
  517. obj_ids = obj.search(cr, uid, domain, context=context)
  518. data = obj.read(
  519. cr, uid, obj_ids, field_names, context=context)
  520. res[query.name] = [AutoStruct(**d) for d in data]
  521. elif query.aggregate == 'sum':
  522. data = obj.read_group(
  523. cr, uid, domain, field_names, '', context=context)
  524. s = AutoStruct(count=data[0]['_count'])
  525. for field_name in field_names:
  526. v = data[0][field_name]
  527. setattr(s, field_name, v)
  528. res[query.name] = s
  529. else:
  530. obj_ids = obj.search(cr, uid, domain, context=context)
  531. data = obj.read(
  532. cr, uid, obj_ids, field_names, context=context)
  533. s = AutoStruct(count=len(data))
  534. if query.aggregate == 'min':
  535. agg = min
  536. elif query.aggregate == 'max':
  537. agg = max
  538. elif query.aggregate == 'avg':
  539. agg = lambda l: sum(l) / float(len(l))
  540. for field_name in field_names:
  541. setattr(s, field_name,
  542. agg([d[field_name] for d in data]))
  543. res[query.name] = s
  544. return res
  545. def _compute(self, cr, uid, lang_id, c, aep, context=None):
  546. if context is None:
  547. context = {}
  548. kpi_obj = self.pool['mis.report.kpi']
  549. res = {}
  550. localdict = {
  551. 'registry': self.pool,
  552. 'sum': _sum,
  553. 'min': _min,
  554. 'max': _max,
  555. 'len': len,
  556. 'avg': _avg,
  557. }
  558. localdict.update(self._fetch_queries(cr, uid, c, context=context))
  559. aep.do_queries(cr, uid, c.date_from, c.date_to,
  560. c.period_from, c.period_to,
  561. c.report_instance_id.target_move,
  562. context=context)
  563. compute_queue = c.report_instance_id.report_id.kpi_ids
  564. recompute_queue = []
  565. while True:
  566. for kpi in compute_queue:
  567. try:
  568. kpi_val_comment = kpi.name + " = " + kpi.expression
  569. kpi_eval_expression = aep.replace_expr(kpi.expression)
  570. kpi_val = safe_eval(kpi_eval_expression, localdict)
  571. except ZeroDivisionError:
  572. kpi_val = None
  573. kpi_val_rendered = '#DIV/0'
  574. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  575. except (NameError, ValueError):
  576. recompute_queue.append(kpi)
  577. kpi_val = None
  578. kpi_val_rendered = '#ERR'
  579. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  580. except:
  581. kpi_val = None
  582. kpi_val_rendered = '#ERR'
  583. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  584. else:
  585. kpi_val_rendered = kpi_obj.render(
  586. cr, uid, lang_id, kpi, kpi_val, context=context)
  587. localdict[kpi.name] = kpi_val
  588. try:
  589. kpi_style = None
  590. if kpi.css_style:
  591. kpi_style = safe_eval(kpi.css_style, localdict)
  592. except:
  593. _logger.warning("error evaluating css stype expression %s",
  594. kpi.css_style, exc_info=True)
  595. kpi_style = None
  596. drilldown = (kpi_val is not None and
  597. AEP.has_account_var(kpi.expression))
  598. res[kpi.name] = {
  599. 'val': kpi_val,
  600. 'val_r': kpi_val_rendered,
  601. 'val_c': kpi_val_comment,
  602. 'style': kpi_style,
  603. 'default_style': kpi.default_css_style or None,
  604. 'suffix': kpi.suffix,
  605. 'dp': kpi.dp,
  606. 'is_percentage': kpi.type == 'pct',
  607. 'period_id': c.id,
  608. 'expr': kpi.expression,
  609. 'drilldown': drilldown,
  610. }
  611. if len(recompute_queue) == 0:
  612. # nothing to recompute, we are done
  613. break
  614. if len(recompute_queue) == len(compute_queue):
  615. # could not compute anything in this iteration
  616. # (ie real Value errors or cyclic dependency)
  617. # so we stop trying
  618. break
  619. # try again
  620. compute_queue = recompute_queue
  621. recompute_queue = []
  622. return res
  623. class MisReportInstance(orm.Model):
  624. """The MIS report instance combines everything to compute
  625. a MIS report template for a set of periods."""
  626. def _compute_pivot_date(self, cr, uid, ids, field_name, arg, context=None):
  627. res = {}
  628. for r in self.browse(cr, uid, ids, context=context):
  629. if r.date:
  630. res[r.id] = r.date
  631. else:
  632. res[r.id] = fields.date.context_today(self, cr, uid,
  633. context=context)
  634. return res
  635. _name = 'mis.report.instance'
  636. _columns = {
  637. 'name': fields.char(size=32, required=True,
  638. string='Name', translate=True),
  639. 'description': fields.char(required=False,
  640. string='Description', translate=True),
  641. 'date': fields.date(string='Base date',
  642. help='Report base date '
  643. '(leave empty to use current date)'),
  644. 'pivot_date': fields.function(_compute_pivot_date,
  645. type='date',
  646. string="Pivot date"),
  647. 'report_id': fields.many2one('mis.report',
  648. required=True,
  649. string='Report'),
  650. 'period_ids': fields.one2many('mis.report.instance.period',
  651. 'report_instance_id',
  652. required=True,
  653. string='Periods'),
  654. 'target_move': fields.selection([('posted', 'All Posted Entries'),
  655. ('all', 'All Entries'),
  656. ], 'Target Moves', required=True),
  657. 'company_id': fields.related('root_account', 'company_id',
  658. type='many2one', relation='res.company',
  659. string='Company', readonly=True,
  660. store=True),
  661. 'root_account': fields.many2one('account.account',
  662. domain='[("parent_id", "=", False)]',
  663. string="Account chart",
  664. required=True),
  665. 'landscape_pdf': fields.boolean(string='Landscape PDF')
  666. }
  667. _defaults = {
  668. 'target_move': 'posted',
  669. }
  670. def create(self, cr, uid, vals, context=None):
  671. if not vals:
  672. return context.get('active_id', None)
  673. # TODO: explain this
  674. if 'period_ids' in vals:
  675. mis_report_instance_period_obj = self.pool.get(
  676. 'mis.report.instance.period')
  677. for idx, line in enumerate(vals['period_ids']):
  678. if line[0] == 0:
  679. line[2]['sequence'] = idx + 1
  680. else:
  681. mis_report_instance_period_obj.write(
  682. cr, uid, [line[1]], {'sequence': idx + 1},
  683. context=context)
  684. return super(MisReportInstance, self).create(cr, uid, vals,
  685. context=context)
  686. def write(self, cr, uid, ids, vals, context=None):
  687. # TODO: explain this
  688. res = super(MisReportInstance, self).write(
  689. cr, uid, ids, vals, context=context)
  690. mis_report_instance_period_obj = self.pool.get(
  691. 'mis.report.instance.period')
  692. for instance in self.browse(cr, uid, ids, context):
  693. for idx, period in enumerate(instance.period_ids):
  694. mis_report_instance_period_obj.write(
  695. cr, uid, [period.id], {'sequence': idx + 1},
  696. context=context)
  697. return res
  698. def preview(self, cr, uid, ids, context=None):
  699. assert len(ids) == 1
  700. view_id = self.pool['ir.model.data'].get_object_reference(
  701. cr, uid, 'mis_builder',
  702. 'mis_report_instance_result_view_form')[1]
  703. return {
  704. 'type': 'ir.actions.act_window',
  705. 'res_model': 'mis.report.instance',
  706. 'res_id': ids[0],
  707. 'view_mode': 'form',
  708. 'view_type': 'form',
  709. 'view_id': view_id,
  710. 'target': 'new',
  711. }
  712. def _format_date(self, cr, uid, lang_id, date, context=None):
  713. # format date following user language
  714. tformat = self.pool['res.lang'].read(
  715. cr, uid, lang_id, ['date_format'])[0]['date_format']
  716. date = datetime.datetime.strptime(date,
  717. tools.DEFAULT_SERVER_DATE_FORMAT)
  718. return date.strftime(tformat)
  719. def compute(self, cr, uid, _id, context=None):
  720. assert isinstance(_id, (int, long))
  721. if context is None:
  722. context = {}
  723. r = self.browse(cr, uid, _id, context=context)
  724. # prepare AccountingExpressionProcessor
  725. aep = AEP(cr)
  726. for kpi in r.report_id.kpi_ids:
  727. aep.parse_expr(kpi.expression)
  728. aep.done_parsing(cr, uid, r.root_account, context=context)
  729. report_instance_period_obj = self.pool['mis.report.instance.period']
  730. kpi_obj = self.pool.get('mis.report.kpi')
  731. # fetch user language only once
  732. # TODO: is this necessary?
  733. lang = self.pool['res.users'].read(
  734. cr, uid, uid, ['lang'], context=context)['lang']
  735. if not lang:
  736. lang = 'en_US'
  737. lang_id = self.pool['res.lang'].search(
  738. cr, uid, [('code', '=', lang)], context=context)
  739. # compute kpi values for each period
  740. kpi_values_by_period_ids = {}
  741. for period in r.period_ids:
  742. if not period.valid:
  743. continue
  744. kpi_values = report_instance_period_obj._compute(
  745. cr, uid, lang_id, period, aep, context=context)
  746. kpi_values_by_period_ids[period.id] = kpi_values
  747. # prepare header and content
  748. header = []
  749. header.append({
  750. 'kpi_name': '',
  751. 'cols': []
  752. })
  753. content = []
  754. rows_by_kpi_name = {}
  755. for kpi in r.report_id.kpi_ids:
  756. rows_by_kpi_name[kpi.name] = {
  757. 'kpi_name': kpi.description,
  758. 'cols': [],
  759. 'default_style': kpi.default_css_style
  760. }
  761. content.append(rows_by_kpi_name[kpi.name])
  762. # populate header and content
  763. for period in r.period_ids:
  764. if not period.valid:
  765. continue
  766. # add the column header
  767. if period.duration > 1 or period.type == 'w':
  768. # from, to
  769. if period.period_from and period.period_to:
  770. date_from = period.period_from.name
  771. date_to = period.period_to.name
  772. else:
  773. date_from = self._format_date(
  774. cr, uid, lang_id, period.date_from)
  775. date_to = self._format_date(
  776. cr, uid, lang_id, period.date_to)
  777. header_date = _('from %s to %s') % (date_from, date_to)
  778. else:
  779. # one period or one day
  780. if period.period_from and period.period_to:
  781. header_date = period.period_from.name
  782. else:
  783. header_date = self._format_date(
  784. cr, uid, lang_id, period.date_from)
  785. header[0]['cols'].append(dict(name=period.name, date=header_date))
  786. # add kpi values
  787. kpi_values = kpi_values_by_period_ids[period.id]
  788. for kpi_name in kpi_values:
  789. rows_by_kpi_name[kpi_name]['cols'].append(kpi_values[kpi_name])
  790. # add comparison columns
  791. for compare_col in period.comparison_column_ids:
  792. compare_kpi_values = \
  793. kpi_values_by_period_ids.get(compare_col.id)
  794. if compare_kpi_values:
  795. # add the comparison column header
  796. header[0]['cols'].append(
  797. dict(name=_('%s vs %s') % (period.name,
  798. compare_col.name),
  799. date=''))
  800. # add comparison values
  801. for kpi in r.report_id.kpi_ids:
  802. rows_by_kpi_name[kpi.name]['cols'].append({
  803. 'val_r': kpi_obj._render_comparison(
  804. cr,
  805. uid,
  806. lang_id,
  807. kpi,
  808. kpi_values[kpi.name]['val'],
  809. compare_kpi_values[kpi.name]['val'],
  810. period.normalize_factor,
  811. compare_col.normalize_factor,
  812. context=context)
  813. })
  814. return {'header': header,
  815. 'content': content}