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.

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