Requirement--
I have one custom Object(Lead_map__c) where values are stored Like leadSource={'Web','Email','Phone'} and respective userIds in userId_assignee__c column
Whenever lead is updated with Checkbox Need Assistance=true then ownerId will be change based on Lead_map__c table and needs to create and assgine task to owner and when Lead is updated to false then userid needs to be change with currentUser
I have written a code which is working but if anyone can suggest a best practice or let me know any issue,mistake,any other simple way to write this logic.
public class LeadMapHandler {
public static boolean isrun =true;
public static void updateLeadOwner(List<lead> leadList,map<id,lead>oldmap) {
set<string> leadSource = new set<string>();
try{
for(lead l:leadList) {
leadSource.add(l.leadsource); //get the source of lead
}
map<string,lead_map__c> leadMap = new map<string,lead_map__c>();
for(lead_map__c lm : [select id,UserId_to_assign__c,Lead_Source__c from Lead_Map__c where Lead_Source__c in:leadSource]) {
leadMap.put(lm.lead_source__c,lm);
}
List<lead> updateLead = new List<lead>();
for(lead leadRecord:leadList) {
lead oldlead =oldmap.get(leadRecord.id);
if((oldlead.Need_Assistance__c!=leadRecord.Need_Assistance__c) && leadRecord.Need_Assistance__c) {
if(leadMap.get(leadRecord.LeadSource)!=null) {
lead ls = new lead();
ls.id=leadRecord.Id;
ls.OwnerId =leadMap.get(leadRecord.LeadSource).UserId_to_assign__c;
updateLead.add(ls);
createTask(leadMap.get(leadRecord.LeadSource).UserId_to_assign__c);
}
}
else if(leadRecord.Need_Assistance__c== false){
updateLeadBack(leadRecord); //call a method to update Owner with CurrentLoged in User
}
}
if(updateLead.size()>0) {
update updateLead;
}
}
catch(exception e) {
system.debug('EXCEPTION OCCURED-->'+e);
}
}
public static void updateLeadBack(lead l) {
lead ld = new lead();
ld.Id=l.id;
ld.OwnerId=userinfo.getUserId();
List<lead> updateLeadback = new List<lead>();
updateLeadback.add(ld);
update updateLeadback;
}