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.

768 lines
31 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # mis_builder module for Odoo, Management Information System Builder
  5. # Copyright (C) 2014-2015 ACSONE SA/NV (<http://acsone.eu>)
  6. #
  7. # This file is a part of mis_builder
  8. #
  9. # mis_builder is free software: you can redistribute it and/or modify
  10. # it under the terms of the GNU Affero General Public License v3 or later
  11. # as published by the Free Software Foundation, either version 3 of the
  12. # License, or (at your option) any later version.
  13. #
  14. # mis_builder is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU Affero General Public License v3 or later for more details.
  18. #
  19. # You should have received a copy of the GNU Affero General Public License
  20. # v3 or later along with this program.
  21. # If not, see <http://www.gnu.org/licenses/>.
  22. #
  23. ##############################################################################
  24. from 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. }
  99. _defaults = {
  100. 'type': 'num',
  101. 'divider': '1',
  102. 'dp': 0,
  103. 'compare_method': 'pct',
  104. 'sequence': 100,
  105. }
  106. _order = 'sequence'
  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'
  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. this = self.browse(cr, uid, _id, context=context)[0]
  398. env = Environment(cr, uid, {})
  399. aep = AccountingExpressionProcessor(env)
  400. if aep.has_account_var(expr):
  401. aep.parse_expr(expr)
  402. aep.done_parsing(this.report_instance_id.root_account)
  403. domain = aep.get_aml_domain_for_expr(
  404. expr, this.date_from, this.date_to,
  405. this.period_from, this.period_to,
  406. this.report_instance_id.target_move)
  407. return {
  408. 'name': expr + ' - ' + this.name,
  409. 'domain': domain,
  410. 'type': 'ir.actions.act_window',
  411. 'res_model': 'account.move.line',
  412. 'views': [[False, 'list'], [False, 'form']],
  413. 'view_type': 'list',
  414. 'view_mode': 'list',
  415. 'target': 'current',
  416. }
  417. else:
  418. return False
  419. def _fetch_queries(self, cr, uid, c, context):
  420. res = {}
  421. report = c.report_instance_id.report_id
  422. for query in report.query_ids:
  423. obj = self.pool[query.model_id.model]
  424. domain = query.domain and safe_eval(query.domain) or []
  425. if query.date_field.ttype == 'date':
  426. domain.extend([(query.date_field.name, '>=', c.date_from),
  427. (query.date_field.name, '<=', c.date_to)])
  428. else:
  429. datetime_from = _utc_midnight(
  430. c.date_from, context.get('tz', 'UTC'))
  431. datetime_to = _utc_midnight(
  432. c.date_to, context.get('tz', 'UTC'), add_day=1)
  433. domain.extend([(query.date_field.name, '>=', datetime_from),
  434. (query.date_field.name, '<', datetime_to)])
  435. if obj._columns.get('company_id'):
  436. domain.extend(['|', ('company_id', '=', False),
  437. ('company_id', '=', c.company_id.id)])
  438. field_names = [f.name for f in query.field_ids]
  439. if not query.aggregate:
  440. obj_ids = obj.search(cr, uid, domain, context=context)
  441. obj_datas = obj.read(
  442. cr, uid, obj_ids, field_names, context=context)
  443. res[query.name] = [AutoStruct(**d) for d in obj_datas]
  444. elif query.aggregate == 'sum':
  445. obj_datas = obj.read_group(
  446. cr, uid, domain, field_names, [], context=context)
  447. s = AutoStruct(count=obj_datas[0]['__count'])
  448. for field_name in field_names:
  449. setattr(s, field_name, obj_datas[0][field_name])
  450. res[query.name] = s
  451. else:
  452. obj_ids = obj.search(cr, uid, domain, context=context)
  453. obj_datas = obj.read(
  454. cr, uid, obj_ids, field_names, context=context)
  455. s = AutoStruct(count=len(obj_datas))
  456. if query.aggregate == 'min':
  457. agg = min
  458. elif query.aggregate == 'max':
  459. agg = max
  460. elif query.aggregate == 'avg':
  461. agg = lambda l: sum(l) / float(len(l))
  462. for field_name in field_names:
  463. setattr(s, field_name,
  464. agg([d[field_name] for d in obj_datas]))
  465. res[query.name] = s
  466. return res
  467. def _compute(self, cr, uid, lang_id, c, aep, context=None):
  468. if context is None:
  469. context = {}
  470. kpi_obj = self.pool['mis.report.kpi']
  471. res = {}
  472. localdict = {
  473. 'registry': self.pool,
  474. 'sum': sum,
  475. 'min': min,
  476. 'max': max,
  477. 'len': len,
  478. 'avg': lambda l: sum(l) / float(len(l)),
  479. }
  480. localdict.update(self._fetch_queries(cr, uid, c,
  481. context=context))
  482. aep.do_queries(c.date_from, c.date_to,
  483. c.period_from, c.period_to,
  484. c.report_instance_id.target_move)
  485. compute_queue = c.report_instance_id.report_id.kpi_ids
  486. recompute_queue = []
  487. while True:
  488. for kpi in compute_queue:
  489. try:
  490. kpi_val_comment = kpi.name + " = " + kpi.expression
  491. kpi_eval_expression = aep.replace_expr(kpi.expression)
  492. kpi_val = safe_eval(kpi_eval_expression, localdict)
  493. except ZeroDivisionError:
  494. kpi_val = None
  495. kpi_val_rendered = '#DIV/0'
  496. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  497. except (NameError, ValueError):
  498. recompute_queue.append(kpi)
  499. kpi_val = None
  500. kpi_val_rendered = '#ERR'
  501. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  502. except:
  503. kpi_val = None
  504. kpi_val_rendered = '#ERR'
  505. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  506. else:
  507. kpi_val_rendered = kpi_obj._render(
  508. cr, uid, lang_id, kpi, kpi_val, context=context)
  509. localdict[kpi.name] = kpi_val
  510. try:
  511. kpi_style = None
  512. if kpi.css_style:
  513. kpi_style = safe_eval(kpi.css_style, localdict)
  514. except:
  515. kpi_style = None
  516. drilldown = (kpi_val is not None and
  517. aep.has_account_var(kpi.expression))
  518. res[kpi.name] = {
  519. 'val': kpi_val,
  520. 'val_r': kpi_val_rendered,
  521. 'val_c': kpi_val_comment,
  522. 'style': kpi_style,
  523. 'default_style': kpi.default_css_style or None,
  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. r = self.browse(cr, uid, _id, context=context)
  615. content = OrderedDict()
  616. # empty line name for header
  617. header = OrderedDict()
  618. header[''] = {'kpi_name': '', 'cols': [], 'default_style': ''}
  619. env = Environment(cr, uid, {})
  620. aep = AccountingExpressionProcessor(env)
  621. # initialize lines with kpi
  622. for kpi in r.report_id.kpi_ids:
  623. aep.parse_expr(kpi.expression)
  624. content[kpi.name] = {'kpi_name': kpi.description,
  625. 'cols': [],
  626. 'default_style': ''}
  627. aep.done_parsing(r.root_account)
  628. report_instance_period_obj = self.pool.get(
  629. 'mis.report.instance.period')
  630. kpi_obj = self.pool.get('mis.report.kpi')
  631. period_values = {}
  632. lang = self.pool['res.users'].read(
  633. cr, uid, uid, ['lang'], context=context)['lang']
  634. if not lang:
  635. lang = 'en_US'
  636. lang_id = self.pool['res.lang'].search(
  637. cr, uid, [('code', '=', lang)], context=context)
  638. for period in r.period_ids:
  639. if not period.valid:
  640. continue
  641. # add the column header
  642. header['']['cols'].append(dict(
  643. name=period.name,
  644. date=(period.duration > 1 or period.type == 'w') and
  645. _('from %s to %s' %
  646. (period.period_from and period.period_from.name
  647. or self._format_date(cr, uid, lang_id, period.date_from,
  648. context=context),
  649. period.period_to and period.period_to.name
  650. or self._format_date(cr, uid, lang_id, period.date_to,
  651. context=context)))
  652. or period.period_from and period.period_from.name or
  653. period.date_from))
  654. # compute kpi values
  655. values = report_instance_period_obj._compute(
  656. cr, uid, lang_id, period, aep, context=context)
  657. period_values[period.name] = values
  658. for key in values:
  659. content[key]['default_style'] = values[key]['default_style']
  660. content[key]['cols'].append(values[key])
  661. # add comparison column
  662. for period in r.period_ids:
  663. for compare_col in period.comparison_column_ids:
  664. # add the column header
  665. header['']['cols'].append(
  666. dict(name='%s - %s' % (period.name, compare_col.name),
  667. date=''))
  668. column1_values = period_values[period.name]
  669. column2_values = period_values[compare_col.name]
  670. for kpi in r.report_id.kpi_ids:
  671. content[kpi.name]['cols'].append(
  672. {'val_r': kpi_obj._render_comparison(
  673. cr,
  674. uid,
  675. lang_id,
  676. kpi,
  677. column1_values[kpi.name]['val'],
  678. column2_values[kpi.name]['val'],
  679. period.normalize_factor,
  680. compare_col.normalize_factor,
  681. context=context)})
  682. return {'header': header,
  683. 'content': content}