Sunday, September 13, 2015

Rollup summary for lookup relationship

trigger Rollup on Concur_Reports__c (after insert, after delete, after undelete,after update) {
boolean delflag=false;
Set<Id> crids=new Set<Id>();


Map<Id,List<Concur_Reports__c>> rollup=new Map<Id,List<Concur_Reports__c>>();
List<id> opplist= new List<id>();

if(Trigger.isInsert || Trigger.isUndelete || Trigger.isUpdate ){
For(Concur_Reports__c  con1 : Trigger.new){
crids.add(con1.id);
opplist.add(con1.Opportunity__c);
 if(rollup.containsKey(con1.Opportunity__c)){
rollup.get(con1.Opportunity__c).add(con1);
 }
else{
rollup.put(con1.Opportunity__c,new list<Concur_Reports__c>{con1});
}
}
}
 else if(Trigger.isDelete){
 delflag=True;
 For(Concur_Reports__c con1 : Trigger.old){
crids.add(con1.id);
opplist.add(con1.Opportunity__c);
if(rollup.containsKey(con1.Opportunity__c)){
rollup.get(con1.Opportunity__c).add(con1);
 }
else{
rollup.put(con1.Opportunity__c,new list<Concur_Reports__c>{con1});
}
}
}


    


    system.debug('%%%%%%%%%%%%%%%%%%%%%%%%%%'+rollup);


    List<Opportunity> OppUpdateList = New List<Opportunity>() ;


     Map<Id,Opportunity> oppidsfilter=new  Map<Id,Opportunity>([SELECT AccountId,Total_Expense__c,Amount,CampaignId,CloseDate,CreatedById,CreatedDate,CurrentGenerators__c,DeliveryInstallationStatus__c,Description,develoepername__c,ExpectedRevenue,Expense__c,Id,IsClosed,IsDeleted,IsPrivate,IsWon,LastActivityDate,LastModifiedById,LastModifiedDate,LastReferencedDate,LastViewedDate,LeadSource,MainCompetitors__c,Name,NextStep,OrderNumber__c,OwnerId,Pricebook2Id,Probability,RecordTypeId,StageName,SystemModstamp,TotalOpportunityQuantity,TrackingNumber__c,Type FROM Opportunity where id in:opplist]);


   Integer total;


   if(rollup.keyset()!=Null)


   {


  for(Id ids:rollup.keyset())


  {


  total=0;


   List<Concur_Reports__c> cr3=rollup.get(ids);


   Opportunity oppr=oppidsfilter.get(ids);


  


   for(Concur_Reports__c cr4:cr3)


   {
   total=total+Integer.valueof(cr4.ReportTotal__c);


    system.debug('%%%%%%%%%%total%%%%%%%%%%%%'+total);


   }

   if(oppr!=Null){
 if(delflag!=True){
oppr.Expense__c=oppr.Expense__c+total;

  }

  else{

   oppr.Expense__c=oppr.Expense__c-total;


  }


  OppUpdateList.add(oppr);


   system.debug('%%%%%%%%%%OppUpdateList%%%%%%%%%%%%'+OppUpdateList);


    }


  }

try{
    if(OppUpdateList.size()>0){


    Update OppUpdateList;


} else  {

}


}


catch(exception ex){
}


}




 }


No comments:

Post a Comment