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.

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