Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save danieljpeter/5340968 to your computer and use it in GitHub Desktop.
Save danieljpeter/5340968 to your computer and use it in GitHub Desktop.
trigger LeadConvertReparentChatTranscript on Lead (before update) {
Map<Id,Id> convertedLeadsWithContactIds = new Map<Id,Id>();
for (Lead theLead:Trigger.new) {
Lead beforeUpdate = System.Trigger.oldMap.get(theLead.Id);
if ((theLead.ConvertedContactId != null) && (beforeUpdate.ConvertedContactId == null)) {
//if the converted contactId just went from not populated, to populated
//meaning we are converting the lead into a contact
convertedLeadsWithContactIds.put(theLead.Id,theLead.ConvertedContactId);
}
}
if (!convertedLeadsWithContactIds.isEmpty()) {
LeadReparentChatTranscript.doUpdate(convertedLeadsWithContactIds);
}
}
public class LeadReparentChatTranscript {
public static void doUpdate(Map<Id,Id> convertedLeadsWithContactIds) {
//convertedLeadsWithContactIds, key is the LeadId, value is the ConvertedContactId;
//go through and get all the corresponding Transcript records
List<LiveChatTranscript> tList = new List<LiveChatTranscript>();
tList = [SELECT Id, LeadId, ContactId FROM LiveChatTranscript WHERE LeadId IN: convertedLeadsWithContactIds.keySet() LIMIT 10000];
if (!tList.isEmpty()) {
for(LiveChatTranscript l : tList) {
l.ContactId = convertedLeadsWithContactIds.get(l.LeadId);
}
update tList;
}
}
static testMethod void doTest() {
Map<Id,Id> convertedLeadsWithContactIds = new Map<Id,Id>();
//create a contact
Contact testContact = new Contact(LastName='Smith');
insert testContact;
update testContact;
//create a lead
Lead testLead = new Lead(LastName='Smith', Company='ACME');
insert testLead;
update testLead;
//create a live chat visitor
LiveChatVisitor testVisit = new LiveChatVisitor();
insert testVisit;
update testVisit;
//create a transcript
LiveChatTranscript testTrans = new LiveChatTranscript(LeadId=testLead.Id, LiveChatVisitorId=testVisit.Id);
insert testTrans;
update testTrans;
convertedLeadsWithContactIds.put(testLead.Id, testContact.Id);
LeadReparentChatTranscript.doUpdate(convertedLeadsWithContactIds);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment