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.

855 lines
33 KiB

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