Tuesday, 9 February 2016

Lead First Call Trigger and Test Class

Lead First Call Trigger and Test Class

Ever wanted to grab the date of the First call you made to a hot new Lead in your Salesforce.com system?

If so, this Trigger and Class could be for you...

Logic

The Trigger below will fire each time a new activity is stored which is Type = Inbound or Outbound.

The Trigger will then look at the Lead object and identify whether the new Activity/Task record is the earliest date.

If it is, then the field on the Lead called "First Call Made" will be populated with the date from the Task.

Why would you use this?

You could use this Trigger to work out how quickly you are contacting your Leads. Just calculate the difference between the creation date/time and the date/time of the first Call or other activity.

How do I set this up?

You will need 2 new custom fields on the Lead object

Name: Creation > First Call Made (mins)
API Name: First_Call_min__c
Type: Formula
Formula: (Call_made__c - CreatedDate)*1440

Name: First Call Made
API Name: Call_made__c
Type: Date

Then you will need to create a Trigger and Apex Class using the code below.

The Trigger

trigger TaskTrigger on Task (before insert) {
    
    /*   Trigger to populate a field labelled Call_made__c on the Lead object 
    with the Date/Time of the First call made   */
    
    System.debug('Trigger TaskTrigger Start ----------------------------------------------------');
                
    Set taskIds = new Set();
    //Set of TaskIDs - used for SOQL
        
    /* Only pull in Type Call to this Trigger
  Other Tasks should not change First Call Date field */
    
    for(Task ptl : Trigger.new) {
       //Populate list of IDs to work with - only Inbound and Outbound calls get added
           if (ptl.WhoId != null && (ptl.CallType == 'Inbound' || ptl.CallType == 'Outbound')) {
              taskIds.add(ptl.WhoId);
            }
        }
    
  if (taskIds.size() > 0) {
    //Only do something if we have TaskIDs to work with
    //Get all the Leads we'll update:
    
    List leadList = [SELECT Id, Call_made__c FROM lead where Id IN :taskIds];    
    
    //Build map of Leads
            
            for (Lead l : leadList) {
          if (l.Call_made__c == Null) {
                        //If there is no First Call Made populate it
                         l.Call_made__c = System.today();
                        System.debug('Update First Call Made');
                    }
                    else if (l.Call_made__c > System.Today()) {
                      l.Call_made__c = System.today();

                        //Check if there is an earlier date in there
                        System.debug('Older date already set for First Call Made - leaving value');                        
                    }
              
            }
    
    //Set new Call_made__c date
    update leadList;
        
  } //end if statement

    System.debug('Trigger TaskTrigger End ----------------------------------------------------');

}

Test Class

@isTest
public class testTaskTrigger {
    /* Trigger Logic
* Trigger looks at each new task created on lead. 
* If it is a Call, we check whether there is a current First Call Date on the Lead
* If the Lead does not have a First Call Date - poplulate it
* If the Lead First Call Date is newer than current Call Date/Time then update it
*/
    
    static testMethod void testFirstCallDate() {
        // Principle #1: Create records from scratch!
        
        // Insert 201 Leads
        List<Lead> leads = new List<Lead>();
        for (Integer i = 0; i < 10; i++) {
            Lead l = new Lead();
            l.FirstName = 'Test';
            l.LastName = 'Person';
            leads.add(l);
        }
        insert leads;
        
        // Loop through each new Lead - link the Task to the new leads
        List<Task> tasks = new List<Task>();
        for (Lead createdLeads: leads) {
            Task t = new Task();
            t.CallType = 'Inbound';
            t.NVMContactWorld__CW_Call_Start_Time__c = datetime.newInstance(2014, 9, 15, 12, 30, 0);
            t.NVMContactWorld__CW_Call_End_Time__c = datetime.newInstance(2014, 9, 15, 13, 30, 0);
            t.WhoId = createdLeads.Id;
            tasks.add(t);
        }
        
        try {
            insert tasks; 
            
        }    
        catch (Exception e) {
            System.assert(false, 'Exception ' + e);
        }
        System.debug('Task size is ' + tasks.size());
        
        //Add Task ID to Lead to relate them    
        
        // "Setup" data has been entered, begin testing
        // This trick gives us a new set of Governor Limits!
        Test.startTest();
        
        // Principle #4: Test in bulk (200+ records)!
        
        // Get all Leads and their First Call Date
        leads = [SELECT Id, Call_made__c FROM lead ];
        
        System.debug('Lead size is ' + leads.size());
        
        // Assert each Lead has a First Call Date
        
        for (lead a : leads) {
            DateTime dateCheck = System.today();
            System.debug('Checking comparison for ' + a.Id + ' ' + dateCheck + 'compared to ' + a.Call_made__c);
            System.assertEquals(dateCheck, a.Call_made__c);
        }               
        
        // Principle #3: Test things that shouldn't work!
        
        List<Task> newTasks = new List<Task>();
        
        for (Lead createdLeads: leads) {
            Task u = new Task();
            u.CallType = 'Inbound';
            u.NVMContactWorld__CW_Call_Start_Time__c = datetime.newInstance(2013, 9, 15, 12, 30, 0);
            u.NVMContactWorld__CW_Call_End_Time__c = datetime.newInstance(2013, 9, 15, 13, 30, 0);
            u.WhoId = createdLeads.Id;
            newTasks.add(u);
        }
        try {
            insert newTasks; 
            
        }    
        catch (Exception e) {
            System.assert(false, 'Exception ' + e);
        }     
        System.debug('Task size is ' + leads.size());
        
        // We inserted older date tasks - they should now show as the earlier date
        
        for (lead a : leads) {
            DateTime dateCheck = System.today()-3;
            System.debug('Checking comparison for ' + a.Id + ' ' + dateCheck + 'compared to ' + a.Call_made__c);
            System.assertNOTEquals(dateCheck, a.Call_made__c);
        }      
        
        Test.stopTest();
        
    }
}
Enjoy! Icon from IconFinder, artist Yana Kulakova