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.

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