public with sharing class ContactTriggerHandler {
//
// custom trigger handler setup to handler all triggers received on Contact object
//
public Boolean isTriggerExecuted = true;
private boolean myIsExecuting = false;
private integer BatchSize = 0;
public ContactTriggerHandler(boolean isExecuting, integer size) {
myIsExecuting = isExecuting;
BatchSize = size;
}
//
// On Before Insert
//
public void OnBeforeInsert(List<Contact> contactList){
List<String> emailList = new List<String>();
for(Contact contact : contactList){
emailList.add(contact.email);
}
List<Contact> newContactList = new List<Contact>();
List<Lead> leadList = [SELECT id,firstname,lastname, email,LeadSource,phone, MobilePhone,OwnerId,HasOptedOutOfEmail FROM Lead WHERE email IN :emailList];
for(Contact cItem : contactList){
//Merge
for(Lead lItem: leadList){
cItem.HasOptedOutOfEmail = lItem.HasOptedOutOfEmail;
cItem.OwnerId = lItem.OwnerId;
cItem.LeadSource = lItem.LeadSource;
cItem.MobilePhone = lItem.MobilePhone;
cItem.phone = lItem.phone;
cItem.LeadSource = lItem.LeadSource;
newContactList.add(cItem);
}
}
}
//
// On After Insert
//
public void OnAfterInsert(List<Contact> contactList) {
List<String> emailList = new List<String>();
for(Contact contact : contactList){
emailList.add(contact.email);
}
List<Lead> leadList = [SELECT id,firstname,lastname, email,LeadSource,phone, MobilePhone,OwnerId,HasOptedOutOfEmail FROM Lead WHERE email IN :emailList];
List<Task> taskTransferList = [SELECT Id, Who.Id, Who.Type FROM Task WHERE Who.Type = 'Lead'];
List<Task> taskUpdate = new List<Task>();
for(Contact cItem : contactList){
//Move Task to Contact
for(Lead lItem: leadList){
if(taskTransferList.size() > 0){
for(Task taskItem :taskTransferList){
taskItem.whoid = cItem.id;
taskUpdate.add(taskItem);
}
}
}
upsert taskUpdate;
delete leadList;
}
}