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.

514 lines
22 KiB

9 years ago
9 years ago
9 years ago
  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # OpenERP, Open Source Management Solution
  5. # Copyright (C) 2013 ABF OSIELL (<http://osiell.com>).
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as
  9. # published by the Free Software Foundation, either version 3 of the
  10. # License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. from openerp import models, fields, api, modules, _, SUPERUSER_ID, sql_db
  22. FIELDS_BLACKLIST = [
  23. 'id', 'create_uid', 'create_date', 'write_uid', 'write_date',
  24. 'display_name', '__last_update',
  25. ]
  26. # Used for performance, to avoid a dictionary instanciation when we need an
  27. # empty dict to simplify algorithms
  28. EMPTY_DICT = {}
  29. class DictDiffer(object):
  30. """Calculate the difference between two dictionaries as:
  31. (1) items added
  32. (2) items removed
  33. (3) keys same in both but changed values
  34. (4) keys same in both and unchanged values
  35. """
  36. def __init__(self, current_dict, past_dict):
  37. self.current_dict, self.past_dict = current_dict, past_dict
  38. self.set_current = set(current_dict)
  39. self.set_past = set(past_dict)
  40. self.intersect = self.set_current.intersection(self.set_past)
  41. def added(self):
  42. return self.set_current - self.intersect
  43. def removed(self):
  44. return self.set_past - self.intersect
  45. def changed(self):
  46. return set(o for o in self.intersect
  47. if self.past_dict[o] != self.current_dict[o])
  48. def unchanged(self):
  49. return set(o for o in self.intersect
  50. if self.past_dict[o] == self.current_dict[o])
  51. class auditlog_rule(models.Model):
  52. _name = 'auditlog.rule'
  53. _description = "Auditlog - Rule"
  54. name = fields.Char(u"Name", size=32, required=True)
  55. model_id = fields.Many2one(
  56. 'ir.model', u"Model", required=True,
  57. help=u"Select model for which you want to generate log.")
  58. user_ids = fields.Many2many(
  59. 'res.users',
  60. 'audittail_rules_users',
  61. 'user_id', 'rule_id',
  62. string=u"Users",
  63. help=u"if User is not added then it will applicable for all users")
  64. log_read = fields.Boolean(
  65. u"Log Reads",
  66. help=(u"Select this if you want to keep track of read/open on any "
  67. u"record of the model of this rule"))
  68. log_write = fields.Boolean(
  69. u"Log Writes", default=True,
  70. help=(u"Select this if you want to keep track of modification on any "
  71. u"record of the model of this rule"))
  72. log_unlink = fields.Boolean(
  73. u"Log Deletes", default=True,
  74. help=(u"Select this if you want to keep track of deletion on any "
  75. u"record of the model of this rule"))
  76. log_create = fields.Boolean(
  77. u"Log Creates", default=True,
  78. help=(u"Select this if you want to keep track of creation on any "
  79. u"record of the model of this rule"))
  80. # log_action = fields.Boolean(
  81. # "Log Action",
  82. # help=("Select this if you want to keep track of actions on the "
  83. # "model of this rule"))
  84. # log_workflow = fields.Boolean(
  85. # "Log Workflow",
  86. # help=("Select this if you want to keep track of workflow on any "
  87. # "record of the model of this rule"))
  88. state = fields.Selection(
  89. [('draft', "Draft"), ('subscribed', "Subscribed")],
  90. string=u"State", required=True, default='draft')
  91. action_id = fields.Many2one(
  92. 'ir.actions.act_window', string="Action")
  93. _sql_constraints = [
  94. ('model_uniq', 'unique(model_id)',
  95. ("There is already a rule defined on this model\n"
  96. "You cannot define another: please edit the existing one."))
  97. ]
  98. def _register_hook(self, cr, ids=None):
  99. """Get all rules and apply them to log method calls."""
  100. super(auditlog_rule, self)._register_hook(cr)
  101. if not hasattr(self.pool, '_auditlog_field_cache'):
  102. self.pool._auditlog_field_cache = {}
  103. if not hasattr(self.pool, '_auditlog_model_cache'):
  104. self.pool._auditlog_model_cache = {}
  105. if ids is None:
  106. ids = self.search(cr, SUPERUSER_ID, [('state', '=', 'subscribed')])
  107. return self._patch_methods(cr, SUPERUSER_ID, ids)
  108. @api.multi
  109. def _patch_methods(self):
  110. """Patch ORM methods of models defined in rules to log their calls."""
  111. updated = False
  112. model_cache = self.pool._auditlog_model_cache
  113. for rule in self:
  114. if rule.state != 'subscribed':
  115. continue
  116. if not self.pool.get(rule.model_id.model):
  117. # ignore rules for models not loadable currently
  118. continue
  119. model_cache[rule.model_id.model] = rule.model_id.id
  120. model_model = self.env[rule.model_id.model]
  121. # CRUD
  122. # -> create
  123. check_attr = 'auditlog_ruled_create'
  124. if getattr(rule, 'log_create') \
  125. and not hasattr(model_model, check_attr):
  126. model_model._patch_method('create', self._make_create())
  127. setattr(model_model, check_attr, True)
  128. updated = True
  129. # -> read
  130. check_attr = 'auditlog_ruled_read'
  131. if getattr(rule, 'log_read') \
  132. and not hasattr(model_model, check_attr):
  133. model_model._patch_method('read', self._make_read())
  134. setattr(model_model, check_attr, True)
  135. updated = True
  136. # -> write
  137. check_attr = 'auditlog_ruled_write'
  138. if getattr(rule, 'log_write') \
  139. and not hasattr(model_model, check_attr):
  140. model_model._patch_method('write', self._make_write())
  141. setattr(model_model, check_attr, True)
  142. updated = True
  143. # -> unlink
  144. check_attr = 'auditlog_ruled_unlink'
  145. if getattr(rule, 'log_unlink') \
  146. and not hasattr(model_model, check_attr):
  147. model_model._patch_method('unlink', self._make_unlink())
  148. setattr(model_model, check_attr, True)
  149. updated = True
  150. return updated
  151. @api.multi
  152. def _revert_methods(self):
  153. """Restore original ORM methods of models defined in rules."""
  154. updated = False
  155. for rule in self:
  156. model_model = self.env[rule.model_id.model]
  157. for method in ['create', 'read', 'write', 'unlink']:
  158. if getattr(rule, 'log_%s' % method):
  159. model_model._revert_method(method)
  160. updated = True
  161. if updated:
  162. modules.registry.RegistryManager.signal_registry_change(
  163. self.env.cr.dbname)
  164. # Unable to find a way to declare the `create` method with the new API,
  165. # errors occurs with the `_register_hook()` BaseModel method.
  166. def create(self, cr, uid, vals, context=None):
  167. """Update the registry when a new rule is created."""
  168. res_id = super(auditlog_rule, self).create(
  169. cr, uid, vals, context=context)
  170. if self._register_hook(cr, [res_id]):
  171. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  172. return res_id
  173. # Unable to find a way to declare the `write` method with the new API,
  174. # errors occurs with the `_register_hook()` BaseModel method.
  175. def write(self, cr, uid, ids, vals, context=None):
  176. """Update the registry when existing rules are updated."""
  177. if isinstance(ids, (int, long)):
  178. ids = [ids]
  179. super(auditlog_rule, self).write(cr, uid, ids, vals, context=context)
  180. if self._register_hook(cr, ids):
  181. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  182. return True
  183. @api.multi
  184. def unlink(self):
  185. """Unsubscribe rules before removing them."""
  186. self.unsubscribe()
  187. return super(auditlog_rule, self).unlink()
  188. def _make_create(self):
  189. """Instanciate a create method that log its calls."""
  190. @api.model
  191. @api.returns('self', lambda value: value.id)
  192. def create(self, vals, **kwargs):
  193. self = self.with_context(auditlog_disabled=True)
  194. rule_model = self.env['auditlog.rule']
  195. new_record = create.origin(self, vals, **kwargs)
  196. new_values = dict(
  197. (d['id'], d) for d in new_record.sudo().read(
  198. list(self._fields)))
  199. rule_model.sudo().create_logs(
  200. self.env.uid, self._name, new_record.ids,
  201. 'create', None, new_values)
  202. return new_record
  203. return create
  204. def _make_read(self):
  205. """Instanciate a read method that log its calls."""
  206. def read(self, *args, **kwargs):
  207. result = read.origin(self, *args, **kwargs)
  208. # Sometimes the result is not a list but a dictionary
  209. # Also, we can not modify the current result as it will break calls
  210. result2 = result
  211. if not isinstance(result2, list):
  212. result2 = [result]
  213. read_values = dict((d['id'], d) for d in result2)
  214. # Old API
  215. if args and isinstance(args[0], sql_db.Cursor):
  216. cr, uid, ids = args[0], args[1], args[2]
  217. if isinstance(ids, (int, long)):
  218. ids = [ids]
  219. # If the call came from auditlog itself, skip logging:
  220. # avoid logs on `read` produced by auditlog during internal
  221. # processing: read data of relevant records, 'ir.model',
  222. # 'ir.model.fields'... (no interest in logging such operations)
  223. if kwargs.get('context', {}).get('auditlog_disabled'):
  224. return result
  225. env = api.Environment(cr, uid, {'auditlog_disabled': True})
  226. rule_model = env['auditlog.rule']
  227. rule_model.sudo().create_logs(
  228. env.uid, self._name, ids,
  229. 'read', read_values)
  230. # New API
  231. else:
  232. # If the call came from auditlog itself, skip logging:
  233. # avoid logs on `read` produced by auditlog during internal
  234. # processing: read data of relevant records, 'ir.model',
  235. # 'ir.model.fields'... (no interest in logging such operations)
  236. if self.env.context.get('auditlog_disabled'):
  237. return result
  238. self = self.with_context(auditlog_disabled=True)
  239. rule_model = self.env['auditlog.rule']
  240. rule_model.sudo().create_logs(
  241. self.env.uid, self._name, self.ids,
  242. 'read', read_values)
  243. return result
  244. return read
  245. def _make_write(self):
  246. """Instanciate a write method that log its calls."""
  247. @api.multi
  248. def write(self, vals, **kwargs):
  249. self = self.with_context(auditlog_disabled=True)
  250. rule_model = self.env['auditlog.rule']
  251. old_values = dict(
  252. (d['id'], d) for d in self.sudo().read(list(self._fields)))
  253. result = write.origin(self, vals, **kwargs)
  254. new_values = dict(
  255. (d['id'], d) for d in self.sudo().read(list(self._fields)))
  256. rule_model.sudo().create_logs(
  257. self.env.uid, self._name, self.ids,
  258. 'write', old_values, new_values)
  259. return result
  260. return write
  261. def _make_unlink(self):
  262. """Instanciate an unlink method that log its calls."""
  263. @api.multi
  264. def unlink(self, **kwargs):
  265. self = self.with_context(auditlog_disabled=True)
  266. rule_model = self.env['auditlog.rule']
  267. old_values = dict(
  268. (d['id'], d) for d in self.sudo().read(list(self._fields)))
  269. rule_model.sudo().create_logs(
  270. self.env.uid, self._name, self.ids, 'unlink', old_values)
  271. return unlink.origin(self, **kwargs)
  272. return unlink
  273. def create_logs(self, uid, res_model, res_ids, method,
  274. old_values=None, new_values=None,
  275. additional_log_values=None):
  276. """Create logs. `old_values` and `new_values` are dictionnaries, e.g:
  277. {RES_ID: {'FIELD': VALUE, ...}}
  278. """
  279. if old_values is None:
  280. old_values = EMPTY_DICT
  281. if new_values is None:
  282. new_values = EMPTY_DICT
  283. log_model = self.env['auditlog.log']
  284. for res_id in res_ids:
  285. model_model = self.env[res_model]
  286. name = model_model.browse(res_id).name_get()
  287. res_name = name and name[0] and name[0][1]
  288. vals = {
  289. 'name': res_name,
  290. 'model_id': self.pool._auditlog_model_cache[res_model],
  291. 'res_id': res_id,
  292. 'method': method,
  293. 'user_id': uid,
  294. }
  295. vals.update(additional_log_values or {})
  296. log = log_model.create(vals)
  297. diff = DictDiffer(
  298. new_values.get(res_id, EMPTY_DICT),
  299. old_values.get(res_id, EMPTY_DICT))
  300. if method is 'create':
  301. self._create_log_line_on_create(log, diff.added(), new_values)
  302. elif method is 'read':
  303. self._create_log_line_on_read(
  304. log, old_values.get(res_id, EMPTY_DICT).keys(), old_values)
  305. elif method is 'write':
  306. self._create_log_line_on_write(
  307. log, diff.changed(), old_values, new_values)
  308. def _get_field(self, model, field_name):
  309. cache = self.pool._auditlog_field_cache
  310. if field_name not in cache.get(model.model, {}):
  311. cache.setdefault(model.model, {})
  312. # - we use 'search()' then 'read()' instead of the 'search_read()'
  313. # to take advantage of the 'classic_write' loading
  314. # - search the field in the current model and those it inherits
  315. field_model = self.env['ir.model.fields']
  316. all_model_ids = [model.id]
  317. all_model_ids.extend(model.inherited_model_ids.ids)
  318. field = field_model.search(
  319. [('model_id', 'in', all_model_ids), ('name', '=', field_name)])
  320. # The field can be a dummy one, like 'in_group_X' on 'res.users'
  321. # As such we can't log it (field_id is required to create a log)
  322. if not field:
  323. cache[model.model][field_name] = False
  324. else:
  325. field_data = field.read(load='_classic_write')[0]
  326. cache[model.model][field_name] = field_data
  327. return cache[model.model][field_name]
  328. def _create_log_line_on_read(
  329. self, log, fields_list, read_values):
  330. """Log field filled on a 'read' operation."""
  331. log_line_model = self.env['auditlog.log.line']
  332. for field_name in fields_list:
  333. if field_name in FIELDS_BLACKLIST:
  334. continue
  335. field = self._get_field(log.model_id, field_name)
  336. # not all fields have an ir.models.field entry (ie. related fields)
  337. if field:
  338. log_vals = self._prepare_log_line_vals_on_read(
  339. log, field, read_values)
  340. log_line_model.create(log_vals)
  341. def _prepare_log_line_vals_on_read(self, log, field, read_values):
  342. """Prepare the dictionary of values used to create a log line on a
  343. 'read' operation.
  344. """
  345. vals = {
  346. 'field_id': field['id'],
  347. 'log_id': log.id,
  348. 'old_value': read_values[log.res_id][field['name']],
  349. 'old_value_text': read_values[log.res_id][field['name']],
  350. 'new_value': False,
  351. 'new_value_text': False,
  352. }
  353. if field['relation'] and '2many' in field['ttype']:
  354. old_value_text = self.env[field['relation']].browse(
  355. vals['old_value']).name_get()
  356. vals['old_value_text'] = old_value_text
  357. return vals
  358. def _create_log_line_on_write(
  359. self, log, fields_list, old_values, new_values):
  360. """Log field updated on a 'write' operation."""
  361. log_line_model = self.env['auditlog.log.line']
  362. for field_name in fields_list:
  363. if field_name in FIELDS_BLACKLIST:
  364. continue
  365. field = self._get_field(log.model_id, field_name)
  366. # not all fields have an ir.models.field entry (ie. related fields)
  367. if field:
  368. log_vals = self._prepare_log_line_vals_on_write(
  369. log, field, old_values, new_values)
  370. log_line_model.create(log_vals)
  371. def _prepare_log_line_vals_on_write(
  372. self, log, field, old_values, new_values):
  373. """Prepare the dictionary of values used to create a log line on a
  374. 'write' operation.
  375. """
  376. vals = {
  377. 'field_id': field['id'],
  378. 'log_id': log.id,
  379. 'old_value': old_values[log.res_id][field['name']],
  380. 'old_value_text': old_values[log.res_id][field['name']],
  381. 'new_value': new_values[log.res_id][field['name']],
  382. 'new_value_text': new_values[log.res_id][field['name']],
  383. }
  384. # for *2many fields, log the name_get
  385. if field['relation'] and '2many' in field['ttype']:
  386. # Filter IDs to prevent a 'name_get()' call on deleted resources
  387. existing_ids = self.env[field['relation']]._search(
  388. [('id', 'in', vals['old_value'])])
  389. old_value_text = []
  390. if existing_ids:
  391. existing_values = self.env[field['relation']].browse(
  392. existing_ids).name_get()
  393. old_value_text.extend(existing_values)
  394. # Deleted resources will have a 'DELETED' text representation
  395. deleted_ids = set(vals['old_value']) - set(existing_ids)
  396. for deleted_id in deleted_ids:
  397. old_value_text.append((deleted_id, 'DELETED'))
  398. vals['old_value_text'] = old_value_text
  399. new_value_text = self.env[field['relation']].browse(
  400. vals['new_value']).name_get()
  401. vals['new_value_text'] = new_value_text
  402. return vals
  403. def _create_log_line_on_create(
  404. self, log, fields_list, new_values):
  405. """Log field filled on a 'create' operation."""
  406. log_line_model = self.env['auditlog.log.line']
  407. for field_name in fields_list:
  408. if field_name in FIELDS_BLACKLIST:
  409. continue
  410. field = self._get_field(log.model_id, field_name)
  411. # not all fields have an ir.models.field entry (ie. related fields)
  412. if field:
  413. log_vals = self._prepare_log_line_vals_on_create(
  414. log, field, new_values)
  415. log_line_model.create(log_vals)
  416. def _prepare_log_line_vals_on_create(self, log, field, new_values):
  417. """Prepare the dictionary of values used to create a log line on a
  418. 'create' operation.
  419. """
  420. vals = {
  421. 'field_id': field['id'],
  422. 'log_id': log.id,
  423. 'old_value': False,
  424. 'old_value_text': False,
  425. 'new_value': new_values[log.res_id][field['name']],
  426. 'new_value_text': new_values[log.res_id][field['name']],
  427. }
  428. if field['relation'] and '2many' in field['ttype']:
  429. new_value_text = self.env[field['relation']].browse(
  430. vals['new_value']).name_get()
  431. vals['new_value_text'] = new_value_text
  432. return vals
  433. @api.multi
  434. def subscribe(self):
  435. """Subscribe Rule for auditing changes on model and apply shortcut
  436. to view logs on that model.
  437. """
  438. act_window_model = self.env['ir.actions.act_window']
  439. model_data_model = self.env['ir.model.data']
  440. for rule in self:
  441. # Create a shortcut to view logs
  442. domain = "[('model_id', '=', %s), ('res_id', '=', active_id)]" % (
  443. rule.model_id.id)
  444. vals = {
  445. 'name': _(u"View logs"),
  446. 'res_model': 'auditlog.log',
  447. 'src_model': rule.model_id.model,
  448. 'domain': domain,
  449. }
  450. act_window = act_window_model.sudo().create(vals)
  451. rule.write({'state': 'subscribed', 'action_id': act_window.id})
  452. keyword = 'client_action_relate'
  453. value = 'ir.actions.act_window,%s' % act_window.id
  454. model_data_model.sudo().ir_set(
  455. 'action', keyword, 'View_log_' + rule.model_id.model,
  456. [rule.model_id.model], value, replace=True,
  457. isobject=True, xml_id=False)
  458. return True
  459. @api.multi
  460. def unsubscribe(self):
  461. """Unsubscribe Auditing Rule on model."""
  462. act_window_model = self.env['ir.actions.act_window']
  463. ir_values_model = self.env['ir.values']
  464. # Revert patched methods
  465. self._revert_methods()
  466. for rule in self:
  467. # Remove the shortcut to view logs
  468. act_window = act_window_model.search(
  469. [('name', '=', 'View Log'),
  470. ('res_model', '=', 'auditlog.log'),
  471. ('src_model', '=', rule.model_id.model)])
  472. if act_window:
  473. value = 'ir.actions.act_window,%s' % act_window.id
  474. act_window.unlink()
  475. ir_value = ir_values_model.search(
  476. [('model', '=', rule.model_id.model),
  477. ('value', '=', value)])
  478. if ir_value:
  479. ir_value.unlink()
  480. self.write({'state': 'draft'})
  481. return True