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.

432 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.keys())
  39. self.set_past = set(past_dict.keys())
  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 ids is None:
  102. ids = self.search(cr, SUPERUSER_ID, [('state', '=', 'subscribed')])
  103. return self._patch_methods(cr, SUPERUSER_ID, ids)
  104. @api.multi
  105. def _patch_methods(self):
  106. """Patch ORM methods of models defined in rules to log their calls."""
  107. updated = False
  108. for rule in self:
  109. if rule.state != 'subscribed':
  110. continue
  111. if not self.pool.get(rule.model_id.model):
  112. # ignore rules for models not loadable currently
  113. continue
  114. model_model = self.env[rule.model_id.model]
  115. # CRUD
  116. # -> create
  117. check_attr = 'auditlog_ruled_create'
  118. if getattr(rule, 'log_create') \
  119. and not hasattr(model_model, check_attr):
  120. model_model._patch_method('create', self._make_create())
  121. setattr(model_model, check_attr, True)
  122. updated = True
  123. # -> read
  124. check_attr = 'auditlog_ruled_read'
  125. if getattr(rule, 'log_read') \
  126. and not hasattr(model_model, check_attr):
  127. model_model._patch_method('read', self._make_read())
  128. setattr(model_model, check_attr, True)
  129. updated = True
  130. # -> write
  131. check_attr = 'auditlog_ruled_write'
  132. if getattr(rule, 'log_write') \
  133. and not hasattr(model_model, check_attr):
  134. model_model._patch_method('write', self._make_write())
  135. setattr(model_model, check_attr, True)
  136. updated = True
  137. # -> unlink
  138. check_attr = 'auditlog_ruled_unlink'
  139. if getattr(rule, 'log_unlink') \
  140. and not hasattr(model_model, check_attr):
  141. model_model._patch_method('unlink', self._make_unlink())
  142. setattr(model_model, check_attr, True)
  143. updated = True
  144. return updated
  145. @api.multi
  146. def _revert_methods(self):
  147. """Restore original ORM methods of models defined in rules."""
  148. updated = False
  149. for rule in self:
  150. model_model = self.env[rule.model_id.model]
  151. for method in ['create', 'read', 'write', 'unlink']:
  152. if getattr(rule, 'log_%s' % method):
  153. model_model._revert_method(method)
  154. updated = True
  155. if updated:
  156. modules.registry.RegistryManager.signal_registry_change(
  157. self.env.cr.dbname)
  158. # Unable to find a way to declare the `create` method with the new API,
  159. # errors occurs with the `_register_hook()` BaseModel method.
  160. def create(self, cr, uid, vals, context=None):
  161. """Update the registry when a new rule is created."""
  162. res_id = super(auditlog_rule, self).create(
  163. cr, uid, vals, context=context)
  164. if self._register_hook(cr, [res_id]):
  165. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  166. return res_id
  167. # Unable to find a way to declare the `write` method with the new API,
  168. # errors occurs with the `_register_hook()` BaseModel method.
  169. def write(self, cr, uid, ids, vals, context=None):
  170. """Update the registry when existing rules are updated."""
  171. if isinstance(ids, (int, long)):
  172. ids = [ids]
  173. super(auditlog_rule, self).write(cr, uid, ids, vals, context=context)
  174. if self._register_hook(cr, ids):
  175. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  176. return True
  177. def _make_create(self):
  178. """Instanciate a create method that log its calls."""
  179. @api.model
  180. def create(self, vals, **kwargs):
  181. rule_model = self.env['auditlog.rule']
  182. new_record = create.origin(self, vals, **kwargs)
  183. new_values = dict(
  184. (d['id'], d) for d in new_record.sudo().read(
  185. list(self._columns)))
  186. rule_model.sudo().create_logs(
  187. self.env.uid, self._name, new_record.ids,
  188. 'create', None, new_values)
  189. return new_record
  190. return create
  191. def _make_read(self):
  192. """Instanciate a read method that log its calls."""
  193. # FIXME: read() seems a bit tricky, improve to handle old/new api
  194. # @api.v7
  195. # def read(self, cr, user, ids, fields=None, context=None,
  196. # load='_classic_read', **kwargs):
  197. # print "LOG READ", fields, load, kwargs
  198. # # avoid loops
  199. # if self.env.context.get('auditlog_method_intercepted'):
  200. # return read.origin(
  201. # self, cr, user, ids, fields, context, load, **kwargs)
  202. # # call original method with a modified context
  203. # context = dict(
  204. # self.env.context, auditlog_method_intercepted=True)
  205. # result = read.origin(
  206. # self.with_context(context),
  207. # cr, user, ids, fields, context, load, **kwargs)
  208. # print "RESULT", result
  209. # return result
  210. # @api.v8
  211. # def read(self, fields=None, load='_classic_read', **kwargs):
  212. # print "LOG READ", fields, load, kwargs
  213. # # avoid loops
  214. # if self.env.context.get('auditlog_method_intercepted'):
  215. # return read.origin(self, fields, load, **kwargs)
  216. # # call original method with a modified context
  217. # context = dict(
  218. # self.env.context, auditlog_method_intercepted=True)
  219. # result = read.origin(
  220. # self.with_context(context), fields, load, **kwargs)
  221. # print "RESULT", result
  222. # return result
  223. def read(self, *args, **kwargs):
  224. result = read.origin(self, *args, **kwargs)
  225. return result
  226. return read
  227. def _make_write(self):
  228. """Instanciate a write method that log its calls."""
  229. @api.multi
  230. def write(self, vals, **kwargs):
  231. rule_model = self.env['auditlog.rule']
  232. old_values = dict(
  233. (d['id'], d) for d in self.sudo().read(list(self._columns)))
  234. result = write.origin(self, vals, **kwargs)
  235. new_values = dict(
  236. (d['id'], d) for d in self.sudo().read(list(self._columns)))
  237. rule_model.sudo().create_logs(
  238. self.env.uid, self._name, self.ids,
  239. 'write', old_values, new_values)
  240. return result
  241. return write
  242. def _make_unlink(self):
  243. """Instanciate an unlink method that log its calls."""
  244. @api.multi
  245. def unlink(self, **kwargs):
  246. rule_model = self.env['auditlog.rule']
  247. rule_model.sudo().create_logs(
  248. self.env.uid, self._name, self.ids, 'unlink')
  249. return unlink.origin(self, **kwargs)
  250. return unlink
  251. def create_logs(self, uid, res_model, res_ids, method,
  252. old_values=None, new_values=None):
  253. """Create logs. `old_values` and `new_values` are dictionnaries, e.g:
  254. {RES_ID: {'FIELD': VALUE, ...}}
  255. """
  256. if old_values is None:
  257. old_values = EMPTY_DICT
  258. if new_values is None:
  259. new_values = EMPTY_DICT
  260. log_model = self.env['auditlog.log']
  261. ir_model = self.env['ir.model']
  262. model = ir_model.search([('model', '=', res_model)])
  263. for res_id in res_ids:
  264. model_model = self.env[res_model]
  265. res_name = model_model.browse(res_id).name_get()
  266. vals = {
  267. 'name': res_name and res_name[0] and res_name[0][1] or False,
  268. 'model_id': model.id,
  269. 'res_id': res_id,
  270. 'method': method,
  271. 'user_id': uid,
  272. }
  273. log = log_model.create(vals)
  274. diff = DictDiffer(
  275. new_values.get(res_id, EMPTY_DICT),
  276. old_values.get(res_id, EMPTY_DICT))
  277. self._create_log_line_on_write(
  278. log, diff.changed(), old_values, new_values)
  279. self._create_log_line_on_create(log, diff.added(), new_values)
  280. def _create_log_line_on_write(
  281. self, log, fields_list, old_values, new_values):
  282. """Log field updated on a 'write' operation."""
  283. log_line_model = self.env['auditlog.log.line']
  284. ir_model_field = self.env['ir.model.fields']
  285. for field_name in fields_list:
  286. if field_name in FIELDS_BLACKLIST:
  287. continue
  288. field = ir_model_field.search(
  289. [('model_id', '=', log.model_id.id),
  290. ('name', '=', field_name)])
  291. log_vals = self._prepare_log_line_vals_on_write(
  292. log, field, old_values, new_values)
  293. log_line_model.create(log_vals)
  294. def _prepare_log_line_vals_on_write(
  295. self, log, field, old_values, new_values):
  296. """Prepare the dictionary of values used to create a log line on a
  297. 'write' operation.
  298. """
  299. vals = {
  300. 'field_id': field.id,
  301. 'field_name': field.name,
  302. 'field_description': field.field_description,
  303. 'log_id': log.id,
  304. 'old_value': old_values[log.res_id][field.name],
  305. 'old_value_text': old_values[log.res_id][field.name],
  306. 'new_value': new_values[log.res_id][field.name],
  307. 'new_value_text': new_values[log.res_id][field.name],
  308. }
  309. # for *2many fields, log the name_get
  310. if field.relation and '2many' in field.ttype:
  311. old_value_text = self.env[field.relation].browse(
  312. vals['old_value']).name_get()
  313. vals['old_value_text'] = old_value_text
  314. new_value_text = self.env[field.relation].browse(
  315. vals['new_value']).name_get()
  316. vals['new_value_text'] = new_value_text
  317. return vals
  318. def _create_log_line_on_create(
  319. self, log, fields_list, new_values):
  320. """Log field filled on a 'create' operation."""
  321. log_line_model = self.env['auditlog.log.line']
  322. ir_model_field = self.env['ir.model.fields']
  323. for field_name in fields_list:
  324. if field_name in FIELDS_BLACKLIST:
  325. continue
  326. field = ir_model_field.search(
  327. [('model_id', '=', log.model_id.id),
  328. ('name', '=', field_name)])
  329. log_vals = self._prepare_log_line_vals_on_create(
  330. log, field, new_values)
  331. log_line_model.create(log_vals)
  332. def _prepare_log_line_vals_on_create(self, log, field, new_values):
  333. """Prepare the dictionary of values used to create a log line on a
  334. 'create' operation.
  335. """
  336. vals = {
  337. 'field_id': field.id,
  338. 'field_name': field.name,
  339. 'field_description': field.field_description,
  340. 'log_id': log.id,
  341. 'old_value': False,
  342. 'old_value_text': False,
  343. 'new_value': new_values[log.res_id][field.name],
  344. 'new_value_text': new_values[log.res_id][field.name],
  345. }
  346. if field.relation and '2many' in field.ttype:
  347. new_value_text = self.env[field.relation].browse(
  348. vals['new_value']).name_get()
  349. vals['new_value_text'] = new_value_text
  350. return vals
  351. @api.multi
  352. def subscribe(self):
  353. """Subscribe Rule for auditing changes on model and apply shortcut
  354. to view logs on that model.
  355. """
  356. act_window_model = self.env['ir.actions.act_window']
  357. model_data_model = self.env['ir.model.data']
  358. for rule in self:
  359. # Create a shortcut to view logs
  360. domain = "[('model_id', '=', %s), ('res_id', '=', active_id)]" % (
  361. rule.model_id.id)
  362. vals = {
  363. 'name': _(u"View logs"),
  364. 'res_model': 'auditlog.log',
  365. 'src_model': rule.model_id.model,
  366. 'domain': domain,
  367. }
  368. act_window = act_window_model.sudo().create(vals)
  369. rule.write({'state': 'subscribed', 'action_id': act_window.id})
  370. keyword = 'client_action_relate'
  371. value = 'ir.actions.act_window,%s' % act_window.id
  372. model_data_model.sudo().ir_set(
  373. 'action', keyword, 'View_log_' + rule.model_id.model,
  374. [rule.model_id.model], value, replace=True,
  375. isobject=True, xml_id=False)
  376. return True
  377. @api.multi
  378. def unsubscribe(self):
  379. """Unsubscribe Auditing Rule on model."""
  380. act_window_model = self.env['ir.actions.act_window']
  381. ir_values_model = self.env['ir.values']
  382. value = ''
  383. # Revert patched methods
  384. self._revert_methods()
  385. for rule in self:
  386. # Remove the shortcut to view logs
  387. act_window = act_window_model.search(
  388. [('name', '=', 'View Log'),
  389. ('res_model', '=', 'auditlog.log'),
  390. ('src_model', '=', rule.model_id.model)])
  391. if act_window:
  392. value = 'ir.actions.act_window,%s' % act_window.id
  393. act_window.unlink()
  394. if value:
  395. ir_value = ir_values_model.search(
  396. [('model', '=', rule.model_id.model),
  397. ('value', '=', value)])
  398. if ir_value:
  399. ir_value.unlink()
  400. self.write({'state': 'draft'})
  401. return True