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.

447 lines
18 KiB

  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # OpenERP, Open Source Management Solution
  5. # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>).
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as
  9. # published by the Free Software Foundation, either version 3 of the
  10. # License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. from openerp import models, fields, api, modules, _, SUPERUSER_ID
  22. FIELDS_BLACKLIST = [
  23. 'id', 'create_uid', 'create_date', 'write_uid', 'write_date',
  24. 'display_name', '__last_update',
  25. ]
  26. # Used for performance, to avoid a dictionary instanciation when we need an
  27. # empty dict to simplify algorithms
  28. EMPTY_DICT = {}
  29. class DictDiffer(object):
  30. """Calculate the difference between two dictionaries as:
  31. (1) items added
  32. (2) items removed
  33. (3) keys same in both but changed values
  34. (4) keys same in both and unchanged values
  35. """
  36. def __init__(self, current_dict, past_dict):
  37. self.current_dict, self.past_dict = current_dict, past_dict
  38. self.set_current = set(current_dict)
  39. self.set_past = set(past_dict)
  40. self.intersect = self.set_current.intersection(self.set_past)
  41. def added(self):
  42. return self.set_current - self.intersect
  43. def removed(self):
  44. return self.set_past - self.intersect
  45. def changed(self):
  46. return set(o for o in self.intersect
  47. if self.past_dict[o] != self.current_dict[o])
  48. def unchanged(self):
  49. return set(o for o in self.intersect
  50. if self.past_dict[o] == self.current_dict[o])
  51. class auditlog_rule(models.Model):
  52. _name = 'auditlog.rule'
  53. _description = "Auditlog - Rule"
  54. name = fields.Char(u"Name", size=32, required=True)
  55. model_id = fields.Many2one(
  56. 'ir.model', u"Model", required=True,
  57. help=u"Select model for which you want to generate log.")
  58. user_ids = fields.Many2many(
  59. 'res.users',
  60. 'audittail_rules_users',
  61. 'user_id', 'rule_id',
  62. string=u"Users",
  63. help=u"if User is not added then it will applicable for all users")
  64. log_read = fields.Boolean(
  65. u"Log Reads",
  66. help=(u"Select this if you want to keep track of read/open on any "
  67. u"record of the model of this rule"))
  68. log_write = fields.Boolean(
  69. u"Log Writes", default=True,
  70. help=(u"Select this if you want to keep track of modification on any "
  71. u"record of the model of this rule"))
  72. log_unlink = fields.Boolean(
  73. u"Log Deletes", default=True,
  74. help=(u"Select this if you want to keep track of deletion on any "
  75. u"record of the model of this rule"))
  76. log_create = fields.Boolean(
  77. u"Log Creates", default=True,
  78. help=(u"Select this if you want to keep track of creation on any "
  79. u"record of the model of this rule"))
  80. # log_action = fields.Boolean(
  81. # "Log Action",
  82. # help=("Select this if you want to keep track of actions on the "
  83. # "model of this rule"))
  84. # log_workflow = fields.Boolean(
  85. # "Log Workflow",
  86. # help=("Select this if you want to keep track of workflow on any "
  87. # "record of the model of this rule"))
  88. state = fields.Selection(
  89. [('draft', "Draft"), ('subscribed', "Subscribed")],
  90. string=u"State", required=True, default='draft')
  91. action_id = fields.Many2one(
  92. 'ir.actions.act_window', string="Action")
  93. _sql_constraints = [
  94. ('model_uniq', 'unique(model_id)',
  95. ("There is already a rule defined on this model\n"
  96. "You cannot define another: please edit the existing one."))
  97. ]
  98. def _register_hook(self, cr, ids=None):
  99. """Get all rules and apply them to log method calls."""
  100. super(auditlog_rule, self)._register_hook(cr)
  101. if not hasattr(self.pool, '_auditlog_field_cache'):
  102. self.pool._auditlog_field_cache = {}
  103. if not hasattr(self.pool, '_auditlog_model_cache'):
  104. self.pool._auditlog_model_cache = {}
  105. if ids is None:
  106. ids = self.search(cr, SUPERUSER_ID, [('state', '=', 'subscribed')])
  107. return self._patch_methods(cr, SUPERUSER_ID, ids)
  108. @api.multi
  109. def _patch_methods(self):
  110. """Patch ORM methods of models defined in rules to log their calls."""
  111. updated = False
  112. model_cache = self.pool._auditlog_model_cache
  113. for rule in self:
  114. if rule.state != 'subscribed':
  115. continue
  116. if not self.pool.get(rule.model_id.model):
  117. # ignore rules for models not loadable currently
  118. continue
  119. model_cache[rule.model_id.model] = rule.model_id
  120. model_model = self.env[rule.model_id.model]
  121. # CRUD
  122. # -> create
  123. check_attr = 'auditlog_ruled_create'
  124. if getattr(rule, 'log_create') \
  125. and not hasattr(model_model, check_attr):
  126. model_model._patch_method('create', self._make_create())
  127. setattr(model_model, check_attr, True)
  128. updated = True
  129. # -> read
  130. check_attr = 'auditlog_ruled_read'
  131. if getattr(rule, 'log_read') \
  132. and not hasattr(model_model, check_attr):
  133. model_model._patch_method('read', self._make_read())
  134. setattr(model_model, check_attr, True)
  135. updated = True
  136. # -> write
  137. check_attr = 'auditlog_ruled_write'
  138. if getattr(rule, 'log_write') \
  139. and not hasattr(model_model, check_attr):
  140. model_model._patch_method('write', self._make_write())
  141. setattr(model_model, check_attr, True)
  142. updated = True
  143. # -> unlink
  144. check_attr = 'auditlog_ruled_unlink'
  145. if getattr(rule, 'log_unlink') \
  146. and not hasattr(model_model, check_attr):
  147. model_model._patch_method('unlink', self._make_unlink())
  148. setattr(model_model, check_attr, True)
  149. updated = True
  150. return updated
  151. @api.multi
  152. def _revert_methods(self):
  153. """Restore original ORM methods of models defined in rules."""
  154. updated = False
  155. for rule in self:
  156. model_model = self.env[rule.model_id.model]
  157. for method in ['create', 'read', 'write', 'unlink']:
  158. if getattr(rule, 'log_%s' % method):
  159. model_model._revert_method(method)
  160. updated = True
  161. if updated:
  162. modules.registry.RegistryManager.signal_registry_change(
  163. self.env.cr.dbname)
  164. # Unable to find a way to declare the `create` method with the new API,
  165. # errors occurs with the `_register_hook()` BaseModel method.
  166. def create(self, cr, uid, vals, context=None):
  167. """Update the registry when a new rule is created."""
  168. res_id = super(auditlog_rule, self).create(
  169. cr, uid, vals, context=context)
  170. if self._register_hook(cr, [res_id]):
  171. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  172. return res_id
  173. # Unable to find a way to declare the `write` method with the new API,
  174. # errors occurs with the `_register_hook()` BaseModel method.
  175. def write(self, cr, uid, ids, vals, context=None):
  176. """Update the registry when existing rules are updated."""
  177. if isinstance(ids, (int, long)):
  178. ids = [ids]
  179. super(auditlog_rule, self).write(cr, uid, ids, vals, context=context)
  180. if self._register_hook(cr, ids):
  181. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  182. return True
  183. def _make_create(self):
  184. """Instanciate a create method that log its calls."""
  185. @api.model
  186. def create(self, vals, **kwargs):
  187. rule_model = self.env['auditlog.rule']
  188. new_record = create.origin(self, vals, **kwargs)
  189. new_values = dict(
  190. (d['id'], d) for d in new_record.sudo().read(
  191. list(self._columns)))
  192. rule_model.sudo().create_logs(
  193. self.env.uid, self._name, new_record.ids,
  194. 'create', None, new_values)
  195. return new_record
  196. return create
  197. def _make_read(self):
  198. """Instanciate a read method that log its calls."""
  199. # FIXME: read() seems a bit tricky, improve to handle old/new api
  200. # @api.v7
  201. # def read(self, cr, user, ids, fields=None, context=None,
  202. # load='_classic_read', **kwargs):
  203. # print "LOG READ", fields, load, kwargs
  204. # # avoid loops
  205. # if self.env.context.get('auditlog_method_intercepted'):
  206. # return read.origin(
  207. # self, cr, user, ids, fields, context, load, **kwargs)
  208. # # call original method with a modified context
  209. # context = dict(
  210. # self.env.context, auditlog_method_intercepted=True)
  211. # result = read.origin(
  212. # self.with_context(context),
  213. # cr, user, ids, fields, context, load, **kwargs)
  214. # print "RESULT", result
  215. # return result
  216. # @api.v8
  217. # def read(self, fields=None, load='_classic_read', **kwargs):
  218. # print "LOG READ", fields, load, kwargs
  219. # # avoid loops
  220. # if self.env.context.get('auditlog_method_intercepted'):
  221. # return read.origin(self, fields, load, **kwargs)
  222. # # call original method with a modified context
  223. # context = dict(
  224. # self.env.context, auditlog_method_intercepted=True)
  225. # result = read.origin(
  226. # self.with_context(context), fields, load, **kwargs)
  227. # print "RESULT", result
  228. # return result
  229. def read(self, *args, **kwargs):
  230. result = read.origin(self, *args, **kwargs)
  231. return result
  232. return read
  233. def _make_write(self):
  234. """Instanciate a write method that log its calls."""
  235. @api.multi
  236. def write(self, vals, **kwargs):
  237. rule_model = self.env['auditlog.rule']
  238. old_values = dict(
  239. (d['id'], d) for d in self.sudo().read(list(self._columns)))
  240. result = write.origin(self, vals, **kwargs)
  241. new_values = dict(
  242. (d['id'], d) for d in self.sudo().read(list(self._columns)))
  243. rule_model.sudo().create_logs(
  244. self.env.uid, self._name, self.ids,
  245. 'write', old_values, new_values)
  246. return result
  247. return write
  248. def _make_unlink(self):
  249. """Instanciate an unlink method that log its calls."""
  250. @api.multi
  251. def unlink(self, **kwargs):
  252. rule_model = self.env['auditlog.rule']
  253. old_values = dict(
  254. (d['id'], d) for d in self.sudo().read(list(self._columns)))
  255. rule_model.sudo().create_logs(
  256. self.env.uid, self._name, self.ids, 'unlink', old_values)
  257. return unlink.origin(self, **kwargs)
  258. return unlink
  259. def create_logs(self, uid, res_model, res_ids, method,
  260. old_values=None, new_values=None,
  261. additional_log_values=None):
  262. """Create logs. `old_values` and `new_values` are dictionnaries, e.g:
  263. {RES_ID: {'FIELD': VALUE, ...}}
  264. """
  265. if old_values is None:
  266. old_values = EMPTY_DICT
  267. if new_values is None:
  268. new_values = EMPTY_DICT
  269. log_model = self.env['auditlog.log']
  270. ir_model = self.env['ir.model']
  271. for res_id in res_ids:
  272. model_model = self.env[res_model]
  273. res_name = model_model.browse(res_id).name_get()
  274. vals = {
  275. 'name': res_name and res_name[0] and res_name[0][1] or False,
  276. 'model_id': self.pool._auditlog_model_cache[res_model].id,
  277. 'res_id': res_id,
  278. 'method': method,
  279. 'user_id': uid,
  280. }
  281. vals.update(additional_log_values or {})
  282. log = log_model.create(vals)
  283. diff = DictDiffer(
  284. new_values.get(res_id, EMPTY_DICT),
  285. old_values.get(res_id, EMPTY_DICT))
  286. self._create_log_line_on_write(
  287. log, diff.changed(), old_values, new_values)
  288. self._create_log_line_on_create(log, diff.added(), new_values)
  289. def _get_field(self, model, field_name):
  290. cache = self.pool._auditlog_field_cache
  291. if field_name not in cache.get(model.model, {}):
  292. cache.setdefault(model.model, {})
  293. cache[model.model][field_name] = self.env['ir.model.fields']\
  294. .search(
  295. [
  296. ('model_id', '=', model.id),
  297. ('name', '=', field_name),
  298. ])
  299. return cache[model.model][field_name]
  300. def _create_log_line_on_write(
  301. self, log, fields_list, old_values, new_values):
  302. """Log field updated on a 'write' operation."""
  303. log_line_model = self.env['auditlog.log.line']
  304. for field_name in fields_list:
  305. if field_name in FIELDS_BLACKLIST:
  306. continue
  307. field = self._get_field(log.model_id, field_name)
  308. log_vals = self._prepare_log_line_vals_on_write(
  309. log, field, old_values, new_values)
  310. log_line_model.create(log_vals)
  311. def _prepare_log_line_vals_on_write(
  312. self, log, field, old_values, new_values):
  313. """Prepare the dictionary of values used to create a log line on a
  314. 'write' operation.
  315. """
  316. vals = {
  317. 'field_id': field.id,
  318. 'field_name': field.name,
  319. 'field_description': field.field_description,
  320. 'log_id': log.id,
  321. 'old_value': old_values[log.res_id][field.name],
  322. 'old_value_text': old_values[log.res_id][field.name],
  323. 'new_value': new_values[log.res_id][field.name],
  324. 'new_value_text': new_values[log.res_id][field.name],
  325. }
  326. # for *2many fields, log the name_get
  327. if field.relation and '2many' in field.ttype:
  328. old_value_text = self.env[field.relation].browse(
  329. vals['old_value']).name_get()
  330. vals['old_value_text'] = old_value_text
  331. new_value_text = self.env[field.relation].browse(
  332. vals['new_value']).name_get()
  333. vals['new_value_text'] = new_value_text
  334. return vals
  335. def _create_log_line_on_create(
  336. self, log, fields_list, new_values):
  337. """Log field filled on a 'create' operation."""
  338. log_line_model = self.env['auditlog.log.line']
  339. for field_name in fields_list:
  340. if field_name in FIELDS_BLACKLIST:
  341. continue
  342. field = self._get_field(log.model_id, field_name)
  343. log_vals = self._prepare_log_line_vals_on_create(
  344. log, field, new_values)
  345. log_line_model.create(log_vals)
  346. def _prepare_log_line_vals_on_create(self, log, field, new_values):
  347. """Prepare the dictionary of values used to create a log line on a
  348. 'create' operation.
  349. """
  350. vals = {
  351. 'field_id': field.id,
  352. 'field_name': field.name,
  353. 'field_description': field.field_description,
  354. 'log_id': log.id,
  355. 'old_value': False,
  356. 'old_value_text': False,
  357. 'new_value': new_values[log.res_id][field.name],
  358. 'new_value_text': new_values[log.res_id][field.name],
  359. }
  360. if field.relation and '2many' in field.ttype:
  361. new_value_text = self.env[field.relation].browse(
  362. vals['new_value']).name_get()
  363. vals['new_value_text'] = new_value_text
  364. return vals
  365. @api.multi
  366. def subscribe(self):
  367. """Subscribe Rule for auditing changes on model and apply shortcut
  368. to view logs on that model.
  369. """
  370. act_window_model = self.env['ir.actions.act_window']
  371. model_data_model = self.env['ir.model.data']
  372. for rule in self:
  373. # Create a shortcut to view logs
  374. domain = "[('model_id', '=', %s), ('res_id', '=', active_id)]" % (
  375. rule.model_id.id)
  376. vals = {
  377. 'name': _(u"View logs"),
  378. 'res_model': 'auditlog.log',
  379. 'src_model': rule.model_id.model,
  380. 'domain': domain,
  381. }
  382. act_window = act_window_model.sudo().create(vals)
  383. rule.write({'state': 'subscribed', 'action_id': act_window.id})
  384. keyword = 'client_action_relate'
  385. value = 'ir.actions.act_window,%s' % act_window.id
  386. model_data_model.sudo().ir_set(
  387. 'action', keyword, 'View_log_' + rule.model_id.model,
  388. [rule.model_id.model], value, replace=True,
  389. isobject=True, xml_id=False)
  390. return True
  391. @api.multi
  392. def unsubscribe(self):
  393. """Unsubscribe Auditing Rule on model."""
  394. act_window_model = self.env['ir.actions.act_window']
  395. ir_values_model = self.env['ir.values']
  396. value = ''
  397. # Revert patched methods
  398. self._revert_methods()
  399. for rule in self:
  400. # Remove the shortcut to view logs
  401. act_window = act_window_model.search(
  402. [('name', '=', 'View Log'),
  403. ('res_model', '=', 'auditlog.log'),
  404. ('src_model', '=', rule.model_id.model)])
  405. if act_window:
  406. value = 'ir.actions.act_window,%s' % act_window.id
  407. act_window.unlink()
  408. if value:
  409. ir_value = ir_values_model.search(
  410. [('model', '=', rule.model_id.model),
  411. ('value', '=', value)])
  412. if ir_value:
  413. ir_value.unlink()
  414. self.write({'state': 'draft'})
  415. return True