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.

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