Skip to content
This repository has been archived by the owner on Jan 20, 2024. It is now read-only.

Batch ability for big campaigns #2

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 69 additions & 10 deletions src/classes/batchSegmentCreator.cls
Original file line number Diff line number Diff line change
Expand Up @@ -26,43 +26,101 @@ OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISE
OF THE POSSIBILITY OF SUCH DAMAGE.

*/
global class batchSegmentCreator implements Database.Batchable<SObject>{
global class batchSegmentCreator implements Database.Batchable<SObject>,Database.Stateful{
global String query;
global String email;
global Id parentCampaignId;
global List<Id> segmentCampaignIds;
global List<Integer> segmentSizes;
global List<Integer> membersAdded;
global Boolean success;
global String errorTxt = '';
global boolean keepOriginal;

global database.querylocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);}

global void execute(Database.BatchableContext BC, List<sObject> scope){
//Old code from AppEx
/*
boolean thisBatchSuccess = memberAssignment.assignMembersNow(parentCampaignId,segmentCampaignIds,segmentSizes,membersAdded);
if(!thisBatchSuccess){
success = false;
}
*/

List<CampaignMember> newCampaignMembers = new List<CampaignMember>();

for(sObject s : scope){

CampaignMember oldCM = (CampaignMember)s;

Boolean assigned = false;

while(assigned == false){
Integer assignedList = Math.floor(segmentCampaignIds.size() * Math.Random()).intValue();

if((membersAdded[assignedList] < segmentSizes[assignedList])){
newCampaignMembers.add(
new CampaignMember(
CampaignId = segmentCampaignIds[assignedList],
LeadId = oldCM.LeadId,
ContactId = oldCM.ContactId
)
);
assigned = true;

membersAdded[assignedList]++;

}
}

}

if(!newCampaignMembers.isEmpty()){
Database.saveresult[] srList = database.insert(newCampaignMembers,false);

List<CampaignMember> deleteMe = new List<CampaignMember>();
for(Integer i = 0;i<srList.size();i++){
Database.saveresult sr = srList[i];

if(sr.isSuccess() && !keepOriginal){
deleteMe.add( (CampaignMember)scope[i] );
}
else{
for(Database.Error e : sr.getErrors()){
errorTxt = errorTxt + 'Original Record Id:' + scope[i].get('Id') + '\n' + 'Error:' + e.getMessage() + '\n\n';
}

}
}

if(!deleteMe.isEmpty()){
delete deleteMe;
}

}

}
global void finish(Database.BatchableContext BC){
String resultHeader;

String hasErrors;
String resultBody;
if(success){
resultHeader = 'Success';
if(errorTxt == ''){
hasErrors = '';
resultBody = ' has completed successfully.';
} else {
resultHeader = 'Failure';
resultBody = ' has failed. Please try again.';
hasErrors = 'with Errors';
resultBody = ' has complted with errors. \n\n' + errorTxt + '\n\n';
}
//query the parent and make a better body
Campaign parentCampaign = [select id, name from Campaign where id=:parentCampaignId];

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();

mail.setToAddresses(new String[] {email});
mail.setReplyTo('[email protected]');
mail.setReplyTo(email);
mail.setSenderDisplayName('Batch Processing of Campaigns');
mail.setSubject(resultHeader + ': Campaign Segmentation Completed - ' + parentCampaign.name);
mail.setSubject('Campaign Segmentation Completed - ' + parentCampaign.name + ' ' + hasErrors);
mail.setPlainTextBody('The segmentation of ' + parentCampaign.name + resultBody +' https://na1.salesforce.com/' + parentCampaign.Id);

Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
Expand Down Expand Up @@ -119,7 +177,7 @@ global class batchSegmentCreator implements Database.Batchable<SObject>{
for(Campaign myCamp : segmentCampaigns){
mySegmentIds.add(myCamp.Id);
}
//set sizes for segments
//set sizes
List<Integer> sizes = new List<Integer>();
sizes.add(100);
sizes.add(100);
Expand All @@ -136,6 +194,7 @@ global class batchSegmentCreator implements Database.Batchable<SObject>{
batch.segmentCampaignIds = mySegmentIds;
batch.segmentSizes = sizes;
batch.membersAdded = members;
batch.keepOriginal = false;
ID batchprocessid = Database.executeBatch(batch);
Test.StopTest();
System.AssertEquals(database.countquery('SELECT count()' +' FROM CampaignMember WHERE campaignId=\'' + parentCampaign.Id + '\''), 0);
Expand Down
18 changes: 12 additions & 6 deletions src/classes/memberAssignment.cls
Original file line number Diff line number Diff line change
Expand Up @@ -33,25 +33,31 @@ public with sharing class memberAssignment {
static List<Integer> sizes;
static List<Integer> members;
static List<CampaignMember> newCampaignMembers;
static Boolean keep;

public static boolean assignMembersNow(Id parentCampaignId, List<Id> segmentCampaignIds, List<Integer> segmentSizes, List<Integer> membersAdded){
public static boolean assignMembersNow(Id parentCampaignId, List<Id> segmentCampaignIds, List<Integer> segmentSizes, List<Integer> membersAdded, Boolean keepOriginal){
campId = parentCampaignId;
semgmentIds = segmentCampaignIds;
sizes = segmentSizes;
members = membersAdded;

keep = keepOriginal;
newCampaignMembers = new List<CampaignMember>();

for(CampaignMember thisMember : [select id,campaignId, leadId, contactid from campaignMember where CampaignId = :campId]){
List<CampaignMember> oldMembers = [select id,campaignId, leadId, contactid from campaignMember where CampaignId = :campId];

for(CampaignMember thisMember : oldMembers){
assignMember(thisMember);
}

if(newCampaignMembers.size()!=0){
system.debug('******newCampaignMembers = '+newCampaignMembers);
if(!newCampaignMembers.isEmpty()){
try {
insert newCampaignMembers;
delete [select id,campaignId, leadId, contactid from campaignMember where CampaignId = :campId];
if(!keep){
delete oldMembers;
}
return true;
} catch (exception e){
system.debug('******EXCEPTION = ' + e);
return false;
}
} else {
Expand Down
Loading