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.

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