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.

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