global class LeadConversionBatch implements Database.Batchable<sObject> {
List<QueryException> mergeErrors {get; set;}
global Integer numberOfLeadsConvert = 0;
global Integer numberOfFailures = 0;
global Database.QueryLocator start(Database.BatchableContext bc) {
// collect the batches of records or objects to be passed to execute
// create list of profiles that the lead owner should have
List<String> profileNames = new List<String> {
'Boomi-Salesforce Sync',
'GIA Education User LON',
'GIA Education User US',
'GIA G&G User',
'GIA Integration',
'GIA Laboratory User US',
'GIA Management LON',
'GIA Management US',
'Marketing User',
'Marketo-Salesforce Sync',
'Read Only',
'Solution Manager',
'Standard User',
'System Administrator',
'US-Business Development',
'US – Marketing'
};
// get org profile id
List<Profile> profiles = [SELECT Id, Name
FROM Profile
WHERE Name IN :profileNames];
List<String> profileIds = new List<String>();
for(Profile p : profiles) {
profileIds.add(String.valueOf(p.Id));
}
// get all lead owner ids that have appropriate profile
List<User> owners = [SELECT Id, Name, ProfileId
FROM User
WHERE ProfileId IN :profileIds];
List<String> ownerIds = new List<String>();
for(User o : owners) {
ownerIds.add(String.valueOf(o.Id));
}
// get leads where owner is equal to one of the owners with
// the right profile
// and the lead has not been converted
return Database.getQueryLocator(
'SELECT Id, Email, IsConverted, FirstName, LastName, OwnerId, Subscription_AlumConnect__c, Subscription_EQ_Email__c, Subscription_Gems_Gemology_Email__c, Subscription_GIA_Insider__c, Subscription_Products_and_Services__c, Subscription_Retailer_Support__c ' +
'FROM Lead ' +
'WHERE OwnerId IN :ownerIds ' +
'AND IsConverted = false ' +
'AND Marketo_Sync__c = true'
);
}
global void execute(Database.BatchableContext bc, List<Lead> leads){
// process each batch of records
List<Integer> results = LeadService.Conversion(leads);
System.debug('results list' + results);
numberOfLeadsConvert = numberOfLeadsConvert + results[0];
numberOfFailures = numberOfFailures + results[1];
}
global void finish(Database.BatchableContext bc){
// execute any post-processing operations
// send an email after batch is complete to user
// who started batch
AsyncApexJob a = [Select Id, Status, ExtendedStatus, NumberOfErrors,
JobItemsProcessed, TotalJobItems, CreatedBy.Email
from AsyncApexJob where Id =:bc.getJobId()];
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {a.CreatedBy.Email};
mail.setToAddresses(toAddresses);
mail.setSubject('Match Merge Batch ' + a.Status);
String emailBody = '';
if(mergeErrors != null) {
emailBody = 'leads converted: ' + numberOfLeadsConvert +
'. Failures: ' + numberOfFailures + '.';
} else {
emailBody = 'leads converted: ' + numberOfLeadsConvert +
'. Failures: ' + numberOfFailures + '.';
}
mail.setPlainTextBody(emailBody);
Messaging.sendEmail(new Messaging.Email[] { mail });
}
}