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.

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