public class StageProcessingHandler {
public static void processStaging(List<StageRecord__c> incomingRecords) {
// Ensure processing if there are records to avoid unnecessary queries/calculations
if (incomingRecords == null || incomingRecords.isEmpty()) {
return;
}
Map<Id, StageRecord__c> currentDataMap = new Map<Id, StageRecord__c>();
Map<String, StageRecord__c> freshDataMap = new Map<String, StageRecord__c>();
// Divide incoming records into respective maps based on LinkID__c or MortgageID__c
for (StageRecord__c record : incomingRecords) {
if (record.LinkID__c != null) {
currentDataMap.put(record.LinkID__c, record);
} else if (record.MortgageID__c != null) {
freshDataMap.put(record.MortgageID__c, record);
}
}
// Skip if there is no fresh data to process
if (freshDataMap.isEmpty()) {
return;
}
// Retrieve matching deals from the database
Map<Id, Deal> dealMap = new Map<Id, Deal>([
SELECT Id, MortgageID__c FROM Deal WHERE MortgageID__c IN :freshDataMap.keySet()
]);
// Handle existing deals and check for absent deals using a separate method
Map<Id,Deal> absentData = Deal_Processing.getDealInstances(dealMap.keySet());
List<Deal> newEntries = new List<Deal>();
// Map the absent deals to be inserted
for (Deal loanDeal : absentData.values()) {
Deal adjustedDeal = Deal_Processing.applyMapping(loanDeal);
if (adjustedDeal != null) { // Null check for safe processing.
newEntries.add(adjustedDeal);
}
}
// Insert all new entries in bulk if there are any
if (!newEntries.isEmpty()) {
try {
insert newEntries;
} catch (DmlException ex) {
// Log the error and handle failed inserts appropriately
System.debug('Failed to insert deals: ' + ex.getMessage());
}
}
}
}