Requirement : There is rollup (Sum) between opportunity and opportunitylineitem. Insert and update event is working fine but for delete event is not working correct.
I have one opportunity and one opportunitylineitem amount of 25k$ and its sum also showing on opportunity custom field which is Total OLI see below image.
After delete the opportunitylineitem the value of Total OLI on Opportunity should be 0 but its not refelecting its showing last oppotunitylineitem value. see below image
------------------Trigger code--------------------------------
trigger OppProductPrice on OpportunityLineItem (After delete) {
if(Trigger.isDelete ){
OpportunityPriceHandler.performDelete(Trigger.old);
}
}
----------------Handler Code------------------------
public class OpportunityPriceHandler{
public set<Id> OppId = new set<Id>();
public static void performDelete( LIst<OpportunityLineItem>oldValue ){
if( oldValue.size() > 0 ){
set<Id> OppId = new set<Id>();
for( OpportunityLineItem item : oldValue ){
OppId.add( item.opportunityId );
}
List<Opportunity> opList = new List<Opportunity>();
List<AggregateResult> result = [Select OpportunityId, Sum(TotalPrice) TP From OpportunityLineItem where OpportunityId IN : OppId and OpportunityId != null Group By OpportunityId];
for(AggregateResult ar : result){
id str = (ID)ar.get('OpportunityId');
if(str != null){
Opportunity op = new Opportunity(id = str);
op.lightning_vip__Total_OLI__c = (Decimal)ar.get('TP');
opList.add(op);
}
}
if(opList != null){
update opList;
}
}
}
}
aggr result
is empty as you have deleted the OLI for that Opp and no OLI so it will not go in the for loop and hence it won't have any value and it will persist the old value. If you try to add 2 OLI and delete 1 it will work. So you need to check if the result is empty make theTotal_OLI to zero