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.

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