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.

577 lines
24 KiB

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