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