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.

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