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.

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