Make Sum of grand child field and show it on Parent record

aggregateresultapextrigger

my requirement is whenever OpportunityLineItem Created makes the sum of quantity available for Opportunity and also take care of rest of Opportunity for particular Account and update Total Sales Quantity.

Here is the code I'm Coming up with.

**Can Someone suggest any other Linear Way or my Code is fine?**

public class OpportunityLineItemHandler {
    public static void getTotalSalesQuantity(List<OpportunityLineItem> newOpportunityLineItemList){
        Set<Id> ParentOppIdsSet = new Set<Id>();
        for(OpportunityLineItem objOppLine : newOpportunityLineItemList){
            ParentOppIdsSet.add(objOppLine.OpportunityId);
        }
        Map<Id,Decimal> NoOfOpportunityQuantity = new Map<Id,Decimal>();
        for(AggregateResult ar : [SELECT OpportunityId,SUM(Quantity)sumOfQuantity FROM OpportunityLineItem GROUP BY OpportunityId ]){
            NoOfOpportunityQuantity.put( (Id)ar.get('OpportunityId') , (Decimal)ar.get('sumOfQuantity') );
        }
        
        Set<Id> grandParentAccount = new Set<Id>();
        for(Opportunity oppObj : [SELECT Id,AccountId FROM Opportunity WHERE Id IN : ParentOppIdsSet]){
            
             grandParentAccount.add(oppObj.AccountId);
        }
        List<Account> accountsToBeupdated = new List<Account>();
        for(Account objAcc : [SELECT Id, Total_Sales_Quantity__c,(SELECT Id FROM Opportunities) FROM Account WHERE Id IN : grandParentAccount]){
            Decimal totalSalesbyAccountId = 0;
            for(Opportunity objOpp : objAcc.Opportunities){
                if(NoOfOpportunityQuantity.containsKey(objOpp.Id)){
                    totalSalesbyAccountId = totalSalesbyAccountId + NoOfOpportunityQuantity.get(objOpp.Id);
                }
            }
            objAcc.Total_Sales_Quantity__c = totalSalesbyAccountId;
            accountsToBeupdated.add(objAcc);
        }
        update accountsToBeupdated;
    }
}

Best Answer

In your particular use case, the easiest thing to do is:

  • Define a RSF field Opportunity.Quantity__c thats rolls up OpportunityLineItem.Quantity
  • Define a RSF field Account.AllOpportunityQuantity__c that sums Opportunity.Quantity__c

No Apex code involved

Should you have lookup relationships to sum over, use the free open source packages which are widely used:

Related Topic