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.

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