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.

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