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.

866 lines
35 KiB

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