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.

548 lines
23 KiB

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