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.

773 lines
31 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. # -*- encoding: 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 pytz
  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, tz_name, 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. utc_tz = pytz.timezone('UTC')
  48. context_tz = pytz.timezone(tz_name)
  49. local_timestamp = context_tz.localize(d, is_dst=False)
  50. return datetime.strftime(local_timestamp.astimezone(utc_tz),
  51. tools.DEFAULT_SERVER_DATETIME_FORMAT)
  52. def _python_var(var_str):
  53. return re.sub(r'\W|^(?=\d)', '_', var_str).lower()
  54. def _python_bal_var(account_code):
  55. return 'bal_' + re.sub(r'\W', '_', account_code)
  56. def _get_bal_vars_in_expr(expr):
  57. return re.findall(expr, r'\bbal_\w+')
  58. def _get_vars_in_expr(expr, varnames=None):
  59. if not varnames:
  60. return []
  61. varnames_re = r'\b' + r'\b|\b'.join(varnames) + r'\b'
  62. return re.findall(expr, varnames_re)
  63. class mis_report_kpi(orm.Model):
  64. """ A KPI is an element of a MIS report.
  65. In addition to a name and description, it has an expression
  66. to compute it based on queries defined in the MIS report.
  67. It also has various informations defining how to render it
  68. (numeric or percentage or a string, a suffix, divider) and
  69. how to render comparison of two values of the KPI.
  70. KPI are ordered inside the MIS report, as some KPI expressions
  71. can depend on other KPI that need to be computed before.
  72. """
  73. _name = 'mis.report.kpi'
  74. _columns = {
  75. 'name': fields.char(size=32, required=True,
  76. string='Name'),
  77. 'description': fields.char(required=True,
  78. string='Description',
  79. translate=True),
  80. 'expression': fields.char(required=True,
  81. string='Expression'),
  82. 'css_style': fields.char(string='CSS style expression'),
  83. 'type': fields.selection([('num', _('Numeric')),
  84. ('pct', _('Percentage')),
  85. ('str', _('String'))],
  86. required=True,
  87. string='Type'),
  88. 'divider': fields.selection([('1e-6', _('µ')),
  89. ('1e-3', _('m')),
  90. ('1', _('1')),
  91. ('1e3', _('k')),
  92. ('1e6', _('M'))],
  93. string='Factor'),
  94. 'dp': fields.integer(string='Rounding'),
  95. 'suffix': fields.char(size=16, string='Suffix'),
  96. 'compare_method': fields.selection([('diff', _('Difference')),
  97. ('pct', _('Percentage')),
  98. ('none', _('None'))],
  99. required=True,
  100. string='Comparison Method'),
  101. 'sequence': fields.integer(string='Sequence'),
  102. 'report_id': fields.many2one('mis.report', string='Report'),
  103. }
  104. _defaults = {
  105. 'type': 'num',
  106. 'divider': '1',
  107. 'dp': 0,
  108. 'compare_method': 'pct',
  109. 'sequence': 100,
  110. }
  111. _order = 'sequence'
  112. def _check_name(self, cr, uid, ids, context=None):
  113. # TODO: kpi name cannot start with bal
  114. # TODO: factor out the name check function (DRY)
  115. for record_name in self.read(cr, uid, ids, ['name']):
  116. if not re.match("[_A-Za-z][_a-zA-Z0-9]*$", record_name['name']):
  117. return False
  118. return True
  119. _constraints = [
  120. (_check_name, 'The name must be a valid python identifier', ['name']),
  121. ]
  122. def onchange_name(self, cr, uid, ids, name, context=None):
  123. # TODO: factor out the name check function (DRY)
  124. # check it is a valid python identifier
  125. res = {}
  126. if name and not re.match("[_A-Za-z][_a-zA-Z0-9]*$", name):
  127. res['warning'] = {
  128. 'title': 'Invalid name',
  129. 'message': 'The name must be a valid python identifier'}
  130. return res
  131. def onchange_description(self, cr, uid, ids, description, name,
  132. context=None):
  133. # construct name from description
  134. res = {}
  135. if description and not name:
  136. res = {'value': {'name': _python_var(description)}}
  137. return res
  138. def onchange_type(self, cr, uid, ids, kpi_type, context=None):
  139. res = {}
  140. if kpi_type == 'pct':
  141. res['value'] = {'compare_method': 'diff'}
  142. elif kpi_type == 'str':
  143. res['value'] = {'compare_method': 'none',
  144. 'divider': '',
  145. 'dp': 0}
  146. return res
  147. def _render(self, cr, uid, kpi, value, context=None):
  148. """ render a KPI value as a unicode string, ready for display """
  149. if kpi.type == 'num':
  150. return self._render_num(cr, uid, value, kpi.divider, kpi.dp,
  151. kpi.suffix, context=context)
  152. elif kpi.type == 'pct':
  153. return self._render_num(cr, uid, value, 0.01, kpi.dp, '%',
  154. context=context)
  155. else:
  156. return unicode(value)
  157. def _render_comparison(self, cr, uid, kpi, value, base_value,
  158. average_value, average_base_value, context=None):
  159. """ render the comparison of two KPI values, ready for display """
  160. if value is None or base_value is None:
  161. return ''
  162. if kpi.type == 'pct':
  163. return self._render_num(cr, uid, value - base_value, 0.01, kpi.dp,
  164. _('pp'), sign='+', context=context)
  165. elif kpi.type == 'num':
  166. if average_value:
  167. value = value / float(average_value)
  168. if average_base_value:
  169. base_value = base_value / float(average_base_value)
  170. if kpi.compare_method == 'diff':
  171. return self._render_num(cr, uid, value - base_value,
  172. kpi.divider,
  173. kpi.dp, kpi.suffix, sign='+',
  174. context=context)
  175. elif kpi.compare_method == 'pct' and base_value != 0:
  176. return self._render_num(cr, uid, value / base_value - 1,
  177. 0.01, kpi.dp, '%',
  178. sign='+', context=context)
  179. return ''
  180. def _render_num(self, cr, uid, value, divider, dp, suffix, sign='-',
  181. context=None):
  182. divider_label = _get_selection_label(
  183. self._columns['divider'].selection, divider)
  184. if divider_label == '1':
  185. divider_label = ''
  186. # format number following user language
  187. lang = self.pool['res.users'].read(
  188. cr, uid, uid, ['lang'], context=context)['lang']
  189. language_id = self.pool['res.lang'].search(
  190. cr, uid, [('code', '=', lang)], context=context)
  191. value = round(value / float(divider or 1), dp) or 0
  192. return '%s %s%s' % (self.pool['res.lang'].format(cr, uid, language_id,
  193. '%%%s.%df' % (
  194. sign, dp),
  195. value,
  196. grouping=True,
  197. context=context),
  198. divider_label, suffix or '')
  199. class mis_report_query(orm.Model):
  200. """ A query to fetch data for a MIS report.
  201. A query works on a model and has a domain and list of fields to fetch.
  202. At runtime, the domain is expanded with a "and" on the date/datetime field.
  203. """
  204. _name = 'mis.report.query'
  205. def _get_field_names(self, cr, uid, ids, name, args, context=None):
  206. res = {}
  207. for query in self.browse(cr, uid, ids, context=context):
  208. field_names = []
  209. for field in query.field_ids:
  210. field_names.append(field.name)
  211. res[query.id] = ', '.join(field_names)
  212. return res
  213. def onchange_field_ids(self, cr, uid, ids, field_ids, context=None):
  214. # compute field_names
  215. field_names = []
  216. for field in self.pool.get('ir.model.fields').read(cr, uid,
  217. field_ids[0][2],
  218. ['name'],
  219. context=context):
  220. field_names.append(field['name'])
  221. return {'value': {'field_names': ', '.join(field_names)}}
  222. _columns = {
  223. 'name': fields.char(size=32, required=True,
  224. string='Name'),
  225. 'model_id': fields.many2one('ir.model', required=True,
  226. string='Model'),
  227. 'field_ids': fields.many2many('ir.model.fields', required=True,
  228. string='Fields to fetch'),
  229. 'field_names': fields.function(_get_field_names, type='char',
  230. string='Fetched fields name',
  231. store={'mis.report.query':
  232. (lambda self, cr, uid, ids, c={}:
  233. ids, ['field_ids'], 20), }),
  234. 'date_field': fields.many2one('ir.model.fields', required=True,
  235. string='Date field',
  236. domain=[('ttype', 'in', ('date',
  237. 'datetime'))]),
  238. 'domain': fields.char(string='Domain'),
  239. 'report_id': fields.many2one('mis.report', string='Report'),
  240. }
  241. _order = 'name'
  242. def _check_name(self, cr, uid, ids, context=None):
  243. # TODO: factor out the name check function (DRY)
  244. # TODO: query name must start with bal
  245. for record_name in self.read(cr, uid, ids, ['name']):
  246. if not re.match("[_A-Za-z][_a-zA-Z0-9]*$", record_name['name']):
  247. return False
  248. return True
  249. _constraints = [
  250. (_check_name, 'The name must be a valid python identifier', ['name']),
  251. ]
  252. class mis_report(orm.Model):
  253. """ A MIS report template (without period information)
  254. The MIS report holds:
  255. * an implicit query fetching allow the account balances;
  256. for each account, the balance is stored in a variable named
  257. bal_{code} where {code} is the account code
  258. * a list of explicit queries; the result of each query is
  259. stored in a variable with same name as a query, containing as list
  260. of data structures populated with attributes for each fields to fetch
  261. * a list of KPI to be evaluated based on the variables resulting
  262. from the balance and queries
  263. """
  264. _name = 'mis.report'
  265. _columns = {
  266. 'name': fields.char(size=32, required=True,
  267. string='Name', translate=True),
  268. 'description': fields.char(required=False,
  269. string='Description', translate=True),
  270. 'query_ids': fields.one2many('mis.report.query', 'report_id',
  271. string='Queries'),
  272. 'kpi_ids': fields.one2many('mis.report.kpi', 'report_id',
  273. string='KPI\'s'),
  274. }
  275. # TODO: kpi name cannot be start with query name
  276. def create(self, cr, uid, vals, context=None):
  277. # TODO: explain this
  278. if 'kpi_ids' in vals:
  279. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  280. for idx, line in enumerate(vals['kpi_ids']):
  281. if line[0] == 0:
  282. line[2]['sequence'] = idx + 1
  283. else:
  284. mis_report_kpi_obj.write(
  285. cr, uid, [line[1]], {'sequence': idx + 1},
  286. context=context)
  287. return super(mis_report, self).create(cr, uid, vals, context=context)
  288. def write(self, cr, uid, ids, vals, context=None):
  289. # TODO: explain this
  290. res = super(mis_report, self).write(
  291. cr, uid, ids, vals, context=context)
  292. mis_report_kpi_obj = self.pool.get('mis.report.kpi')
  293. for report in self.browse(cr, uid, ids, context):
  294. for idx, kpi in enumerate(report.kpi_ids):
  295. mis_report_kpi_obj.write(
  296. cr, uid, [kpi.id], {'sequence': idx + 1}, context=context)
  297. return res
  298. class mis_report_instance_period(orm.Model):
  299. """ A MIS report instance has the logic to compute
  300. a report template for a give date period.
  301. Periods have a duration (day, week, fiscal period) and
  302. are defined as an offset relative to a pivot date.
  303. """
  304. def _get_dates(self, cr, uid, ids, field_names, arg, context=None):
  305. if isinstance(ids, (int, long)):
  306. ids = [ids]
  307. res = {}
  308. for c in self.browse(cr, uid, ids, context=context):
  309. d = parser.parse(c.report_instance_id.pivot_date)
  310. if c.type == 'd':
  311. date_from = d + timedelta(days=c.offset)
  312. date_to = date_from + timedelta(days=c.duration - 1)
  313. date_from = date_from.strftime(
  314. tools.DEFAULT_SERVER_DATE_FORMAT)
  315. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  316. period_ids = None
  317. elif c.type == 'w':
  318. date_from = d - timedelta(d.weekday())
  319. date_from = date_from + timedelta(days=c.offset * 7)
  320. date_to = date_from + timedelta(days=(7 * c.duration) - 1)
  321. date_from = date_from.strftime(
  322. tools.DEFAULT_SERVER_DATE_FORMAT)
  323. date_to = date_to.strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
  324. period_ids = None
  325. elif c.type == 'fp':
  326. period_obj = self.pool['account.period']
  327. all_period_ids = period_obj.search(
  328. cr, uid,
  329. [('special', '=', False),
  330. '|', (
  331. 'company_id', '=',
  332. False),
  333. ('company_id', '=',
  334. c.company_id.id)],
  335. order='date_start',
  336. context=context)
  337. current_period_ids = period_obj.search(
  338. cr, uid,
  339. [('special', '=', False),
  340. ('date_start', '<=', d),
  341. ('date_stop',
  342. '>=', d),
  343. '|',
  344. ('company_id',
  345. '=', False),
  346. ('company_id', '=', c.company_id.id)],
  347. context=context)
  348. if not current_period_ids:
  349. raise orm.except_orm(_("Error!"),
  350. _("No current fiscal period for %s")
  351. % d)
  352. p = all_period_ids.index(current_period_ids[0]) + c.offset
  353. if p < 0 or p >= len(all_period_ids):
  354. raise orm.except_orm(_("Error!"),
  355. _("No such fiscal period for %s "
  356. "with offset %d") % (d, c.offset))
  357. period_ids = all_period_ids[p:p + c.duration]
  358. periods = period_obj.browse(cr, uid, period_ids,
  359. context=context)
  360. date_from = periods[0].date_start
  361. date_to = periods[-1].date_stop
  362. else:
  363. raise orm.except_orm(_("Error!"),
  364. _("Unimplemented period type %s") %
  365. (c.type,))
  366. res[c.id] = {
  367. 'date_from': date_from,
  368. 'date_to': date_to,
  369. 'period_from': period_ids and period_ids[0],
  370. 'period_to': period_ids and period_ids[-1],
  371. }
  372. return res
  373. _name = 'mis.report.instance.period'
  374. _columns = {
  375. 'name': fields.char(size=32, required=True,
  376. string='Description', translate=True),
  377. 'type': fields.selection([('d', _('Day')),
  378. ('w', _('Week')),
  379. ('fp', _('Fiscal Period')),
  380. # ('fy', _('Fiscal Year'))
  381. ],
  382. required=True,
  383. string='Period type'),
  384. 'offset': fields.integer(string='Offset',
  385. help='Offset from current period'),
  386. 'duration': fields.integer(string='Duration',
  387. help='Number of periods'),
  388. 'date_from': fields.function(_get_dates,
  389. type='date',
  390. multi="dates",
  391. string="From"),
  392. 'date_to': fields.function(_get_dates,
  393. type='date',
  394. multi="dates",
  395. string="To"),
  396. 'period_from': fields.function(_get_dates,
  397. type='many2one', obj='account.period',
  398. multi="dates", string="From period"),
  399. 'period_to': fields.function(_get_dates,
  400. type='many2one', obj='account.period',
  401. multi="dates", string="To period"),
  402. 'sequence': fields.integer(string='Sequence'),
  403. 'report_instance_id': fields.many2one('mis.report.instance',
  404. string='Report Instance'),
  405. 'comparison_column_ids': fields.many2many(
  406. 'mis.report.instance.period',
  407. 'mis_report_instance_period_rel',
  408. 'period_id',
  409. 'compare_period_id',
  410. string='Compare with'),
  411. 'company_id': fields.many2one('res.company', 'Company', required=True),
  412. 'normalize_factor': fields.integer(
  413. string='Factor',
  414. help='Factor to use to normalize the period (used in comparison'),
  415. }
  416. _defaults = {
  417. 'offset': -1,
  418. 'duration': 1,
  419. 'sequence': 100,
  420. 'normalize_factor': 1,
  421. 'company_id': lambda s, cr, uid, c:
  422. s.pool.get('res.company')._company_default_get(
  423. cr, uid,
  424. 'mis.report.instance.period',
  425. context=c)
  426. }
  427. _order = 'sequence'
  428. _sql_constraints = [
  429. ('duration', 'CHECK (duration>0)',
  430. 'Wrong duration, it must be positive!'),
  431. ('normalize_factor', 'CHECK (normalize_factor>0)',
  432. 'Wrong normalize factor, it must be positive!'),
  433. ('name_unique', 'unique(name, report_instance_id)',
  434. 'Period name should be unique by report'),
  435. ]
  436. def _fetch_balances(self, cr, uid, c, context=None):
  437. """ fetch the general account balances for the given period
  438. returns a dictionary {bal_<account.code>: account.balance}
  439. """
  440. if context is None:
  441. context = {}
  442. account_obj = self.pool['account.account']
  443. search_ctx = dict(context)
  444. if c.period_from:
  445. search_ctx.update({'period_from': c.period_from.id,
  446. 'period_to': c.period_to.id})
  447. else:
  448. search_ctx.update({'date_from': c.date_from,
  449. 'date_to': c.date_to})
  450. # TODO: initial balance?
  451. # TODO: use child of company_id?
  452. account_ids = account_obj.search(
  453. cr, uid,
  454. ['|', ('company_id', '=', False),
  455. ('company_id', '=', c.company_id.id)],
  456. context=context)
  457. account_datas = account_obj.read(
  458. cr, uid, account_ids, ['code', 'balance'], context=search_ctx)
  459. balances = {}
  460. for account_data in account_datas:
  461. key = _python_bal_var(account_data['code'])
  462. assert key not in balances
  463. balances[key] = account_data['balance']
  464. return balances
  465. def _fetch_queries(self, cr, uid, c, context):
  466. res = {}
  467. report = c.report_instance_id.report_id
  468. for query in report.query_ids:
  469. obj = self.pool[query.model_id.model]
  470. domain = query.domain and safe_eval(query.domain) or []
  471. if query.date_field.ttype == 'date':
  472. domain.extend([(query.date_field.name, '>=', c.date_from),
  473. (query.date_field.name, '<=', c.date_to)])
  474. else:
  475. datetime_from = _utc_midnight(
  476. c.date_from, context.get('tz', 'UTC'))
  477. datetime_to = _utc_midnight(
  478. c.date_to, context.get('tz', 'UTC'), add_day=1)
  479. domain.extend([(query.date_field.name, '>=', datetime_from),
  480. (query.date_field.name, '<', datetime_to)])
  481. if obj._columns.get('company_id', False):
  482. domain.extend(['|', ('company_id', '=', False),
  483. ('company_id', '=', c.company_id.id)])
  484. field_names = [field.name for field in query.field_ids]
  485. obj_ids = obj.search(cr, uid, domain, context=context)
  486. obj_datas = obj.read(
  487. cr, uid, obj_ids, field_names, context=context)
  488. res[query.name] = [AutoStruct(**d) for d in obj_datas]
  489. return res
  490. def _get_bal_vars_in_report(self, report):
  491. res = set()
  492. for kpi in report.kpi_ids:
  493. for bal_var in _get_bal_vars_in_expr(kpi.expression):
  494. res.add(bal_var)
  495. return res
  496. def _compute(self, cr, uid, c, context=None):
  497. if context is None:
  498. context = {}
  499. kpi_obj = self.pool['mis.report.kpi']
  500. res = {}
  501. localdict = {
  502. 'registry': self.pool,
  503. 'sum': sum,
  504. 'min': min,
  505. 'max': max,
  506. 'len': len,
  507. 'avg': lambda l: sum(l) / float(len(l)),
  508. }
  509. localdict.update(self._fetch_balances(cr, uid, c, context=context))
  510. localdict.update(self._fetch_queries(cr, uid, c, context=context))
  511. for kpi in c.report_instance_id.report_id.kpi_ids:
  512. try:
  513. kpi_val = safe_eval(kpi.expression, localdict)
  514. except ZeroDivisionError:
  515. kpi_val = None
  516. kpi_val_rendered = '#DIV/0'
  517. kpi_val_comment = traceback.format_exc()
  518. except:
  519. kpi_val = None
  520. kpi_val_rendered = '#ERR'
  521. kpi_val_comment = traceback.format_exc()
  522. else:
  523. kpi_val_rendered = kpi_obj._render(
  524. cr, uid, kpi, kpi_val, context=context)
  525. kpi_val_comment = None
  526. localdict[kpi.name] = kpi_val
  527. try:
  528. kpi_style = None
  529. if kpi.css_style:
  530. kpi_style = safe_eval(kpi.css_style, localdict)
  531. except:
  532. kpi_style = None
  533. res[kpi.name] = {
  534. 'val': kpi_val,
  535. 'val_r': kpi_val_rendered,
  536. 'val_c': kpi_val_comment,
  537. 'style': kpi_style,
  538. 'suffix': kpi.suffix,
  539. 'dp': kpi.dp,
  540. 'is_percentage': kpi.type == 'pct',
  541. }
  542. return res
  543. class mis_report_instance(orm.Model):
  544. """ The MIS report instance combines compute and
  545. display a MIS report template for a set of periods """
  546. def _get_pivot_date(self, cr, uid, ids, field_name, arg, context=None):
  547. res = {}
  548. for r in self.browse(cr, uid, ids, context=context):
  549. if r.date:
  550. res[r.id] = r.date
  551. else:
  552. res[r.id] = fields.date.context_today(self, cr, uid,
  553. context=context)
  554. return res
  555. _name = 'mis.report.instance'
  556. _columns = {
  557. 'name': fields.char(size=32, required=True,
  558. string='Name', translate=True),
  559. 'description': fields.char(required=False,
  560. string='Description', translate=True),
  561. 'date': fields.date(string='Base date',
  562. help='Report base date '
  563. '(leave empty to use current date)'),
  564. 'pivot_date': fields.function(_get_pivot_date,
  565. type='date',
  566. string="Pivot date"),
  567. 'report_id': fields.many2one('mis.report',
  568. required=True,
  569. string='Report'),
  570. 'period_ids': fields.one2many('mis.report.instance.period',
  571. 'report_instance_id',
  572. required=True,
  573. string='Periods'),
  574. 'target_move': fields.selection([('posted', 'All Posted Entries'),
  575. ('all', 'All Entries'),
  576. ], 'Target Moves', required=True),
  577. }
  578. _defaults = {
  579. 'target_move': 'posted',
  580. }
  581. def create(self, cr, uid, vals, context=None):
  582. if 'period_ids' in vals:
  583. mis_report_instance_period_obj = self.pool.get(
  584. 'mis.report.instance.period')
  585. for idx, line in enumerate(vals['period_ids']):
  586. if line[0] == 0:
  587. line[2]['sequence'] = idx + 1
  588. else:
  589. mis_report_instance_period_obj.write(
  590. cr, uid, [line[1]], {'sequence': idx + 1},
  591. context=context)
  592. return super(mis_report_instance, self).create(cr, uid, vals,
  593. context=context)
  594. def write(self, cr, uid, ids, vals, context=None):
  595. res = super(mis_report_instance, self).write(
  596. cr, uid, ids, vals, context=context)
  597. mis_report_instance_period_obj = self.pool.get(
  598. 'mis.report.instance.period')
  599. for instance in self.browse(cr, uid, ids, context):
  600. for idx, period in enumerate(instance.period_ids):
  601. mis_report_instance_period_obj.write(
  602. cr, uid, [period.id], {'sequence': idx + 1},
  603. context=context)
  604. return res
  605. def _format_date(self, cr, uid, date, context=None):
  606. # format date following user language
  607. lang = self.pool['res.users'].read(
  608. cr, uid, uid, ['lang'], context=context)['lang']
  609. language_id = self.pool['res.lang'].search(
  610. cr, uid, [('code', '=', lang)], context=context)[0]
  611. tformat = self.pool['res.lang'].read(
  612. cr, uid, language_id, ['date_format'])['date_format']
  613. return datetime.strftime(datetime.strptime(
  614. date,
  615. tools.DEFAULT_SERVER_DATE_FORMAT),
  616. tformat)
  617. def compute(self, cr, uid, _ids, context=None):
  618. assert isinstance(_ids, (int, long))
  619. if context is None:
  620. context = {}
  621. r = self.browse(cr, uid, _ids, context=context)
  622. context['state'] = r.target_move
  623. content = OrderedDict()
  624. # empty line name for header
  625. header = OrderedDict()
  626. header[''] = {'kpi_name': '', 'cols': []}
  627. # initialize lines with kpi
  628. for kpi in r.report_id.kpi_ids:
  629. content[kpi.name] = {'kpi_name': kpi.description, 'cols': []}
  630. report_instance_period_obj = self.pool.get(
  631. 'mis.report.instance.period')
  632. kpi_obj = self.pool.get('mis.report.kpi')
  633. period_values = {}
  634. for period in r.period_ids:
  635. # add the column header
  636. header['']['cols'].append(dict(
  637. name=period.name,
  638. date=(period.duration > 1 or period.type == 'w') and
  639. _('from %s to %s' %
  640. (period.period_from and period.period_from.name
  641. or self._format_date(cr, uid, period.date_from,
  642. context=context),
  643. period.period_to and period.period_to.name
  644. or self._format_date(cr, uid, period.date_to,
  645. context=context)))
  646. or period.period_from and period.period_from.name or
  647. period.date_from))
  648. # compute kpi values
  649. values = report_instance_period_obj._compute(
  650. cr, uid, period, context=context)
  651. period_values[period.name] = values
  652. for key in values:
  653. content[key]['cols'].append(values[key])
  654. # add comparison column
  655. for period in r.period_ids:
  656. for compare_col in period.comparison_column_ids:
  657. # add the column header
  658. header['']['cols'].append(
  659. dict(name='%s - %s' % (period.name, compare_col.name),
  660. date=''))
  661. column1_values = period_values[period.name]
  662. column2_values = period_values[compare_col.name]
  663. for kpi in r.report_id.kpi_ids:
  664. content[kpi.name]['cols'].append(
  665. {'val_r': kpi_obj._render_comparison(
  666. cr,
  667. uid,
  668. kpi,
  669. column1_values[kpi.name]['val'],
  670. column2_values[kpi.name]['val'],
  671. period.normalize_factor,
  672. compare_col.normalize_factor,
  673. context=context)})
  674. return {'header': header,
  675. 'content': content}