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.

574 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(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(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(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(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. updated = True
  155. if updated:
  156. modules.registry.RegistryManager.signal_registry_change(
  157. self.env.cr.dbname)
  158. @api.model
  159. def create(self, vals):
  160. """Update the registry when a new rule is created."""
  161. new_record = super(AuditlogRule, self).create(vals)
  162. if new_record._register_hook():
  163. modules.registry.RegistryManager.signal_registry_change(
  164. self.env.cr.dbname)
  165. return new_record
  166. @api.multi
  167. def write(self, vals):
  168. """Update the registry when existing rules are updated."""
  169. super(AuditlogRule, self).write(vals)
  170. if self._register_hook():
  171. modules.registry.RegistryManager.signal_registry_change(
  172. self.env.cr.dbname)
  173. return True
  174. @api.multi
  175. def unlink(self):
  176. """Unsubscribe rules before removing them."""
  177. self.unsubscribe()
  178. return super(AuditlogRule, self).unlink()
  179. @api.multi
  180. def _make_create(self):
  181. """Instanciate a create method that log its calls."""
  182. self.ensure_one()
  183. log_type = self.log_type
  184. @api.model
  185. @api.returns('self', lambda value: value.id)
  186. def create_full(self, vals, **kwargs):
  187. self = self.with_context(auditlog_disabled=True)
  188. rule_model = self.env['auditlog.rule']
  189. new_record = create_full.origin(self, vals, **kwargs)
  190. new_values = dict(
  191. (d['id'], d) for d in new_record.sudo()
  192. .with_context(prefetch_fields=False).read(list(self._fields)))
  193. rule_model.sudo().create_logs(
  194. self.env.uid, self._name, new_record.ids,
  195. 'create', None, new_values, {'log_type': log_type})
  196. return new_record
  197. @api.model
  198. @api.returns('self', lambda value: value.id)
  199. def create_fast(self, vals, **kwargs):
  200. self = self.with_context(auditlog_disabled=True)
  201. rule_model = self.env['auditlog.rule']
  202. vals2 = dict(vals)
  203. new_record = create_fast.origin(self, vals, **kwargs)
  204. new_values = {new_record.id: vals2}
  205. rule_model.sudo().create_logs(
  206. self.env.uid, self._name, new_record.ids,
  207. 'create', None, new_values, {'log_type': log_type})
  208. return new_record
  209. return create_full if self.log_type == 'full' else create_fast
  210. @api.multi
  211. def _make_read(self):
  212. """Instanciate a read method that log its calls."""
  213. self.ensure_one()
  214. log_type = self.log_type
  215. def read(self, *args, **kwargs):
  216. result = read.origin(self, *args, **kwargs)
  217. # Sometimes the result is not a list but a dictionary
  218. # Also, we can not modify the current result as it will break calls
  219. result2 = result
  220. if not isinstance(result2, list):
  221. result2 = [result]
  222. read_values = dict((d['id'], d) for d in result2)
  223. # Old API
  224. if args and isinstance(args[0], sql_db.Cursor):
  225. cr, uid, ids = args[0], args[1], args[2]
  226. if isinstance(ids, (int, long)):
  227. ids = [ids]
  228. # If the call came from auditlog itself, skip logging:
  229. # avoid logs on `read` produced by auditlog during internal
  230. # processing: read data of relevant records, 'ir.model',
  231. # 'ir.model.fields'... (no interest in logging such operations)
  232. if kwargs.get('context', {}).get('auditlog_disabled'):
  233. return result
  234. env = api.Environment(cr, uid, {'auditlog_disabled': True})
  235. rule_model = env['auditlog.rule']
  236. rule_model.sudo().create_logs(
  237. env.uid, self._name, ids,
  238. 'read', read_values, None, {'log_type': log_type})
  239. # New API
  240. else:
  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(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, old_values.get(res_id, EMPTY_DICT).keys(), old_values)
  352. elif method is 'write':
  353. self._create_log_line_on_write(
  354. log, diff.changed(), old_values, new_values)
  355. def _get_field(self, model, field_name):
  356. cache = self.pool._auditlog_field_cache
  357. if field_name not in cache.get(model.model, {}):
  358. cache.setdefault(model.model, {})
  359. # - we use 'search()' then 'read()' instead of the 'search_read()'
  360. # to take advantage of the 'classic_write' loading
  361. # - search the field in the current model and those it inherits
  362. field_model = self.env['ir.model.fields']
  363. all_model_ids = [model.id]
  364. all_model_ids.extend(model.inherited_model_ids.ids)
  365. field = field_model.search(
  366. [('model_id', 'in', all_model_ids), ('name', '=', field_name)])
  367. # The field can be a dummy one, like 'in_group_X' on 'res.users'
  368. # As such we can't log it (field_id is required to create a log)
  369. if not field:
  370. cache[model.model][field_name] = False
  371. else:
  372. field_data = field.read(load='_classic_write')[0]
  373. cache[model.model][field_name] = field_data
  374. return cache[model.model][field_name]
  375. def _create_log_line_on_read(
  376. self, log, fields_list, read_values):
  377. """Log field filled on a 'read' operation."""
  378. log_line_model = self.env['auditlog.log.line']
  379. for field_name in fields_list:
  380. if field_name in FIELDS_BLACKLIST:
  381. continue
  382. field = self._get_field(log.model_id, field_name)
  383. # not all fields have an ir.models.field entry (ie. related fields)
  384. if field:
  385. log_vals = self._prepare_log_line_vals_on_read(
  386. log, field, read_values)
  387. log_line_model.create(log_vals)
  388. def _prepare_log_line_vals_on_read(self, log, field, read_values):
  389. """Prepare the dictionary of values used to create a log line on a
  390. 'read' operation.
  391. """
  392. vals = {
  393. 'field_id': field['id'],
  394. 'log_id': log.id,
  395. 'old_value': read_values[log.res_id][field['name']],
  396. 'old_value_text': read_values[log.res_id][field['name']],
  397. 'new_value': False,
  398. 'new_value_text': False,
  399. }
  400. if field['relation'] and '2many' in field['ttype']:
  401. old_value_text = self.env[field['relation']].browse(
  402. vals['old_value']).name_get()
  403. vals['old_value_text'] = old_value_text
  404. return vals
  405. def _create_log_line_on_write(
  406. self, log, fields_list, old_values, new_values):
  407. """Log field updated on a 'write' operation."""
  408. log_line_model = self.env['auditlog.log.line']
  409. for field_name in fields_list:
  410. if field_name in FIELDS_BLACKLIST:
  411. continue
  412. field = self._get_field(log.model_id, field_name)
  413. # not all fields have an ir.models.field entry (ie. related fields)
  414. if field:
  415. log_vals = self._prepare_log_line_vals_on_write(
  416. log, field, old_values, new_values)
  417. log_line_model.create(log_vals)
  418. def _prepare_log_line_vals_on_write(
  419. self, log, field, old_values, new_values):
  420. """Prepare the dictionary of values used to create a log line on a
  421. 'write' operation.
  422. """
  423. vals = {
  424. 'field_id': field['id'],
  425. 'log_id': log.id,
  426. 'old_value': old_values[log.res_id][field['name']],
  427. 'old_value_text': old_values[log.res_id][field['name']],
  428. 'new_value': new_values[log.res_id][field['name']],
  429. 'new_value_text': new_values[log.res_id][field['name']],
  430. }
  431. # for *2many fields, log the name_get
  432. if log.log_type == 'full' and field['relation'] \
  433. and '2many' in field['ttype']:
  434. # Filter IDs to prevent a 'name_get()' call on deleted resources
  435. existing_ids = self.env[field['relation']]._search(
  436. [('id', 'in', vals['old_value'])])
  437. old_value_text = []
  438. if existing_ids:
  439. existing_values = self.env[field['relation']].browse(
  440. existing_ids).name_get()
  441. old_value_text.extend(existing_values)
  442. # Deleted resources will have a 'DELETED' text representation
  443. deleted_ids = set(vals['old_value']) - set(existing_ids)
  444. for deleted_id in deleted_ids:
  445. old_value_text.append((deleted_id, 'DELETED'))
  446. vals['old_value_text'] = old_value_text
  447. new_value_text = self.env[field['relation']].browse(
  448. vals['new_value']).name_get()
  449. vals['new_value_text'] = new_value_text
  450. return vals
  451. def _create_log_line_on_create(
  452. self, log, fields_list, new_values):
  453. """Log field filled on a 'create' operation."""
  454. log_line_model = self.env['auditlog.log.line']
  455. for field_name in fields_list:
  456. if field_name in FIELDS_BLACKLIST:
  457. continue
  458. field = self._get_field(log.model_id, field_name)
  459. # not all fields have an ir.models.field entry (ie. related fields)
  460. if field:
  461. log_vals = self._prepare_log_line_vals_on_create(
  462. log, field, new_values)
  463. log_line_model.create(log_vals)
  464. def _prepare_log_line_vals_on_create(self, log, field, new_values):
  465. """Prepare the dictionary of values used to create a log line on a
  466. 'create' operation.
  467. """
  468. vals = {
  469. 'field_id': field['id'],
  470. 'log_id': log.id,
  471. 'old_value': False,
  472. 'old_value_text': False,
  473. 'new_value': new_values[log.res_id][field['name']],
  474. 'new_value_text': new_values[log.res_id][field['name']],
  475. }
  476. if log.log_type == 'full' and field['relation'] \
  477. and '2many' in field['ttype']:
  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. @api.multi
  483. def subscribe(self):
  484. """Subscribe Rule for auditing changes on model and apply shortcut
  485. to view logs on that model.
  486. """
  487. act_window_model = self.env['ir.actions.act_window']
  488. model_ir_values = self.env['ir.values']
  489. for rule in self:
  490. # Create a shortcut to view logs
  491. domain = "[('model_id', '=', %s), ('res_id', '=', active_id)]" % (
  492. rule.model_id.id)
  493. vals = {
  494. 'name': _(u"View logs"),
  495. 'res_model': 'auditlog.log',
  496. 'src_model': rule.model_id.model,
  497. 'domain': domain,
  498. }
  499. act_window = act_window_model.sudo().create(vals)
  500. rule.write({'state': 'subscribed', 'action_id': act_window.id})
  501. keyword = 'client_action_relate'
  502. value = 'ir.actions.act_window,%s' % act_window.id
  503. model_ir_values.sudo().set_action(
  504. 'View_log_' + rule.model_id.model,
  505. action_slot=keyword,
  506. model=rule.model_id.model,
  507. action=value)
  508. return True
  509. @api.multi
  510. def unsubscribe(self):
  511. """Unsubscribe Auditing Rule on model."""
  512. act_window_model = self.env['ir.actions.act_window']
  513. ir_values_model = self.env['ir.values']
  514. # Revert patched methods
  515. self._revert_methods()
  516. for rule in self:
  517. # Remove the shortcut to view logs
  518. act_window = act_window_model.search(
  519. [('name', '=', 'View Log'),
  520. ('res_model', '=', 'auditlog.log'),
  521. ('src_model', '=', rule.model_id.model)])
  522. if act_window:
  523. value = 'ir.actions.act_window,%s' % act_window.id
  524. act_window.unlink()
  525. ir_value = ir_values_model.search(
  526. [('model', '=', rule.model_id.model),
  527. ('value', '=', value)])
  528. if ir_value:
  529. ir_value.unlink()
  530. self.write({'state': 'draft'})
  531. return True