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.

538 lines
22 KiB

7 years ago
10 years ago
10 years ago
10 years ago
  1. # © 2015 ABF OSIELL <https://osiell.com>
  2. # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl).
  3. from odoo import models, fields, api, modules, _
  4. FIELDS_BLACKLIST = [
  5. 'id', 'create_uid', 'create_date', 'write_uid', 'write_date',
  6. 'display_name', '__last_update',
  7. ]
  8. # Used for performance, to avoid a dictionary instanciation when we need an
  9. # empty dict to simplify algorithms
  10. EMPTY_DICT = {}
  11. class DictDiffer(object):
  12. """Calculate the difference between two dictionaries as:
  13. (1) items added
  14. (2) items removed
  15. (3) keys same in both but changed values
  16. (4) keys same in both and unchanged values
  17. """
  18. def __init__(self, current_dict, past_dict):
  19. self.current_dict, self.past_dict = current_dict, past_dict
  20. self.set_current = set(current_dict)
  21. self.set_past = set(past_dict)
  22. self.intersect = self.set_current.intersection(self.set_past)
  23. def added(self):
  24. return self.set_current - self.intersect
  25. def removed(self):
  26. return self.set_past - self.intersect
  27. def changed(self):
  28. return set(o for o in self.intersect
  29. if self.past_dict[o] != self.current_dict[o])
  30. def unchanged(self):
  31. return set(o for o in self.intersect
  32. if self.past_dict[o] == self.current_dict[o])
  33. class AuditlogRule(models.Model):
  34. _name = 'auditlog.rule'
  35. _description = "Auditlog - Rule"
  36. name = fields.Char("Name", size=32, required=True)
  37. model_id = fields.Many2one(
  38. 'ir.model', "Model", required=True,
  39. help="Select model for which you want to generate log.")
  40. user_ids = fields.Many2many(
  41. 'res.users',
  42. 'audittail_rules_users',
  43. 'user_id', 'rule_id',
  44. string="Users",
  45. help="if User is not added then it will applicable for all users")
  46. log_read = fields.Boolean(
  47. "Log Reads",
  48. help=("Select this if you want to keep track of read/open on any "
  49. "record of the model of this rule"))
  50. log_write = fields.Boolean(
  51. "Log Writes", default=True,
  52. help=("Select this if you want to keep track of modification on any "
  53. "record of the model of this rule"))
  54. log_unlink = fields.Boolean(
  55. "Log Deletes", default=True,
  56. help=("Select this if you want to keep track of deletion on any "
  57. "record of the model of this rule"))
  58. log_create = fields.Boolean(
  59. "Log Creates", default=True,
  60. help=("Select this if you want to keep track of creation on any "
  61. "record of the model of this rule"))
  62. log_type = fields.Selection(
  63. [('full', "Full log"),
  64. ('fast', "Fast log"),
  65. ],
  66. string="Type", required=True, default='full',
  67. help=("Full log: make a diff between the data before and after "
  68. "the operation (log more info like computed fields which were "
  69. "updated, but it is slower)\n"
  70. "Fast log: only log the changes made through the create and "
  71. "write operations (less information, but it is faster)"))
  72. # log_action = fields.Boolean(
  73. # "Log Action",
  74. # help=("Select this if you want to keep track of actions on the "
  75. # "model of this rule"))
  76. # log_workflow = fields.Boolean(
  77. # "Log Workflow",
  78. # help=("Select this if you want to keep track of workflow on any "
  79. # "record of the model of this rule"))
  80. state = fields.Selection(
  81. [('draft', "Draft"), ('subscribed', "Subscribed")],
  82. string="State", required=True, default='draft')
  83. action_id = fields.Many2one(
  84. 'ir.actions.act_window', string="Action")
  85. _sql_constraints = [
  86. ('model_uniq', 'unique(model_id)',
  87. ("There is already a rule defined on this model\n"
  88. "You cannot define another: please edit the existing one."))
  89. ]
  90. def _register_hook(self):
  91. """Get all rules and apply them to log method calls."""
  92. super(AuditlogRule, self)._register_hook()
  93. if not hasattr(self.pool, '_auditlog_field_cache'):
  94. self.pool._auditlog_field_cache = {}
  95. if not hasattr(self.pool, '_auditlog_model_cache'):
  96. self.pool._auditlog_model_cache = {}
  97. if not self:
  98. self = self.search([('state', '=', 'subscribed')])
  99. return self._patch_methods()
  100. @api.multi
  101. def _patch_methods(self):
  102. """Patch ORM methods of models defined in rules to log their calls."""
  103. updated = False
  104. model_cache = self.pool._auditlog_model_cache
  105. for rule in self:
  106. if rule.state != 'subscribed':
  107. continue
  108. if not self.pool.get(rule.model_id.model):
  109. # ignore rules for models not loadable currently
  110. continue
  111. model_cache[rule.model_id.model] = rule.model_id.id
  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', rule._make_create())
  119. setattr(type(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', rule._make_read())
  126. setattr(type(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', rule._make_write())
  133. setattr(type(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', rule._make_unlink())
  140. setattr(type(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) and hasattr(
  151. getattr(model_model, method), 'origin'):
  152. model_model._revert_method(method)
  153. delattr(type(model_model), 'auditlog_ruled_%s' % method)
  154. updated = True
  155. if updated:
  156. modules.registry.Registry(self.env.cr.dbname).signal_changes()
  157. @api.model
  158. def create(self, vals):
  159. """Update the registry when a new rule is created."""
  160. new_record = super(AuditlogRule, self).create(vals)
  161. if new_record._register_hook():
  162. modules.registry.Registry(self.env.cr.dbname).signal_changes()
  163. return new_record
  164. @api.multi
  165. def write(self, vals):
  166. """Update the registry when existing rules are updated."""
  167. super(AuditlogRule, self).write(vals)
  168. if self._register_hook():
  169. modules.registry.Registry(self.env.cr.dbname).signal_changes()
  170. return True
  171. @api.multi
  172. def unlink(self):
  173. """Unsubscribe rules before removing them."""
  174. self.unsubscribe()
  175. return super(AuditlogRule, self).unlink()
  176. @api.multi
  177. def _make_create(self):
  178. """Instanciate a create method that log its calls."""
  179. self.ensure_one()
  180. log_type = self.log_type
  181. @api.model
  182. @api.returns('self', lambda value: value.id)
  183. def create_full(self, vals, **kwargs):
  184. self = self.with_context(auditlog_disabled=True)
  185. rule_model = self.env['auditlog.rule']
  186. new_record = create_full.origin(self, vals, **kwargs)
  187. new_values = dict(
  188. (d['id'], d) for d in new_record.sudo()
  189. .with_context(prefetch_fields=False).read(list(self._fields)))
  190. rule_model.sudo().create_logs(
  191. self.env.uid, self._name, new_record.ids,
  192. 'create', None, new_values, {'log_type': log_type})
  193. return new_record
  194. @api.model
  195. @api.returns('self', lambda value: value.id)
  196. def create_fast(self, vals, **kwargs):
  197. self = self.with_context(auditlog_disabled=True)
  198. rule_model = self.env['auditlog.rule']
  199. vals2 = dict(vals)
  200. new_record = create_fast.origin(self, vals, **kwargs)
  201. new_values = {new_record.id: vals2}
  202. rule_model.sudo().create_logs(
  203. self.env.uid, self._name, new_record.ids,
  204. 'create', None, new_values, {'log_type': log_type})
  205. return new_record
  206. return create_full if self.log_type == 'full' else create_fast
  207. @api.multi
  208. def _make_read(self):
  209. """Instanciate a read method that log its calls."""
  210. self.ensure_one()
  211. log_type = self.log_type
  212. def read(self, fields=None, load='_classic_read', **kwargs):
  213. result = read.origin(self, fields, load, **kwargs)
  214. # Sometimes the result is not a list but a dictionary
  215. # Also, we can not modify the current result as it will break calls
  216. result2 = result
  217. if not isinstance(result2, list):
  218. result2 = [result]
  219. read_values = dict((d['id'], d) for d in result2)
  220. # Old API
  221. # If the call came from auditlog itself, skip logging:
  222. # avoid logs on `read` produced by auditlog during internal
  223. # processing: read data of relevant records, 'ir.model',
  224. # 'ir.model.fields'... (no interest in logging such operations)
  225. if self.env.context.get('auditlog_disabled'):
  226. return result
  227. self = self.with_context(auditlog_disabled=True)
  228. rule_model = self.env['auditlog.rule']
  229. rule_model.sudo().create_logs(
  230. self.env.uid, self._name, self.ids,
  231. 'read', read_values, None, {'log_type': log_type})
  232. return result
  233. return read
  234. @api.multi
  235. def _make_write(self):
  236. """Instanciate a write method that log its calls."""
  237. self.ensure_one()
  238. log_type = self.log_type
  239. @api.multi
  240. def write_full(self, vals, **kwargs):
  241. self = self.with_context(auditlog_disabled=True)
  242. rule_model = self.env['auditlog.rule']
  243. old_values = dict(
  244. (d['id'], d) for d in self.sudo()
  245. .with_context(prefetch_fields=False).read(list(self._fields)))
  246. result = write_full.origin(self, vals, **kwargs)
  247. new_values = dict(
  248. (d['id'], d) for d in self.sudo()
  249. .with_context(prefetch_fields=False).read(list(self._fields)))
  250. rule_model.sudo().create_logs(
  251. self.env.uid, self._name, self.ids,
  252. 'write', old_values, new_values, {'log_type': log_type})
  253. return result
  254. @api.multi
  255. def write_fast(self, vals, **kwargs):
  256. self = self.with_context(auditlog_disabled=True)
  257. rule_model = self.env['auditlog.rule']
  258. # Log the user input only, no matter if the `vals` is updated
  259. # afterwards as it could not represent the real state
  260. # of the data in the database
  261. vals2 = dict(vals)
  262. old_vals2 = dict.fromkeys(list(vals2.keys()), False)
  263. old_values = dict((id_, old_vals2) for id_ in self.ids)
  264. new_values = dict((id_, vals2) for id_ in self.ids)
  265. result = write_fast.origin(self, vals, **kwargs)
  266. rule_model.sudo().create_logs(
  267. self.env.uid, self._name, self.ids,
  268. 'write', old_values, new_values, {'log_type': log_type})
  269. return result
  270. return write_full if self.log_type == 'full' else write_fast
  271. @api.multi
  272. def _make_unlink(self):
  273. """Instanciate an unlink method that log its calls."""
  274. self.ensure_one()
  275. log_type = self.log_type
  276. @api.multi
  277. def unlink_full(self, **kwargs):
  278. self = self.with_context(auditlog_disabled=True)
  279. rule_model = self.env['auditlog.rule']
  280. old_values = dict(
  281. (d['id'], d) for d in self.sudo()
  282. .with_context(prefetch_fields=False).read(list(self._fields)))
  283. rule_model.sudo().create_logs(
  284. self.env.uid, self._name, self.ids, 'unlink', old_values, None,
  285. {'log_type': log_type})
  286. return unlink_full.origin(self, **kwargs)
  287. @api.multi
  288. def unlink_fast(self, **kwargs):
  289. self = self.with_context(auditlog_disabled=True)
  290. rule_model = self.env['auditlog.rule']
  291. rule_model.sudo().create_logs(
  292. self.env.uid, self._name, self.ids, 'unlink', None, None,
  293. {'log_type': log_type})
  294. return unlink_fast.origin(self, **kwargs)
  295. return unlink_full if self.log_type == 'full' else unlink_fast
  296. def create_logs(self, uid, res_model, res_ids, method,
  297. old_values=None, new_values=None,
  298. additional_log_values=None):
  299. """Create logs. `old_values` and `new_values` are dictionaries, e.g:
  300. {RES_ID: {'FIELD': VALUE, ...}}
  301. """
  302. if old_values is None:
  303. old_values = EMPTY_DICT
  304. if new_values is None:
  305. new_values = EMPTY_DICT
  306. log_model = self.env['auditlog.log']
  307. http_request_model = self.env['auditlog.http.request']
  308. http_session_model = self.env['auditlog.http.session']
  309. for res_id in res_ids:
  310. model_model = self.env[res_model]
  311. name = model_model.browse(res_id).name_get()
  312. res_name = name and name[0] and name[0][1]
  313. vals = {
  314. 'name': res_name,
  315. 'model_id': self.pool._auditlog_model_cache[res_model],
  316. 'res_id': res_id,
  317. 'method': method,
  318. 'user_id': uid,
  319. 'http_request_id': http_request_model.current_http_request(),
  320. 'http_session_id': http_session_model.current_http_session(),
  321. }
  322. vals.update(additional_log_values or {})
  323. log = log_model.create(vals)
  324. diff = DictDiffer(
  325. new_values.get(res_id, EMPTY_DICT),
  326. old_values.get(res_id, EMPTY_DICT))
  327. if method is 'create':
  328. self._create_log_line_on_create(log, diff.added(), new_values)
  329. elif method is 'read':
  330. self._create_log_line_on_read(
  331. log,
  332. list(old_values.get(res_id, EMPTY_DICT).keys()), old_values
  333. )
  334. elif method is 'write':
  335. self._create_log_line_on_write(
  336. log, diff.changed(), old_values, new_values)
  337. def _get_field(self, model, field_name):
  338. cache = self.pool._auditlog_field_cache
  339. if field_name not in cache.get(model.model, {}):
  340. cache.setdefault(model.model, {})
  341. # - we use 'search()' then 'read()' instead of the 'search_read()'
  342. # to take advantage of the 'classic_write' loading
  343. # - search the field in the current model and those it inherits
  344. field_model = self.env['ir.model.fields']
  345. all_model_ids = [model.id]
  346. all_model_ids.extend(model.inherited_model_ids.ids)
  347. field = field_model.search(
  348. [('model_id', 'in', all_model_ids), ('name', '=', field_name)])
  349. # The field can be a dummy one, like 'in_group_X' on 'res.users'
  350. # As such we can't log it (field_id is required to create a log)
  351. if not field:
  352. cache[model.model][field_name] = False
  353. else:
  354. field_data = field.read(load='_classic_write')[0]
  355. cache[model.model][field_name] = field_data
  356. return cache[model.model][field_name]
  357. def _create_log_line_on_read(
  358. self, log, fields_list, read_values):
  359. """Log field filled on a 'read' operation."""
  360. log_line_model = self.env['auditlog.log.line']
  361. for field_name in fields_list:
  362. if field_name in FIELDS_BLACKLIST:
  363. continue
  364. field = self._get_field(log.model_id, field_name)
  365. # not all fields have an ir.models.field entry (ie. related fields)
  366. if field:
  367. log_vals = self._prepare_log_line_vals_on_read(
  368. log, field, read_values)
  369. log_line_model.create(log_vals)
  370. def _prepare_log_line_vals_on_read(self, log, field, read_values):
  371. """Prepare the dictionary of values used to create a log line on a
  372. 'read' operation.
  373. """
  374. vals = {
  375. 'field_id': field['id'],
  376. 'log_id': log.id,
  377. 'old_value': read_values[log.res_id][field['name']],
  378. 'old_value_text': read_values[log.res_id][field['name']],
  379. 'new_value': False,
  380. 'new_value_text': False,
  381. }
  382. if field['relation'] and '2many' in field['ttype']:
  383. old_value_text = self.env[field['relation']].browse(
  384. vals['old_value']).name_get()
  385. vals['old_value_text'] = old_value_text
  386. return vals
  387. def _create_log_line_on_write(
  388. self, log, fields_list, old_values, new_values):
  389. """Log field updated on a 'write' operation."""
  390. log_line_model = self.env['auditlog.log.line']
  391. for field_name in fields_list:
  392. if field_name in FIELDS_BLACKLIST:
  393. continue
  394. field = self._get_field(log.model_id, field_name)
  395. # not all fields have an ir.models.field entry (ie. related fields)
  396. if field:
  397. log_vals = self._prepare_log_line_vals_on_write(
  398. log, field, old_values, new_values)
  399. log_line_model.create(log_vals)
  400. def _prepare_log_line_vals_on_write(
  401. self, log, field, old_values, new_values):
  402. """Prepare the dictionary of values used to create a log line on a
  403. 'write' operation.
  404. """
  405. vals = {
  406. 'field_id': field['id'],
  407. 'log_id': log.id,
  408. 'old_value': old_values[log.res_id][field['name']],
  409. 'old_value_text': old_values[log.res_id][field['name']],
  410. 'new_value': new_values[log.res_id][field['name']],
  411. 'new_value_text': new_values[log.res_id][field['name']],
  412. }
  413. # for *2many fields, log the name_get
  414. if log.log_type == 'full' and field['relation'] \
  415. and '2many' in field['ttype']:
  416. # Filter IDs to prevent a 'name_get()' call on deleted resources
  417. existing_ids = self.env[field['relation']]._search(
  418. [('id', 'in', vals['old_value'])])
  419. old_value_text = []
  420. if existing_ids:
  421. existing_values = self.env[field['relation']].browse(
  422. existing_ids).name_get()
  423. old_value_text.extend(existing_values)
  424. # Deleted resources will have a 'DELETED' text representation
  425. deleted_ids = set(vals['old_value']) - set(existing_ids)
  426. for deleted_id in deleted_ids:
  427. old_value_text.append((deleted_id, 'DELETED'))
  428. vals['old_value_text'] = old_value_text
  429. new_value_text = self.env[field['relation']].browse(
  430. vals['new_value']).name_get()
  431. vals['new_value_text'] = new_value_text
  432. return vals
  433. def _create_log_line_on_create(
  434. self, log, fields_list, new_values):
  435. """Log field filled on a 'create' operation."""
  436. log_line_model = self.env['auditlog.log.line']
  437. for field_name in fields_list:
  438. if field_name in FIELDS_BLACKLIST:
  439. continue
  440. field = self._get_field(log.model_id, field_name)
  441. # not all fields have an ir.models.field entry (ie. related fields)
  442. if field:
  443. log_vals = self._prepare_log_line_vals_on_create(
  444. log, field, new_values)
  445. log_line_model.create(log_vals)
  446. def _prepare_log_line_vals_on_create(self, log, field, new_values):
  447. """Prepare the dictionary of values used to create a log line on a
  448. 'create' operation.
  449. """
  450. vals = {
  451. 'field_id': field['id'],
  452. 'log_id': log.id,
  453. 'old_value': False,
  454. 'old_value_text': False,
  455. 'new_value': new_values[log.res_id][field['name']],
  456. 'new_value_text': new_values[log.res_id][field['name']],
  457. }
  458. if log.log_type == 'full' and field['relation'] \
  459. and '2many' in field['ttype']:
  460. new_value_text = self.env[field['relation']].browse(
  461. vals['new_value']).name_get()
  462. vals['new_value_text'] = new_value_text
  463. return vals
  464. @api.multi
  465. def subscribe(self):
  466. """Subscribe Rule for auditing changes on model and apply shortcut
  467. to view logs on that model.
  468. """
  469. act_window_model = self.env['ir.actions.act_window']
  470. for rule in self:
  471. # Create a shortcut to view logs
  472. domain = "[('model_id', '=', %s), ('res_id', '=', active_id)]" % (
  473. rule.model_id.id)
  474. vals = {
  475. 'name': _("View logs"),
  476. 'res_model': 'auditlog.log',
  477. 'src_model': rule.model_id.model,
  478. 'binding_model_id': rule.model_id.id,
  479. 'domain': domain,
  480. }
  481. act_window = act_window_model.sudo().create(vals)
  482. rule.write({'state': 'subscribed', 'action_id': act_window.id})
  483. return True
  484. @api.multi
  485. def unsubscribe(self):
  486. """Unsubscribe Auditing Rule on model."""
  487. # Revert patched methods
  488. self._revert_methods()
  489. for rule in self:
  490. # Remove the shortcut to view logs
  491. act_window = rule.action_id
  492. if act_window:
  493. act_window.unlink()
  494. self.write({'state': 'draft'})
  495. return True