x2m_model_id = x2m_model_ids and x2m_model_ids[0] or False
assert x2m_model_id, _("'%s' Model does not exist..." %(field_obj._obj))
x2m_model = pool.get('ir.model').browse(cr, SUPERUSER_ID, x2m_model_id)
- # the resource_ids that need to be checked are the sum of both old and previous values (because we
- # need to log also creation or deletion in those lists).
- x2m_old_values_ids = old_values.get(key, {'value': {}})['value'].get(field_name, [])
- x2m_new_values_ids = new_values.get(key, {'value': {}})['value'].get(field_name, [])
- # We use list(set(...)) to remove duplicates.
- res_ids = list(set(x2m_old_values_ids + x2m_new_values_ids))
+ field_resource_ids = list(set(resource[field]))
if model.model == x2m_model.model:
# we need to remove current resource_id from the many2many to prevent an infinit loop
- if resource_id in res_ids:
- res_ids.remove(resource_id)
- for res_id in res_ids:
- lines.update(self.prepare_audittrail_log_line(cr, SUPERUSER_ID, pool, x2m_model, res_id, method, old_values, new_values, field_list))
- # if the value value is different than the old value: record the change
- if key not in old_values or key not in new_values or old_values[key]['value'][field_name] != new_values[key]['value'][field_name]:
- data = {
- 'name': field_name,
- 'new_value': key in new_values and new_values[key]['value'].get(field_name),
- 'old_value': key in old_values and old_values[key]['value'].get(field_name),
- 'new_value_text': key in new_values and new_values[key]['text'].get(field_name),
- 'old_value_text': key in old_values and old_values[key]['text'].get(field_name)
- }
- lines[key].append(data)
- return lines
+ if resource_id in field_resource_ids:
+ field_resource_ids.remove(resource_id)
+ data.update(get_data(cr, SUPERUSER_ID, pool, field_resource_ids, x2m_model, method))
- def process_data(self, cr, uid, pool, res_ids, model, method, old_values=None, new_values=None, field_list=None):
- """
- This function processes and iterates recursively to log the difference between the old
- data (i.e before the method was executed) and the new data and creates audittrail log
- accordingly.
+ data[(model.id, resource_id)] = {'text':values_text, 'value': values}
+ return data
- :param cr: the current row, from the database cursor,
- :param uid: the current user’s ID,
- :param pool: current db's pooler object.
- :param res_ids: Id's of resource to be logged/compared.
- :param model: model object which values are being changed
- :param method: method to log: create, read, unlink, write, actions, workflow actions
- :param old_values: dict of values read before execution of the method
- :param new_values: dict of values read after execution of the method
- :param field_list: optional argument containing the list of fields to log. Currently only
- used when performing a read, it could be usefull later on if we want to log the write
- on specific fields only.
- :return: True
- """
- if field_list is None:
- field_list = []
- # loop on all the given ids
- for res_id in res_ids:
- # compare old and new values and get audittrail log lines accordingly
- lines = self.prepare_audittrail_log_line(cr, uid, pool, model, res_id, method, old_values, new_values, field_list)
-
- # if at least one modification has been found
- for model_id, resource_id in lines:
- line_model = pool.get('ir.model').browse(cr, SUPERUSER_ID, model_id).model
-
- vals = {
- 'method': method,
- 'object_id': model_id,
- 'user_id': uid,
- 'res_id': resource_id,
- }
- if (model_id, resource_id) not in old_values and method not in ('copy', 'read'):
- # the resource was not existing so we are forcing the method to 'create'
- # (because it could also come with the value 'write' if we are creating
- # new record through a one2many field)
- vals.update({'method': 'create'})
- if (model_id, resource_id) not in new_values and method not in ('copy', 'read'):
- # the resource is not existing anymore so we are forcing the method to 'unlink'
- # (because it could also come with the value 'write' if we are deleting the
- # record through a one2many field)
- name = old_values[(model_id, resource_id)]['value'].get('name',False)
- vals.update({'method': 'unlink'})
- else :
- name = pool[line_model].name_get(cr, uid, [resource_id])[0][1]
- vals.update({'name': name})
- # create the audittrail log in super admin mode, only if a change has been detected
- if lines[(model_id, resource_id)]:
- log_id = pool.get('audittrail.log').create(cr, SUPERUSER_ID, vals)
- model = pool.get('ir.model').browse(cr, uid, model_id)
- self.create_log_line(cr, SUPERUSER_ID, log_id, model, lines[(model_id, resource_id)])
- return True
+def prepare_audittrail_log_line(cr, uid, pool, model, resource_id, method, old_values, new_values, field_list=None):
+ """
+ This function compares the old data (i.e before the method was executed) and the new data
+ (after the method was executed) and returns a structure with all the needed information to
+ log those differences.
+
+ :param cr: the current row, from the database cursor,
+ :param uid: the current user’s ID. This parameter is currently not used as every
+ operation to get data is made as super admin. Though, it could be usefull later.
+ :param pool: current db's pooler object.
+ :param model: model object which values are being changed
+ :param resource_id: ID of record to which values are being changed
+ :param method: method to log: create, read, unlink, write, actions, workflow actions
+ :param old_values: dict of values read before execution of the method
+ :param new_values: dict of values read after execution of the method
+ :param field_list: optional argument containing the list of fields to log. Currently only
+ used when performing a read, it could be usefull later on if we want to log the write
+ on specific fields only.
+
+ :return: dictionary with
+ * keys: tuples build as ID of model object to log and ID of resource to log
+ * values: list of all the changes in field values for this couple (model, resource)
+ return {
+ (model.id, resource_id): []
+ }
+
+ The reason why the structure returned is build as above is because when modifying an existing
+ record, we may have to log a change done in a x2many field of that object
+ """
+ if field_list is None:
+ field_list = []
+ key = (model.id, resource_id)
+ lines = {
+ key: []
+ }
+ # loop on all the fields
+ for field_name, field_definition in pool[model.model]._all_columns.items():
+ if field_name in ('__last_update', 'id'):
+ continue
+ #if the field_list param is given, skip all the fields not in that list
+ if field_list and field_name not in field_list:
+ continue
+ field_obj = field_definition.column
+ if field_obj._type in ('one2many','many2many'):
+ # checking if an audittrail rule apply in super admin mode
+ if check_rules(cr, SUPERUSER_ID, field_obj._obj, method):
+ # checking if the model associated to a *2m field exists, in super admin mode
+ x2m_model_ids = pool.get('ir.model').search(cr, SUPERUSER_ID, [('model', '=', field_obj._obj)])
+ x2m_model_id = x2m_model_ids and x2m_model_ids[0] or False
+ assert x2m_model_id, _("'%s' Model does not exist..." %(field_obj._obj))
+ x2m_model = pool.get('ir.model').browse(cr, SUPERUSER_ID, x2m_model_id)
+ # the resource_ids that need to be checked are the sum of both old and previous values (because we
+ # need to log also creation or deletion in those lists).
+ x2m_old_values_ids = old_values.get(key, {'value': {}})['value'].get(field_name, [])
+ x2m_new_values_ids = new_values.get(key, {'value': {}})['value'].get(field_name, [])
+ # We use list(set(...)) to remove duplicates.
+ res_ids = list(set(x2m_old_values_ids + x2m_new_values_ids))
+ if model.model == x2m_model.model:
+ # we need to remove current resource_id from the many2many to prevent an infinit loop
+ if resource_id in res_ids:
+ res_ids.remove(resource_id)
+ for res_id in res_ids:
+ lines.update(prepare_audittrail_log_line(cr, SUPERUSER_ID, pool, x2m_model, res_id, method, old_values, new_values, field_list))
+ # if the value value is different than the old value: record the change
+ if key not in old_values or key not in new_values or old_values[key]['value'][field_name] != new_values[key]['value'][field_name]:
+ data = {
+ 'name': field_name,
+ 'new_value': key in new_values and new_values[key]['value'].get(field_name),
+ 'old_value': key in old_values and old_values[key]['value'].get(field_name),
+ 'new_value_text': key in new_values and new_values[key]['text'].get(field_name),
+ 'old_value_text': key in old_values and old_values[key]['text'].get(field_name)
+ }
+ lines[key].append(data)
+ return lines
- def check_rules(self, cr, uid, model, method):
- """
- Checks if auditrails is installed for that db and then if one rule match
- @param cr: the current row, from the database cursor,
- @param uid: the current user’s ID,
- @param model: value of _name of the object which values are being changed
- @param method: method to log: create, read, unlink,write,actions,workflow actions
- @return: True or False
- """
- pool = pooler.get_pool(cr.dbname)
- if 'audittrail.rule' in pool.models:
- model_ids = pool.get('ir.model').search(cr, SUPERUSER_ID, [('model', '=', model)])
- model_id = model_ids and model_ids[0] or False
- if model_id:
- rule_ids = pool.get('audittrail.rule').search(cr, SUPERUSER_ID, [('object_id', '=', model_id), ('state', '=', 'subscribed')])
- for rule in pool.get('audittrail.rule').read(cr, SUPERUSER_ID, rule_ids, ['user_id','log_read','log_write','log_create','log_unlink','log_action','log_workflow']):
- if len(rule['user_id']) == 0 or uid in rule['user_id']:
- if rule.get('log_'+method,0):
+def process_data(cr, uid, pool, res_ids, model, method, old_values=None, new_values=None, field_list=None):
+ """
+ This function processes and iterates recursively to log the difference between the old
+ data (i.e before the method was executed) and the new data and creates audittrail log
+ accordingly.
+
+ :param cr: the current row, from the database cursor,
+ :param uid: the current user’s ID,
+ :param pool: current db's pooler object.
+ :param res_ids: Id's of resource to be logged/compared.
+ :param model: model object which values are being changed
+ :param method: method to log: create, read, unlink, write, actions, workflow actions
+ :param old_values: dict of values read before execution of the method
+ :param new_values: dict of values read after execution of the method
+ :param field_list: optional argument containing the list of fields to log. Currently only
+ used when performing a read, it could be usefull later on if we want to log the write
+ on specific fields only.
+ :return: True
+ """
+ if field_list is None:
+ field_list = []
+ # loop on all the given ids
+ for res_id in res_ids:
+ # compare old and new values and get audittrail log lines accordingly
+ lines = prepare_audittrail_log_line(cr, uid, pool, model, res_id, method, old_values, new_values, field_list)
+
+ # if at least one modification has been found
+ for model_id, resource_id in lines:
+ line_model = pool.get('ir.model').browse(cr, SUPERUSER_ID, model_id).model
- name = pool.get(line_model).name_get(cr, uid, [resource_id])[0][1]
+
+ vals = {
+ 'method': method,
+ 'object_id': model_id,
+ 'user_id': uid,
+ 'res_id': resource_id,
- 'name': name,
+ }
+ if (model_id, resource_id) not in old_values and method not in ('copy', 'read'):
+ # the resource was not existing so we are forcing the method to 'create'
+ # (because it could also come with the value 'write' if we are creating
+ # new record through a one2many field)
+ vals.update({'method': 'create'})
+ if (model_id, resource_id) not in new_values and method not in ('copy', 'read'):
+ # the resource is not existing anymore so we are forcing the method to 'unlink'
+ # (because it could also come with the value 'write' if we are deleting the
+ # record through a one2many field)
++ name = old_values[(model_id, resource_id)]['value'].get('name',False)
+ vals.update({'method': 'unlink'})
++ else :
++ name = pool[line_model].name_get(cr, uid, [resource_id])[0][1]
++ vals.update({'name': name})
+ # create the audittrail log in super admin mode, only if a change has been detected
+ if lines[(model_id, resource_id)]:
+ log_id = pool.get('audittrail.log').create(cr, SUPERUSER_ID, vals)
+ model = pool.get('ir.model').browse(cr, uid, model_id)
+ create_log_line(cr, SUPERUSER_ID, log_id, model, lines[(model_id, resource_id)])
+ return True
+
+def check_rules(cr, uid, model, method):
+ """
+ Checks if auditrails is installed for that db and then if one rule match
+ @param cr: the current row, from the database cursor,
+ @param uid: the current user’s ID,
+ @param model: value of _name of the object which values are being changed
+ @param method: method to log: create, read, unlink,write,actions,workflow actions
+ @return: True or False
+ """
+ pool = openerp.registry(cr.dbname)
+ if 'audittrail.rule' in pool.models:
+ model_ids = pool.get('ir.model').search(cr, SUPERUSER_ID, [('model', '=', model)])
+ model_id = model_ids and model_ids[0] or False
+ if model_id:
+ rule_ids = pool.get('audittrail.rule').search(cr, SUPERUSER_ID, [('object_id', '=', model_id), ('state', '=', 'subscribed')])
+ for rule in pool.get('audittrail.rule').read(cr, SUPERUSER_ID, rule_ids, ['user_id','log_read','log_write','log_create','log_unlink','log_action','log_workflow']):
+ if len(rule['user_id']) == 0 or uid in rule['user_id']:
+ if rule.get('log_'+method,0):
+ return True
+ 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', 'read_group', 'import_data'):
+ if rule['log_action']:
return True
- 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', 'read_group', 'import_data'):
- if rule['log_action']:
- return True
-
- def execute_cr(self, cr, uid, model, method, *args, **kw):
- fct_src = super(audittrail_objects_proxy, self).execute_cr
- if self.check_rules(cr,uid,model,method):
- return self.log_fct(cr, uid, model, method, fct_src, *args, **kw)
- return fct_src(cr, uid, model, method, *args, **kw)
-
- def exec_workflow_cr(self, cr, uid, model, method, *args, **kw):
- fct_src = super(audittrail_objects_proxy, self).exec_workflow_cr
- if self.check_rules(cr,uid,model,'workflow'):
- return self.log_fct(cr, uid, model, method, fct_src, *args, **kw)
- return fct_src(cr, uid, model, method, *args, **kw)
-
-audittrail_objects_proxy()
+
+# Replace the openerp.service.model functions.
+
+original_execute_cr = openerp.service.model.execute_cr
+original_exec_workflow_cr = openerp.service.model.exec_workflow_cr
+
+def execute_cr(cr, uid, model, method, *args, **kw):
+ fct_src = original_execute_cr
+ if check_rules(cr,uid,model,method):
+ return log_fct(cr, uid, model, method, fct_src, *args, **kw)
+ return fct_src(cr, uid, model, method, *args, **kw)
+
+def exec_workflow_cr(cr, uid, model, method, *args, **kw):
+ fct_src = original_exec_workflow_cr
+ if check_rules(cr,uid,model,'workflow'):
+ return log_fct(cr, uid, model, method, fct_src, *args, **kw)
+ return fct_src(cr, uid, model, method, *args, **kw)
+
+openerp.service.model.execute_cr = execute_cr
+openerp.service.model.exec_workflow_cr = exec_workflow_cr
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
def onchange_stage_id(self, cr, uid, ids, stage_id, context=None):
if not stage_id:
- return {'value':{}}
- stage = self.pool.get('crm.case.stage').browse(cr, uid, stage_id, context)
+ return {'value': {}}
+ stage = self.pool.get('crm.case.stage').browse(cr, uid, stage_id, context=context)
if not stage.on_change:
- return {'value':{}}
- return {'value':{'probability': stage.probability}}
+ return {'value': {}}
- return {'value': {'probability': stage.probability}}
++ vals = {'probability': stage.probability}
++ if stage.probability >= 100 or (stage.probability == 0 and stage.sequence > 1):
++ vals['date_closed'] = fields.datetime.now()
++ return {'value': vals}
- def on_change_partner(self, cr, uid, ids, partner_id, context=None):
+ def on_change_partner_id(self, cr, uid, ids, partner_id, context=None):
values = {}
if partner_id:
partner = self.pool.get('res.partner').browse(cr, uid, partner_id, context=context)
return stage_ids[0]
return False
- def case_cancel(self, cr, uid, ids, context=None):
- """ Overrides case_cancel from base_stage to set probability """
- res = super(crm_lead, self).case_cancel(cr, uid, ids, context=context)
- self.write(cr, uid, ids, {'probability' : 0.0}, context=context)
- return res
-
- def case_reset(self, cr, uid, ids, context=None):
- """ Overrides case_reset from base_stage to set probability """
- res = super(crm_lead, self).case_reset(cr, uid, ids, context=context)
- self.write(cr, uid, ids, {'probability': 0.0}, context=context)
- return res
-
def case_mark_lost(self, cr, uid, ids, context=None):
- """ Mark the case as lost: state=cancel and probability=0 """
- for lead in self.browse(cr, uid, ids):
- stage_id = self.stage_find(cr, uid, [lead], lead.section_id.id or False, [('probability', '=', 0.0),('on_change','=',True)], context=context)
+ """ Mark the case as lost: state=cancel and probability=0
+ :deprecated: this method will be removed in OpenERP v8.
+ """
+ stages_leads = {}
+ for lead in self.browse(cr, uid, ids, context=context):
+ stage_id = self.stage_find(cr, uid, [lead], lead.section_id.id or False, [('probability', '=', 0.0), ('fold', '=', True), ('sequence', '>', 1)], context=context)
if stage_id:
- self.case_set(cr, uid, [lead.id], values_to_update={'probability': 0.0, 'date_closed': fields.datetime.now()}, new_stage_id=stage_id, context=context)
+ if stages_leads.get(stage_id):
+ stages_leads[stage_id].append(lead.id)
+ else:
+ stages_leads[stage_id] = [lead.id]
+ else:
+ raise osv.except_osv(_('Warning!'),
+ _('To relieve your sales pipe and group all Lost opportunities, configure one of your sales stage as follow:\n'
+ 'probability = 0 %, select "Change Probability Automatically".\n'
+ 'Create a specific stage or edit an existing one by editing columns of your opportunity pipe.'))
+ for stage_id, lead_ids in stages_leads.items():
- self.write(cr, uid, lead_ids, {'stage_id': stage_id, 'date_closed': fields.datetime.now()}, context=context)
++ self.write(cr, uid, lead_ids, {'stage_id': stage_id}, context=context)
return True
def case_mark_won(self, cr, uid, ids, context=None):
- """ Mark the case as won: state=done and probability=100 """
- for lead in self.browse(cr, uid, ids):
- stage_id = self.stage_find(cr, uid, [lead], lead.section_id.id or False, [('probability', '=', 100.0),('on_change','=',True)], context=context)
+ """ Mark the case as won: state=done and probability=100
+ :deprecated: this method will be removed in OpenERP v8.
+ """
+ stages_leads = {}
+ for lead in self.browse(cr, uid, ids, context=context):
+ stage_id = self.stage_find(cr, uid, [lead], lead.section_id.id or False, [('probability', '=', 100.0), ('fold', '=', True)], context=context)
if stage_id:
- self.case_set(cr, uid, [lead.id], values_to_update={'probability': 100.0, 'date_closed': fields.datetime.now()}, new_stage_id=stage_id, context=context)
+ if stages_leads.get(stage_id):
+ stages_leads[stage_id].append(lead.id)
+ else:
+ stages_leads[stage_id] = [lead.id]
+ else:
+ raise osv.except_osv(_('Warning!'),
+ _('To relieve your sales pipe and group all Won opportunities, configure one of your sales stage as follow:\n'
+ 'probability = 100 % and select "Change Probability Automatically".\n'
+ 'Create a specific stage or edit an existing one by editing columns of your opportunity pipe.'))
+ for stage_id, lead_ids in stages_leads.items():
- self.write(cr, uid, lead_ids, {'stage_id': stage_id, 'date_closed': fields.datetime.now()}, context=context)
++ self.write(cr, uid, lead_ids, {'stage_id': stage_id}, context=context)
+ return True
+
+ def case_escalate(self, cr, uid, ids, context=None):
+ """ Escalates case to parent level """
+ for case in self.browse(cr, uid, ids, context=context):
+ data = {'active': True}
+ if case.section_id.parent_id:
+ data['section_id'] = case.section_id.parent_id.id
+ if case.section_id.parent_id.change_responsible:
+ if case.section_id.parent_id.user_id:
+ data['user_id'] = case.section_id.parent_id.user_id.id
+ else:
+ raise osv.except_osv(_('Error!'), _("You are already at the top level of your sales-team category.\nTherefore you cannot escalate furthermore."))
+ self.write(cr, uid, [case.id], data, context=context)
return True
- def set_priority(self, cr, uid, ids, priority):
+ def set_priority(self, cr, uid, ids, priority, context=None):
""" Set lead priority
"""
- return self.write(cr, uid, ids, {'priority' : priority})
+ return self.write(cr, uid, ids, {'priority': priority}, context=context)
def set_high_priority(self, cr, uid, ids, context=None):
""" Set lead priority to high