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.

814 lines
34 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
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 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 %s' % 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. 'groupby': fields.boolean(string="Group by"),
  226. 'groupby_field_ids': fields.many2many('ir.model.fields',
  227. 'ir_model_fields_'
  228. 'mis_report_query_groupby_rel',
  229. string='Fields to group by'),
  230. 'date_field': fields.many2one('ir.model.fields', required=True,
  231. string='Date field',
  232. domain=[('ttype', 'in',
  233. ('date', 'datetime'))]),
  234. 'domain': fields.char(string='Domain'),
  235. 'report_id': fields.many2one('mis.report', string='Report',
  236. ondelete='cascade'),
  237. }
  238. _order = 'name'
  239. def _check_name(self, cr, uid, ids, context=None):
  240. for record_name in self.read(cr, uid, ids, ['name']):
  241. if not _is_valid_python_var(record_name['name']):
  242. return False
  243. return True
  244. _constraints = [
  245. (_check_name, 'The name must be a valid python identifier', ['name']),
  246. ]
  247. class mis_report(orm.Model):
  248. """ A MIS report template (without period information)
  249. The MIS report holds:
  250. * an implicit query fetching all the account balances;
  251. for each account, the balance is stored in a variable named
  252. bal_{code} where {code} is the account code
  253. * an implicit query fetching all the account balances solde;
  254. for each account, the balance solde is stored in a variable named
  255. bals_{code} where {code} is the account code
  256. * a list of explicit queries; the result of each query is
  257. stored in a variable with same name as a query, containing as list
  258. of data structures populated with attributes for each fields to fetch
  259. * a list of KPI to be evaluated based on the variables resulting
  260. from the balance and queries
  261. """
  262. _name = 'mis.report'
  263. _columns = {
  264. 'name': fields.char(size=32, required=True,
  265. string='Name', translate=True),
  266. 'description': fields.char(required=False,
  267. string='Description', translate=True),
  268. 'query_ids': fields.one2many('mis.report.query', 'report_id',
  269. string='Queries'),
  270. 'kpi_ids': fields.one2many('mis.report.kpi', 'report_id',
  271. string='KPI\'s'),
  272. }
  273. # TODO: kpi name cannot be start with query name
  274. def create(self, cr, uid, vals, context=None):
  275. # TODO: explain this
  276. if 'kpi_ids' in vals:
  277. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  278. for idx, line in enumerate(vals['kpi_ids']):
  279. if line[0] == 0:
  280. line[2]['sequence'] = idx + 1
  281. else:
  282. mis_report_kpi_obj.write(
  283. cr, uid, [line[1]], {'sequence': idx + 1},
  284. context=context)
  285. return super(mis_report, self).create(cr, uid, vals, context=context)
  286. def write(self, cr, uid, ids, vals, context=None):
  287. # TODO: explain this
  288. res = super(mis_report, self).write(
  289. cr, uid, ids, vals, context=context)
  290. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  291. for report in self.browse(cr, uid, ids, context):
  292. for idx, kpi in enumerate(report.kpi_ids):
  293. mis_report_kpi_obj.write(
  294. cr, uid, [kpi.id], {'sequence': idx + 1}, context=context)
  295. return res
  296. class mis_report_instance_period(orm.Model):
  297. """ A MIS report instance has the logic to compute
  298. a report template for a given date period.
  299. Periods have a duration (day, week, fiscal period) and
  300. are defined as an offset relative to a pivot date.
  301. """
  302. def _get_dates(self, cr, uid, ids, field_names, arg, context=None):
  303. if isinstance(ids, (int, long)):
  304. ids = [ids]
  305. res = {}
  306. for c in self.browse(cr, uid, ids, context=context):
  307. d = parser.parse(c.report_instance_id.pivot_date)
  308. if c.type == 'd':
  309. date_from = d + timedelta(days=c.offset)
  310. date_to = date_from + timedelta(days=c.duration - 1)
  311. date_from = date_from.strftime(
  312. tools.DEFAULT_SERVER_DATE_FORMAT)
  313. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  314. period_ids = None
  315. elif c.type == 'w':
  316. date_from = d - timedelta(d.weekday())
  317. date_from = date_from + timedelta(days=c.offset * 7)
  318. date_to = date_from + timedelta(days=(7 * c.duration) - 1)
  319. date_from = date_from.strftime(
  320. tools.DEFAULT_SERVER_DATE_FORMAT)
  321. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  322. period_ids = None
  323. elif c.type == 'fp':
  324. period_obj = self.pool['account.period']
  325. all_period_ids = period_obj.search(
  326. cr, uid,
  327. [('special', '=', False),
  328. ('company_id', '=', c.company_id.id)],
  329. order='date_start',
  330. context=context)
  331. current_period_ids = period_obj.search(
  332. cr, uid,
  333. [('special', '=', False),
  334. ('date_start', '<=', d),
  335. ('date_stop', '>=', d),
  336. ('company_id', '=', c.company_id.id)],
  337. context=context)
  338. if not current_period_ids:
  339. raise orm.except_orm(_("Error!"),
  340. _("No current fiscal period for %s")
  341. % d)
  342. p = all_period_ids.index(current_period_ids[0]) + c.offset
  343. if p < 0 or p >= len(all_period_ids):
  344. raise orm.except_orm(_("Error!"),
  345. _("No such fiscal period for %s "
  346. "with offset %d") % (d, c.offset))
  347. period_ids = all_period_ids[p:p + c.duration]
  348. periods = period_obj.browse(cr, uid, period_ids,
  349. context=context)
  350. date_from = periods[0].date_start
  351. date_to = periods[-1].date_stop
  352. else:
  353. raise orm.except_orm(_("Error!"),
  354. _("Unimplemented period type %s") %
  355. (c.type,))
  356. res[c.id] = {
  357. 'date_from': date_from,
  358. 'date_to': date_to,
  359. 'period_from': period_ids and period_ids[0] or False,
  360. 'period_to': period_ids and period_ids[-1] or False,
  361. }
  362. return res
  363. _name = 'mis.report.instance.period'
  364. _columns = {
  365. 'name': fields.char(size=32, required=True,
  366. string='Description', translate=True),
  367. 'type': fields.selection([('d', _('Day')),
  368. ('w', _('Week')),
  369. ('fp', _('Fiscal Period')),
  370. # ('fy', _('Fiscal Year'))
  371. ],
  372. required=True,
  373. string='Period type'),
  374. 'offset': fields.integer(string='Offset',
  375. help='Offset from current period'),
  376. 'duration': fields.integer(string='Duration',
  377. help='Number of periods'),
  378. 'date_from': fields.function(_get_dates,
  379. type='date',
  380. multi="dates",
  381. string="From"),
  382. 'date_to': fields.function(_get_dates,
  383. type='date',
  384. multi="dates",
  385. string="To"),
  386. 'period_from': fields.function(_get_dates,
  387. type='many2one', obj='account.period',
  388. multi="dates", string="From period"),
  389. 'period_to': fields.function(_get_dates,
  390. type='many2one', obj='account.period',
  391. multi="dates", string="To period"),
  392. 'sequence': fields.integer(string='Sequence'),
  393. 'report_instance_id': fields.many2one('mis.report.instance',
  394. string='Report Instance',
  395. ondelete='cascade'),
  396. 'comparison_column_ids': fields.many2many(
  397. 'mis.report.instance.period',
  398. 'mis_report_instance_period_rel',
  399. 'period_id',
  400. 'compare_period_id',
  401. string='Compare with'),
  402. 'company_id': fields.related('report_instance_id', 'company_id',
  403. type="many2one", relation="res.company",
  404. string="Company", readonly=True),
  405. 'normalize_factor': fields.integer(
  406. string='Factor',
  407. help='Factor to use to normalize the period (used in comparison'),
  408. }
  409. _defaults = {
  410. 'offset': -1,
  411. 'duration': 1,
  412. 'sequence': 100,
  413. 'normalize_factor': 1,
  414. }
  415. _order = 'sequence'
  416. _sql_constraints = [
  417. ('duration', 'CHECK (duration>0)',
  418. 'Wrong duration, it must be positive!'),
  419. ('normalize_factor', 'CHECK (normalize_factor>0)',
  420. 'Wrong normalize factor, it must be positive!'),
  421. ('name_unique', 'unique(name, report_instance_id)',
  422. 'Period name should be unique by report'),
  423. ]
  424. def drilldown(self, cr, uid, _id, expr, context=None):
  425. this = self.browse(cr, uid, _id, context=context)[0]
  426. env = Environment(cr, uid, {})
  427. aep = AccountingExpressionProcessor(env)
  428. if aep.has_account_var(expr):
  429. aep.parse_expr(expr)
  430. aep.done_parsing(this.report_instance_id.root_account)
  431. domain = aep.get_aml_domain_for_expr(
  432. expr, this.date_from, this.date_to,
  433. this.period_from, this.period_to,
  434. this.report_instance_id.target_move)
  435. return {
  436. 'name': expr + ' - ' + this.name,
  437. 'domain': domain,
  438. 'type': 'ir.actions.act_window',
  439. 'res_model': 'account.move.line',
  440. 'views': [[False, 'list'], [False, 'form']],
  441. 'view_type': 'list',
  442. 'view_mode': 'list',
  443. 'target': 'current',
  444. }
  445. else:
  446. return False
  447. def _fetch_queries(self, cr, uid, c, context):
  448. res = {}
  449. report = c.report_instance_id.report_id
  450. for query in report.query_ids:
  451. obj = self.pool[query.model_id.model]
  452. domain = query.domain and safe_eval(query.domain) or []
  453. if query.date_field.ttype == 'date':
  454. domain.extend([(query.date_field.name, '>=', c.date_from),
  455. (query.date_field.name, '<=', c.date_to)])
  456. else:
  457. datetime_from = _utc_midnight(
  458. c.date_from, context.get('tz', 'UTC'))
  459. datetime_to = _utc_midnight(
  460. c.date_to, context.get('tz', 'UTC'), add_day=1)
  461. domain.extend([(query.date_field.name, '>=', datetime_from),
  462. (query.date_field.name, '<', datetime_to)])
  463. if obj._columns.get('company_id', False):
  464. domain.extend(['|', ('company_id', '=', False),
  465. ('company_id', '=', c.company_id.id)])
  466. field_names = [f.name for f in query.field_ids]
  467. if not query.groupby:
  468. obj_ids = obj.search(cr, uid, domain, context=context)
  469. obj_datas = obj.read(
  470. cr, uid, obj_ids, field_names, context=context)
  471. res[query.name] = [AutoStruct(**d) for d in obj_datas]
  472. else:
  473. groupby_field_names = [f.name for f in query.groupby_field_ids]
  474. obj_datas = obj.read_group(
  475. cr, uid, domain, field_names, groupby_field_names,
  476. context=context)
  477. if groupby_field_names or not obj_datas:
  478. res[query.name] = [AutoStruct(**d) for d in obj_datas]
  479. else:
  480. res[query.name] = AutoStruct(**obj_datas[0])
  481. return res
  482. def _compute(self, cr, uid, lang_id, c, aep, context=None):
  483. if context is None:
  484. context = {}
  485. kpi_obj = self.pool['mis.report.kpi']
  486. res = {}
  487. localdict = {
  488. 'registry': self.pool,
  489. 'sum': sum,
  490. 'min': min,
  491. 'max': max,
  492. 'len': len,
  493. 'avg': lambda l: sum(l) / float(len(l)),
  494. }
  495. localdict.update(self._fetch_queries(cr, uid, c,
  496. context=context))
  497. aep.do_queries(c.date_from, c.date_to,
  498. c.period_from, c.period_to,
  499. c.report_instance_id.target_move)
  500. compute_queue = c.report_instance_id.report_id.kpi_ids
  501. recompute_queue = []
  502. while True:
  503. for kpi in compute_queue:
  504. try:
  505. kpi_val_comment = kpi.name + " = " + kpi.expression
  506. kpi_eval_expression = aep.replace_expr(kpi.expression)
  507. kpi_val = safe_eval(kpi_eval_expression, localdict)
  508. except ZeroDivisionError:
  509. kpi_val = None
  510. kpi_val_rendered = '#DIV/0'
  511. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  512. except NameError:
  513. recompute_queue.append(kpi)
  514. kpi_val = None
  515. kpi_val_rendered = '#ERR'
  516. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  517. except:
  518. kpi_val = None
  519. kpi_val_rendered = '#ERR'
  520. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  521. else:
  522. kpi_val_rendered = kpi_obj._render(
  523. cr, uid, lang_id, kpi, kpi_val, context=context)
  524. localdict[kpi.name] = kpi_val
  525. try:
  526. kpi_style = None
  527. if kpi.css_style:
  528. kpi_style = safe_eval(kpi.css_style, localdict)
  529. except:
  530. kpi_style = None
  531. drilldown = (kpi_val is not None and
  532. aep.has_account_var(kpi.expression))
  533. res[kpi.name] = {
  534. 'val': kpi_val,
  535. 'val_r': kpi_val_rendered,
  536. 'val_c': kpi_val_comment,
  537. 'style': kpi_style,
  538. 'default_style': kpi.default_css_style or None,
  539. 'suffix': kpi.suffix,
  540. 'dp': kpi.dp,
  541. 'is_percentage': kpi.type == 'pct',
  542. 'period_id': c.id,
  543. 'expr': kpi.expression,
  544. 'drilldown': drilldown,
  545. }
  546. if len(recompute_queue) == 0:
  547. # nothing to recompute, we are done
  548. break
  549. if len(recompute_queue) == len(compute_queue):
  550. # could not compute anything in this iteration
  551. # (ie real Value errors or cyclic dependency)
  552. # so we stop trying
  553. break
  554. # try again
  555. compute_queue = recompute_queue
  556. recompute_queue = []
  557. return res
  558. class mis_report_instance(orm.Model):
  559. """ The MIS report instance combines compute and
  560. display a MIS report template for a set of periods """
  561. def _get_pivot_date(self, cr, uid, ids, field_name, arg, context=None):
  562. res = {}
  563. for r in self.browse(cr, uid, ids, context=context):
  564. if r.date:
  565. res[r.id] = r.date
  566. else:
  567. res[r.id] = fields.date.context_today(self, cr, uid,
  568. context=context)
  569. return res
  570. def _get_root_account(self, cr, uid, ids, field_name, arg, context=None):
  571. res = {}
  572. account_obj = self.pool['account.account']
  573. for r in self.browse(cr, uid, ids, context=context):
  574. account_ids = account_obj.search(
  575. cr, uid,
  576. [('parent_id', '=', False),
  577. ('company_id', '=', r.company_id.id)],
  578. context=context)
  579. if len(account_ids) == 1:
  580. res[r.id] = account_ids[0]
  581. return res
  582. _name = 'mis.report.instance'
  583. _columns = {
  584. 'name': fields.char(size=32, required=True,
  585. string='Name', translate=True),
  586. 'description': fields.char(required=False,
  587. string='Description', translate=True),
  588. 'date': fields.date(string='Base date',
  589. help='Report base date '
  590. '(leave empty to use current date)'),
  591. 'pivot_date': fields.function(_get_pivot_date,
  592. type='date',
  593. string="Pivot date"),
  594. 'report_id': fields.many2one('mis.report',
  595. required=True,
  596. string='Report'),
  597. 'period_ids': fields.one2many('mis.report.instance.period',
  598. 'report_instance_id',
  599. required=True,
  600. string='Periods'),
  601. 'target_move': fields.selection([('posted', 'All Posted Entries'),
  602. ('all', 'All Entries'),
  603. ], 'Target Moves', required=True),
  604. 'company_id': fields.many2one('res.company', 'Company', required=True),
  605. 'root_account': fields.function(_get_root_account,
  606. type='many2one', obj='account.account',
  607. string="Account chart"),
  608. }
  609. _defaults = {
  610. 'target_move': 'posted',
  611. 'company_id': lambda s, cr, uid, c:
  612. s.pool.get('res.company')._company_default_get(
  613. cr, uid,
  614. 'mis.report.instance',
  615. context=c)
  616. }
  617. def create(self, cr, uid, vals, context=None):
  618. if not vals:
  619. return context.get('active_id', None)
  620. # TODO: explain this
  621. if 'period_ids' in vals:
  622. mis_report_instance_period_obj = self.pool.get(
  623. 'mis.report.instance.period')
  624. for idx, line in enumerate(vals['period_ids']):
  625. if line[0] == 0:
  626. line[2]['sequence'] = idx + 1
  627. else:
  628. mis_report_instance_period_obj.write(
  629. cr, uid, [line[1]], {'sequence': idx + 1},
  630. context=context)
  631. return super(mis_report_instance, self).create(cr, uid, vals,
  632. context=context)
  633. def write(self, cr, uid, ids, vals, context=None):
  634. # TODO: explain this
  635. res = super(mis_report_instance, self).write(
  636. cr, uid, ids, vals, context=context)
  637. mis_report_instance_period_obj = self.pool.get(
  638. 'mis.report.instance.period')
  639. for instance in self.browse(cr, uid, ids, context):
  640. for idx, period in enumerate(instance.period_ids):
  641. mis_report_instance_period_obj.write(
  642. cr, uid, [period.id], {'sequence': idx + 1},
  643. context=context)
  644. return res
  645. def _format_date(self, cr, uid, lang_id, date, context=None):
  646. # format date following user language
  647. tformat = self.pool['res.lang'].read(
  648. cr, uid, lang_id, ['date_format'])[0]['date_format']
  649. return datetime.strftime(datetime.strptime(
  650. date,
  651. tools.DEFAULT_SERVER_DATE_FORMAT),
  652. tformat)
  653. def compute(self, cr, uid, _id, context=None):
  654. assert isinstance(_id, (int, long))
  655. if context is None:
  656. context = {}
  657. r = self.browse(cr, uid, _id, context=context)
  658. content = OrderedDict()
  659. # empty line name for header
  660. header = OrderedDict()
  661. header[''] = {'kpi_name': '', 'cols': [], 'default_style': ''}
  662. env = Environment(cr, uid, {})
  663. aep = AccountingExpressionProcessor(env)
  664. # initialize lines with kpi
  665. for kpi in r.report_id.kpi_ids:
  666. aep.parse_expr(kpi.expression)
  667. content[kpi.name] = {'kpi_name': kpi.description,
  668. 'cols': [],
  669. 'default_style': ''}
  670. aep.done_parsing(r.root_account)
  671. report_instance_period_obj = self.pool.get(
  672. 'mis.report.instance.period')
  673. kpi_obj = self.pool.get('mis.report.kpi')
  674. period_values = {}
  675. lang = self.pool['res.users'].read(
  676. cr, uid, uid, ['lang'], context=context)['lang']
  677. if not lang:
  678. lang = 'en_US'
  679. lang_id = self.pool['res.lang'].search(
  680. cr, uid, [('code', '=', lang)], context=context)
  681. for period in r.period_ids:
  682. # add the column header
  683. header['']['cols'].append(dict(
  684. name=period.name,
  685. date=(period.duration > 1 or period.type == 'w') and
  686. _('from %s to %s' %
  687. (period.period_from and period.period_from.name
  688. or self._format_date(cr, uid, lang_id, period.date_from,
  689. context=context),
  690. period.period_to and period.period_to.name
  691. or self._format_date(cr, uid, lang_id, period.date_to,
  692. context=context)))
  693. or period.period_from and period.period_from.name or
  694. period.date_from))
  695. # compute kpi values
  696. values = report_instance_period_obj._compute(
  697. cr, uid, lang_id, period, aep, context=context)
  698. period_values[period.name] = values
  699. for key in values:
  700. content[key]['default_style'] = values[key]['default_style']
  701. content[key]['cols'].append(values[key])
  702. # add comparison column
  703. for period in r.period_ids:
  704. for compare_col in period.comparison_column_ids:
  705. # add the column header
  706. header['']['cols'].append(
  707. dict(name='%s - %s' % (period.name, compare_col.name),
  708. date=''))
  709. column1_values = period_values[period.name]
  710. column2_values = period_values[compare_col.name]
  711. for kpi in r.report_id.kpi_ids:
  712. content[kpi.name]['cols'].append(
  713. {'val_r': kpi_obj._render_comparison(
  714. cr,
  715. uid,
  716. lang_id,
  717. kpi,
  718. column1_values[kpi.name]['val'],
  719. column2_values[kpi.name]['val'],
  720. period.normalize_factor,
  721. compare_col.normalize_factor,
  722. context=context)})
  723. return {'header': header,
  724. 'content': content}