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.

874 lines
34 KiB

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