Skip to content

Instantly share code, notes, and snippets.

@durveshshah
Created February 22, 2024 22:46
Show Gist options
  • Save durveshshah/3b78c21f7f2764714542ba426ec26aca to your computer and use it in GitHub Desktop.
Save durveshshah/3b78c21f7f2764714542ba426ec26aca to your computer and use it in GitHub Desktop.
public class LeadChangeEventHandler {
public static void publishLeadEvent(List<LeadChangeEvent> leadEvents){
// List to hold the Lead_Created_Event__e records to be published
List<Lead_Created_Event__e> leadEventsToAdd = new List<Lead_Created_Event__e>();
Map<String, Object> changedFieldsWithValues = new Map<String, Object>();
// Gather IDs of deleted leads
Set<Id> deletedLeadIds = new Set<Id>();
for(LeadChangeEvent leadChangeEvent : leadEvents) {
EventBus.ChangeEventHeader header = leadChangeEvent.ChangeEventHeader;
if(header.changeType == 'DELETE') {
deletedLeadIds.add(header.recordIds[0]);
}
}
// Query deleted leads outside the loop
Map<Id, Lead> deletedLeadsMap = new Map<Id, Lead>([SELECT Id, Company, Name, IsDeleted FROM Lead WHERE Id IN :deletedLeadIds ALL ROWS]);
for(LeadChangeEvent leadChangeEvent : leadEvents) {
EventBus.ChangeEventHeader header = leadChangeEvent.ChangeEventHeader;
if(header.changeType == 'DELETE'){
// Check if lead is deleted
Lead deletedLead = deletedLeadsMap.get(header.recordIds[0]);
if(deletedLead != null && deletedLead.IsDeleted) {
// Create new Lead_Created_Event__e
Lead_Created_Event__e newEvent = new Lead_Created_Event__e();
// Add specific fields to the event
for(String fieldName : new String[] {'Company', 'Id', 'Name', 'IsDeleted'}) {
changedFieldsWithValues.put(fieldName, deletedLead.get(fieldName));
}
// Serialize the changed fields
newEvent.Changed_Fields__c = JSON.serialize(changedFieldsWithValues);
newEvent.CommitUser__c = header.CommitUser;
leadEventsToAdd.add(newEvent);
}
}
else if(header.changeType == 'UPDATE'){
// Create new Lead_Created_Event__e
Lead_Created_Event__e newEvent = new Lead_Created_Event__e();
// Populate the fields with data from the LeadChangeEvent
newEvent.Company_Name__c = leadChangeEvent.Company;
newEvent.Lead_Name__c = leadChangeEvent.Name;
newEvent.CommitUser__c = header.CommitUser;
// Add the changed fields and their new values to the event
for(String field : header.changedFields){
changedFieldsWithValues.put(field, leadChangeEvent.get(field));
}
newEvent.Changed_Fields__c = JSON.serialize(changedFieldsWithValues);
// Add the event to the list
leadEventsToAdd.add(newEvent);
}
}
// Publish the Platform Events
if(!leadEventsToAdd.isEmpty()) {
Database.SaveResult[] results = EventBus.publish(leadEventsToAdd);
// Check for errors
for(Database.SaveResult result : results) {
if(!result.isSuccess()) {
for(Database.Error error : result.getErrors()) {
System.debug('Error publishing event: ' + error.getStatusCode() + ' - ' + error.getMessage());
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment