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.

575 lines
24 KiB

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