Apex Triggers - 15 (Amazon Interview Question)

 1. Scenario Overview

This automation solves an Amazon Interview Question based on a parent-child relationship between a parent object, Tax_Firm__c, and a child object, Employee__c . The parent features two currency fields: Max_Salary__c and Min_Salary__c . The system must dynamically recalculate and roll up the highest and lowest employee salary values to these parent fields whenever any child employee record is inserted, updated, deleted, or undeleted .
Additionally, the solution handles the edge case where all related employees are deleted from a firm, safely resetting the parent summary values to zero instead of leaving stale metrics behind .
or
Show the Min & Max Salary of Employee records on the Parent Company record.

2. Apex Handler Class
public class EmployeeTriggerHandler {
    public static void updateSalaryRollups(List<Employee__c> newEmployees, List<Employee__c> oldEmployees, Map<Id, Employee__c> oldEmployeeMap) {
        Set<Id> taxFirmIds = new Set<Id>();
        
        // 1. Process inserts, updates, and undeletes
        if (newEmployees != null) {
            for (Employee__c emp : newEmployees) {
                
                // Track current parent (Handles Scenario 1 & Scenario 2)
                if (emp.Tax_Firm__c != null) {
                    taxFirmIds.add(emp.Tax_Firm__c);
                }
                
                // Track historical parent during updates (Handles Scenario 1 & Scenario 3)
                if (oldEmployeeMap != null && oldEmployeeMap.containsKey(emp.Id)) {
                    Employee__c oldEmp = oldEmployeeMap.get(emp.Id);
                    
                    // If the parent lookup value has changed at all
                    if (oldEmp.Tax_Firm__c != emp.Tax_Firm__c) {
                        // Add the old parent if it wasn't null
                        if (oldEmp.Tax_Firm__c != null) {
                            taxFirmIds.add(oldEmp.Tax_Firm__c);
                        }
                    }
                }
            }
        }
        
        // 2. Process complete deletions
        if (oldEmployees != null && newEmployees == null) {
            for (Employee__c oldEmp : oldEmployees) {
                if (oldEmp.Tax_Firm__c != null) {
                    taxFirmIds.add(oldEmp.Tax_Firm__c);
                }
            }
        }
        
        if (taxFirmIds.isEmpty()) {
            return;
        }
        
        // 3. Initialize map with zero-out defaults for all tracked firms
        Map<Id, Tax_Firm__c> taxFirmsToUpdateMap = new Map<Id, Tax_Firm__c>();
        for (Id firmId : taxFirmIds) {
            taxFirmsToUpdateMap.put(firmId, new Tax_Firm__c(
                Id = firmId,
                Max_Salary__c = 0,
                Min_Salary__c = 0
            ));
        }
        
        // 4. Run aggregate query for actual min/max values
        List<AggregateResult> groupedResults = [
            SELECT Tax_Firm__c firmId, MAX(Salary__c) maxSal, MIN(Salary__c) minSal 
            FROM Employee__c 
            WHERE Tax_Firm__c IN :taxFirmIds AND Salary__c != null 
            GROUP BY Tax_Firm__c
        ];
        
        // 5. Populate calculated values, overwriting defaults
        for (AggregateResult ar : groupedResults) {
            Id firmId = (Id)ar.get('firmId');
            Tax_Firm__c firmRecord = taxFirmsToUpdateMap.get(firmId);
            
            firmRecord.Max_Salary__c = (Decimal)ar.get('maxSal');
            firmRecord.Min_Salary__c = (Decimal)ar.get('minSal');
        }
        
        // 6. Perform bulk update
        if (!taxFirmsToUpdateMap.isEmpty()) {
            update taxFirmsToUpdateMap.values();
        }
    }
}



3. Apex Trigger

trigger EmployeeTrigger on Employee__c (after insert, after update, after delete, after undelete) {
    // Route records to handler processing frameworks inside after-commit lifecycle stages
    if (Trigger.isAfter) {
        if (Trigger.isInsert || Trigger.isUndelete) {
            EmployeeTriggerHandler.updateSalaryRollups(Trigger.new, null,null);
        } else if (Trigger.isUpdate) {
            EmployeeTriggerHandler.updateSalaryRollups(Trigger.new, Trigger.oldMap,Trigger.old);
}
else if (Trigger.isDelete) { EmployeeTriggerHandler.updateSalaryRollups(Trigger.old, null,null); } } }

Comments

Popular posts from this blog

Multi currency in Salesforce - Revenue Cloud Advance - Revenue Lifecycle Management

Create the Callout Step in DRO - Salesfroce - Dynamic Revenue Orchestrator