Return to Snippet

Revision: 33858
at October 16, 2010 13:24 by leeclint


Updated Code
global class LeadReassignOnActivityHistory implements Database.Batchable<sObject>{

    private Date reassignDate = System.Today() - 10; // Sets the cutoff period on which you want to protect Leads
    
    global Iterable<sObject> start(Database.BatchableContext BC) {
    	// This set will hold the Id's of the Leads that we will reassign.
    	Set <ID> LeadIds = new Set <ID>();
    	
    	// Query all the Leads in your database and sub-query all existing Activities that match your criteria (i.e. Type), and return the newest one.
    	List <Lead> startLeads = new List <Lead>([Select (Select WhoId, ActivityDate FROM ActivityHistories WHERE ActivityType='Call' OR ActivityType='Ownership Transferred' ORDER BY ActivityDate DESC Limit 1) FROM Lead]);
    	
    	// Iterate through the list of leads returned above.
    	for (Lead l : startLeads) {
     
                // if the Lead does not have any Activities associated with it then reassign it.
            if (l.ActivityHistories.size() == 0 || l.ActivityHistories.size() == null) {
                LeadIds.add(l.Id);
            }
    		
    		//for each lead, iterate through its related Activities
    		for (ActivityHistory activity : l.ActivityHistories) {
    			
    			// if the Activity is older than the reassignDate variable you set above, then this lead's ID will be added to the list that will be reassigned.
    			if (activity.ActivityDate < reassignDate) {
    			LeadIds.add(activity.WhoId);
    		    }
    		} // close inner for-loop 		
    	} //close outer for-loop
    	
    	// Using the list of ID's above, query the database for all related leads and get the necessary fields.
    	List <Lead> leadsToReassign = new List <Lead>([Select Id, Location__c, OwnerId FROM Lead WHERE Id IN :LeadIds]);
    	
    	// Return this list of leads, which will get passed to our execute() method below.
    	return leadsToReassign;
    	
    } //close start method
    
    global void execute(Database.BatchableContext BC, List <Lead> scope) {
       // This list of tasks will be used to hold tasks for insert.
       List <Task> taskList = new List<Task>();
               
        // Iterate through the scope of Leads that were passed through to the execute method and transfer ownership based on the location.  
        // This example only has two locations.  
        // Create a Task that's associated with each Lead, this can be used so that we don't reassign the same Lead every day if no activity is being logged.
        for(Lead l : scope) {
            if(l.Location__c == 'Location A') {
                l.OwnerId = '005A0000000i84o'; // reassigns ownership via hardcoded Id
                Task tsk = new Task(); // Create the new task and populate it with data.
                tsk.WhoId = l.Id;
                tsk.ActivityDate = System.today();
                tsk.Status = 'Completed';
                tsk.Subject = 'Ownership Transferred';
                tsk.Type = 'Other';
                
                taskList.add(tsk); // add the task to the list.
                
            } //close if statement 
            else { 
                l.OwnerId='005A0000000i84z';
                Task tsk = new Task();
                tsk.WhoId = l.Id;
                tsk.ActivityDate = System.today();
                tsk.Status = 'Completed';
                tsk.Subject = 'Ownership Transferred';
                tsk.Type='Other';
                
                taskList.add(tsk);
            } //close else
        } //close for-loop
        
        try {
            insert taskList;
        } catch (system.dmlexception e) {
            System.debug('Tasks not inserted: ' + e);
        }
         
        try {
            update scope;
        } catch (system.dmlexception e) {
            System.debug('Scope not updated: ' + e);
        }
                    
    } //close execute method
    
    global void finish(Database.BatchableContext BC) {
        
        AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            from AsyncApexJob where Id =
            :BC.getJobId()];
        
        // Create and send an email with the results of the batch.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        mail.setToAddresses(new String[] {a.CreatedBy.Email});
        mail.setReplyTo('[email protected]');
        mail.setSenderDisplayName('Lead Reassignment Results');
        mail.setSubject('Lead Reassignment ' + a.Status);
        mail.setPlainTextBody('The batch apex job processed ' + a.TotalJobItems + 
        ' batches with ' + a.NumberofErrors + ' failures.');

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        
    } //close finish method
} //close class

Revision: 33857
at October 14, 2010 10:34 by leeclint


Updated Code
global class LeadReassignOnActivityHistory implements Database.Batchable<sObject>{

    private Date reassignDate = System.Today() - 10; // Sets the cutoff period on which you want to protect Leads
    
    global Iterable<sObject> start(Database.BatchableContext BC) {
    	// This set will hold the Id's of the Leads that we will reassign.
    	Set <ID> LeadIds = new Set <ID>();
    	
    	// Query all the Leads in your database and sub-query all existing Activities that match your criteria (i.e. Type), and return the newest one.
    	List <Lead> startLeads = new List <Lead>([Select (Select WhoId, ActivityDate FROM ActivityHistories WHERE ActivityType='Call' OR ActivityType='Ownership Transferred' ORDER BY ActivityDate DESC Limit 1) FROM Lead]);
    	
    	// Iterate through the list of leads returned above.
    	for (Lead l : startLeads) {
    		
    		//for each lead, iterate through its related Activities
    		for (ActivityHistory activity : l.ActivityHistories) {
    			
    			// if the Activity is older than the reassignDate variable you set above, then this lead's ID will be added to the list that will be reassigned.
    			if (activity.ActivityDate < reassignDate) {
    			LeadIds.add(activity.WhoId);
    		    }
    		} // close inner for-loop 		
    	} //close outer for-loop
    	
    	// Using the list of ID's above, query the database for all related leads and get the necessary fields.
    	List <Lead> leadsToReassign = new List <Lead>([Select Id, Location__c, OwnerId FROM Lead WHERE Id IN :LeadIds]);
    	
    	// Return this list of leads, which will get passed to our execute() method below.
    	return leadsToReassign;
    	
    } //close start method
    
    global void execute(Database.BatchableContext BC, List <Lead> scope) {
       // This list of tasks will be used to hold tasks for insert.
       List <Task> taskList = new List<Task>();
               
        // Iterate through the scope of Leads that were passed through to the execute method and transfer ownership based on the location.  
        // This example only has two locations.  
        // Create a Task that's associated with each Lead, this can be used so that we don't reassign the same Lead every day if no activity is being logged.
        for(Lead l : scope) {
            if(l.Location__c == 'Location A') {
                l.OwnerId = '005A0000000i84o'; // reassigns ownership via hardcoded Id
                Task tsk = new Task(); // Create the new task and populate it with data.
                tsk.WhoId = l.Id;
                tsk.ActivityDate = System.today();
                tsk.Status = 'Completed';
                tsk.Subject = 'Ownership Transferred';
                tsk.Type = 'Other';
                
                taskList.add(tsk); // add the task to the list.
                
            } //close if statement 
            else { 
                l.OwnerId='005A0000000i84z';
                Task tsk = new Task();
                tsk.WhoId = l.Id;
                tsk.ActivityDate = System.today();
                tsk.Status = 'Completed';
                tsk.Subject = 'Ownership Transferred';
                tsk.Type='Other';
                
                taskList.add(tsk);
            } //close else
        } //close for-loop
        
        try {
            insert taskList;
        } catch (system.dmlexception e) {
            System.debug('Tasks not inserted: ' + e);
        }
         
        try {
            update scope;
        } catch (system.dmlexception e) {
            System.debug('Scope not updated: ' + e);
        }
                    
    } //close execute method
    
    global void finish(Database.BatchableContext BC) {
        
        AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            from AsyncApexJob where Id =
            :BC.getJobId()];
        
        // Create and send an email with the results of the batch.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        mail.setToAddresses(new String[] {a.CreatedBy.Email});
        mail.setReplyTo('[email protected]');
        mail.setSenderDisplayName('Lead Reassignment Results');
        mail.setSubject('Lead Reassignment ' + a.Status);
        mail.setPlainTextBody('The batch apex job processed ' + a.TotalJobItems + 
        ' batches with ' + a.NumberofErrors + ' failures.');

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        
    } //close finish method
} //close class

Revision: 33856
at October 14, 2010 10:30 by leeclint


Initial Code
global class LeadReassignOnActivityHistory implements Database.Batchable<sObject>{

    private Date reassignDate = System.Today() - 10; // Sets the cutoff period on which you want to protect Leads
    
    global Iterable<sObject> start(Database.BatchableContext BC) {
    	// This set will hold the Id's of the Leads that we will reassign.
    	Set <ID> LeadIds = new Set <ID>();
    	
    	// Query all the Leads in your database and sub-query all existing Activities that match your criteria (i.e. Type), and return the newest one.
    	List <Lead> startLeads = new List <Lead>([Select (Select WhoId, ActivityDate FROM ActivityHistories WHERE ActivityType='Call' OR ActivityType='Ownership Transferred' ORDER BY ActivityDate DESC Limit 1) FROM Lead]);
    	
    	// Iterate through the list of leads returned above.
    	for (Lead l : startLeads) {
    		
    		//for each lead, iterate through its related Activities
    		for (ActivityHistory activity : l.ActivityHistories) {
    			
    			// if the Activity is older than the reassignDate variable you set above, then this lead's ID will be added to the list that will be reassigned.
    			if (activity.ActivityDate < reassignDate) {
    			LeadIds.add(activity.WhoId);
    		    }
    		} // close inner for-loop 		
    	} //close outer for-loop
    	
    	// Using the list of ID's above, query the database for all related leads and get the necessary fields.
    	List <Lead> leadsToReassign = new List <Lead>([Select Id, Club_Location__c, OwnerId FROM Lead WHERE Id IN :LeadIds]);
    	
    	// Return this list of leads, which will get passed to our execute() method below.
    	return leadsToReassign;
    	
    } //close start method
    
    global void execute(Database.BatchableContext BC, List <Lead> scope) {
       // This list of tasks will be used to hold tasks for insert.
       List <Task> taskList = new List<Task>();
               
        // Iterate through the scope of Leads that were passed through to the execute method and transfer ownership based on the location.  
        // This example only has two locations.  
        // Create a Task that's associated with each Lead, this can be used so that we don't reassign the same Lead every day if no activity is being logged.
        for(Lead l : scope) {
            if(l.Club_Location__c == 'Evans Road') {
                l.OwnerId = '005A0000000i84o'; // reassigns ownership
                Task tsk = new Task(); // Create the new task and populate it with data.
                tsk.WhoId = l.Id;
                tsk.ActivityDate = System.today();
                tsk.Status = 'Completed';
                tsk.Subject = 'Ownership Transferred';
                tsk.Type = 'Other';
                
                taskList.add(tsk); // add the task to the list.
                
            } //close if statement 
            else { 
                l.OwnerId='005A0000000i84z';
                Task tsk = new Task();
                tsk.WhoId = l.Id;
                tsk.ActivityDate = System.today();
                tsk.Status = 'Completed';
                tsk.Subject = 'Ownership Transferred';
                tsk.Type='Other';
                
                taskList.add(tsk);
            } //close else
        } //close for-loop
        
        try {
            insert taskList;
        } catch (system.dmlexception e) {
            System.debug('Tasks not inserted: ' + e);
        }
         
        try {
            update scope;
        } catch (system.dmlexception e) {
            System.debug('Scope not updated: ' + e);
        }
                    
    } //close execute method
    
    global void finish(Database.BatchableContext BC) {
        
        AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
            TotalJobItems, CreatedBy.Email
            from AsyncApexJob where Id =
            :BC.getJobId()];
        
        // Create and send an email with the results of the batch.
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

        mail.setToAddresses(new String[] {a.CreatedBy.Email});
        mail.setReplyTo('[email protected]');
        mail.setSenderDisplayName('Lead Reassignment Results');
        mail.setSubject('Lead Reassignment ' + a.Status);
        mail.setPlainTextBody('The batch apex job processed ' + a.TotalJobItems + 
        ' batches with ' + a.NumberofErrors + ' failures.');

        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        
    } //close finish method
} //close class

Initial URL

                                

Initial Description
Batch Apex class that allows you to reassign leads based on ActivityHistory.

Initial Title
Reassign Leads in Salesforce - APEX language

Initial Tags

                                

Initial Language
Java