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.

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