Reassign Leads in Salesforce - APEX language


/ Published in: Java
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. global class LeadReassignOnActivityHistory implements Database.Batchable<sObject>{
  2.  
  3. private Date reassignDate = System.Today() - 10; // Sets the cutoff period on which you want to protect Leads
  4.  
  5. global Iterable<sObject> start(Database.BatchableContext BC) {
  6. // This set will hold the Id's of the Leads that we will reassign.
  7. Set <ID> LeadIds = new Set <ID>();
  8.  
  9. // 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.
  10. 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]);
  11.  
  12. // Iterate through the list of leads returned above.
  13. for (Lead l : startLeads) {
  14.  
  15. // if the Lead does not have any Activities associated with it then reassign it.
  16. if (l.ActivityHistories.size() == 0 || l.ActivityHistories.size() == null) {
  17. LeadIds.add(l.Id);
  18. }
  19.  
  20. //for each lead, iterate through its related Activities
  21. for (ActivityHistory activity : l.ActivityHistories) {
  22.  
  23. // 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.
  24. if (activity.ActivityDate < reassignDate) {
  25. LeadIds.add(activity.WhoId);
  26. }
  27. } // close inner for-loop
  28. } //close outer for-loop
  29.  
  30. // Using the list of ID's above, query the database for all related leads and get the necessary fields.
  31. List <Lead> leadsToReassign = new List <Lead>([Select Id, Location__c, OwnerId FROM Lead WHERE Id IN :LeadIds]);
  32.  
  33. // Return this list of leads, which will get passed to our execute() method below.
  34. return leadsToReassign;
  35.  
  36. } //close start method
  37.  
  38. global void execute(Database.BatchableContext BC, List <Lead> scope) {
  39. // This list of tasks will be used to hold tasks for insert.
  40. List <Task> taskList = new List<Task>();
  41.  
  42. // Iterate through the scope of Leads that were passed through to the execute method and transfer ownership based on the location.
  43. // This example only has two locations.
  44. // 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.
  45. for(Lead l : scope) {
  46. if(l.Location__c == 'Location A') {
  47. l.OwnerId = '005A0000000i84o'; // reassigns ownership via hardcoded Id
  48. Task tsk = new Task(); // Create the new task and populate it with data.
  49. tsk.WhoId = l.Id;
  50. tsk.ActivityDate = System.today();
  51. tsk.Status = 'Completed';
  52. tsk.Subject = 'Ownership Transferred';
  53. tsk.Type = 'Other';
  54.  
  55. taskList.add(tsk); // add the task to the list.
  56.  
  57. } //close if statement
  58. else {
  59. l.OwnerId='005A0000000i84z';
  60. Task tsk = new Task();
  61. tsk.WhoId = l.Id;
  62. tsk.ActivityDate = System.today();
  63. tsk.Status = 'Completed';
  64. tsk.Subject = 'Ownership Transferred';
  65. tsk.Type='Other';
  66.  
  67. taskList.add(tsk);
  68. } //close else
  69. } //close for-loop
  70.  
  71. try {
  72. insert taskList;
  73. } catch (system.dmlexception e) {
  74. System.debug('Tasks not inserted: ' + e);
  75. }
  76.  
  77. try {
  78. update scope;
  79. } catch (system.dmlexception e) {
  80. System.debug('Scope not updated: ' + e);
  81. }
  82.  
  83. } //close execute method
  84.  
  85. global void finish(Database.BatchableContext BC) {
  86.  
  87. AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
  88. TotalJobItems, CreatedBy.Email
  89. from AsyncApexJob where Id =
  90. :BC.getJobId()];
  91.  
  92. // Create and send an email with the results of the batch.
  93. Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
  94.  
  95. mail.setToAddresses(new String[] {a.CreatedBy.Email});
  96. mail.setReplyTo('[email protected]');
  97. mail.setSenderDisplayName('Lead Reassignment Results');
  98. mail.setSubject('Lead Reassignment ' + a.Status);
  99. mail.setPlainTextBody('The batch apex job processed ' + a.TotalJobItems +
  100. ' batches with ' + a.NumberofErrors + ' failures.');
  101.  
  102. Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
  103.  
  104. } //close finish method
  105. } //close class

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.