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.

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