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.

603 lines
27 KiB

  1. # vim: set fileencoding=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. class AutoStruct(object):
  35. def __init__(self, **kwargs):
  36. for k, v in kwargs.items():
  37. setattr(self, k, v)
  38. def _get_selection_label(selection, value):
  39. for v, l in selection:
  40. if v == value:
  41. return l
  42. return ''
  43. def _utc_midnight(d, tz_name, add_day=0):
  44. d = datetime.strptime(d, tools.DEFAULT_SERVER_DATE_FORMAT)
  45. if add_day:
  46. d = d + timedelta(days=add_day)
  47. utc_tz = pytz.timezone('UTC')
  48. context_tz = pytz.timezone(tz_name)
  49. local_timestamp = context_tz.localize(d, is_dst=False)
  50. return datetime.strftime(local_timestamp.astimezone(utc_tz), tools.DEFAULT_SERVER_DATETIME_FORMAT)
  51. def _clean(varStr):
  52. return re.sub('\W|^(?=\d)', '_', varStr)
  53. class mis_report_kpi(orm.Model):
  54. """ A KPI is an element of a MIS report.
  55. In addition to a name and description, it has an expression
  56. to compute it based on queries defined in the MIS report.
  57. It also has various informations defining how to render it
  58. (numeric or percentage or a string, a suffix, divider) and
  59. how to render comparison of two values of the KPI.
  60. KPI are ordered inside the MIS report, as some KPI expressions
  61. can depend on other KPI that need to be computed before.
  62. """
  63. _name = 'mis.report.kpi'
  64. _columns = {
  65. 'name': fields.char(size=32, required=True,
  66. string='Name'),
  67. 'description': fields.char(required=True,
  68. string='Description',
  69. translate=True),
  70. 'expression': fields.char(required=True,
  71. string='Expression'),
  72. 'css_style': fields.char(string='CSS style'),
  73. 'type': fields.selection([('num', _('Numeric')),
  74. ('pct', _('Percentage')),
  75. ('str', _('String'))],
  76. required=True,
  77. string='Type'),
  78. 'divider': fields.selection([('1e-6', _('µ')),
  79. ('1e-3', _('m')),
  80. ('1', _('1')),
  81. ('1e3', _('k')),
  82. ('1e6', _('M'))],
  83. string='Factor'),
  84. 'dp': fields.integer(string='Rounding'),
  85. 'suffix': fields.char(size=16, string='Suffix'),
  86. 'compare_method': fields.selection([('diff', _('Difference')),
  87. ('pct', _('Percentage')),
  88. ('none', _('None'))],
  89. required=True,
  90. string='Comparison Method'),
  91. 'sequence': fields.integer(string='Sequence'),
  92. 'report_id': fields.many2one('mis.report', string='Report'),
  93. }
  94. _defaults = {
  95. 'type': 'num',
  96. 'divider': '1',
  97. 'dp': 0,
  98. 'compare_method': 'pct',
  99. 'sequence': 1,
  100. }
  101. _order = 'sequence'
  102. def _check_name(self, cr, uid, ids, context=None):
  103. for record_name in self.read(cr, uid, ids, ['name']):
  104. if not re.match("[_A-Za-z][_a-zA-Z0-9]*$", record_name['name']):
  105. return False
  106. return True
  107. _constraints = [
  108. (_check_name, 'The name must be a valid python identifier', ['name']),
  109. ]
  110. def onchange_name(self, cr, uid, ids, name, context=None):
  111. # check it is a valid python identifier
  112. res = {}
  113. if name and not re.match("[_A-Za-z][_a-zA-Z0-9]*$", name):
  114. res['warning'] = {'title': 'Invalid name', 'message': 'The name must be a valid python identifier'}
  115. return res
  116. def onchange_description(self, cr, uid, ids, description, name, context=None):
  117. # construct name from description
  118. res = {}
  119. if description and not name:
  120. res = {'value': {'name': _clean(description)}}
  121. return res
  122. def onchange_type(self, cr, uid, ids, kpi_type, context=None):
  123. res = {}
  124. if kpi_type == 'pct':
  125. res['value'] = {'compare_method': 'diff'}
  126. elif kpi_type == 'str':
  127. res['value'] = {'compare_method': 'none',
  128. 'divider': '',
  129. 'dp': 0}
  130. return res
  131. def _render(self, cr, uid, kpi, value, context=None):
  132. """ render a KPI value as a unicode string, ready for display """
  133. if kpi.type == 'num':
  134. return self._render_num(cr, uid, value, kpi.divider, kpi.dp, kpi.suffix, context=context)
  135. elif kpi.type == 'pct':
  136. return self._render_num(cr, uid, value, 0.01, kpi.dp, '%', context=context)
  137. else:
  138. return unicode(value)
  139. def _render_comparison(self, cr, uid, kpi, value, base_value, average_value, average_base_value, context=None):
  140. """ render the comparison of two KPI values, ready for display """
  141. if value is None or base_value is None:
  142. return ''
  143. if kpi.type == 'pct':
  144. return self._render_num(cr, uid, value - base_value, 0.01, kpi.dp, _('pp'), sign='+', context=context)
  145. elif kpi.type == 'num':
  146. if average_value:
  147. value = value / float(average_value)
  148. if average_base_value:
  149. base_value = base_value / float(average_base_value)
  150. if kpi.compare_method == 'diff':
  151. return self._render_num(cr, uid, value - base_value, kpi.divider,
  152. kpi.dp, kpi.suffix, sign='+', context=context)
  153. elif kpi.compare_method == 'pct' and base_value != 0:
  154. return self._render_num(cr, uid, value / base_value - 1,
  155. 0.01, kpi.dp, '%',
  156. sign='+', context=context)
  157. return ''
  158. def _render_num(self, cr, uid, value, divider, dp, suffix, sign='-', context=None):
  159. divider_label = _get_selection_label(self._columns['divider'].selection, divider)
  160. if divider_label == '1':
  161. divider_label = ''
  162. # format number following user language
  163. lang = self.pool['res.users'].read(cr, uid, uid, ['lang'], context=context)['lang']
  164. language_id = self.pool['res.lang'].search(cr, uid, [('code', '=', lang)], context=context)
  165. value = round(value / float(divider or 1), dp) or 0
  166. return '%s %s%s' % (self.pool['res.lang'].format(cr, uid, language_id,
  167. '%%%s.%df' % (sign, dp),
  168. value, context=context),
  169. divider_label, suffix or '')
  170. class mis_report_query(orm.Model):
  171. """ A query to fetch data for a MIS report.
  172. A query works on a model and has a domain and list of fields to fetch.
  173. At runtime, the domain is expanded with a "and" on the date/datetime field.
  174. """
  175. _name = 'mis.report.query'
  176. def _get_field_names(self, cr, uid, ids, name, args, context=None):
  177. res = {}
  178. for query in self.browse(cr, uid, ids, context=context):
  179. field_name = []
  180. for field in query.field_ids:
  181. field_name.append(field.name)
  182. res[query.id] = ', '.join(field_name)
  183. return res
  184. _columns = {
  185. 'name': fields.char(size=32, required=True,
  186. string='Name'),
  187. 'model_id': fields.many2one('ir.model', required=True,
  188. string='Model'),
  189. 'field_ids': fields.many2many('ir.model.fields', required=True,
  190. string='Fields to fetch'),
  191. 'field_name': fields.function(_get_field_names, type='char', string='Fetched fields name',
  192. store={'mis.report.query':
  193. (lambda self, cr, uid, ids, c={}: ids, ['field_ids'], 20), }),
  194. 'date_field': fields.many2one('ir.model.fields', required=True,
  195. string='Date field',
  196. domain=[('ttype', 'in', ('date', 'datetime'))]),
  197. 'domain': fields.char(string='Domain'),
  198. 'report_id': fields.many2one('mis.report', string='Report'),
  199. }
  200. _order = 'name'
  201. def _check_name(self, cr, uid, ids, context=None):
  202. for record_name in self.read(cr, uid, ids, ['name']):
  203. if not re.match("[_A-Za-z][_a-zA-Z0-9]*$", record_name['name']):
  204. return False
  205. return True
  206. _constraints = [
  207. (_check_name, 'The name must be a valid python identifier', ['name']),
  208. ]
  209. class mis_report(orm.Model):
  210. """ A MIS report template (without period information)
  211. The MIS report holds:
  212. * an implicit query fetching allow the account balances;
  213. for each account, the balance is stored in a variable named
  214. bal_{code} where {code} is the account code
  215. * a list of explicit queries; the result of each query is
  216. stored in a variable with same name as a query, containing as list
  217. of data structures populated with attributes for each fields to fetch
  218. * a list of KPI to be evaluated based on the variables resulting
  219. from the balance and queries
  220. """
  221. _name = 'mis.report'
  222. _columns = {
  223. 'name': fields.char(size=32, required=True,
  224. string='Name', translate=True),
  225. 'description': fields.char(required=False,
  226. string='Description', translate=True),
  227. 'query_ids': fields.one2many('mis.report.query', 'report_id',
  228. string='Queries'),
  229. 'kpi_ids': fields.one2many('mis.report.kpi', 'report_id',
  230. string='KPI\'s'),
  231. }
  232. class mis_report_instance_period(orm.Model):
  233. """ A MIS report instance has the logic to compute
  234. a report template for a give date period.
  235. Periods have a duration (day, week, fiscal period) and
  236. are defined as an offset relative to a pivot date.
  237. """
  238. def _get_dates(self, cr, uid, ids, field_names, arg, context=None):
  239. if isinstance(ids, (int, long)):
  240. ids = [ids]
  241. res = {}
  242. for c in self.browse(cr, uid, ids, context=context):
  243. d = parser.parse(c.report_instance_id.pivot_date)
  244. if c.type == 'd':
  245. date_from = d + timedelta(days=c.offset)
  246. date_to = date_from + timedelta(days=c.duration - 1)
  247. date_from = date_from.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  248. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  249. period_ids = None
  250. elif c.type == 'w':
  251. date_from = d - timedelta(d.weekday())
  252. date_from = date_from + timedelta(days=c.offset * 7)
  253. date_to = date_from + timedelta(days=(7 * c.duration) - 1)
  254. date_from = date_from.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  255. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  256. period_ids = None
  257. elif c.type == 'fp':
  258. period_obj = self.pool['account.period']
  259. all_period_ids = period_obj.search(cr, uid,
  260. [('special', '=', False), ('company_id', '=', c.company_id.id)],
  261. order='date_start',
  262. context=context)
  263. current_period_ids = period_obj.search(cr, uid,
  264. [('special', '=', False),
  265. ('date_start', '<=', d),
  266. ('date_stop', '>=', d),
  267. ('company_id', '=', c.company_id.id)],
  268. context=context)
  269. if not current_period_ids:
  270. raise orm.except_orm(_("Error!"),
  271. _("No current fiscal period for %s") % d)
  272. p = all_period_ids.index(current_period_ids[0]) + c.offset
  273. if p < 0 or p >= len(all_period_ids):
  274. raise orm.except_orm(_("Error!"),
  275. _("No such fiscal period for %s "
  276. "with offset %d") % (d, c.offset))
  277. period_ids = all_period_ids[p:p + c.duration]
  278. periods = period_obj.browse(cr, uid, period_ids,
  279. context=context)
  280. date_from = periods[0].date_start
  281. date_to = periods[-1].date_stop
  282. else:
  283. raise orm.except_orm(_("Error!"),
  284. _("Unimplemented period type %s") %
  285. (c.type,))
  286. res[c.id] = {
  287. 'date_from': date_from,
  288. 'date_to': date_to,
  289. 'period_from': period_ids and period_ids[0],
  290. 'period_to': period_ids and period_ids[-1],
  291. }
  292. return res
  293. _name = 'mis.report.instance.period'
  294. _columns = {
  295. 'name': fields.char(size=32, required=True,
  296. string='Description', translate=True),
  297. 'type': fields.selection([('d', _('Day')),
  298. ('w', _('Week')),
  299. ('fp', _('Fiscal Period')),
  300. # ('fy', _('Fiscal Year'))
  301. ],
  302. required=True,
  303. string='Period type'),
  304. 'offset': fields.integer(string='Offset',
  305. help='Offset from current period'),
  306. 'duration': fields.integer(string='Duration',
  307. help='Number of periods'),
  308. 'date_from': fields.function(_get_dates,
  309. type='date',
  310. multi="dates",
  311. string="From"),
  312. 'date_to': fields.function(_get_dates,
  313. type='date',
  314. multi="dates",
  315. string="To"),
  316. 'period_from': fields.function(_get_dates,
  317. type='many2one', obj='account.period',
  318. multi="dates", string="From period"),
  319. 'period_to': fields.function(_get_dates,
  320. type='many2one', obj='account.period',
  321. multi="dates", string="To period"),
  322. 'sequence': fields.integer(string='Sequence'),
  323. 'report_instance_id': fields.many2one('mis.report.instance',
  324. string='Report Instance'),
  325. 'comparison_column_ids': fields.many2many('mis.report.instance.period', 'mis_report_instance_period_rel',
  326. 'period_id', 'compare_period_id', string='Compare with'),
  327. 'company_id': fields.many2one('res.company', 'Company', required=True)
  328. }
  329. _defaults = {
  330. 'offset': -1,
  331. 'duration': 1,
  332. 'sequence': 1,
  333. 'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid,
  334. 'mis.report.instance.period',
  335. context=c)
  336. }
  337. _order = 'sequence'
  338. _sql_constraints = [
  339. ('duration', 'CHECK (duration>0)', 'Wrong duration, it must be positive!'),
  340. ('name_unique', 'unique(name, report_instance_id)', 'Period name should be unique by report'),
  341. ]
  342. def _fetch_balances(self, cr, uid, c, context=None):
  343. """ fetch the general account balances for the given period
  344. returns a dictionary {bal_<account.code>: account.balance}
  345. """
  346. if context is None:
  347. context = {}
  348. account_obj = self.pool['account.account']
  349. search_ctx = dict(context)
  350. if c.period_from:
  351. search_ctx.update({'period_from': c.period_from.id,
  352. 'period_to': c.period_to.id})
  353. else:
  354. search_ctx.update({'date_from': c.date_from,
  355. 'date_to': c.date_to})
  356. # TODO: initial balance?
  357. account_ids = account_obj.search(cr, uid, [('company_id', '=', c.company_id.id)], context=context)
  358. account_datas = account_obj.read(cr, uid, account_ids, ['code', 'balance'], context=search_ctx)
  359. balances = {}
  360. for account_data in account_datas:
  361. key = 'bal' + _clean(account_data['code'])
  362. assert key not in balances
  363. balances[key] = account_data['balance']
  364. return balances
  365. def _fetch_queries(self, cr, uid, c, context):
  366. res = {}
  367. report = c.report_instance_id.report_id
  368. for query in report.query_ids:
  369. obj = self.pool[query.model_id.model]
  370. domain = query.domain and safe_eval(query.domain) or []
  371. if query.date_field.ttype == 'date':
  372. domain.extend([(query.date_field.name, '>=', c.date_from),
  373. (query.date_field.name, '<=', c.date_to)])
  374. else:
  375. datetime_from = _utc_midnight(c.date_from, context.get('tz', 'UTC'))
  376. datetime_to = _utc_midnight(c.date_to, context.get('tz', 'UTC'), add_day=1)
  377. domain.extend([(query.date_field.name, '>=', datetime_from),
  378. (query.date_field.name, '<', datetime_to)])
  379. if obj._columns.get('company_id', False):
  380. domain.extend([('company_id', '=', c.company_id.id)])
  381. field_names = [field.name for field in query.field_ids]
  382. obj_ids = obj.search(cr, uid, domain, context=context)
  383. obj_datas = obj.read(cr, uid, obj_ids, field_names, context=context)
  384. res[query.name] = [AutoStruct(**d) for d in obj_datas]
  385. return res
  386. def _compute(self, cr, uid, c, context=None):
  387. if context is None:
  388. context = {}
  389. kpi_obj = self.pool['mis.report.kpi']
  390. res = {}
  391. localdict = {
  392. 'registry': self.pool,
  393. 'sum': sum,
  394. 'min': min,
  395. 'max': max,
  396. 'len': len,
  397. 'avg': lambda l: sum(l) / float(len(l)),
  398. }
  399. localdict.update(self._fetch_balances(cr, uid, c, context=context))
  400. localdict.update(self._fetch_queries(cr, uid, c, context=context))
  401. for kpi in c.report_instance_id.report_id.kpi_ids:
  402. try:
  403. kpi_val = safe_eval(kpi.expression, localdict)
  404. except ZeroDivisionError:
  405. kpi_val = None
  406. kpi_val_rendered = '#DIV/0'
  407. kpi_val_comment = traceback.format_exc()
  408. except:
  409. kpi_val = None
  410. kpi_val_rendered = '#ERR'
  411. kpi_val_comment = traceback.format_exc()
  412. else:
  413. kpi_val_rendered = kpi_obj._render(cr, uid, kpi, kpi_val, context=context)
  414. kpi_val_comment = None
  415. localdict[kpi.name] = kpi_val
  416. try:
  417. kpi_style = None
  418. if kpi.css_style:
  419. kpi_style = safe_eval(kpi.css_style, localdict)
  420. except:
  421. kpi_style = None
  422. res[kpi.name] = {
  423. 'val': kpi_val,
  424. 'val_r': kpi_val_rendered,
  425. 'val_c': kpi_val_comment,
  426. 'style': kpi_style,
  427. }
  428. return res
  429. class mis_report_instance(orm.Model):
  430. """ The MIS report instance combines compute and
  431. display a MIS report template for a set of periods """
  432. def _get_pivot_date(self, cr, uid, ids, field_name, arg, context=None):
  433. res = {}
  434. for r in self.browse(cr, uid, ids, context=context):
  435. if r.date:
  436. res[r.id] = r.date
  437. else:
  438. res[r.id] = fields.date.context_today(self, cr, uid,
  439. context=context)
  440. return res
  441. _name = 'mis.report.instance'
  442. _columns = {
  443. 'name': fields.char(size=32, required=True,
  444. string='Name', translate=True),
  445. 'description': fields.char(required=False,
  446. string='Description', translate=True),
  447. 'date': fields.date(string='Base date',
  448. help='Report base date '
  449. '(leave empty to use current date)'),
  450. 'pivot_date': fields.function(_get_pivot_date,
  451. type='date',
  452. string="Pivot date"),
  453. 'report_id': fields.many2one('mis.report',
  454. required=True,
  455. string='Report'),
  456. 'period_ids': fields.one2many('mis.report.instance.period',
  457. 'report_instance_id',
  458. required=True,
  459. string='Periods'),
  460. 'target_move': fields.selection([('posted', 'All Posted Entries'),
  461. ('all', 'All Entries'),
  462. ], 'Target Moves', required=True),
  463. }
  464. _defaults = {
  465. 'target_move': 'posted',
  466. }
  467. def _format_date(self, cr, uid, date, context=None):
  468. # format date following user language
  469. lang = self.pool['res.users'].read(cr, uid, uid, ['lang'], context=context)['lang']
  470. language_id = self.pool['res.lang'].search(cr, uid, [('code', '=', lang)], context=context)[0]
  471. tformat = self.pool['res.lang'].read(cr, uid, language_id, ['date_format'])['date_format']
  472. return datetime.strftime(datetime.strptime(date, tools.DEFAULT_SERVER_DATE_FORMAT), tformat)
  473. def compute(self, cr, uid, _ids, context=None):
  474. assert isinstance(_ids, (int, long))
  475. if context is None:
  476. context = {}
  477. r = self.browse(cr, uid, _ids, context=context)
  478. context['state'] = r.target_move
  479. content = OrderedDict()
  480. #empty line name for header
  481. header = OrderedDict()
  482. header[''] = {'kpi_name': '', 'cols': []}
  483. #initialize lines with kpi
  484. for kpi in r.report_id.kpi_ids:
  485. content[kpi.name] = {'kpi_name': kpi.description, 'cols': []}
  486. report_instance_period_obj = self.pool.get('mis.report.instance.period')
  487. kpi_obj = self.pool.get('mis.report.kpi')
  488. period_values = {}
  489. for period in r.period_ids:
  490. # add the column header
  491. header['']['cols'].append(dict(name=period.name,
  492. date=period.duration > 1 and
  493. _('from %s to %s' %
  494. (period.period_from and period.period_from.name
  495. or self._format_date(cr, uid, period.date_from, context=context),
  496. period.period_to and period.period_to.name
  497. or self._format_date(cr, uid, period.date_to, context=context)))
  498. or period.period_from and period.period_from.name or period.date_from))
  499. # compute kpi values
  500. values = report_instance_period_obj._compute(cr, uid, period, context=context)
  501. period_values[period.name] = values
  502. for key in values:
  503. content[key]['cols'].append(values[key])
  504. # add comparison column
  505. for period in r.period_ids:
  506. for compare_col in period.comparison_column_ids:
  507. # add the column header
  508. header['']['cols'].append(dict(name='%s - %s' % (period.name, compare_col.name), date=''))
  509. column1_values = period_values[period.name]
  510. column2_values = period_values[compare_col.name]
  511. for kpi in r.report_id.kpi_ids:
  512. content[kpi.name]['cols'].append({'val_r': kpi_obj._render_comparison(cr, uid, kpi,
  513. column1_values[kpi.name]['val'],
  514. column2_values[kpi.name]['val'],
  515. (datetime.strptime(period.date_to, tools.DEFAULT_SERVER_DATE_FORMAT) -
  516. datetime.strptime(period.date_from,
  517. tools.DEFAULT_SERVER_DATE_FORMAT)).days + 1,
  518. (datetime.strptime(compare_col.date_to, tools.DEFAULT_SERVER_DATE_FORMAT) -
  519. datetime.strptime(compare_col.date_from,
  520. tools.DEFAULT_SERVER_DATE_FORMAT)).days + 1,
  521. context=context)})
  522. return {'header': header,
  523. 'content': content}