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.

394 lines
16 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. def create(self, cr, uid, vals, context=None):
  157. """Update the registry when a new rule is created."""
  158. res_id = super(auditlog_rule, self).create(
  159. cr, uid, vals, context=context)
  160. if self._register_hook(cr, [res_id]):
  161. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  162. return res_id
  163. def write(self, cr, uid, ids, vals, context=None):
  164. """Update the registry when existing rules are updated."""
  165. if isinstance(ids, (int, long)):
  166. ids = [ids]
  167. super(auditlog_rule, self).write(cr, uid, ids, vals, context=context)
  168. if self._register_hook(cr, ids):
  169. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  170. return True
  171. def _make_create(self):
  172. """Instanciate a create method that log its calls."""
  173. @api.model
  174. def create(self, vals, **kwargs):
  175. rule_model = self.env['auditlog.rule']
  176. new_record = create.origin(self, vals, **kwargs)
  177. new_values = dict(
  178. (d['id'], d) for d in new_record.sudo().read(
  179. list(self._columns)))
  180. rule_model.sudo().create_logs(
  181. self.env.uid, self._name, new_record.ids,
  182. 'create', None, new_values)
  183. return new_record
  184. return create
  185. def _make_read(self):
  186. """Instanciate a read method that log its calls."""
  187. # FIXME: read() seems a bit tricky, improve to handle old/new api
  188. #@api.v7
  189. #def read(self, cr, user, ids, fields=None, context=None, load='_classic_read', **kwargs):
  190. # print "LOG READ", fields, load, kwargs
  191. # # avoid loops
  192. # if self.env.context.get('auditlog_method_intercepted'):
  193. # return read.origin(self, cr, user, ids, fields, context, load, **kwargs)
  194. # # call original method with a modified context
  195. # context = dict(self.env.context, auditlog_method_intercepted=True)
  196. # result = read.origin(
  197. # self.with_context(context),
  198. # cr, user, ids, fields, context, load, **kwargs)
  199. # print "RESULT", result
  200. # return result
  201. #@api.v8
  202. #def read(self, fields=None, 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(self, fields, load, **kwargs)
  207. # # call original method with a modified context
  208. # context = dict(self.env.context, auditlog_method_intercepted=True)
  209. # result = read.origin(
  210. # self.with_context(context), fields, load, **kwargs)
  211. # print "RESULT", result
  212. # return result
  213. def read(self, *args, **kwargs):
  214. result = read.origin(self, *args, **kwargs)
  215. return result
  216. return read
  217. def _make_write(self):
  218. """Instanciate a write method that log its calls."""
  219. @api.multi
  220. def write(self, vals, **kwargs):
  221. rule_model = self.env['auditlog.rule']
  222. old_values = dict(
  223. (d['id'], d) for d in self.sudo().read(list(self._columns)))
  224. result = write.origin(self, vals, **kwargs)
  225. new_values = dict(
  226. (d['id'], d) for d in self.sudo().read(list(self._columns)))
  227. rule_model.sudo().create_logs(
  228. self.env.uid, self._name, self.ids,
  229. 'write', old_values, new_values)
  230. return result
  231. return write
  232. def _make_unlink(self):
  233. """Instanciate an unlink method that log its calls."""
  234. @api.multi
  235. def unlink(self, **kwargs):
  236. rule_model = self.env['auditlog.rule']
  237. rule_model.sudo().create_logs(
  238. self.env.uid, self._name, self.ids, 'unlink')
  239. return unlink.origin(self, **kwargs)
  240. return unlink
  241. def create_logs(self, uid, res_model, res_ids, method,
  242. old_values=None, new_values=None):
  243. """Create logs. `old_values` and `new_values` are dictionnaries, e.g:
  244. {RES_ID: {'FIELD': VALUE, ...}}
  245. """
  246. if old_values is None:
  247. old_values = EMPTY_DICT
  248. if new_values is None:
  249. new_values = EMPTY_DICT
  250. log_model = self.env['auditlog.log']
  251. log_line_model = self.env['auditlog.log.line']
  252. ir_model = self.env['ir.model']
  253. ir_model_field = self.env['ir.model.fields']
  254. model = ir_model.search([('model', '=', res_model)])
  255. for res_id in res_ids:
  256. model_model = self.env[res_model]
  257. res_name = model_model.browse(res_id).name_get()
  258. vals = {
  259. 'name': res_name and res_name[0] and res_name[0][1] or False,
  260. 'model_id': model.id,
  261. 'res_id': res_id,
  262. 'method': method,
  263. 'user_id': uid,
  264. }
  265. log = log_model.create(vals)
  266. diff = DictDiffer(
  267. new_values.get(res_id, EMPTY_DICT),
  268. old_values.get(res_id, EMPTY_DICT))
  269. # 'write' case (old_values and new_values defined)
  270. for fchanged in diff.changed():
  271. if fchanged in FIELDS_BLACKLIST:
  272. continue
  273. field_ = ir_model_field.search(
  274. [('model_id', '=', model.id), ('name', '=', fchanged)])
  275. log_vals = {
  276. 'field_id': field_.id,
  277. 'field_name': field_.name,
  278. 'field_description': field_.field_description,
  279. 'log_id': log.id,
  280. 'old_value': old_values[res_id][fchanged],
  281. 'old_value_text': old_values[res_id][fchanged],
  282. 'new_value': new_values[res_id][fchanged],
  283. 'new_value_text': new_values[res_id][fchanged],
  284. }
  285. # for *2many fields, log the name_get
  286. if field_.relation and '2many' in field_.ttype:
  287. old_value_text = self.env[field_.relation].browse(
  288. log_vals['old_value']).name_get()
  289. log_vals['old_value_text'] = old_value_text
  290. new_value_text = self.env[field_.relation].browse(
  291. log_vals['new_value']).name_get()
  292. log_vals['new_value_text'] = new_value_text
  293. log_line_model.create(log_vals)
  294. # 'create' case (old_values => EMPTY_DICT)
  295. for fchanged in diff.added():
  296. if fchanged in FIELDS_BLACKLIST:
  297. continue
  298. field_ = ir_model_field.search(
  299. [('model_id', '=', model.id), ('name', '=', fchanged)])
  300. log_vals = {
  301. 'field_id': field_.id,
  302. 'field_name': field_.name,
  303. 'field_description': field_.field_description,
  304. 'log_id': log.id,
  305. 'old_value': False,
  306. 'old_value_text': False,
  307. 'new_value': new_values[res_id][fchanged],
  308. 'new_value_text': new_values[res_id][fchanged],
  309. }
  310. if field_.relation and '2many' in field_.ttype:
  311. new_value_text = self.env[field_.relation].browse(
  312. log_vals['new_value']).name_get()
  313. log_vals['new_value_text'] = new_value_text
  314. log_line_model.create(log_vals)
  315. @api.multi
  316. def subscribe(self):
  317. """Subscribe Rule for auditing changes on model and apply shortcut
  318. to view logs on that model.
  319. """
  320. act_window_model = self.env['ir.actions.act_window']
  321. model_data_model = self.env['ir.model.data']
  322. for rule in self:
  323. # Create a shortcut to view logs
  324. domain = "[('model_id', '=', %s), ('res_id', '=', active_id)]" % (
  325. rule.model_id.id)
  326. vals = {
  327. 'name': _(u"View logs"),
  328. 'res_model': 'auditlog.log',
  329. 'src_model': rule.model_id.model,
  330. 'domain': domain,
  331. }
  332. act_window = act_window_model.sudo().create(vals)
  333. rule.write({'state': 'subscribed', 'action_id': act_window.id})
  334. keyword = 'client_action_relate'
  335. value = 'ir.actions.act_window,%s' % act_window.id
  336. model_data_model.sudo().ir_set(
  337. 'action', keyword, 'View_log_' + rule.model_id.model,
  338. [rule.model_id.model], value, replace=True,
  339. isobject=True, xml_id=False)
  340. return True
  341. @api.multi
  342. def unsubscribe(self):
  343. """Unsubscribe Auditing Rule on model."""
  344. act_window_model = self.env['ir.actions.act_window']
  345. ir_values_model = self.env['ir.values']
  346. value = ''
  347. self._revert_methods()
  348. for rule in self:
  349. # Revert patched methods
  350. # Remove the shortcut to view logs
  351. act_window = act_window_model.search(
  352. [('name', '=', 'View Log'),
  353. ('res_model', '=', 'auditlog.log'),
  354. ('src_model', '=', rule.model_id.model)])
  355. if act_window:
  356. value = 'ir.actions.act_window,%s' % act_window.id
  357. act_window.unlink()
  358. if value:
  359. ir_value = ir_values_model.search(
  360. [('model', '=', rule.model_id.model), ('value', '=', value)])
  361. if ir_value:
  362. ir_value.unlink()
  363. self.write({'state': 'draft'})
  364. return True
  365. # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: