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.

559 lines
23 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.multi
  188. def _make_create(self):
  189. """Instanciate a create method that log its calls."""
  190. self.ensure_one()
  191. log_type = self.log_type
  192. @api.model_create_multi
  193. @api.returns('self', lambda value: value.id)
  194. def create_full(self, vals_list, **kwargs):
  195. self = self.with_context(auditlog_disabled=True)
  196. rule_model = self.env['auditlog.rule']
  197. new_records = create_full.origin(self, vals_list, **kwargs)
  198. # Take a snapshot of record values from the cache instead of using
  199. # 'read()'. It avoids issues with related/computed fields which
  200. # stored in the database only at the end of the transaction, but
  201. # their values exist in cache.
  202. new_values = {}
  203. for new_record in new_records:
  204. new_values.setdefault(new_record.id, {})
  205. for fname, field in new_record._fields.items():
  206. new_values[new_record.id][fname] = field.convert_to_read(
  207. new_record[fname], new_record)
  208. rule_model.sudo().create_logs(
  209. self.env.uid, self._name, new_records.ids,
  210. 'create', None, new_values, {'log_type': log_type})
  211. return new_records
  212. @api.model_create_multi
  213. @api.returns('self', lambda value: value.id)
  214. def create_fast(self, vals_list, **kwargs):
  215. self = self.with_context(auditlog_disabled=True)
  216. rule_model = self.env['auditlog.rule']
  217. vals_list2 = copy.deepcopy(vals_list)
  218. new_records = create_fast.origin(self, vals_list, **kwargs)
  219. new_values = {}
  220. for vals, new_record in zip(vals_list2, new_records):
  221. new_values.setdefault(new_record.id, vals)
  222. rule_model.sudo().create_logs(
  223. self.env.uid, self._name, new_records.ids,
  224. 'create', None, new_values, {'log_type': log_type})
  225. return new_records
  226. return create_full if self.log_type == 'full' else create_fast
  227. @api.multi
  228. def _make_read(self):
  229. """Instanciate a read method that log its calls."""
  230. self.ensure_one()
  231. log_type = self.log_type
  232. def read(self, fields=None, load='_classic_read', **kwargs):
  233. result = read.origin(self, fields, load, **kwargs)
  234. # Sometimes the result is not a list but a dictionary
  235. # Also, we can not modify the current result as it will break calls
  236. result2 = result
  237. if not isinstance(result2, list):
  238. result2 = [result]
  239. read_values = dict((d['id'], d) for d in result2)
  240. # Old API
  241. # If the call came from auditlog itself, skip logging:
  242. # avoid logs on `read` produced by auditlog during internal
  243. # processing: read data of relevant records, 'ir.model',
  244. # 'ir.model.fields'... (no interest in logging such operations)
  245. if self.env.context.get('auditlog_disabled'):
  246. return result
  247. self = self.with_context(auditlog_disabled=True)
  248. rule_model = self.env['auditlog.rule']
  249. rule_model.sudo().create_logs(
  250. self.env.uid, self._name, self.ids,
  251. 'read', read_values, None, {'log_type': log_type})
  252. return result
  253. return read
  254. @api.multi
  255. def _make_write(self):
  256. """Instanciate a write method that log its calls."""
  257. self.ensure_one()
  258. log_type = self.log_type
  259. @api.multi
  260. def write_full(self, vals, **kwargs):
  261. self = self.with_context(auditlog_disabled=True)
  262. rule_model = self.env['auditlog.rule']
  263. old_values = dict(
  264. (d['id'], d) for d in self.sudo()
  265. .with_context(prefetch_fields=False).read(list(self._fields)))
  266. result = write_full.origin(self, vals, **kwargs)
  267. new_values = dict(
  268. (d['id'], d) for d in self.sudo()
  269. .with_context(prefetch_fields=False).read(list(self._fields)))
  270. rule_model.sudo().create_logs(
  271. self.env.uid, self._name, self.ids,
  272. 'write', old_values, new_values, {'log_type': log_type})
  273. return result
  274. @api.multi
  275. def write_fast(self, vals, **kwargs):
  276. self = self.with_context(auditlog_disabled=True)
  277. rule_model = self.env['auditlog.rule']
  278. # Log the user input only, no matter if the `vals` is updated
  279. # afterwards as it could not represent the real state
  280. # of the data in the database
  281. vals2 = dict(vals)
  282. old_vals2 = dict.fromkeys(list(vals2.keys()), False)
  283. old_values = dict((id_, old_vals2) for id_ in self.ids)
  284. new_values = dict((id_, vals2) for id_ in self.ids)
  285. result = write_fast.origin(self, vals, **kwargs)
  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. return write_full if self.log_type == 'full' else write_fast
  291. @api.multi
  292. def _make_unlink(self):
  293. """Instanciate an unlink method that log its calls."""
  294. self.ensure_one()
  295. log_type = self.log_type
  296. @api.multi
  297. def unlink_full(self, **kwargs):
  298. self = self.with_context(auditlog_disabled=True)
  299. rule_model = self.env['auditlog.rule']
  300. old_values = dict(
  301. (d['id'], d) for d in self.sudo()
  302. .with_context(prefetch_fields=False).read(list(self._fields)))
  303. rule_model.sudo().create_logs(
  304. self.env.uid, self._name, self.ids, 'unlink', old_values, None,
  305. {'log_type': log_type})
  306. return unlink_full.origin(self, **kwargs)
  307. @api.multi
  308. def unlink_fast(self, **kwargs):
  309. self = self.with_context(auditlog_disabled=True)
  310. rule_model = self.env['auditlog.rule']
  311. rule_model.sudo().create_logs(
  312. self.env.uid, self._name, self.ids, 'unlink', None, None,
  313. {'log_type': log_type})
  314. return unlink_fast.origin(self, **kwargs)
  315. return unlink_full if self.log_type == 'full' else unlink_fast
  316. def create_logs(self, uid, res_model, res_ids, method,
  317. old_values=None, new_values=None,
  318. additional_log_values=None):
  319. """Create logs. `old_values` and `new_values` are dictionaries, e.g:
  320. {RES_ID: {'FIELD': VALUE, ...}}
  321. """
  322. if old_values is None:
  323. old_values = EMPTY_DICT
  324. if new_values is None:
  325. new_values = EMPTY_DICT
  326. log_model = self.env['auditlog.log']
  327. http_request_model = self.env['auditlog.http.request']
  328. http_session_model = self.env['auditlog.http.session']
  329. for res_id in res_ids:
  330. model_model = self.env[res_model]
  331. name = model_model.browse(res_id).name_get()
  332. res_name = name and name[0] and name[0][1]
  333. vals = {
  334. 'name': res_name,
  335. 'model_id': self.pool._auditlog_model_cache[res_model],
  336. 'res_id': res_id,
  337. 'method': method,
  338. 'user_id': uid,
  339. 'http_request_id': http_request_model.current_http_request(),
  340. 'http_session_id': http_session_model.current_http_session(),
  341. }
  342. vals.update(additional_log_values or {})
  343. log = log_model.create(vals)
  344. diff = DictDiffer(
  345. new_values.get(res_id, EMPTY_DICT),
  346. old_values.get(res_id, EMPTY_DICT))
  347. if method is 'create':
  348. self._create_log_line_on_create(log, diff.added(), new_values)
  349. elif method is 'read':
  350. self._create_log_line_on_read(
  351. log,
  352. list(old_values.get(res_id, EMPTY_DICT).keys()), old_values
  353. )
  354. elif method is 'write':
  355. self._create_log_line_on_write(
  356. log, diff.changed(), old_values, new_values)
  357. def _get_field(self, model, field_name):
  358. cache = self.pool._auditlog_field_cache
  359. if field_name not in cache.get(model.model, {}):
  360. cache.setdefault(model.model, {})
  361. # - we use 'search()' then 'read()' instead of the 'search_read()'
  362. # to take advantage of the 'classic_write' loading
  363. # - search the field in the current model and those it inherits
  364. field_model = self.env['ir.model.fields']
  365. all_model_ids = [model.id]
  366. all_model_ids.extend(model.inherited_model_ids.ids)
  367. field = field_model.search(
  368. [('model_id', 'in', all_model_ids), ('name', '=', field_name)])
  369. # The field can be a dummy one, like 'in_group_X' on 'res.users'
  370. # As such we can't log it (field_id is required to create a log)
  371. if not field:
  372. cache[model.model][field_name] = False
  373. else:
  374. field_data = field.read(load='_classic_write')[0]
  375. cache[model.model][field_name] = field_data
  376. return cache[model.model][field_name]
  377. def _create_log_line_on_read(
  378. self, log, fields_list, read_values):
  379. """Log field filled on a 'read' operation."""
  380. log_line_model = self.env['auditlog.log.line']
  381. for field_name in fields_list:
  382. if field_name in FIELDS_BLACKLIST:
  383. continue
  384. field = self._get_field(log.model_id, field_name)
  385. # not all fields have an ir.models.field entry (ie. related fields)
  386. if field:
  387. log_vals = self._prepare_log_line_vals_on_read(
  388. log, field, read_values)
  389. log_line_model.create(log_vals)
  390. def _prepare_log_line_vals_on_read(self, log, field, read_values):
  391. """Prepare the dictionary of values used to create a log line on a
  392. 'read' operation.
  393. """
  394. vals = {
  395. 'field_id': field['id'],
  396. 'log_id': log.id,
  397. 'old_value': read_values[log.res_id][field['name']],
  398. 'old_value_text': read_values[log.res_id][field['name']],
  399. 'new_value': False,
  400. 'new_value_text': False,
  401. }
  402. if field['relation'] and '2many' in field['ttype']:
  403. old_value_text = self.env[field['relation']].browse(
  404. vals['old_value']).name_get()
  405. vals['old_value_text'] = old_value_text
  406. return vals
  407. def _create_log_line_on_write(
  408. self, log, fields_list, old_values, new_values):
  409. """Log field updated on a 'write' operation."""
  410. log_line_model = self.env['auditlog.log.line']
  411. for field_name in fields_list:
  412. if field_name in FIELDS_BLACKLIST:
  413. continue
  414. field = self._get_field(log.model_id, field_name)
  415. # not all fields have an ir.models.field entry (ie. related fields)
  416. if field:
  417. log_vals = self._prepare_log_line_vals_on_write(
  418. log, field, old_values, new_values)
  419. log_line_model.create(log_vals)
  420. def _prepare_log_line_vals_on_write(
  421. self, log, field, old_values, new_values):
  422. """Prepare the dictionary of values used to create a log line on a
  423. 'write' operation.
  424. """
  425. vals = {
  426. 'field_id': field['id'],
  427. 'log_id': log.id,
  428. 'old_value': old_values[log.res_id][field['name']],
  429. 'old_value_text': old_values[log.res_id][field['name']],
  430. 'new_value': new_values[log.res_id][field['name']],
  431. 'new_value_text': new_values[log.res_id][field['name']],
  432. }
  433. # for *2many fields, log the name_get
  434. if log.log_type == 'full' and field['relation'] \
  435. and '2many' in field['ttype']:
  436. # Filter IDs to prevent a 'name_get()' call on deleted resources
  437. existing_ids = self.env[field['relation']]._search(
  438. [('id', 'in', vals['old_value'])])
  439. old_value_text = []
  440. if existing_ids:
  441. existing_values = self.env[field['relation']].browse(
  442. existing_ids).name_get()
  443. old_value_text.extend(existing_values)
  444. # Deleted resources will have a 'DELETED' text representation
  445. deleted_ids = set(vals['old_value']) - set(existing_ids)
  446. for deleted_id in deleted_ids:
  447. old_value_text.append((deleted_id, 'DELETED'))
  448. vals['old_value_text'] = old_value_text
  449. new_value_text = self.env[field['relation']].browse(
  450. vals['new_value']).name_get()
  451. vals['new_value_text'] = new_value_text
  452. return vals
  453. def _create_log_line_on_create(
  454. self, log, fields_list, new_values):
  455. """Log field filled on a 'create' operation."""
  456. log_line_model = self.env['auditlog.log.line']
  457. for field_name in fields_list:
  458. if field_name in FIELDS_BLACKLIST:
  459. continue
  460. field = self._get_field(log.model_id, field_name)
  461. # not all fields have an ir.models.field entry (ie. related fields)
  462. if field:
  463. log_vals = self._prepare_log_line_vals_on_create(
  464. log, field, new_values)
  465. log_line_model.create(log_vals)
  466. def _prepare_log_line_vals_on_create(self, log, field, new_values):
  467. """Prepare the dictionary of values used to create a log line on a
  468. 'create' operation.
  469. """
  470. vals = {
  471. 'field_id': field['id'],
  472. 'log_id': log.id,
  473. 'old_value': False,
  474. 'old_value_text': False,
  475. 'new_value': new_values[log.res_id][field['name']],
  476. 'new_value_text': new_values[log.res_id][field['name']],
  477. }
  478. if log.log_type == 'full' and field['relation'] \
  479. and '2many' in field['ttype']:
  480. new_value_text = self.env[field['relation']].browse(
  481. vals['new_value']).name_get()
  482. vals['new_value_text'] = new_value_text
  483. return vals
  484. @api.multi
  485. def subscribe(self):
  486. """Subscribe Rule for auditing changes on model and apply shortcut
  487. to view logs on that model.
  488. """
  489. act_window_model = self.env['ir.actions.act_window']
  490. for rule in self:
  491. # Create a shortcut to view logs
  492. domain = "[('model_id', '=', %s), ('res_id', '=', active_id)]" % (
  493. rule.model_id.id)
  494. vals = {
  495. 'name': _("View logs"),
  496. 'res_model': 'auditlog.log',
  497. 'src_model': rule.model_id.model,
  498. 'binding_model_id': rule.model_id.id,
  499. 'domain': domain,
  500. }
  501. act_window = act_window_model.sudo().create(vals)
  502. rule.write({'state': 'subscribed', 'action_id': act_window.id})
  503. return True
  504. @api.multi
  505. def unsubscribe(self):
  506. """Unsubscribe Auditing Rule on model."""
  507. # Revert patched methods
  508. self._revert_methods()
  509. for rule in self:
  510. # Remove the shortcut to view logs
  511. act_window = rule.action_id
  512. if act_window:
  513. act_window.unlink()
  514. self.write({'state': 'draft'})
  515. return True