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.

1054 lines
43 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 review
  494. def compute_domain(self, cr, uid, ids, account_, context=None):
  495. if isinstance(ids, (int, long)):
  496. ids = [ids]
  497. domain_list = []
  498. # extract all bal code
  499. res_vars = {}
  500. domain_mapping = {}
  501. _get_account_vars_in_expr(account_, res_vars, domain_mapping,
  502. is_solde=False, is_initial=False)
  503. for key_domain, account_code in res_vars.iteritems():
  504. key, domain = key_domain
  505. partial_domain = [('account_id.code', 'in', list(account_code))]
  506. if domain != '':
  507. partial_domain.insert(0, '&')
  508. domain_eval = safe_eval(domain)
  509. partial_domain.extend(domain_eval)
  510. domain_list.extend(partial_domain)
  511. nb_or = len(res_vars) - 1
  512. while nb_or > 0:
  513. domain_list.insert(0, '|')
  514. nb_or -= 1
  515. # compute date/period
  516. period_ids = []
  517. date_from = None
  518. date_to = None
  519. period_obj = self.pool['account.period']
  520. for c in self.browse(cr, uid, ids, context=context):
  521. target_move = c.report_instance_id.target_move
  522. if target_move == 'posted':
  523. domain_list.append(('move_id.state', '=', target_move))
  524. if c.period_from:
  525. compute_period_ids = period_obj.build_ctx_periods(
  526. cr, uid, c.period_from.id, c.period_to.id)
  527. period_ids.extend(compute_period_ids)
  528. else:
  529. if not date_from or date_from > c.date_from:
  530. date_from = c.date_from
  531. if not date_to or date_to < c.date_to:
  532. date_to = c.date_to
  533. if period_ids:
  534. if date_from:
  535. domain_list.append('|')
  536. domain_list.append(('period_id', 'in', period_ids))
  537. if date_from:
  538. domain_list.extend([('date', '>=', c.date_from),
  539. ('date', '<=', c.date_to)])
  540. return domain_list
  541. def _fetch_account(self, cr, uid, company_id, account_vars, context=None,
  542. is_solde=False, is_initial=False):
  543. account_obj = self.pool['account.account']
  544. account_move_line_obj = self.pool['account.move.line']
  545. # TODO: use child of company_id?
  546. # first fetch all codes and filter the one we need+
  547. balances = {}
  548. for key_domain, account_code in account_vars.iteritems():
  549. key, domain = key_domain
  550. account_ids = account_obj.search(
  551. cr, uid,
  552. ['|', ('company_id', '=', False),
  553. ('company_id', '=', company_id),
  554. ('code', 'in', list(account_code))],
  555. context=context)
  556. # fetch balances
  557. where_clause = ''
  558. where_clause_params = ()
  559. if domain != '':
  560. domain_eval = safe_eval(domain)
  561. query = account_move_line_obj._where_calc(cr, uid, domain_eval,
  562. context=context)
  563. from_clause, where_clause, where_clause_params = \
  564. query.get_sql()
  565. assert from_clause == '"account_move_line"'
  566. where_clause = where_clause.replace("account_move_line", "l")
  567. where_clause_params = tuple(where_clause_params)
  568. context.update({'query': where_clause,
  569. 'query_params': where_clause_params})
  570. account_datas = account_obj\
  571. .read(cr, uid, account_ids,
  572. ['code', 'balance', 'credit', 'debit'], context=context)
  573. for account_data in account_datas:
  574. for item in FUNCTION:
  575. var = _python_account_var(item[1], account_data['code'],
  576. is_solde=is_solde,
  577. is_initial=is_initial)
  578. var = var + key
  579. assert key not in balances
  580. balances[var] = account_data[item[0]]
  581. return balances
  582. def _get_context_period(self, cr, uid, report_period, is_solde=False,
  583. is_initial=False, context=None):
  584. context_period = {}
  585. move_obj = self.pool['account.move']
  586. period_obj = self.pool['account.period']
  587. if not is_solde and not is_initial:
  588. if report_period.period_from:
  589. context_period.\
  590. update({'period_from': report_period.period_from.id,
  591. 'period_to': report_period.period_to.id})
  592. else:
  593. context_period.update({'date_from': report_period.date_from,
  594. 'date_to': report_period.date_to})
  595. else:
  596. period_to = report_period.period_to
  597. if is_initial:
  598. move_id = move_obj.search(
  599. cr, uid, [('period_id.special', '=', False),
  600. ('period_id.date_start', '<',
  601. period_to.date_start)],
  602. order="period_id desc", limit=1, context=context)
  603. if move_id:
  604. computed_period_to = move_obj.browse(
  605. cr, uid, move_id[0], context=context).period_id.id
  606. else:
  607. computed_period_to = self.pool['account.period'].search(
  608. cr, uid, [('company_id', '=',
  609. report_period.company_id.id)],
  610. order='date_start desc', limit=1)[0]
  611. # Change start period to search correctly period from
  612. period_to = period_obj.browse(cr, uid, [computed_period_to],
  613. context=context)[0]
  614. move_id = move_obj.search(
  615. cr, uid, [('period_id.special', '=', True),
  616. ('period_id.date_start', '<=',
  617. period_to.date_start)],
  618. order="period_id desc", limit=1, context=context)
  619. if move_id:
  620. computed_period_from = move_obj.browse(
  621. cr, uid, move_id[0], context=context).period_id.id
  622. else:
  623. computed_period_from = self.pool['account.period'].search(
  624. cr, uid, [('company_id', '=',
  625. report_period.company_id.id)],
  626. order='date_start', limit=1)[0]
  627. context_period.update({'period_from': computed_period_from,
  628. 'period_to': period_to.id})
  629. return context_period
  630. def _fetch_balances(self, cr, uid, c, account_vars, context=None):
  631. """ fetch the general account balances for the given period
  632. returns a dictionary {bal_<account.code>: account.balance}
  633. """
  634. if not account_vars:
  635. return {}
  636. if context is None:
  637. context = {}
  638. search_ctx = dict(context)
  639. search_ctx.update(self._get_context_period(cr, uid, c,
  640. context=context))
  641. # fetch balances
  642. return self._fetch_account(cr, uid, c.company_id.id, account_vars,
  643. search_ctx)
  644. def _fetch_balances_solde(self, cr, uid, c, account_vars, context=None):
  645. """ fetch the general account balances solde at the end of
  646. the given period
  647. the period from is computed by searching the last special period
  648. with journal entries.
  649. If nothing is found, the first period is used.
  650. returns a dictionary {bals_<account.code>: account.balance.solde}
  651. """
  652. if context is None:
  653. context = {}
  654. balances = {}
  655. if not account_vars:
  656. return balances
  657. search_ctx = dict(context)
  658. if c.period_to:
  659. search_ctx.update(self._get_context_period(cr, uid, c,
  660. is_solde=True,
  661. context=context))
  662. else:
  663. return balances
  664. # fetch balances
  665. return self._fetch_account(cr, uid, c.company_id.id, account_vars,
  666. search_ctx, is_solde=True)
  667. def _fetch_balances_initial(self, cr, uid, c, account_vars, context=None):
  668. if context is None:
  669. context = {}
  670. balances = {}
  671. if not account_vars:
  672. return balances
  673. search_ctx = dict(context)
  674. if c.period_to:
  675. search_ctx.update(self._get_context_period(cr, uid, c,
  676. is_initial=True,
  677. context=context))
  678. else:
  679. return balances
  680. # fetch balances
  681. return self._fetch_account(cr, uid, c.company_id.id, account_vars,
  682. search_ctx, is_initial=True)
  683. def _fetch_queries(self, cr, uid, c, context):
  684. res = {}
  685. report = c.report_instance_id.report_id
  686. for query in report.query_ids:
  687. obj = self.pool[query.model_id.model]
  688. domain = query.domain and safe_eval(query.domain) or []
  689. if query.date_field.ttype == 'date':
  690. domain.extend([(query.date_field.name, '>=', c.date_from),
  691. (query.date_field.name, '<=', c.date_to)])
  692. else:
  693. datetime_from = _utc_midnight(
  694. c.date_from, context.get('tz', 'UTC'))
  695. datetime_to = _utc_midnight(
  696. c.date_to, context.get('tz', 'UTC'), add_day=1)
  697. domain.extend([(query.date_field.name, '>=', datetime_from),
  698. (query.date_field.name, '<', datetime_to)])
  699. if obj._columns.get('company_id', False):
  700. domain.extend(['|', ('company_id', '=', False),
  701. ('company_id', '=', c.company_id.id)])
  702. field_names = [field.name for field in query.field_ids]
  703. obj_ids = obj.search(cr, uid, domain, context=context)
  704. obj_datas = obj.read(
  705. cr, uid, obj_ids, field_names, context=context)
  706. res[query.name] = [AutoStruct(**d) for d in obj_datas]
  707. return res
  708. def _compute(self, cr, uid, lang_id, c, account_vars, accounts_vars,
  709. accounti_vars, domain_mapping, context=None):
  710. if context is None:
  711. context = {}
  712. kpi_obj = self.pool['mis.report.kpi']
  713. res = {}
  714. localdict = {
  715. 'registry': self.pool,
  716. 'sum': sum,
  717. 'min': min,
  718. 'max': max,
  719. 'len': len,
  720. 'avg': lambda l: sum(l) / float(len(l)),
  721. }
  722. localdict.update(self._fetch_balances(cr, uid, c, account_vars,
  723. context=context))
  724. localdict.update(self._fetch_balances_solde(cr, uid, c, accounts_vars,
  725. context=context))
  726. localdict.update(self._fetch_balances_initial(cr, uid, c,
  727. accounti_vars,
  728. context=context))
  729. localdict.update(self._fetch_queries(cr, uid, c,
  730. context=context))
  731. for kpi in c.report_instance_id.report_id.kpi_ids:
  732. try:
  733. kpi_eval_expression = _get_eval_expression(kpi.expression,
  734. domain_mapping)
  735. kpi_val_comment = kpi.expression
  736. kpi_val = safe_eval(kpi_eval_expression, localdict)
  737. except ZeroDivisionError:
  738. kpi_val = None
  739. kpi_val_rendered = '#DIV/0'
  740. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  741. except:
  742. kpi_val = None
  743. kpi_val_rendered = '#ERR'
  744. kpi_val_comment += '\n\n%s' % (traceback.format_exc(),)
  745. else:
  746. kpi_val_rendered = kpi_obj._render(
  747. cr, uid, lang_id, kpi, kpi_val, context=context)
  748. localdict[kpi.name] = kpi_val
  749. try:
  750. kpi_style = None
  751. if kpi.css_style:
  752. kpi_style = safe_eval(kpi.css_style, localdict)
  753. except:
  754. kpi_style = None
  755. res[kpi.name] = {
  756. 'val': kpi_val,
  757. 'val_r': kpi_val_rendered,
  758. 'val_c': kpi_val_comment,
  759. 'style': kpi_style,
  760. 'default_style': kpi.default_css_style or None,
  761. 'suffix': kpi.suffix,
  762. 'dp': kpi.dp,
  763. 'is_percentage': kpi.type == 'pct',
  764. 'period_id': c.id,
  765. 'period_name': c.name,
  766. }
  767. return res
  768. class mis_report_instance(orm.Model):
  769. """ The MIS report instance combines compute and
  770. display a MIS report template for a set of periods """
  771. def _get_pivot_date(self, cr, uid, ids, field_name, arg, context=None):
  772. res = {}
  773. for r in self.browse(cr, uid, ids, context=context):
  774. if r.date:
  775. res[r.id] = r.date
  776. else:
  777. res[r.id] = fields.date.context_today(self, cr, uid,
  778. context=context)
  779. return res
  780. _name = 'mis.report.instance'
  781. _columns = {
  782. 'name': fields.char(size=32, required=True,
  783. string='Name', translate=True),
  784. 'description': fields.char(required=False,
  785. string='Description', translate=True),
  786. 'date': fields.date(string='Base date',
  787. help='Report base date '
  788. '(leave empty to use current date)'),
  789. 'pivot_date': fields.function(_get_pivot_date,
  790. type='date',
  791. string="Pivot date"),
  792. 'report_id': fields.many2one('mis.report',
  793. required=True,
  794. string='Report'),
  795. 'period_ids': fields.one2many('mis.report.instance.period',
  796. 'report_instance_id',
  797. required=True,
  798. string='Periods'),
  799. 'target_move': fields.selection([('posted', 'All Posted Entries'),
  800. ('all', 'All Entries'),
  801. ], 'Target Moves', required=True),
  802. 'company_id': fields.many2one('res.company', 'Company', required=True),
  803. }
  804. _defaults = {
  805. 'target_move': 'posted',
  806. 'company_id': lambda s, cr, uid, c:
  807. s.pool.get('res.company')._company_default_get(
  808. cr, uid,
  809. 'mis.report.instance',
  810. context=c)
  811. }
  812. def create(self, cr, uid, vals, context=None):
  813. if not vals:
  814. return context.get('active_id', None)
  815. # TODO: explain this
  816. if 'period_ids' in vals:
  817. mis_report_instance_period_obj = self.pool.get(
  818. 'mis.report.instance.period')
  819. for idx, line in enumerate(vals['period_ids']):
  820. if line[0] == 0:
  821. line[2]['sequence'] = idx + 1
  822. else:
  823. mis_report_instance_period_obj.write(
  824. cr, uid, [line[1]], {'sequence': idx + 1},
  825. context=context)
  826. return super(mis_report_instance, self).create(cr, uid, vals,
  827. context=context)
  828. def write(self, cr, uid, ids, vals, context=None):
  829. # TODO: explain this
  830. res = super(mis_report_instance, self).write(
  831. cr, uid, ids, vals, context=context)
  832. mis_report_instance_period_obj = self.pool.get(
  833. 'mis.report.instance.period')
  834. for instance in self.browse(cr, uid, ids, context):
  835. for idx, period in enumerate(instance.period_ids):
  836. mis_report_instance_period_obj.write(
  837. cr, uid, [period.id], {'sequence': idx + 1},
  838. context=context)
  839. return res
  840. def _format_date(self, cr, uid, lang_id, date, context=None):
  841. # format date following user language
  842. tformat = self.pool['res.lang'].read(
  843. cr, uid, lang_id, ['date_format'])[0]['date_format']
  844. return datetime.strftime(datetime.strptime(
  845. date,
  846. tools.DEFAULT_SERVER_DATE_FORMAT),
  847. tformat)
  848. def compute(self, cr, uid, _ids, context=None):
  849. assert isinstance(_ids, (int, long))
  850. if context is None:
  851. context = {}
  852. r = self.browse(cr, uid, _ids, context=context)
  853. context['state'] = r.target_move
  854. content = OrderedDict()
  855. # empty line name for header
  856. header = OrderedDict()
  857. header[''] = {'kpi_name': '', 'cols': [], 'default_style': ''}
  858. # initialize lines with kpi
  859. for kpi in r.report_id.kpi_ids:
  860. content[kpi.name] = {'kpi_name': kpi.description,
  861. 'cols': [],
  862. 'default_style': ''}
  863. report_instance_period_obj = self.pool.get(
  864. 'mis.report.instance.period')
  865. kpi_obj = self.pool.get('mis.report.kpi')
  866. period_values = {}
  867. domain_mapping = {}
  868. account_vars = _get_account_vars_in_report(r.report_id,
  869. domain_mapping)
  870. accounts_vars = _get_account_vars_in_report(r.report_id,
  871. domain_mapping,
  872. is_solde=True)
  873. accounti_vars = _get_account_vars_in_report(r.report_id,
  874. domain_mapping,
  875. is_initial=True)
  876. lang = self.pool['res.users'].read(
  877. cr, uid, uid, ['lang'], context=context)['lang']
  878. lang_id = self.pool['res.lang'].search(
  879. cr, uid, [('code', '=', lang)], context=context)
  880. for period in r.period_ids:
  881. # add the column header
  882. header['']['cols'].append(dict(
  883. name=period.name,
  884. date=(period.duration > 1 or period.type == 'w') and
  885. _('from %s to %s' %
  886. (period.period_from and period.period_from.name
  887. or self._format_date(cr, uid, lang_id, period.date_from,
  888. context=context),
  889. period.period_to and period.period_to.name
  890. or self._format_date(cr, uid, lang_id, period.date_to,
  891. context=context)))
  892. or period.period_from and period.period_from.name or
  893. period.date_from))
  894. # compute kpi values
  895. values = report_instance_period_obj._compute(
  896. cr, uid, lang_id, period, account_vars, accounts_vars,
  897. accounti_vars, domain_mapping, context=context)
  898. period_values[period.name] = values
  899. for key in values:
  900. content[key]['default_style'] = values[key]['default_style']
  901. content[key]['cols'].append(values[key])
  902. # add comparison column
  903. for period in r.period_ids:
  904. for compare_col in period.comparison_column_ids:
  905. # add the column header
  906. header['']['cols'].append(
  907. dict(name='%s - %s' % (period.name, compare_col.name),
  908. date=''))
  909. column1_values = period_values[period.name]
  910. column2_values = period_values[compare_col.name]
  911. for kpi in r.report_id.kpi_ids:
  912. content[kpi.name]['cols'].append(
  913. {'val_r': kpi_obj._render_comparison(
  914. cr,
  915. uid,
  916. lang_id,
  917. kpi,
  918. column1_values[kpi.name]['val'],
  919. column2_values[kpi.name]['val'],
  920. period.normalize_factor,
  921. compare_col.normalize_factor,
  922. context=context)})
  923. return {'header': header,
  924. 'content': content}