[FIX]:remove log_id which does not have any lines to log
[odoo/odoo.git] / addons / audittrail / audittrail.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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
22 from osv import fields, osv
23 from osv.osv import object_proxy
24 from tools.translate import _
25 import pooler
26 import time
27 import tools
28
29 class audittrail_rule(osv.osv):
30     """
31     For Auddittrail Rule
32     """
33     _name = 'audittrail.rule'
34     _description = "Audittrail Rule"
35     _columns = {
36         "name": fields.char("Rule Name", size=32, required=True),
37         "object_id": fields.many2one('ir.model', 'Object', required=True, help="Select object for which you want to generate log."),
38         "user_id": fields.many2many('res.users', 'audittail_rules_users',
39                                             'user_id', 'rule_id', 'Users', help="if  User is not added then it will applicable for all users"),
40         "log_read": fields.boolean("Log Reads", help="Select this if you want to keep track of read/open on any record of the object of this rule"),
41         "log_write": fields.boolean("Log Writes", help="Select this if you want to keep track of modification on any record of the object of this rule"),
42         "log_unlink": fields.boolean("Log Deletes", help="Select this if you want to keep track of deletion on any record of the object of this rule"),
43         "log_create": fields.boolean("Log Creates",help="Select this if you want to keep track of creation on any record of the object of this rule"),
44         "log_action": fields.boolean("Log Action",help="Select this if you want to keep track of actions on the object of this rule"),
45         "log_workflow": fields.boolean("Log Workflow",help="Select this if you want to keep track of workflow on any record of the object of this rule"),
46         "state": fields.selection((("draft", "Draft"), ("subscribed", "Subscribed")), "State", required=True),
47         "action_id": fields.many2one('ir.actions.act_window', "Action ID"),
48     }
49     _defaults = {
50         'state': lambda *a: 'draft',
51         'log_create': lambda *a: 1,
52         'log_unlink': lambda *a: 1,
53         'log_write': lambda *a: 1,
54     }
55     _sql_constraints = [
56         ('model_uniq', 'unique (object_id)', """There is already a rule defined on this object\n You cannot define another: please edit the existing one.""")
57     ]
58     __functions = {}
59
60     def subscribe(self, cr, uid, ids, *args):
61         """
62         Subscribe Rule for auditing changes on object and apply shortcut for logs on that object.
63         @param cr: the current row, from the database cursor,
64         @param uid: the current user’s ID for security checks,
65         @param ids: List of Auddittrail Rule’s IDs.
66         @return: True
67         """
68         obj_action = self.pool.get('ir.actions.act_window')
69         obj_model = self.pool.get('ir.model.data')
70         #start Loop
71         for thisrule in self.browse(cr, uid, ids):
72             obj = self.pool.get(thisrule.object_id.model)
73             if not obj:
74                 raise osv.except_osv(
75                         _('WARNING: audittrail is not part of the pool'),
76                         _('Change audittrail depends -- Setting rule as DRAFT'))
77                 self.write(cr, uid, [thisrule.id], {"state": "draft"})
78             val = {
79                  "name": 'View Log',
80                  "res_model": 'audittrail.log',
81                  "src_model": thisrule.object_id.model,
82                  "domain": "[('object_id','=', " + str(thisrule.object_id.id) + "), ('res_id', '=', active_id)]"
83
84             }
85             action_id = obj_action.create(cr, uid, val)
86             self.write(cr, uid, [thisrule.id], {"state": "subscribed", "action_id": action_id})
87             keyword = 'client_action_relate'
88             value = 'ir.actions.act_window,' + str(action_id)
89             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)
90             #End Loop
91         return True
92
93     def unsubscribe(self, cr, uid, ids, *args):
94         """
95         Unsubscribe Auditing Rule on object
96         @param cr: the current row, from the database cursor,
97         @param uid: the current user’s ID for security checks,
98         @param ids: List of Auddittrail Rule’s IDs.
99         @return: True
100         """
101         obj_action = self.pool.get('ir.actions.act_window')
102         ir_values_obj = self.pool.get('ir.values')
103         value=''
104         #start Loop
105         for thisrule in self.browse(cr, uid, ids):
106             if thisrule.id in self.__functions:
107                 for function in self.__functions[thisrule.id]:
108                     setattr(function[0], function[1], function[2])
109             w_id = obj_action.search(cr, uid, [('name', '=', 'View Log'), ('res_model', '=', 'audittrail.log'), ('src_model', '=', thisrule.object_id.model)])
110             if w_id:
111                 obj_action.unlink(cr, uid, w_id)
112                 value = "ir.actions.act_window" + ',' + str(w_id[0])
113             val_id = ir_values_obj.search(cr, uid, [('model', '=', thisrule.object_id.model), ('value', '=', value)])
114             if val_id:
115                 ir_values_obj = pooler.get_pool(cr.dbname).get('ir.values')
116                 res = ir_values_obj.unlink(cr, uid, [val_id[0]])
117             self.write(cr, uid, [thisrule.id], {"state": "draft"})
118         #End Loop
119         return True
120
121 class audittrail_log(osv.osv):
122     """
123     For Audittrail Log
124     """
125     _name = 'audittrail.log'
126     _description = "Audittrail Log"
127
128     def _name_get_resname(self, cr, uid, ids, *args):
129         data = {}
130         for resname in self.browse(cr, uid, ids,[]):
131             model_object = resname.object_id
132             res_id = resname.res_id
133             if model_object and res_id:
134                 model_pool = self.pool.get(model_object.model)
135                 res = model_pool.read(cr, uid, res_id, ['name'])
136                 data[resname.id] = res['name']
137             else:
138                  data[resname.id] = False
139         return data
140
141     _columns = {
142         "name": fields.char("Resource Name",size=64),
143         "object_id": fields.many2one('ir.model', 'Object'),
144         "user_id": fields.many2one('res.users', 'User'),
145         "method": fields.char("Method", size=64),
146         "timestamp": fields.datetime("Date"),
147         "res_id": fields.integer('Resource Id'),
148         "line_ids": fields.one2many('audittrail.log.line', 'log_id', 'Log lines'),
149     }
150
151     _defaults = {
152         "timestamp": lambda *a: time.strftime("%Y-%m-%d %H:%M:%S")
153     }
154     _order = "timestamp desc"
155
156 class audittrail_log_line(osv.osv):
157     """
158     Audittrail Log Line.
159     """
160     _name = 'audittrail.log.line'
161     _description = "Log Line"
162     _columns = {
163           'field_id': fields.many2one('ir.model.fields', 'Fields', required=True),
164           'log_id': fields.many2one('audittrail.log', 'Log'),
165           'log': fields.integer("Log ID"),
166           'old_value': fields.text("Old Value"),
167           'new_value': fields.text("New Value"),
168           'old_value_text': fields.text('Old value Text'),
169           'new_value_text': fields.text('New value Text'),
170           'field_description': fields.char('Field Description', size=64),
171         }
172
173 class audittrail_objects_proxy(object_proxy):
174     """ Uses Object proxy for auditing changes on object of subscribed Rules"""
175
176     def get_value_text(self, cr, uid, pool, resource_pool, method, field, value, recursive=True):
177         """
178         Gets textual values for the fields. 
179             If the field is a many2one, it returns the name. 
180             If it's a one2many or a many2many, it returns a list of name. 
181             In other cases, it just returns the value.
182         """
183         field_obj = (resource_pool._all_columns.get(field)).column
184         if field_obj._type in ('one2many','many2many'):
185             if recursive:
186                 self.log_fct(cr, uid, field_obj._obj, method, None, value, 'child_relation_log')
187             data = pool.get(field_obj._obj).name_get(cr, uid, value)
188             #return the modifications on *2many fields as a list of names
189             return map(lambda x:x[1], data)
190         elif field_obj._type == 'many2one':
191             #return the modifications on a many2one field as the name of the value
192             return value and value[1] or value
193         return value
194
195     def create_log_line(self, cr, uid, log_id, model, lines=[]):
196         """
197         Creates lines for changed fields with its old and new values
198
199         @param cr: the current row, from the database cursor,
200         @param uid: the current user’s ID for security checks,
201         @param model: Object who's values are being changed
202         @param lines: List of values for line is to be created
203         """
204         pool = pooler.get_pool(cr.dbname)
205         obj_pool = pool.get(model.model)
206         model_pool = pool.get('ir.model')
207         field_pool = pool.get('ir.model.fields')
208         log_line_pool = pool.get('audittrail.log.line')
209         line_id = False
210         for line in lines:
211             field_obj = obj_pool._all_columns.get(line['name'])
212             assert field_obj, _("'%s' field does not exist in '%s' model" %(line['name'], model.model))
213             field_obj = field_obj.column
214             old_value = line.get('old_value', '')
215             new_value = line.get('new_value', '')
216             old_value_text = line.get('old_value_text', '')
217             new_value_text = line.get('new_value_text', '')
218             search_models = [model.id]
219             if obj_pool._inherits:
220                 search_models += model_pool.search(cr, uid, [('model', 'in', obj_pool._inherits.keys())])
221             field_id = field_pool.search(cr, uid, [('name', '=', line['name']), ('model_id', 'in', search_models)])
222             if old_value_text == new_value_text:
223                 continue
224             if field_obj._type == 'many2one':
225                 old_value = old_value and old_value[0] or old_value
226                 new_value = new_value and new_value[0] or new_value
227             vals = {
228                     "log_id": log_id,
229                     "field_id": field_id and field_id[0] or False,
230                     "old_value": old_value,
231                     "new_value": new_value,
232                     "old_value_text": old_value_text,
233                     "new_value_text": new_value_text,
234                     "field_description": field_obj.string
235                     }
236             line_id = log_line_pool.create(cr, uid, vals)
237         if not line_id:  
238             pool.get('audittrail.log').unlink(cr, uid, log_id)
239         return True
240    
241     def start_log_process(self, cr, user_id, model, method, resource_data, pool, resource_pool):
242         key1 = '%s_value'%(method == 'create' and 'new' or 'old')
243         key2 = '%s_value_text'%(method == 'create' and 'new' or 'old')
244         uid = 1
245         vals = { 'method': method, 'object_id': model.id,'user_id': user_id}
246         for resource, fields in resource_data.iteritems():
247             vals.update({'res_id': resource})
248             log_id = pool.get('audittrail.log').create(cr, uid, vals)
249             lines = []
250             for field_key, value in fields.iteritems():
251                 if field_key in ('__last_update', 'id'):continue
252                 ret_val = self.get_value_text(cr, uid, pool, resource_pool, method, field_key, value, method != 'read')
253                 line = {
254                       'name': field_key,
255                       key1: value,
256                       key2: ret_val and ret_val or value
257                       }
258                 lines.append(line)
259             self.create_log_line(cr, uid, log_id, model, lines)
260         return True
261     
262     def log_fct(self, cr, uid, model, method, fct_src, *args):
263         """
264         Logging function: This function is performing the logging operation
265         :param model: Object which values are being changed
266         :param method: method to log: create, read, write, unlink
267         :param fct_src: execute method of Object proxy
268
269         :return: Returns result as per method of Object proxy
270         """
271         uid_orig = uid
272         uid = 1
273         pool = pooler.get_pool(cr.dbname)
274         resource_pool = pool.get(model)
275         model_pool = pool.get('ir.model')
276         log_pool = pool.get('audittrail.log')
277         model_ids = model_pool.search(cr, 1, [('model', '=', model)])
278         model_id = model_ids and model_ids[0] or False
279         assert model_id, _("'%s' Model does not exist..." %(model))
280         model = model_pool.browse(cr, uid, model_id)
281         relational_table_log = True if (args and args[-1] == 'child_relation_log') else False
282
283         if method == 'create':
284             resource_data = {}
285             fields_to_read = []
286             if relational_table_log:
287                 res_id = args[0]
288             else:
289                 res_id = fct_src(cr, uid_orig, model.model, method, *args)
290                 fields_to_read = args[0].keys()
291             if res_id:
292                 resource = resource_pool.read(cr, uid, res_id, fields_to_read)
293                 if not isinstance(resource,list):
294                     resource = [resource]
295                 map(lambda x: resource_data.setdefault(x['id'], x), resource)
296                 self.start_log_process(cr, uid_orig, model, method, resource_data, pool, resource_pool)
297             return res_id
298
299         elif method in('read', 'unlink'):
300             res_ids = args[0]
301             old_values = {}
302             if method == 'read':
303                 res = fct_src(cr, uid_orig, model.model, method, *args)
304                 map(lambda x: old_values.setdefault(x['id'], x), res)
305             else:
306                 res = resource_pool.read(cr, uid, res_ids)
307                 map(lambda x:old_values.setdefault(x['id'], x), res)
308             self.start_log_process(cr, uid_orig, model, method, old_values, pool, resource_pool)
309             if not relational_table_log and method == 'unlink':
310                 res = fct_src(cr, uid_orig, model.model, method, *args)
311             return res
312         else:
313             res_ids = []
314             res = True
315             if args:
316                 res_ids = args[0]
317                 old_values = {}
318                 fields = []
319                 if len(args) > 1 and isinstance(args[1], dict):
320                     fields = args[1].keys()
321                 if isinstance(res_ids, (long, int)):
322                     res_ids = [res_ids]
323             if res_ids:
324                 x2m_old_values = {}
325                 old_values = {}
326                 def inline_process_old_data(res_ids, model, model_id=False):
327                     resource_pool = pool.get(model)
328                     resource_data = resource_pool.read(cr, uid, res_ids)
329                     _old_values = {}
330                     for resource in resource_data:
331                         _old_values_text = {}
332                         _old_value = {}
333                         resource_id = resource['id']
334                         for field in resource.keys():
335                             if field in ('__last_update', 'id'):continue
336                             field_obj = (resource_pool._all_columns.get(field)).column
337                             if field_obj._type in ('one2many','many2many'):
338                                 if self.check_rules(cr, uid, field_obj._obj, method):
339                                     x2m_model_ids = model_pool.search(cr, 1, [('model', '=', field_obj._obj)])
340                                     x2m_model_id = x2m_model_ids and x2m_model_ids[0] or False
341                                     assert x2m_model_id, _("'%s' Model does not exist..." %(field_obj._obj))
342                                     x2m_model = model_pool.browse(cr, uid, x2m_model_id)
343                                     x2m_old_values.update(inline_process_old_data(resource[field], field_obj._obj, x2m_model))
344                             ret_val = self.get_value_text(cr, uid, pool, resource_pool, method, field, resource[field], False)
345                             _old_value[field] = resource[field]
346                             _old_values_text[field] = ret_val and ret_val or resource[field]
347                         _old_values[resource_id] = {'text':_old_values_text, 'value': _old_value}
348                         if model_id:
349                             _old_values[resource_id].update({'model_id':model_id})
350                     return _old_values
351                 old_values.update(inline_process_old_data(res_ids, model.model))
352             res = fct_src(cr, uid_orig, model.model, method, *args)
353             if res_ids:
354                 def inline_process_new_data(res_ids, model, dict_to_use={}):
355                     resource_pool = pool.get(model.model)
356                     resource_data = resource_pool.read(cr, uid, res_ids)
357                     vals = {'method': method,'object_id': model.id,'user_id': uid_orig }
358                     for resource in resource_data:
359                         resource_id = resource['id']
360                         vals.update({'res_id': resource_id})
361                         log_id = log_pool.create(cr, uid, vals)
362                         lines = []
363                         for field in resource.keys():
364                             if field in ('__last_update', 'id'):continue
365                             field_obj = (resource_pool._all_columns.get(field)).column
366                             if field_obj._type in ('one2many','many2many'):
367                                 if self.check_rules(cr, uid, field_obj._obj, method):
368                                     x2m_model_ids = model_pool.search(cr, 1, [('model', '=', field_obj._obj)])
369                                     x2m_model_id = x2m_model_ids and x2m_model_ids[0] or False
370                                     assert x2m_model_id, _("'%s' Model does not exist..." %(field_obj._obj))
371                                     x2m_model = model_pool.browse(cr, uid, x2m_model_id)
372                                     inline_process_new_data(resource[field], x2m_model, x2m_old_values)
373                             ret_val = self.get_value_text(cr, uid, pool, resource_pool, method, field, resource[field], False)
374                             line = {
375                                   'name': field,
376                                   'new_value': resource[field],
377                                   'old_value': resource_id in dict_to_use and dict_to_use[resource_id]['value'].get(field),
378                                   'new_value_text': ret_val and ret_val or resource[field],
379                                   'old_value_text': resource_id in dict_to_use and dict_to_use[resource_id]['text'].get(field)
380                                   }
381                             lines.append(line)
382                         self.create_log_line(cr, uid, log_id, model, lines)
383                     return True
384                 inline_process_new_data(res_ids, model, old_values)
385             return res
386         return True
387
388     def check_rules(self, cr, uid, model, method):
389         pool = pooler.get_pool(cr.dbname)
390         # Check if auditrails is installed for that db and then if one rule match
391         if 'audittrail.rule' in pool.models:
392             model_ids = pool.get('ir.model').search(cr, 1, [('model', '=', model)])
393             model_id = model_ids and model_ids[0] or False
394             if model_id:
395                 rule_ids = pool.get('audittrail.rule').search(cr, 1, [('object_id', '=', model_id), ('state', '=', 'subscribed')])
396                 for rule in pool.get('audittrail.rule').read(cr, 1, rule_ids, ['user_id','log_read','log_write','log_create','log_unlink','log_action','log_workflow']):
397                     if len(rule['user_id'])==0 or uid in rule['user_id']:
398                         if rule.get('log_'+method,0):
399                             return True
400                         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'):
401                             if rule['log_action']:
402                                 return True
403
404     def execute_cr(self, cr, uid, model, method, *args, **kw):
405         fct_src = super(audittrail_objects_proxy, self).execute_cr
406         if self.check_rules(cr,uid,model,method):
407             return self.log_fct(cr, uid, model, method, fct_src, *args)
408         return fct_src(cr, uid, model, method, *args)
409
410     def exec_workflow_cr(self, cr, uid, model, method, *args, **argv):
411         fct_src = super(audittrail_objects_proxy, self).exec_workflow_cr
412         if self.check_rules(cr,uid,model,'workflow'):
413             return self.log_fct(cr, uid, model, method, fct_src, *args)
414         return fct_src(cr, uid, model, method, *args)
415
416 audittrail_objects_proxy()
417
418 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
419