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.

683 lines
29 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. from openerp.exceptions import ValidationError
  6. FIELDS_BLACKLIST = [
  7. 'id', 'create_uid', 'create_date', 'write_uid', 'write_date',
  8. 'display_name', '__last_update',
  9. ]
  10. # Used for performance, to avoid a dictionary instanciation when we need an
  11. # empty dict to simplify algorithms
  12. EMPTY_DICT = {}
  13. class DictDiffer(object):
  14. """Calculate the difference between two dictionaries as:
  15. (1) items added
  16. (2) items removed
  17. (3) keys same in both but changed values
  18. (4) keys same in both and unchanged values
  19. """
  20. def __init__(self, current_dict, past_dict):
  21. self.current_dict, self.past_dict = current_dict, past_dict
  22. self.set_current = set(current_dict)
  23. self.set_past = set(past_dict)
  24. self.intersect = self.set_current.intersection(self.set_past)
  25. def added(self):
  26. return self.set_current - self.intersect
  27. def removed(self):
  28. return self.set_past - self.intersect
  29. def changed(self):
  30. return set(o for o in self.intersect
  31. if self.past_dict[o] != self.current_dict[o])
  32. def unchanged(self):
  33. return set(o for o in self.intersect
  34. if self.past_dict[o] == self.current_dict[o])
  35. class AuditlogRule(models.Model):
  36. _name = 'auditlog.rule'
  37. _description = "Auditlog - Rule"
  38. name = fields.Char(u"Name", size=32, required=True)
  39. model_id = fields.Many2one(
  40. 'ir.model', u"Model", required=True,
  41. help=u"Select model for which you want to generate log.")
  42. user_ids = fields.Many2many(
  43. 'res.users',
  44. 'audittail_rules_users',
  45. 'user_id', 'rule_id',
  46. string=u"Users",
  47. help=u"if User is not added then it will applicable for all users")
  48. log_read = fields.Boolean(
  49. u"Log Reads",
  50. help=(u"Select this if you want to keep track of read/open on any "
  51. u"record of the model of this rule"))
  52. log_write = fields.Boolean(
  53. u"Log Writes", default=True,
  54. help=(u"Select this if you want to keep track of modification on any "
  55. u"record of the model of this rule"))
  56. log_unlink = fields.Boolean(
  57. u"Log Deletes", default=True,
  58. help=(u"Select this if you want to keep track of deletion on any "
  59. u"record of the model of this rule"))
  60. log_create = fields.Boolean(
  61. u"Log Creates", default=True,
  62. help=(u"Select this if you want to keep track of creation on any "
  63. u"record of the model of this rule"))
  64. log_custom = fields.Boolean(
  65. u"Log Methods",
  66. help=(u"Select this if you want to keep track of custom methods on "
  67. u"any record of the model of this rule"))
  68. custom_method_ids = fields.One2many('auditlog.methods', 'rule_id')
  69. log_type = fields.Selection(
  70. [('full', u"Full log"),
  71. ('fast', u"Fast log"),
  72. ],
  73. string=u"Type", required=True, default='full',
  74. help=(u"Full log: make a diff between the data before and after "
  75. u"the operation (log more info like computed fields which were "
  76. u"updated, but it is slower)\n"
  77. u"Fast log: only log the changes made through the create and "
  78. u"write operations (less information, but it is faster)"))
  79. # log_action = fields.Boolean(
  80. # "Log Action",
  81. # help=("Select this if you want to keep track of actions on the "
  82. # "model of this rule"))
  83. # log_workflow = fields.Boolean(
  84. # "Log Workflow",
  85. # help=("Select this if you want to keep track of workflow on any "
  86. # "record of the model of this rule"))
  87. state = fields.Selection(
  88. [('draft', "Draft"), ('subscribed', "Subscribed")],
  89. string=u"State", required=True, default='draft')
  90. action_id = fields.Many2one(
  91. 'ir.actions.act_window', string="Action")
  92. _sql_constraints = [
  93. ('model_uniq', 'unique(model_id)',
  94. ("There is already a rule defined on this model\n"
  95. "You cannot define another: please edit the existing one."))
  96. ]
  97. def _register_hook(self, cr, ids=None):
  98. """Get all rules and apply them to log method calls."""
  99. super(AuditlogRule, self)._register_hook(cr)
  100. if not hasattr(self.pool, '_auditlog_field_cache'):
  101. self.pool._auditlog_field_cache = {}
  102. if not hasattr(self.pool, '_auditlog_model_cache'):
  103. self.pool._auditlog_model_cache = {}
  104. if ids is None:
  105. ids = self.search(cr, SUPERUSER_ID, [('state', '=', 'subscribed')])
  106. return self._patch_methods(cr, SUPERUSER_ID, ids)
  107. @api.multi
  108. def _patch_methods(self):
  109. """Patch ORM methods of models defined in rules to log their calls."""
  110. updated = False
  111. model_cache = self.pool._auditlog_model_cache
  112. for rule in self:
  113. if rule.state != 'subscribed':
  114. continue
  115. if not self.pool.get(rule.model_id.model):
  116. # ignore rules for models not loadable currently
  117. continue
  118. model_cache[rule.model_id.model] = rule.model_id.id
  119. model_model = self.env[rule.model_id.model]
  120. # CRUD
  121. # -> create
  122. check_attr = 'auditlog_ruled_create'
  123. if getattr(rule, 'log_create') \
  124. and not hasattr(model_model, check_attr):
  125. model_model._patch_method('create', rule._make_create())
  126. setattr(model_model, check_attr, True)
  127. updated = True
  128. # -> read
  129. check_attr = 'auditlog_ruled_read'
  130. if getattr(rule, 'log_read') \
  131. and not hasattr(model_model, check_attr):
  132. model_model._patch_method('read', rule._make_read())
  133. setattr(model_model, check_attr, True)
  134. updated = True
  135. # -> write
  136. check_attr = 'auditlog_ruled_write'
  137. if getattr(rule, 'log_write') \
  138. and not hasattr(model_model, check_attr):
  139. model_model._patch_method('write', rule._make_write())
  140. setattr(model_model, check_attr, True)
  141. updated = True
  142. # -> unlink
  143. check_attr = 'auditlog_ruled_unlink'
  144. if getattr(rule, 'log_unlink') \
  145. and not hasattr(model_model, check_attr):
  146. model_model._patch_method('unlink', rule._make_unlink())
  147. setattr(model_model, check_attr, True)
  148. updated = True
  149. # Check if custom methods are enabled and patch the different
  150. # rule methods
  151. if getattr(rule, 'log_custom'):
  152. for custom_method in rule.custom_method_ids:
  153. check_attr = 'auditlog_ruled_%s' % custom_method.name
  154. if not hasattr(model_model, custom_method.name):
  155. raise ValidationError(
  156. _('Method %s does not exist for model %s.' % (
  157. custom_method.name,
  158. model_model
  159. )))
  160. if not hasattr(model_model, check_attr):
  161. model_model._patch_method(
  162. custom_method.name,
  163. rule._make_custom(
  164. custom_method.message,
  165. custom_method.use_active_ids,
  166. custom_method.context_field_number)
  167. )
  168. setattr(model_model, check_attr, True)
  169. updated = True
  170. return updated
  171. @api.multi
  172. def _revert_methods(self):
  173. """Restore original ORM methods of models defined in rules."""
  174. updated = False
  175. for rule in self:
  176. model_model = self.env[rule.model_id.model]
  177. for method in ['create', 'read', 'write', 'unlink']:
  178. if getattr(rule, 'log_%s' % method) and hasattr(
  179. getattr(model_model, method), 'origin'):
  180. model_model._revert_method(method)
  181. updated = True
  182. if hasattr(rule, 'log_custom'):
  183. for custom_method in rule.custom_method_ids:
  184. method = custom_method.name
  185. if hasattr(getattr(model_model, method), 'origin'):
  186. model_model._revert_method(method)
  187. updated = True
  188. if updated:
  189. modules.registry.RegistryManager.signal_registry_change(
  190. self.env.cr.dbname)
  191. # Unable to find a way to declare the `create` method with the new API,
  192. # errors occurs with the `_register_hook()` BaseModel method.
  193. def create(self, cr, uid, vals, context=None):
  194. """Update the registry when a new rule is created."""
  195. res_id = super(AuditlogRule, self).create(
  196. cr, uid, vals, context=context)
  197. if self._register_hook(cr, [res_id]):
  198. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  199. return res_id
  200. # Unable to find a way to declare the `write` method with the new API,
  201. # errors occurs with the `_register_hook()` BaseModel method.
  202. def write(self, cr, uid, ids, vals, context=None):
  203. """Update the registry when existing rules are updated."""
  204. if isinstance(ids, (int, long)):
  205. ids = [ids]
  206. super(AuditlogRule, self).write(cr, uid, ids, vals, context=context)
  207. if self._register_hook(cr, ids):
  208. modules.registry.RegistryManager.signal_registry_change(cr.dbname)
  209. return True
  210. @api.multi
  211. def unlink(self):
  212. """Unsubscribe rules before removing them."""
  213. self.unsubscribe()
  214. return super(AuditlogRule, self).unlink()
  215. @api.multi
  216. def _make_create(self):
  217. """Instanciate a create method that log its calls."""
  218. self.ensure_one()
  219. log_type = self.log_type
  220. @api.model
  221. @api.returns('self', lambda value: value.id)
  222. def create_full(self, vals, **kwargs):
  223. self = self.with_context(auditlog_disabled=True)
  224. rule_model = self.env['auditlog.rule']
  225. new_record = create_full.origin(self, vals, **kwargs)
  226. new_values = dict(
  227. (d['id'], d) for d in new_record.sudo()
  228. .with_context(prefetch_fields=False).read(list(self._fields)))
  229. rule_model.sudo().create_logs(
  230. self.env.uid, self._name, new_record.ids,
  231. 'create', None, new_values, {'log_type': log_type})
  232. return new_record
  233. @api.model
  234. @api.returns('self', lambda value: value.id)
  235. def create_fast(self, vals, **kwargs):
  236. self = self.with_context(auditlog_disabled=True)
  237. rule_model = self.env['auditlog.rule']
  238. vals2 = dict(vals)
  239. new_record = create_fast.origin(self, vals, **kwargs)
  240. new_values = {new_record.id: vals2}
  241. rule_model.sudo().create_logs(
  242. self.env.uid, self._name, new_record.ids,
  243. 'create', None, new_values, {'log_type': log_type})
  244. return new_record
  245. return create_full if self.log_type == 'full' else create_fast
  246. @api.multi
  247. def _make_read(self):
  248. """Instanciate a read method that log its calls."""
  249. self.ensure_one()
  250. log_type = self.log_type
  251. def read(self, *args, **kwargs):
  252. result = read.origin(self, *args, **kwargs)
  253. # Sometimes the result is not a list but a dictionary
  254. # Also, we can not modify the current result as it will break calls
  255. result2 = result
  256. if not isinstance(result2, list):
  257. result2 = [result]
  258. read_values = dict((d['id'], d) for d in result2)
  259. # Old API
  260. if args and isinstance(args[0], sql_db.Cursor):
  261. cr, uid, ids = args[0], args[1], args[2]
  262. if isinstance(ids, (int, long)):
  263. ids = [ids]
  264. # If the call came from auditlog itself, skip logging:
  265. # avoid logs on `read` produced by auditlog during internal
  266. # processing: read data of relevant records, 'ir.model',
  267. # 'ir.model.fields'... (no interest in logging such operations)
  268. if kwargs.get('context', {}).get('auditlog_disabled'):
  269. return result
  270. env = api.Environment(cr, uid, {'auditlog_disabled': True})
  271. rule_model = env['auditlog.rule']
  272. rule_model.sudo().create_logs(
  273. env.uid, self._name, ids,
  274. 'read', read_values, None, {'log_type': log_type})
  275. # New API
  276. else:
  277. # If the call came from auditlog itself, skip logging:
  278. # avoid logs on `read` produced by auditlog during internal
  279. # processing: read data of relevant records, 'ir.model',
  280. # 'ir.model.fields'... (no interest in logging such operations)
  281. if self.env.context.get('auditlog_disabled'):
  282. return result
  283. self = self.with_context(auditlog_disabled=True)
  284. rule_model = self.env['auditlog.rule']
  285. rule_model.sudo().create_logs(
  286. self.env.uid, self._name, self.ids,
  287. 'read', read_values, None, {'log_type': log_type})
  288. return result
  289. return read
  290. @api.multi
  291. def _make_write(self):
  292. """Instanciate a write method that log its calls."""
  293. self.ensure_one()
  294. log_type = self.log_type
  295. @api.multi
  296. def write_full(self, vals, **kwargs):
  297. self = self.with_context(auditlog_disabled=True)
  298. rule_model = self.env['auditlog.rule']
  299. old_values = dict(
  300. (d['id'], d) for d in self.sudo()
  301. .with_context(prefetch_fields=False).read(list(self._fields)))
  302. result = write_full.origin(self, vals, **kwargs)
  303. new_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,
  308. 'write', old_values, new_values, {'log_type': log_type})
  309. return result
  310. @api.multi
  311. def write_fast(self, vals, **kwargs):
  312. self = self.with_context(auditlog_disabled=True)
  313. rule_model = self.env['auditlog.rule']
  314. # Log the user input only, no matter if the `vals` is updated
  315. # afterwards as it could not represent the real state
  316. # of the data in the database
  317. vals2 = dict(vals)
  318. old_vals2 = dict.fromkeys(vals2.keys(), False)
  319. old_values = dict((id_, old_vals2) for id_ in self.ids)
  320. new_values = dict((id_, vals2) for id_ in self.ids)
  321. result = write_fast.origin(self, vals, **kwargs)
  322. rule_model.sudo().create_logs(
  323. self.env.uid, self._name, self.ids,
  324. 'write', old_values, new_values, {'log_type': log_type})
  325. return result
  326. return write_full if self.log_type == 'full' else write_fast
  327. @api.multi
  328. def _make_unlink(self):
  329. """Instanciate an unlink method that log its calls."""
  330. self.ensure_one()
  331. log_type = self.log_type
  332. @api.multi
  333. def unlink_full(self, **kwargs):
  334. self = self.with_context(auditlog_disabled=True)
  335. rule_model = self.env['auditlog.rule']
  336. old_values = dict(
  337. (d['id'], d) for d in self.sudo()
  338. .with_context(prefetch_fields=False).read(list(self._fields)))
  339. rule_model.sudo().create_logs(
  340. self.env.uid, self._name, self.ids, 'unlink', old_values, None,
  341. {'log_type': log_type})
  342. return unlink_full.origin(self, **kwargs)
  343. @api.multi
  344. def unlink_fast(self, **kwargs):
  345. self = self.with_context(auditlog_disabled=True)
  346. rule_model = self.env['auditlog.rule']
  347. rule_model.sudo().create_logs(
  348. self.env.uid, self._name, self.ids, 'unlink', None, None,
  349. {'log_type': log_type})
  350. return unlink_fast.origin(self, **kwargs)
  351. return unlink_full if self.log_type == 'full' else unlink_fast
  352. @api.multi
  353. def _make_custom(self, message, use_active_ids, context_field_number):
  354. """Instanciate a read method that log its calls."""
  355. self.ensure_one()
  356. log_type = self.log_type
  357. def custom(self, *args, **kwargs):
  358. result = custom.origin(self, *args, **kwargs)
  359. result2 = result
  360. if not isinstance(result2, list):
  361. result2 = [result]
  362. # Old API
  363. if args and isinstance(args[0], sql_db.Cursor):
  364. cr, uid, ids = args[0], args[1], args[2]
  365. if isinstance(ids, (int, long)):
  366. ids = [ids]
  367. context = kwargs.get('context', {})
  368. # Set specific context if it is defined by our rule
  369. if not context and context_field_number:
  370. if context_field_number - 1 < len(args):
  371. context = args[context_field_number - 1]
  372. if context.get('auditlog_disabled'):
  373. return result
  374. env = api.Environment(cr, uid, {'auditlog_disabled': True})
  375. rule_model = env['auditlog.rule']
  376. # Overwrite the ids and object_model if it is required
  377. # by the auditlog rule
  378. object_model = self._name
  379. if use_active_ids:
  380. if context.get('active_model'):
  381. if context.get('active_ids'):
  382. object_model = context.get(
  383. 'active_model',
  384. object_model)
  385. ids = context.get('active_ids', ids)
  386. rule_model.sudo().create_logs(
  387. env.uid, object_model, ids,
  388. message, None, None, {'log_type': log_type})
  389. # New API
  390. else:
  391. if self.env.context.get('auditlog_disabled'):
  392. return result
  393. self = self.with_context(auditlog_disabled=True)
  394. context = self.env.context
  395. # Overwrite the ids and object_model if it is required
  396. # by the auditlog rule
  397. ids = self.ids
  398. object_model = self._name
  399. if use_active_ids:
  400. if context.get('active_model'):
  401. if context.get('active_ids'):
  402. object_model = context.get(
  403. 'active_model',
  404. object_model)
  405. ids = context.get('active_ids', ids)
  406. rule_model = self.env['auditlog.rule']
  407. rule_model.sudo().create_logs(
  408. self.env.uid, object_model, ids,
  409. message, None, None, {'log_type': log_type})
  410. return result
  411. return custom
  412. def create_logs(self, uid, res_model, res_ids, method,
  413. old_values=None, new_values=None,
  414. additional_log_values=None):
  415. """Create logs. `old_values` and `new_values` are dictionnaries, e.g:
  416. {RES_ID: {'FIELD': VALUE, ...}}
  417. """
  418. if old_values is None:
  419. old_values = EMPTY_DICT
  420. if new_values is None:
  421. new_values = EMPTY_DICT
  422. log_model = self.env['auditlog.log']
  423. http_request_model = self.env['auditlog.http.request']
  424. http_session_model = self.env['auditlog.http.session']
  425. for res_id in res_ids:
  426. model_model = self.env[res_model]
  427. name = model_model.browse(res_id).name_get()
  428. res_name = name and name[0] and name[0][1]
  429. vals = {
  430. 'name': res_name,
  431. 'model_id': self.pool._auditlog_model_cache[res_model],
  432. 'res_id': res_id,
  433. 'method': method,
  434. 'user_id': uid,
  435. 'http_request_id': http_request_model.current_http_request(),
  436. 'http_session_id': http_session_model.current_http_session(),
  437. }
  438. vals.update(additional_log_values or {})
  439. log = log_model.create(vals)
  440. diff = DictDiffer(
  441. new_values.get(res_id, EMPTY_DICT),
  442. old_values.get(res_id, EMPTY_DICT))
  443. if method is 'create':
  444. self._create_log_line_on_create(log, diff.added(), new_values)
  445. elif method is 'read':
  446. self._create_log_line_on_read(
  447. log, old_values.get(res_id, EMPTY_DICT).keys(), old_values)
  448. elif method is 'write':
  449. self._create_log_line_on_write(
  450. log, diff.changed(), old_values, new_values)
  451. def _get_field(self, model, field_name):
  452. cache = self.pool._auditlog_field_cache
  453. if field_name not in cache.get(model.model, {}):
  454. cache.setdefault(model.model, {})
  455. # - we use 'search()' then 'read()' instead of the 'search_read()'
  456. # to take advantage of the 'classic_write' loading
  457. # - search the field in the current model and those it inherits
  458. field_model = self.env['ir.model.fields']
  459. all_model_ids = [model.id]
  460. all_model_ids.extend(model.inherited_model_ids.ids)
  461. field = field_model.search(
  462. [('model_id', 'in', all_model_ids), ('name', '=', field_name)])
  463. # The field can be a dummy one, like 'in_group_X' on 'res.users'
  464. # As such we can't log it (field_id is required to create a log)
  465. if not field:
  466. cache[model.model][field_name] = False
  467. else:
  468. field_data = field.read(load='_classic_write')[0]
  469. cache[model.model][field_name] = field_data
  470. return cache[model.model][field_name]
  471. def _create_log_line_on_read(
  472. self, log, fields_list, read_values):
  473. """Log field filled on a 'read' operation."""
  474. log_line_model = self.env['auditlog.log.line']
  475. for field_name in fields_list:
  476. if field_name in FIELDS_BLACKLIST:
  477. continue
  478. field = self._get_field(log.model_id, field_name)
  479. # not all fields have an ir.models.field entry (ie. related fields)
  480. if field:
  481. log_vals = self._prepare_log_line_vals_on_read(
  482. log, field, read_values)
  483. log_line_model.create(log_vals)
  484. def _prepare_log_line_vals_on_read(self, log, field, read_values):
  485. """Prepare the dictionary of values used to create a log line on a
  486. 'read' operation.
  487. """
  488. vals = {
  489. 'field_id': field['id'],
  490. 'log_id': log.id,
  491. 'old_value': read_values[log.res_id][field['name']],
  492. 'old_value_text': read_values[log.res_id][field['name']],
  493. 'new_value': False,
  494. 'new_value_text': False,
  495. }
  496. if field['relation'] and '2many' in field['ttype']:
  497. old_value_text = self.env[field['relation']].browse(
  498. vals['old_value']).name_get()
  499. vals['old_value_text'] = old_value_text
  500. return vals
  501. def _create_log_line_on_write(
  502. self, log, fields_list, old_values, new_values):
  503. """Log field updated on a 'write' operation."""
  504. log_line_model = self.env['auditlog.log.line']
  505. for field_name in fields_list:
  506. if field_name in FIELDS_BLACKLIST:
  507. continue
  508. field = self._get_field(log.model_id, field_name)
  509. # not all fields have an ir.models.field entry (ie. related fields)
  510. if field:
  511. log_vals = self._prepare_log_line_vals_on_write(
  512. log, field, old_values, new_values)
  513. log_line_model.create(log_vals)
  514. def _prepare_log_line_vals_on_write(
  515. self, log, field, old_values, new_values):
  516. """Prepare the dictionary of values used to create a log line on a
  517. 'write' operation.
  518. """
  519. vals = {
  520. 'field_id': field['id'],
  521. 'log_id': log.id,
  522. 'old_value': old_values[log.res_id][field['name']],
  523. 'old_value_text': old_values[log.res_id][field['name']],
  524. 'new_value': new_values[log.res_id][field['name']],
  525. 'new_value_text': new_values[log.res_id][field['name']],
  526. }
  527. # for *2many fields, log the name_get
  528. if log.log_type == 'full' and field['relation'] \
  529. and '2many' in field['ttype']:
  530. # Filter IDs to prevent a 'name_get()' call on deleted resources
  531. existing_ids = self.env[field['relation']]._search(
  532. [('id', 'in', vals['old_value'])])
  533. old_value_text = []
  534. if existing_ids:
  535. existing_values = self.env[field['relation']].browse(
  536. existing_ids).name_get()
  537. old_value_text.extend(existing_values)
  538. # Deleted resources will have a 'DELETED' text representation
  539. deleted_ids = set(vals['old_value']) - set(existing_ids)
  540. for deleted_id in deleted_ids:
  541. old_value_text.append((deleted_id, 'DELETED'))
  542. vals['old_value_text'] = old_value_text
  543. new_value_text = self.env[field['relation']].browse(
  544. vals['new_value']).name_get()
  545. vals['new_value_text'] = new_value_text
  546. return vals
  547. def _create_log_line_on_create(
  548. self, log, fields_list, new_values):
  549. """Log field filled on a 'create' operation."""
  550. log_line_model = self.env['auditlog.log.line']
  551. for field_name in fields_list:
  552. if field_name in FIELDS_BLACKLIST:
  553. continue
  554. field = self._get_field(log.model_id, field_name)
  555. # not all fields have an ir.models.field entry (ie. related fields)
  556. if field:
  557. log_vals = self._prepare_log_line_vals_on_create(
  558. log, field, new_values)
  559. log_line_model.create(log_vals)
  560. def _prepare_log_line_vals_on_create(self, log, field, new_values):
  561. """Prepare the dictionary of values used to create a log line on a
  562. 'create' operation.
  563. """
  564. vals = {
  565. 'field_id': field['id'],
  566. 'log_id': log.id,
  567. 'old_value': False,
  568. 'old_value_text': False,
  569. 'new_value': new_values[log.res_id][field['name']],
  570. 'new_value_text': new_values[log.res_id][field['name']],
  571. }
  572. if log.log_type == 'full' and field['relation'] \
  573. and '2many' in field['ttype']:
  574. new_value_text = self.env[field['relation']].browse(
  575. vals['new_value']).name_get()
  576. vals['new_value_text'] = new_value_text
  577. return vals
  578. @api.multi
  579. def subscribe(self):
  580. """Subscribe Rule for auditing changes on model and apply shortcut
  581. to view logs on that model.
  582. """
  583. act_window_model = self.env['ir.actions.act_window']
  584. model_data_model = self.env['ir.model.data']
  585. for rule in self:
  586. # Create a shortcut to view logs
  587. domain = "[('model_id', '=', %s), ('res_id', '=', active_id)]" % (
  588. rule.model_id.id)
  589. vals = {
  590. 'name': _(u"View logs"),
  591. 'res_model': 'auditlog.log',
  592. 'src_model': rule.model_id.model,
  593. 'domain': domain,
  594. }
  595. act_window = act_window_model.sudo().create(vals)
  596. rule.write({'state': 'subscribed', 'action_id': act_window.id})
  597. keyword = 'client_action_relate'
  598. value = 'ir.actions.act_window,%s' % act_window.id
  599. model_data_model.sudo().ir_set(
  600. 'action', keyword, 'View_log_' + rule.model_id.model,
  601. [rule.model_id.model], value, replace=True,
  602. isobject=True, xml_id=False)
  603. return True
  604. @api.multi
  605. def unsubscribe(self):
  606. """Unsubscribe Auditing Rule on model."""
  607. act_window_model = self.env['ir.actions.act_window']
  608. ir_values_model = self.env['ir.values']
  609. # Revert patched methods
  610. self._revert_methods()
  611. for rule in self:
  612. # Remove the shortcut to view logs
  613. act_window = act_window_model.search(
  614. [('name', '=', 'View Log'),
  615. ('res_model', '=', 'auditlog.log'),
  616. ('src_model', '=', rule.model_id.model)])
  617. if act_window:
  618. value = 'ir.actions.act_window,%s' % act_window.id
  619. act_window.unlink()
  620. ir_value = ir_values_model.search(
  621. [('model', '=', rule.model_id.model),
  622. ('value', '=', value)])
  623. if ir_value:
  624. ir_value.unlink()
  625. self.write({'state': 'draft'})
  626. return True