Search Here

Scenario 5: You need to ensure that a custom ‘Total Revenue’ field on Account is always the sum of all related Opportunities’ ‘Amount’ fields. How would you implement this?

 This would involve writing an ‘after insert’, ‘after update’, and ‘after delete’ trigger on the Opportunity object. After any of these operations, the trigger would recalculate the total revenue for the related Account based on the sum of the Amount fields of its Opportunities and update the ‘Total Revenue’ field accordingly.


trigger UpdateAccountRevenue on Opportunity (after insert, after update, after delete, after undelete) {

Set<Id> accountIds = new Set<Id>();


// Collect Account IDs from the Opportunities in the trigger context

if(Trigger.isInsert || Trigger.isUpdate || Trigger.isUndelete){

for(Opportunity opp : Trigger.new){

accountIds.add(opp.AccountId);

}

}

if(Trigger.isUpdate || Trigger.isDelete){

for(Opportunity opp : Trigger.old){

accountIds.add(opp.AccountId);

}

}


// Aggregate the total revenue for each Account

Map<Id, Decimal> accountRevenues = new Map<Id, Decimal>();

for(AggregateResult ar : [SELECT AccountId, SUM(Amount) totalRevenue FROM Opportunity WHERE AccountId IN :accountIds AND IsClosed = false AND IsWon = true GROUP BY AccountId]){

accountRevenues.put((Id)ar.get(‘AccountId’), (Decimal)ar.get(‘totalRevenue’));

}


// Update the Accounts with the new Total Revenue

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

for(Id accId : accountIds){

accountsToUpdate.add(new Account(Id = accId, Total_Revenue__c = accountRevenues.get(accId)));

}

update accountsToUpdate;

}


In this scenario, the trigger ensures that every time an Opportunity is created, updated, deleted, or undeleted, the ‘Total Revenue’ on the related Account is recalculated to reflect the current sum of all related Opportunities’ ‘Amount’ fields. This maintains accurate financial data on the Account record in real-time.

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.