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.

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