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.

993 lines
40 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
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 datetime import datetime, timedelta
  25. from dateutil import parser
  26. import traceback
  27. import re
  28. import pytz
  29. from openerp.osv import orm, fields
  30. from openerp.tools.safe_eval import safe_eval
  31. from openerp.tools.translate import _
  32. from openerp import tools
  33. from collections import OrderedDict
  34. FUNCTION = [('credit', 'cred'),
  35. ('debit', 'deb'),
  36. ('balance', 'bal')
  37. ]
  38. FUNCTION_LIST = [x[1] for x in FUNCTION]
  39. PARAMETERS = ['s_', 'i_', '_']
  40. class AutoStruct(object):
  41. def __init__(self, **kwargs):
  42. for k, v in kwargs.items():
  43. setattr(self, k, v)
  44. def _get_selection_label(selection, value):
  45. for v, l in selection:
  46. if v == value:
  47. return l
  48. return ''
  49. def _utc_midnight(d, tz_name, add_day=0):
  50. d = datetime.strptime(d, tools.DEFAULT_SERVER_DATE_FORMAT)
  51. if add_day:
  52. d = d + timedelta(days=add_day)
  53. utc_tz = pytz.timezone('UTC')
  54. context_tz = pytz.timezone(tz_name)
  55. local_timestamp = context_tz.localize(d, is_dst=False)
  56. return datetime.strftime(local_timestamp.astimezone(utc_tz),
  57. tools.DEFAULT_SERVER_DATETIME_FORMAT)
  58. def _python_var(var_str):
  59. return re.sub(r'\W|^(?=\d)', '_', var_str).lower()
  60. def _get_sufix(is_solde=False, is_initial=False):
  61. if is_solde:
  62. return 's_'
  63. elif is_initial:
  64. return 'i_'
  65. else:
  66. return '_'
  67. def _python_account_var(function, account_code, is_solde=False,
  68. is_initial=False):
  69. prefix = function + _get_sufix(is_solde=is_solde, is_initial=is_initial)
  70. return prefix + re.sub(r'\W', '_', account_code)
  71. def _get_account_code(account_var):
  72. res = re.findall(r'_(\d+)', account_var)
  73. assert len(res) == 1
  74. return res[0]
  75. def _get_account_vars_in_expr(expr, is_solde=False, is_initial=False):
  76. res = []
  77. for function in FUNCTION_LIST:
  78. prefix = function + _get_sufix(is_solde=is_solde,
  79. is_initial=is_initial)
  80. res.extend(re.findall(r'\b%s\w+' % prefix, expr))
  81. return res
  82. def _get_vars_in_expr(expr, varnames=None):
  83. if not varnames:
  84. return []
  85. varnames_re = r'\b' + r'\b|\b'.join(varnames) + r'\b'
  86. return re.findall(varnames_re, expr)
  87. def _get_account_vars_in_report(report, is_solde=False, is_initial=False):
  88. res = set()
  89. for kpi in report.kpi_ids:
  90. for account_var in _get_account_vars_in_expr(kpi.expression, is_solde,
  91. is_initial):
  92. res.add(account_var)
  93. return res
  94. def _is_valid_python_var(name):
  95. for item in FUNCTION_LIST:
  96. for param in PARAMETERS:
  97. if name.startswith(item + param):
  98. return False
  99. return re.match("[_A-Za-z][_a-zA-Z0-9]*$", name)
  100. class mis_report_kpi(orm.Model):
  101. """ A KPI is an element of a MIS report.
  102. In addition to a name and description, it has an expression
  103. to compute it based on queries defined in the MIS report.
  104. It also has various informations defining how to render it
  105. (numeric or percentage or a string, a suffix, divider) and
  106. how to render comparison of two values of the KPI.
  107. KPI are ordered inside the MIS report, as some KPI expressions
  108. can depend on other KPI that need to be computed before.
  109. """
  110. _name = 'mis.report.kpi'
  111. _columns = {
  112. 'name': fields.char(size=32, required=True,
  113. string='Name'),
  114. 'description': fields.char(required=True,
  115. string='Description',
  116. translate=True),
  117. 'expression': fields.char(required=True,
  118. string='Expression'),
  119. 'default_css_style': fields.char(
  120. string='Default CSS style'),
  121. 'css_style': fields.char(string='CSS style expression'),
  122. 'type': fields.selection([('num', _('Numeric')),
  123. ('pct', _('Percentage')),
  124. ('str', _('String'))],
  125. required=True,
  126. string='Type'),
  127. 'divider': fields.selection([('1e-6', _('µ')),
  128. ('1e-3', _('m')),
  129. ('1', _('1')),
  130. ('1e3', _('k')),
  131. ('1e6', _('M'))],
  132. string='Factor'),
  133. 'dp': fields.integer(string='Rounding'),
  134. 'suffix': fields.char(size=16, string='Suffix'),
  135. 'compare_method': fields.selection([('diff', _('Difference')),
  136. ('pct', _('Percentage')),
  137. ('none', _('None'))],
  138. required=True,
  139. string='Comparison Method'),
  140. 'sequence': fields.integer(string='Sequence'),
  141. 'report_id': fields.many2one('mis.report', string='Report'),
  142. }
  143. _defaults = {
  144. 'type': 'num',
  145. 'divider': '1',
  146. 'dp': 0,
  147. 'compare_method': 'pct',
  148. 'sequence': 100,
  149. }
  150. _order = 'sequence'
  151. def _check_name(self, cr, uid, ids, context=None):
  152. for record_name in self.read(cr, uid, ids, ['name']):
  153. if not _is_valid_python_var(record_name['name']):
  154. return False
  155. return True
  156. _constraints = [
  157. (_check_name, 'The name must be a valid python identifier', ['name']),
  158. ]
  159. def onchange_name(self, cr, uid, ids, name, context=None):
  160. res = {}
  161. if name and not _is_valid_python_var(name):
  162. res['warning'] = {
  163. 'title': 'Invalid name',
  164. 'message': 'The name must be a valid python identifier'}
  165. return res
  166. def onchange_description(self, cr, uid, ids, description, name,
  167. context=None):
  168. """ construct name from description """
  169. res = {}
  170. if description and not name:
  171. res = {'value': {'name': _python_var(description)}}
  172. return res
  173. def onchange_type(self, cr, uid, ids, kpi_type, context=None):
  174. res = {}
  175. if kpi_type == 'pct':
  176. res['value'] = {'compare_method': 'diff'}
  177. elif kpi_type == 'str':
  178. res['value'] = {'compare_method': 'none',
  179. 'divider': '',
  180. 'dp': 0}
  181. return res
  182. def _render(self, cr, uid, lang_id, kpi, value, context=None):
  183. """ render a KPI value as a unicode string, ready for display """
  184. if kpi.type == 'num':
  185. return self._render_num(cr, uid, lang_id, value, kpi.divider,
  186. kpi.dp, kpi.suffix, context=context)
  187. elif kpi.type == 'pct':
  188. return self._render_num(cr, uid, lang_id, value, 0.01,
  189. kpi.dp, '%', context=context)
  190. else:
  191. return unicode(value)
  192. def _render_comparison(self, cr, uid, lang_id, kpi, value, base_value,
  193. average_value, average_base_value, context=None):
  194. """ render the comparison of two KPI values, ready for display """
  195. if value is None or base_value is None:
  196. return ''
  197. if kpi.type == 'pct':
  198. return self._render_num(cr, uid, lang_id, value - base_value, 0.01,
  199. kpi.dp, _('pp'), sign='+', context=context)
  200. elif kpi.type == 'num':
  201. if average_value:
  202. value = value / float(average_value)
  203. if average_base_value:
  204. base_value = base_value / float(average_base_value)
  205. if kpi.compare_method == 'diff':
  206. return self._render_num(cr, uid, lang_id, value - base_value,
  207. kpi.divider,
  208. kpi.dp, kpi.suffix, sign='+',
  209. context=context)
  210. elif kpi.compare_method == 'pct' and base_value != 0:
  211. return self._render_num(cr, uid, lang_id,
  212. value / base_value - 1, 0.01,
  213. kpi.dp, '%', sign='+', context=context)
  214. return ''
  215. def _render_num(self, cr, uid, lang_id, value, divider,
  216. dp, suffix, sign='-', context=None):
  217. divider_label = _get_selection_label(
  218. self._columns['divider'].selection, divider)
  219. if divider_label == '1':
  220. divider_label = ''
  221. # format number following user language
  222. value = round(value / float(divider or 1), dp) or 0
  223. return '%s %s%s' % (self.pool['res.lang'].format(
  224. cr, uid, lang_id,
  225. '%%%s.%df' % (
  226. sign, dp),
  227. value,
  228. grouping=True,
  229. context=context),
  230. divider_label, suffix or '')
  231. class mis_report_query(orm.Model):
  232. """ A query to fetch data for a MIS report.
  233. A query works on a model and has a domain and list of fields to fetch.
  234. At runtime, the domain is expanded with a "and" on the date/datetime field.
  235. """
  236. _name = 'mis.report.query'
  237. def _get_field_names(self, cr, uid, ids, name, args, context=None):
  238. res = {}
  239. for query in self.browse(cr, uid, ids, context=context):
  240. field_names = []
  241. for field in query.field_ids:
  242. field_names.append(field.name)
  243. res[query.id] = ', '.join(field_names)
  244. return res
  245. def onchange_field_ids(self, cr, uid, ids, field_ids, context=None):
  246. # compute field_names
  247. field_names = []
  248. for field in self.pool.get('ir.model.fields').read(
  249. cr, uid,
  250. field_ids[0][2],
  251. ['name'],
  252. context=context):
  253. field_names.append(field['name'])
  254. return {'value': {'field_names': ', '.join(field_names)}}
  255. _columns = {
  256. 'name': fields.char(size=32, required=True,
  257. string='Name'),
  258. 'model_id': fields.many2one('ir.model', required=True,
  259. string='Model'),
  260. 'field_ids': fields.many2many('ir.model.fields', required=True,
  261. string='Fields to fetch'),
  262. 'field_names': fields.function(_get_field_names, type='char',
  263. string='Fetched fields name',
  264. store={'mis.report.query':
  265. (lambda self, cr, uid, ids, c={}:
  266. ids, ['field_ids'], 20), }),
  267. 'date_field': fields.many2one('ir.model.fields', required=True,
  268. string='Date field',
  269. domain=[('ttype', 'in',
  270. ('date', 'datetime'))]),
  271. 'domain': fields.char(string='Domain'),
  272. 'report_id': fields.many2one('mis.report', string='Report'),
  273. }
  274. _order = 'name'
  275. def _check_name(self, cr, uid, ids, context=None):
  276. for record_name in self.read(cr, uid, ids, ['name']):
  277. if not _is_valid_python_var(record_name['name']):
  278. return False
  279. return True
  280. _constraints = [
  281. (_check_name, 'The name must be a valid python identifier', ['name']),
  282. ]
  283. class mis_report(orm.Model):
  284. """ A MIS report template (without period information)
  285. The MIS report holds:
  286. * an implicit query fetching all the account balances;
  287. for each account, the balance is stored in a variable named
  288. bal_{code} where {code} is the account code
  289. * an implicit query fetching all the account balances solde;
  290. for each account, the balance solde is stored in a variable named
  291. bals_{code} where {code} is the account code
  292. * a list of explicit queries; the result of each query is
  293. stored in a variable with same name as a query, containing as list
  294. of data structures populated with attributes for each fields to fetch
  295. * a list of KPI to be evaluated based on the variables resulting
  296. from the balance and queries
  297. """
  298. _name = 'mis.report'
  299. _columns = {
  300. 'name': fields.char(size=32, required=True,
  301. string='Name', translate=True),
  302. 'description': fields.char(required=False,
  303. string='Description', translate=True),
  304. 'query_ids': fields.one2many('mis.report.query', 'report_id',
  305. string='Queries'),
  306. 'kpi_ids': fields.one2many('mis.report.kpi', 'report_id',
  307. string='KPI\'s'),
  308. }
  309. # TODO: kpi name cannot be start with query name
  310. def create(self, cr, uid, vals, context=None):
  311. # TODO: explain this
  312. if 'kpi_ids' in vals:
  313. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  314. for idx, line in enumerate(vals['kpi_ids']):
  315. if line[0] == 0:
  316. line[2]['sequence'] = idx + 1
  317. else:
  318. mis_report_kpi_obj.write(
  319. cr, uid, [line[1]], {'sequence': idx + 1},
  320. context=context)
  321. return super(mis_report, self).create(cr, uid, vals, context=context)
  322. def write(self, cr, uid, ids, vals, context=None):
  323. # TODO: explain this
  324. res = super(mis_report, self).write(
  325. cr, uid, ids, vals, context=context)
  326. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  327. for report in self.browse(cr, uid, ids, context):
  328. for idx, kpi in enumerate(report.kpi_ids):
  329. mis_report_kpi_obj.write(
  330. cr, uid, [kpi.id], {'sequence': idx + 1}, context=context)
  331. return res
  332. class mis_report_instance_period(orm.Model):
  333. """ A MIS report instance has the logic to compute
  334. a report template for a given date period.
  335. Periods have a duration (day, week, fiscal period) and
  336. are defined as an offset relative to a pivot date.
  337. """
  338. def _get_dates(self, cr, uid, ids, field_names, arg, context=None):
  339. if isinstance(ids, (int, long)):
  340. ids = [ids]
  341. res = {}
  342. for c in self.browse(cr, uid, ids, context=context):
  343. d = parser.parse(c.report_instance_id.pivot_date)
  344. if c.type == 'd':
  345. date_from = d + timedelta(days=c.offset)
  346. date_to = date_from + timedelta(days=c.duration - 1)
  347. date_from = date_from.strftime(
  348. tools.DEFAULT_SERVER_DATE_FORMAT)
  349. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  350. period_ids = None
  351. elif c.type == 'w':
  352. date_from = d - timedelta(d.weekday())
  353. date_from = date_from + timedelta(days=c.offset * 7)
  354. date_to = date_from + timedelta(days=(7 * c.duration) - 1)
  355. date_from = date_from.strftime(
  356. tools.DEFAULT_SERVER_DATE_FORMAT)
  357. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  358. period_ids = None
  359. elif c.type == 'fp':
  360. period_obj = self.pool['account.period']
  361. all_period_ids = period_obj.search(
  362. cr, uid,
  363. [('special', '=', False),
  364. '|', ('company_id', '=', False),
  365. ('company_id', '=', c.company_id.id)],
  366. order='date_start',
  367. context=context)
  368. current_period_ids = period_obj.search(
  369. cr, uid,
  370. [('special', '=', False),
  371. ('date_start', '<=', d),
  372. ('date_stop', '>=', d),
  373. '|', ('company_id', '=', False),
  374. ('company_id', '=', c.company_id.id)],
  375. context=context)
  376. if not current_period_ids:
  377. raise orm.except_orm(_("Error!"),
  378. _("No current fiscal period for %s")
  379. % d)
  380. p = all_period_ids.index(current_period_ids[0]) + c.offset
  381. if p < 0 or p >= len(all_period_ids):
  382. raise orm.except_orm(_("Error!"),
  383. _("No such fiscal period for %s "
  384. "with offset %d") % (d, c.offset))
  385. period_ids = all_period_ids[p:p + c.duration]
  386. periods = period_obj.browse(cr, uid, period_ids,
  387. context=context)
  388. date_from = periods[0].date_start
  389. date_to = periods[-1].date_stop
  390. else:
  391. raise orm.except_orm(_("Error!"),
  392. _("Unimplemented period type %s") %
  393. (c.type,))
  394. res[c.id] = {
  395. 'date_from': date_from,
  396. 'date_to': date_to,
  397. 'period_from': period_ids and period_ids[0],
  398. 'period_to': period_ids and period_ids[-1],
  399. }
  400. return res
  401. _name = 'mis.report.instance.period'
  402. _columns = {
  403. 'name': fields.char(size=32, required=True,
  404. string='Description', translate=True),
  405. 'type': fields.selection([('d', _('Day')),
  406. ('w', _('Week')),
  407. ('fp', _('Fiscal Period')),
  408. # ('fy', _('Fiscal Year'))
  409. ],
  410. required=True,
  411. string='Period type'),
  412. 'offset': fields.integer(string='Offset',
  413. help='Offset from current period'),
  414. 'duration': fields.integer(string='Duration',
  415. help='Number of periods'),
  416. 'date_from': fields.function(_get_dates,
  417. type='date',
  418. multi="dates",
  419. string="From"),
  420. 'date_to': fields.function(_get_dates,
  421. type='date',
  422. multi="dates",
  423. string="To"),
  424. 'period_from': fields.function(_get_dates,
  425. type='many2one', obj='account.period',
  426. multi="dates", string="From period"),
  427. 'period_to': fields.function(_get_dates,
  428. type='many2one', obj='account.period',
  429. multi="dates", string="To period"),
  430. 'sequence': fields.integer(string='Sequence'),
  431. 'report_instance_id': fields.many2one('mis.report.instance',
  432. string='Report Instance'),
  433. 'comparison_column_ids': fields.many2many(
  434. 'mis.report.instance.period',
  435. 'mis_report_instance_period_rel',
  436. 'period_id',
  437. 'compare_period_id',
  438. string='Compare with'),
  439. 'company_id': fields.related('report_instance_id', 'company_id',
  440. type="many2one", relation="res.company",
  441. string="Company", readonly=True),
  442. 'normalize_factor': fields.integer(
  443. string='Factor',
  444. help='Factor to use to normalize the period (used in comparison'),
  445. }
  446. _defaults = {
  447. 'offset': -1,
  448. 'duration': 1,
  449. 'sequence': 100,
  450. 'normalize_factor': 1,
  451. }
  452. _order = 'sequence'
  453. _sql_constraints = [
  454. ('duration', 'CHECK (duration>0)',
  455. 'Wrong duration, it must be positive!'),
  456. ('normalize_factor', 'CHECK (normalize_factor>0)',
  457. 'Wrong normalize factor, it must be positive!'),
  458. ('name_unique', 'unique(name, report_instance_id)',
  459. 'Period name should be unique by report'),
  460. ]
  461. def compute_domain(self, cr, uid, ids, account_, context=None):
  462. if isinstance(ids, (int, long)):
  463. ids = [ids]
  464. domain = []
  465. # extract all bal code
  466. account = _get_account_vars_in_expr(account_)
  467. account_s = _get_account_vars_in_expr(account_, is_solde=True)
  468. account_i = _get_account_vars_in_expr(account_, is_initial=True)
  469. all_code = []
  470. all_code.extend([_get_account_code(acc) for acc in account])
  471. all_code.extend([_get_account_code(acc) for acc in account_s])
  472. all_code.extend([_get_account_code(acc) for acc in account_i])
  473. domain.append(('account_id.code', 'in', all_code))
  474. # compute date/period
  475. period_ids = []
  476. date_from = None
  477. date_to = None
  478. period_obj = self.pool['account.period']
  479. for c in self.browse(cr, uid, ids, context=context):
  480. target_move = c.report_instance_id.target_move
  481. if target_move == 'posted':
  482. domain.append(('move_id.state', '=', target_move))
  483. if c.period_from:
  484. compute_period_ids = period_obj.build_ctx_periods(
  485. cr, uid, c.period_from.id, c.period_to.id)
  486. period_ids.extend(compute_period_ids)
  487. else:
  488. if not date_from or date_from > c.date_from:
  489. date_from = c.date_from
  490. if not date_to or date_to < c.date_to:
  491. date_to = c.date_to
  492. if period_ids:
  493. if date_from:
  494. domain.append('|')
  495. domain.append(('period_id', 'in', period_ids))
  496. if date_from:
  497. domain.extend([('date', '>=', c.date_from),
  498. ('date', '<=', c.date_to)])
  499. return domain
  500. def _fetch_account(self, cr, uid, company_id, account_vars, context=None,
  501. is_solde=False, is_initial=False):
  502. account_obj = self.pool['account.account']
  503. # TODO: use child of company_id?
  504. # first fetch all codes and filter the one we need+
  505. account_code = []
  506. for account_var in account_vars:
  507. account = _get_account_code(account_var)
  508. if account not in account_code:
  509. account_code.append(account)
  510. account_ids = account_obj.search(
  511. cr, uid,
  512. ['|', ('company_id', '=', False),
  513. ('company_id', '=', company_id),
  514. ('code', 'in', account_code)],
  515. context=context)
  516. # fetch balances
  517. account_datas = account_obj.read(
  518. cr, uid, account_ids, ['code', 'balance', 'credit', 'debit'],
  519. context=context)
  520. balances = {}
  521. for account_data in account_datas:
  522. for item in FUNCTION:
  523. key = _python_account_var(item[1], account_data['code'],
  524. is_solde=is_solde,
  525. is_initial=is_initial)
  526. assert key not in balances
  527. balances[key] = account_data[item[0]]
  528. return balances
  529. def _get_context_period(self, cr, uid, report_period, is_solde=False,
  530. is_initial=False, context=None):
  531. context_period = {}
  532. move_obj = self.pool['account.move']
  533. period_obj = self.pool['account.period']
  534. if not is_solde and not is_initial:
  535. if report_period.period_from:
  536. context_period.\
  537. update({'period_from': report_period.period_from.id,
  538. 'period_to': report_period.period_to.id})
  539. else:
  540. context_period.update({'date_from': report_period.date_from,
  541. 'date_to': report_period.date_to})
  542. else:
  543. period_to = report_period.period_to
  544. if is_initial:
  545. move_id = move_obj.search(
  546. cr, uid, [('period_id.special', '=', False),
  547. ('period_id.date_start', '<',
  548. period_to.date_start)],
  549. order="period_id desc", limit=1, context=context)
  550. if move_id:
  551. computed_period_to = move_obj.browse(
  552. cr, uid, move_id[0], context=context).period_id.id
  553. else:
  554. computed_period_to = self.pool['account.period'].search(
  555. cr, uid, [('company_id', '=',
  556. report_period.company_id.id)],
  557. order='date_start desc', limit=1)[0]
  558. # Change start period to search correctly period from
  559. period_to = period_obj.browse(cr, uid, [computed_period_to],
  560. context=context)[0]
  561. move_id = move_obj.search(
  562. cr, uid, [('period_id.special', '=', True),
  563. ('period_id.date_start', '<=',
  564. period_to.date_start)],
  565. order="period_id desc", limit=1, context=context)
  566. if move_id:
  567. computed_period_from = move_obj.browse(
  568. cr, uid, move_id[0], context=context).period_id.id
  569. else:
  570. computed_period_from = self.pool['account.period'].search(
  571. cr, uid, [('company_id', '=',
  572. report_period.company_id.id)],
  573. order='date_start', limit=1)[0]
  574. context_period.update({'period_from': computed_period_from,
  575. 'period_to': period_to.id})
  576. return context_period
  577. def _fetch_balances(self, cr, uid, c, account_vars, context=None):
  578. """ fetch the general account balances for the given period
  579. returns a dictionary {bal_<account.code>: account.balance}
  580. """
  581. if not account_vars:
  582. return {}
  583. if context is None:
  584. context = {}
  585. search_ctx = dict(context)
  586. search_ctx.update(self._get_context_period(cr, uid, c,
  587. context=context))
  588. # fetch balances
  589. return self._fetch_account(cr, uid, c.company_id.id, account_vars,
  590. search_ctx)
  591. def _fetch_balances_solde(self, cr, uid, c, account_vars, context=None):
  592. """ fetch the general account balances solde at the end of
  593. the given period
  594. the period from is computed by searching the last special period
  595. with journal entries.
  596. If nothing is found, the first period is used.
  597. returns a dictionary {bals_<account.code>: account.balance.solde}
  598. """
  599. if context is None:
  600. context = {}
  601. balances = {}
  602. if not account_vars:
  603. return balances
  604. search_ctx = dict(context)
  605. if c.period_to:
  606. search_ctx.update(self._get_context_period(cr, uid, c,
  607. is_solde=True,
  608. context=context))
  609. else:
  610. return balances
  611. # fetch balances
  612. return self._fetch_account(cr, uid, c.company_id.id, account_vars,
  613. search_ctx, is_solde=True)
  614. def _fetch_balances_initial(self, cr, uid, c, account_vars, context=None):
  615. if context is None:
  616. context = {}
  617. balances = {}
  618. if not account_vars:
  619. return balances
  620. search_ctx = dict(context)
  621. if c.period_to:
  622. search_ctx.update(self._get_context_period(cr, uid, c,
  623. is_initial=True,
  624. context=context))
  625. else:
  626. return balances
  627. # fetch balances
  628. return self._fetch_account(cr, uid, c.company_id.id, account_vars,
  629. search_ctx, is_initial=True)
  630. def _fetch_queries(self, cr, uid, c, context):
  631. res = {}
  632. report = c.report_instance_id.report_id
  633. for query in report.query_ids:
  634. obj = self.pool[query.model_id.model]
  635. domain = query.domain and safe_eval(query.domain) or []
  636. if query.date_field.ttype == 'date':
  637. domain.extend([(query.date_field.name, '>=', c.date_from),
  638. (query.date_field.name, '<=', c.date_to)])
  639. else:
  640. datetime_from = _utc_midnight(
  641. c.date_from, context.get('tz', 'UTC'))
  642. datetime_to = _utc_midnight(
  643. c.date_to, context.get('tz', 'UTC'), add_day=1)
  644. domain.extend([(query.date_field.name, '>=', datetime_from),
  645. (query.date_field.name, '<', datetime_to)])
  646. if obj._columns.get('company_id', False):
  647. domain.extend(['|', ('company_id', '=', False),
  648. ('company_id', '=', c.company_id.id)])
  649. field_names = [field.name for field in query.field_ids]
  650. obj_ids = obj.search(cr, uid, domain, context=context)
  651. obj_datas = obj.read(
  652. cr, uid, obj_ids, field_names, context=context)
  653. res[query.name] = [AutoStruct(**d) for d in obj_datas]
  654. return res
  655. def _compute(self, cr, uid, lang_id, c, account_vars, accounts_vars,
  656. accounti_vars, context=None):
  657. if context is None:
  658. context = {}
  659. kpi_obj = self.pool['mis.report.kpi']
  660. res = {}
  661. localdict = {
  662. 'registry': self.pool,
  663. 'sum': sum,
  664. 'min': min,
  665. 'max': max,
  666. 'len': len,
  667. 'avg': lambda l: sum(l) / float(len(l)),
  668. }
  669. localdict.update(self._fetch_balances(cr, uid, c, account_vars,
  670. context=context))
  671. localdict.update(self._fetch_balances_solde(cr, uid, c, accounts_vars,
  672. context=context))
  673. localdict.update(self._fetch_balances_initial(cr, uid, c,
  674. accounti_vars,
  675. context=context))
  676. localdict.update(self._fetch_queries(cr, uid, c,
  677. context=context))
  678. for kpi in c.report_instance_id.report_id.kpi_ids:
  679. try:
  680. kpi_val_comment = kpi.expression
  681. kpi_val = safe_eval(kpi.expression, localdict)
  682. except ZeroDivisionError:
  683. kpi_val = None
  684. kpi_val_rendered = '#DIV/0'
  685. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  686. except:
  687. kpi_val = None
  688. kpi_val_rendered = '#ERR'
  689. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  690. else:
  691. kpi_val_rendered = kpi_obj._render(
  692. cr, uid, lang_id, kpi, kpi_val, context=context)
  693. localdict[kpi.name] = kpi_val
  694. try:
  695. kpi_style = None
  696. if kpi.css_style:
  697. kpi_style = safe_eval(kpi.css_style, localdict)
  698. except:
  699. kpi_style = None
  700. res[kpi.name] = {
  701. 'val': kpi_val,
  702. 'val_r': kpi_val_rendered,
  703. 'val_c': kpi_val_comment,
  704. 'style': kpi_style,
  705. 'default_style': kpi.default_css_style or None,
  706. 'suffix': kpi.suffix,
  707. 'dp': kpi.dp,
  708. 'is_percentage': kpi.type == 'pct',
  709. 'period_id': c.id,
  710. 'period_name': c.name,
  711. }
  712. return res
  713. class mis_report_instance(orm.Model):
  714. """ The MIS report instance combines compute and
  715. display a MIS report template for a set of periods """
  716. def _get_pivot_date(self, cr, uid, ids, field_name, arg, context=None):
  717. res = {}
  718. for r in self.browse(cr, uid, ids, context=context):
  719. if r.date:
  720. res[r.id] = r.date
  721. else:
  722. res[r.id] = fields.date.context_today(self, cr, uid,
  723. context=context)
  724. return res
  725. _name = 'mis.report.instance'
  726. _columns = {
  727. 'name': fields.char(size=32, required=True,
  728. string='Name', translate=True),
  729. 'description': fields.char(required=False,
  730. string='Description', translate=True),
  731. 'date': fields.date(string='Base date',
  732. help='Report base date '
  733. '(leave empty to use current date)'),
  734. 'pivot_date': fields.function(_get_pivot_date,
  735. type='date',
  736. string="Pivot date"),
  737. 'report_id': fields.many2one('mis.report',
  738. required=True,
  739. string='Report'),
  740. 'period_ids': fields.one2many('mis.report.instance.period',
  741. 'report_instance_id',
  742. required=True,
  743. string='Periods'),
  744. 'target_move': fields.selection([('posted', 'All Posted Entries'),
  745. ('all', 'All Entries'),
  746. ], 'Target Moves', required=True),
  747. 'company_id': fields.many2one('res.company', 'Company', required=True),
  748. }
  749. _defaults = {
  750. 'target_move': 'posted',
  751. 'company_id': lambda s, cr, uid, c:
  752. s.pool.get('res.company')._company_default_get(
  753. cr, uid,
  754. 'mis.report.instance',
  755. context=c)
  756. }
  757. def create(self, cr, uid, vals, context=None):
  758. if not vals:
  759. return context.get('active_id', None)
  760. # TODO: explain this
  761. if 'period_ids' in vals:
  762. mis_report_instance_period_obj = self.pool.get(
  763. 'mis.report.instance.period')
  764. for idx, line in enumerate(vals['period_ids']):
  765. if line[0] == 0:
  766. line[2]['sequence'] = idx + 1
  767. else:
  768. mis_report_instance_period_obj.write(
  769. cr, uid, [line[1]], {'sequence': idx + 1},
  770. context=context)
  771. return super(mis_report_instance, self).create(cr, uid, vals,
  772. context=context)
  773. def write(self, cr, uid, ids, vals, context=None):
  774. # TODO: explain this
  775. res = super(mis_report_instance, self).write(
  776. cr, uid, ids, vals, context=context)
  777. mis_report_instance_period_obj = self.pool.get(
  778. 'mis.report.instance.period')
  779. for instance in self.browse(cr, uid, ids, context):
  780. for idx, period in enumerate(instance.period_ids):
  781. mis_report_instance_period_obj.write(
  782. cr, uid, [period.id], {'sequence': idx + 1},
  783. context=context)
  784. return res
  785. def _format_date(self, cr, uid, lang_id, date, context=None):
  786. # format date following user language
  787. tformat = self.pool['res.lang'].read(
  788. cr, uid, lang_id, ['date_format'])[0]['date_format']
  789. return datetime.strftime(datetime.strptime(
  790. date,
  791. tools.DEFAULT_SERVER_DATE_FORMAT),
  792. tformat)
  793. def compute(self, cr, uid, _ids, context=None):
  794. assert isinstance(_ids, (int, long))
  795. if context is None:
  796. context = {}
  797. r = self.browse(cr, uid, _ids, context=context)
  798. context['state'] = r.target_move
  799. content = OrderedDict()
  800. # empty line name for header
  801. header = OrderedDict()
  802. header[''] = {'kpi_name': '', 'cols': [], 'default_style': ''}
  803. # initialize lines with kpi
  804. for kpi in r.report_id.kpi_ids:
  805. content[kpi.name] = {'kpi_name': kpi.description,
  806. 'cols': [],
  807. 'default_style': ''}
  808. report_instance_period_obj = self.pool.get(
  809. 'mis.report.instance.period')
  810. kpi_obj = self.pool.get('mis.report.kpi')
  811. period_values = {}
  812. account_vars = _get_account_vars_in_report(r.report_id)
  813. accounts_vars = _get_account_vars_in_report(r.report_id, is_solde=True)
  814. accounti_vars = _get_account_vars_in_report(r.report_id,
  815. is_initial=True)
  816. lang = self.pool['res.users'].read(
  817. cr, uid, uid, ['lang'], context=context)['lang']
  818. lang_id = self.pool['res.lang'].search(
  819. cr, uid, [('code', '=', lang)], context=context)
  820. for period in r.period_ids:
  821. # add the column header
  822. header['']['cols'].append(dict(
  823. name=period.name,
  824. date=(period.duration > 1 or period.type == 'w') and
  825. _('from %s to %s' %
  826. (period.period_from and period.period_from.name
  827. or self._format_date(cr, uid, lang_id, period.date_from,
  828. context=context),
  829. period.period_to and period.period_to.name
  830. or self._format_date(cr, uid, lang_id, period.date_to,
  831. context=context)))
  832. or period.period_from and period.period_from.name or
  833. period.date_from))
  834. # compute kpi values
  835. values = report_instance_period_obj._compute(
  836. cr, uid, lang_id, period, account_vars, accounts_vars,
  837. accounti_vars, context=context)
  838. period_values[period.name] = values
  839. for key in values:
  840. content[key]['default_style'] = values[key]['default_style']
  841. content[key]['cols'].append(values[key])
  842. # add comparison column
  843. for period in r.period_ids:
  844. for compare_col in period.comparison_column_ids:
  845. # add the column header
  846. header['']['cols'].append(
  847. dict(name='%s - %s' % (period.name, compare_col.name),
  848. date=''))
  849. column1_values = period_values[period.name]
  850. column2_values = period_values[compare_col.name]
  851. for kpi in r.report_id.kpi_ids:
  852. content[kpi.name]['cols'].append(
  853. {'val_r': kpi_obj._render_comparison(
  854. cr,
  855. uid,
  856. lang_id,
  857. kpi,
  858. column1_values[kpi.name]['val'],
  859. column2_values[kpi.name]['val'],
  860. period.normalize_factor,
  861. compare_col.normalize_factor,
  862. context=context)})
  863. return {'header': header,
  864. 'content': content}