Skip to content

Instantly share code, notes, and snippets.

@winniecluk
Created February 20, 2018 22:47
Show Gist options
  • Save winniecluk/7f3beebe8b8487b5531829112a584c40 to your computer and use it in GitHub Desktop.
Save winniecluk/7f3beebe8b8487b5531829112a584c40 to your computer and use it in GitHub Desktop.
public class Task_Helper {
public static Map<String, Schema.SObjectField> FIELD_MAP = Schema.SObjectType.Task.fields.getMap();
public static void afterInsert(List<Task> newList){
Map<Id, Datetime> dateMap = new Map<Id, Datetime>();
Map<Id, String> descriptionMap = new Map<Id, String>();
Map<Id, Id> userMap = new Map<Id, Id>();
Map<String, Integer> sumMap = new Map<String, Integer>();
List<Lead> leadList = new List<Lead>();
for (Task t : newList){
if (t.WhoId != null && String.valueOf(t.WhoId.getSObjectType()) == 'Lead' && t.Subject.substring(0,4).toLowerCase() == 'call'){
if (!dateMap.containsKey(t.WhoId)){
dateMap.put(t.WhoId, t.CreatedDate);
descriptionMap.put(t.WhoId, t.CallDisposition);
userMap.put(t.WhoId, t.OwnerId);
} else {
// check that this current task's date might be greater than the one already on the map
if (t.CreatedDate > dateMap.get(t.WhoId)){
dateMap.put(t.WhoId, t.CreatedDate);
descriptionMap.put(t.WhoId, t.CallDisposition);
userMap.put(t.WhoId, t.OwnerId);
}
}
}
} // closes for loop through Task
for (AggregateResult ar : [SELECT WhoId, count(Id) cnt FROM Task WHERE WhoId IN :dateMap.keySet() AND Subject LIKE 'Call%' GROUP BY WhoId]){
sumMap.put(String.valueOf(ar.get('WhoId')), Integer.valueOf(ar.get('cnt')));
}
for (Lead l : [SELECT Id,Last_Call_Disposition__c,Last_Call_Made__c,Last_Call_Made_By__c FROM Lead WHERE Id IN :dateMap.keySet()]){
if (l.Last_Call_Made__c != null){
if (l.Last_Call_Made__c < dateMap.get(l.Id)){
l.Last_Call_Made__c = dateMap.get(l.Id);
l.Last_Call_Disposition__c = descriptionMap.get(l.Id);
l.Last_Call_Made_By__c = userMap.get(l.Id);
l.Total_Amount_Of_Calls_Made__c = sumMap.get(l.Id);
leadList.add(l);
}
} else {
l.Last_Call_Made__c = dateMap.get(l.Id);
l.Last_Call_Disposition__c = descriptionMap.get(l.Id);
l.Last_Call_Made_By__c = userMap.get(l.Id);
l.Total_Amount_Of_Calls_Made__c = sumMap.get(l.Id);
leadList.add(l);
}
}
update leadList;
System.debug(leadList);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment