1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
22 from osv import fields, osv
23 from osv.osv import osv_pool
24 from tools.translate import _
30 class audittrail_rule(osv.osv):
34 _name = 'audittrail.rule'
35 _description = "Audittrail Rule"
37 "name": fields.char("Rule Name", size=32, required=True),
38 "object_id": fields.many2one('ir.model', 'Object', required=True),
39 "user_id": fields.many2many('res.users', 'audittail_rules_users',
40 'user_id', 'rule_id', 'Users', help="if User is not added then it will applicable for all users"),
41 "log_read": fields.boolean("Log Reads"),
42 "log_write": fields.boolean("Log Writes"),
43 "log_unlink": fields.boolean("Log Deletes"),
44 "log_create": fields.boolean("Log Creates"),
45 "log_action": fields.boolean("Log Action"),
46 "log_workflow": fields.boolean("Log Workflow"),
47 "state": fields.selection((("draft", "Draft"),
48 ("subscribed", "Subscribed")),
49 "State", required=True),
50 "action_id": fields.many2one('ir.actions.act_window', "Action ID"),
55 'state': lambda *a: 'draft',
56 'log_create': lambda *a: 1,
57 'log_unlink': lambda *a: 1,
58 'log_write': lambda *a: 1,
62 ('model_uniq', 'unique (object_id)', """There is a rule defined on this object\n You can not define other on the same!""")
66 def subscribe(self, cr, uid, ids, *args):
68 Subscribe Rule for auditing changes on object and apply shortcut for logs on that object.
69 @param cr: the current row, from the database cursor,
70 @param uid: the current user’s ID for security checks,
71 @param ids: List of Auddittrail Rule’s IDs.
74 obj_action = self.pool.get('ir.actions.act_window')
75 obj_model = self.pool.get('ir.model.data')
77 for thisrule in self.browse(cr, uid, ids):
78 obj = self.pool.get(thisrule.object_id.model)
81 _('WARNING: audittrail is not part of the pool'),
82 _('Change audittrail depends -- Setting rule as DRAFT'))
83 self.write(cr, uid, [thisrule.id], {"state": "draft"})
86 "res_model": 'audittrail.log',
87 "src_model": thisrule.object_id.model,
88 "domain": "[('object_id','=', " + str(thisrule.object_id.id) + "), ('res_id', '=', active_id)]"
91 action_id = obj_action.create(cr, uid, val)
92 self.write(cr, uid, [thisrule.id], {"state": "subscribed", "action_id": action_id})
93 keyword = 'client_action_relate'
94 value = 'ir.actions.act_window,' + str(action_id)
95 res = obj_model.ir_set(cr, uid, 'action', keyword, 'View_log_' + thisrule.object_id.model, [thisrule.object_id.model], value, replace=True, isobject=True, xml_id=False)
99 def unsubscribe(self, cr, uid, ids, *args):
101 Unsubscribe Auditing Rule on object
102 @param cr: the current row, from the database cursor,
103 @param uid: the current user’s ID for security checks,
104 @param ids: List of Auddittrail Rule’s IDs.
107 obj_action = self.pool.get('ir.actions.act_window')
108 val_obj = self.pool.get('ir.values')
110 for thisrule in self.browse(cr, uid, ids):
111 if thisrule.id in self.__functions:
112 for function in self.__functions[thisrule.id]:
113 setattr(function[0], function[1], function[2])
114 w_id = obj_action.search(cr, uid, [('name', '=', 'View Log'), ('res_model', '=', 'audittrail.log'), ('src_model', '=', thisrule.object_id.model)])
115 obj_action.unlink(cr, uid, w_id)
116 value = "ir.actions.act_window" + ',' + str(w_id[0])
117 val_id = val_obj.search(cr, uid, [('model', '=', thisrule.object_id.model), ('value', '=', value)])
119 res = ir.ir_del(cr, uid, val_id[0])
120 self.write(cr, uid, [thisrule.id], {"state": "draft"})
127 class audittrail_log(osv.osv):
131 _name = 'audittrail.log'
132 _description = "Audittrail Log"
134 def _name_get_resname(self, cr, uid, ids, *args):
136 for resname in self.browse(cr, uid, ids,[]):
137 model_object = resname.object_id
138 res_id = resname.res_id
139 if model_object and res_id:
140 model_pool = self.pool.get(model_object.model)
141 res = model_pool.read(cr, uid, res_id, ['name'])
142 data[resname.id] = res['name']
144 data[resname.id] = False
148 "name": fields.char("Resource Name",size=64),
149 "object_id": fields.many2one('ir.model', 'Object'),
150 "user_id": fields.many2one('res.users', 'User'),
151 "method": fields.char("Method", size=64),
152 "timestamp": fields.datetime("Date"),
153 "res_id": fields.integer('Resource Id'),
154 "line_ids": fields.one2many('audittrail.log.line', 'log_id', 'Log lines'),
158 "timestamp": lambda *a: time.strftime("%Y-%m-%d %H:%M:%S")
160 _order = "timestamp desc"
165 class audittrail_log_line(osv.osv):
169 _name = 'audittrail.log.line'
170 _description = "Log Line"
172 'field_id': fields.many2one('ir.model.fields', 'Fields', required=True),
173 'log_id': fields.many2one('audittrail.log', 'Log'),
174 'log': fields.integer("Log ID"),
175 'old_value': fields.text("Old Value"),
176 'new_value': fields.text("New Value"),
177 'old_value_text': fields.text('Old value Text'),
178 'new_value_text': fields.text('New value Text'),
179 'field_description': fields.char('Field Description', size=64),
182 audittrail_log_line()
185 class audittrail_objects_proxy(osv_pool):
186 """ Uses Object proxy for auditing changes on object of subscribed Rules"""
188 def get_value_text(self, cr, uid, field_name, values, model, context=None):
190 Gets textual values for the fields
191 e.g.: For field of type many2one it gives its name value instead of id
193 @param cr: the current row, from the database cursor,
194 @param uid: the current user’s ID for security checks,
195 @param field_name: List of fields for text values
196 @param values: Values for field to be converted into textual values
197 @return: values: List of textual values for given fields
201 pool = pooler.get_pool(cr.dbname)
202 field_pool = pool.get('ir.model.fields')
203 model_pool = pool.get('ir.model')
204 obj_pool = pool.get(model.model)
205 if obj_pool._inherits:
206 inherits_ids = model_pool.search(cr, uid, [('model', '=', obj_pool._inherits.keys()[0])])
207 field_ids = field_pool.search(cr, uid, [('name', '=', field_name), ('model_id', 'in', (model.id, inherits_ids[0]))])
209 field_ids = field_pool.search(cr, uid, [('name', '=', field_name), ('model_id', '=', model.id)])
210 field_id = field_ids and field_ids[0] or False
211 assert field_id, _("'%s' field is not exits in '%s' model" %(field_name, model.model))
213 field = field_pool.read(cr, uid, field_id)
214 relation_model = field['relation']
215 relation_model_pool = relation_model and pool.get(relation_model) or False
217 if field['ttype'] == 'many2one':
220 if values and type(values) == tuple:
221 relation_id = values[0]
222 if relation_id and relation_model_pool:
223 relation_model_object = relation_model_pool.read(cr, uid, relation_id, [relation_model_pool._rec_name])
224 res = relation_model_object[relation_model_pool._rec_name]
227 elif field['ttype'] in ('many2many','one2many'):
229 for relation_model_object in relation_model_pool.read(cr, uid, values, [relation_model_pool._rec_name]):
230 res.append(relation_model_object[relation_model_pool._rec_name])
235 def create_log_line(self, cr, uid, log_id, model, lines=[]):
237 Creates lines for changed fields with its old and new values
239 @param cr: the current row, from the database cursor,
240 @param uid: the current user’s ID for security checks,
241 @param model: Object who's values are being changed
242 @param lines: List of values for line is to be created
244 pool = pooler.get_pool(cr.dbname)
245 obj_pool = pool.get(model.model)
246 model_pool = pool.get('ir.model')
247 field_pool = pool.get('ir.model.fields')
248 log_line_pool = pool.get('audittrail.log.line')
251 if obj_pool._inherits:
252 inherits_ids = model_pool.search(cr, uid, [('model', '=', obj_pool._inherits.keys()[0])])
253 field_ids = field_pool.search(cr, uid, [('name', '=', line['name']), ('model_id', 'in', (model.id, inherits_ids[0]))])
255 field_ids = field_pool.search(cr, uid, [('name', '=', line['name']), ('model_id', '=', model.id)])
256 field_id = field_ids and field_ids[0] or False
257 assert field_id, _("'%s' field is not exits in '%s' model" %(line['name'], model.model))
259 field = field_pool.read(cr, uid, field_id)
260 old_value = 'old_value' in line and line['old_value'] or ''
261 new_value = 'new_value' in line and line['new_value'] or ''
262 old_value_text = 'old_value_text' in line and line['old_value_text'] or ''
263 new_value_text = 'new_value_text' in line and line['new_value_text'] or ''
265 if old_value_text == new_value_text:
267 if field['ttype'] == 'many2one':
268 if type(old_value) == tuple:
269 old_value = old_value[0]
270 if type(new_value) == tuple:
271 new_value = new_value[0]
274 "field_id": field_id,
275 "old_value": old_value,
276 "new_value": new_value,
277 "old_value_text": old_value_text,
278 "new_value_text": new_value_text,
279 "field_description": field['field_description']
281 line_id = log_line_pool.create(cr, uid, vals)
286 def log_fct(self, db, uid, model, method, fct_src, *args):
288 Logging function: This function is performs logging oprations according to method
289 @param db: the current database
290 @param uid: the current user’s ID for security checks,
291 @param object: Object who's values are being changed
292 @param method: method to log: create, read, write, unlink
293 @param fct_src: execute method of Object proxy
295 @return: Returns result as per method of Object proxy
298 pool = pooler.get_pool(db)
299 cr = pooler.get_db(db).cursor()
300 resource_pool = pool.get(model)
301 log_pool = pool.get('audittrail.log')
302 model_pool = pool.get('ir.model')
304 model_ids = model_pool.search(cr, uid, [('model', '=', model)])
305 model_id = model_ids and model_ids[0] or False
306 assert model_id, _("'%s' Model is not exits..." %(model))
307 model = model_pool.browse(cr, uid, model_id)
309 if method in ('create'):
310 res_id = fct_src(db, uid, model.model, method, *args)
312 resource = resource_pool.read(cr, uid, res_id, args[0].keys())
315 "object_id": model.id,
317 "res_id": resource['id'],
321 log_id = log_pool.create(cr, uid, vals)
323 for field in resource:
326 'new_value': resource[field],
327 'new_value_text': self.get_value_text(cr, uid, field, resource[field], model)
330 self.create_log_line(cr, uid, log_id, model, lines)
336 elif method in ('read'):
339 res = fct_src(db, uid, model.model, method, *args)
340 if type(res) == list:
342 old_values[v['id']] = v
344 old_values[res['id']] = res
345 for res_id in old_values:
348 "object_id": model.id,
353 log_id = log_pool.create(cr, uid, vals)
355 for field in old_values[res_id]:
358 'old_value': old_values[res_id][field],
359 'old_value_text': self.get_value_text(cr, uid, field, old_values[res_id][field], model)
363 self.create_log_line(cr, uid, log_id, model, lines)
368 elif method in ('unlink'):
371 for res_id in res_ids:
372 old_values[res_id] = resource_pool.read(cr, uid, res_id)
374 for res_id in res_ids:
377 "object_id": model.id,
382 log_id = log_pool.create(cr, uid, vals)
384 for field in old_values[res_id]:
389 'old_value': old_values[res_id][field],
390 'old_value_text': self.get_value_text(cr, uid, field, old_values[res_id][field], model)
394 self.create_log_line(cr, uid, log_id, model, lines)
395 res = fct_src(db, uid, model.model, method, *args)
403 if len(args)>1 and type(args[1]) == dict:
404 fields = args[1].keys()
405 if type(res_ids) in (long, int):
408 for resource in resource_pool.read(cr, uid, res_ids):
409 resource_id = resource['id']
414 for field in resource.keys():
415 old_value[field] = resource[field]
416 old_values_text[field] = self.get_value_text(cr, uid, field, resource[field], model)
417 old_values[resource_id] = {'text':old_values_text, 'value': old_value}
419 res = fct_src(db, uid, model.model, method, *args)
423 for resource in resource_pool.read(cr, uid, res_ids):
424 resource_id = resource['id']
429 "object_id": model.id,
431 "res_id": resource_id,
435 log_id = log_pool.create(cr, uid, vals)
437 for field in resource.keys():
440 'new_value': resource[field],
441 'old_value': old_values[resource_id]['value'][field],
442 'new_value_text': self.get_value_text(cr, uid, field, resource[field], model),
443 'old_value_text': old_values[resource_id]['text'][field]
447 self.create_log_line(cr, uid, log_id, model, lines)
455 def execute(self, db, uid, model, method, *args, **kw):
457 Overrides Object Proxy execute method
458 @param db: the current database
459 @param uid: the current user’s ID for security checks,
460 @param object: Object who's values are being changed
461 @param method: get any method and create log
463 @return: Returns result as per method of Object proxy
465 pool = pooler.get_pool(db)
466 model_pool = pool.get('ir.model')
467 rule_pool = pool.get('audittrail.rule')
468 cr = pooler.get_db(db).cursor()
471 fct_src = super(audittrail_objects_proxy, self).execute
473 def my_fct(db, uid, model, method, *args):
475 model_ids = model_pool.search(cr, uid, [('model', '=', model)])
476 model_id = model_ids and model_ids[0] or False
478 for model_name in pool.obj_list():
479 if model_name == 'audittrail.rule':
482 return fct_src(db, uid, model, method, *args)
484 return fct_src(db, uid, model, method, *args)
486 rule_ids = rule_pool.search(cr, uid, [('object_id', '=', model_id), ('state', '=', 'subscribed')])
488 return fct_src(db, uid, model, method, *args)
490 for thisrule in rule_pool.browse(cr, uid, rule_ids):
491 for user in thisrule.user_id:
492 logged_uids.append(user.id)
493 if not logged_uids or uid in logged_uids:
494 if method in ('read', 'write', 'create', 'unlink'):
495 if getattr(thisrule, 'log_' + method):
496 return self.log_fct(db, uid, model, method, fct_src, *args)
498 elif method not in ('default_get','read','fields_view_get','fields_get','search','search_count','name_search','name_get','get','request_get', 'get_sc', 'unlink', 'write', 'create'):
499 if thisrule.log_action:
500 return self.log_fct(db, uid, model, method, fct_src, *args)
502 return fct_src(db, uid, model, method, *args)
503 res = my_fct(db, uid, model, method, *args)
508 def exec_workflow(self, db, uid, model, method, *args, **argv):
509 pool = pooler.get_pool(db)
510 cr = pooler.get_db(db).cursor()
513 fct_src = super(audittrail_objects_proxy, self).exec_workflow
516 model_pool = pool.get('ir.model')
517 rule_pool = pool.get('audittrail.rule')
518 model_ids = model_pool.search(cr, uid, [('model', '=', model)])
519 for obj_name in pool.obj_list():
520 if obj_name == 'audittrail.rule':
524 return super(audittrail_objects_proxy, self).exec_workflow(db, uid, model, method, *args, **argv)
527 return super(audittrail_objects_proxy, self).exec_workflow(db, uid, model, method, *args, **argv)
529 rule_ids = rule_pool.search(cr, uid, [('object_id', 'in', model_ids), ('state', '=', 'subscribed')])
532 return super(audittrail_objects_proxy, self).exec_workflow(db, uid, model, method, *args, **argv)
534 for thisrule in rule_pool.browse(cr, uid, rule_ids):
535 for user in thisrule.user_id:
536 logged_uids.append(user.id)
537 if not logged_uids or uid in logged_uids:
538 if thisrule.log_workflow:
540 return self.log_fct(db, uid, model, method, fct_src, *args)
542 return super(audittrail_objects_proxy, self).exec_workflow(db, uid, model, method, *args, **argv)
547 audittrail_objects_proxy()
549 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: