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.

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