Back to Top

In Salesforce, each Account can have multiple Opportunities associated with it. We need to calculate and store the Total Closed-Won Opportunity Amount for each Account in a custom field called Total_Closed_Won_Amount__c

This field should be updated whenever any Opportunity is:

  1. Inserted (new Opportunity created)
  2. Updated (Stage changes to or from "Closed Won", or the Amount changes)
  3. Deleted (Opportunity is deleted)
  4. Undeleted (Opportunity is restored from the Recycle Bin)

trigger OpportunityTrigger on Opportunity (
    after insert, after update, after delete, after undelete
) {
    if (Trigger.isAfter) {
        OpportunityTriggerHandler.updateAccountTotals(
            Trigger.new,
            Trigger.oldMap
        );
    }
}


public class OpportunityTriggerHandler {

    public static void updateAccountTotals(
        List<Opportunity> newList,
        Map<Id, Opportunity> oldMap
    ) {
        Set<Id> accountIds = new Set<Id>();

        if (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) {
            for (Opportunity opp : newList) {
                if (opp.AccountId != null) {
                    accountIds.add(opp.AccountId);
                }
            }
        }

        if (Trigger.isUpdate || Trigger.isDelete) {
            for (Opportunity opp : oldMap.values()) {
                if (opp.AccountId != null) {
                    accountIds.add(opp.AccountId);
                }
            }
        }

        if (accountIds.isEmpty()) return;

        // 🔥 Aggregate Query
        Map<Id, Decimal> accountToTotalMap = new Map<Id, Decimal>();

        for (AggregateResult ar : [
            SELECT AccountId accId, SUM(Amount) totalAmount
            FROM Opportunity
            WHERE AccountId IN :accountIds
            AND StageName = 'Closed Won'
            GROUP BY AccountId
        ]) {
            accountToTotalMap.put(
                (Id) ar.get('accId'),
                (Decimal) ar.get('totalAmount')
            );
        }

        List<Account> accountsToUpdate = new List<Account>();

        for (Id accId : accountIds) {
            accountsToUpdate.add(new Account(
                Id = accId,
                Total_Closed_Won_Amount__c =
                    accountToTotalMap.containsKey(accId)
                    ? accountToTotalMap.get(accId)
                    : 0
            ));
        }

        if (!accountsToUpdate.isEmpty()) {
            update accountsToUpdate;
        }
    }
}


Other Common Trigger Scenarios Using Aggregate Query


Count of Contacts on Account:
    
SELECT AccountId, COUNT(Id)
FROM Contact
GROUP BY AccountId


Average Case Resolution Time per Account

SELECT AccountId, AVG(Resolution_Time__c)
FROM Case
GROUP BY AccountId

Total Order Amount on Customer:

SELECT Customer__c, SUM(Order_Amount__c)
FROM Order__c
GROUP BY Customer__c

Can we use if (Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete) in handler?

Ans: If your handler method is called directly from a trigger, then the Trigger context variables are still available inside the handler.

It will NOT work if:

  • The handler is called from:

    • Batch Apex

    • Queueable

    • Future method

    • Anonymous Apex

    • Unit test calling the handler directly

Can we use Trigger.isInsert inside a handler class?

Ans: Yes, technically it works if the handler is invoked from a trigger.
However, for testability, reusability, and clean architecture, it’s best practice to pass the trigger context explicitly instead of relying on Trigger.isInsert inside the handler.

0comments

Post a Comment