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.

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