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.

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