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.

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