function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sunny Solanki 11Sunny Solanki 11 

Delete Trigger code not working

Hi Guys, 

I have following Trigger code which is working fine during add but during an update or (especially) deletes it is not updating "invveh.Number_of_Current_Investors__c" value. I think it is because "if(numofcurrentinvestorsMap.containsKey(id))" statement.
Also attaching test class, hope this will help. After delete record in test class assertion failing to validate "TestInvestmentVehicle1[0].Number_of_Current_Investors__c".

 I need your expert advice to fix this code.  
 
trigger InvestorPositionTrigger on Investor_Position__c (after insert, after update, after delete) {

Set<Id> numofhistinvestors = new Set<Id>(); 
Set<Id> numofcurrentinvestors = new Set<Id>(); 
Set<Id> InvestmentVehicleIds = new Set<Id>(); 

List<Investment_Vehicle__c> lstUpdateInvVehicle = new List<Investment_Vehicle__c>();

if(trigger.isafter)
{
    //if(RecursiveHandler.flag)
    //{
       // RecursiveHandler.flag = false;
        if(trigger.isinsert || trigger.isupdate)
        {
            
                for(Investor_Position__c inv : Trigger.New)
                {
                    InvestmentVehicleIds.add(inv.Investment_Vehicle__c);
                }    
        }   
        if(trigger.isdelete)
        {
            
                for(Investor_Position__c inv : Trigger.old)
                {
                    InvestmentVehicleIds.add(inv.Investment_Vehicle__c);
                }    
        }       
       
       /*************************************************************************************
       *  Begaining of SOQL 101 issue fix code  
       ************************************************************************************/
        Map<String,Integer> numofcurrentinvestorsMap = new Map<String,Integer>();
        Map<String,Integer> numofhistinvestorsMap = new Map<String,Integer>();

        for( Investor_Position__c obj : [Select Id,Investor_Position_Account__c,Is_Active__c, Current_Commitments_Functional__c, Source_of_Capital__c,
                                        Investment_Vehicle__r.Id, Investment_Vehicle__r.Number_of_Current_Investors__c, Investment_Vehicle__r.Number_of_Historical_Investors__c
                                        from Investor_Position__c where Investment_Vehicle__r.Id IN:InvestmentVehicleIds])
        {
            
            if(obj.Is_Active__c == TRUE && obj.Source_of_Capital__c != null)
            {                       
            
                if(obj.Current_Commitments_Functional__c > 0 && (obj.Source_of_Capital__c.contains('Limited Partners') || obj.Source_of_Capital__c.contains('Operating Partner')))
                {
                    if(numofcurrentinvestorsMap!=null && numofcurrentinvestorsMap.containsKey(obj.Investment_Vehicle__r.Id)){
                        numofcurrentinvestorsMap.put(obj.Investment_Vehicle__r.Id,numofcurrentinvestorsMap.get(obj.Investment_Vehicle__r.Id)+1);
                    }else{
                        numofcurrentinvestorsMap.put(obj.Investment_Vehicle__r.Id,1);
                    }
                    //numofcurrentinvestors.add(obj.Investor_Position_Account__c);  
                }
                if(obj.Source_of_Capital__c.contains('Limited Partners') || obj.Source_of_Capital__c.contains('Operating Partner'))
                {
                    if(numofhistinvestorsMap!=null && numofhistinvestorsMap.containsKey(obj.Investment_Vehicle__r.Id)){
                        numofhistinvestorsMap.put(obj.Investment_Vehicle__r.Id,numofhistinvestorsMap.get(obj.Investment_Vehicle__r.Id)+1);
                    }else{
                        numofhistinvestorsMap.put(obj.Investment_Vehicle__r.Id,1);
                    }
                    //numofhistinvestors.add(obj.Investor_Position_Account__c); 
                }
            }                   
        }
        System.debug('Map numofcurrentinvestorsMap: ' + numofcurrentinvestorsMap.size());
        System.debug('Map numofhistinvestorsMap: ' + numofhistinvestorsMap.size());
         System.debug('Map numofcurrentinvestorsMap: ' + numofcurrentinvestorsMap);
        System.debug('Map numofhistinvestorsMap: ' + numofhistinvestorsMap);            
        for(Id id : InvestmentVehicleIds)
        {    
            Investment_Vehicle__c invveh = new Investment_Vehicle__c();
            invveh.Id = id;
            if(numofhistinvestorsMap.containsKey(id)){
                invveh.Number_of_Historical_Investors__c = numofhistinvestorsMap.get(id);
                 System.debug('invveh.Number_of_Historical_Investors__c: ' + invveh.Number_of_Historical_Investors__c);
            }
            
            if(numofcurrentinvestorsMap.containsKey(id)){
                invveh.Number_of_Current_Investors__c = numofcurrentinvestorsMap.get(id);
                 System.debug('invveh.Number_of_Current_Investors__c: ' + invveh.Number_of_Current_Investors__c);
            }
            
            lstUpdateInvVehicle.add(invveh);
             System.debug('invveh.Number_of_Historical_Investors__c: ' + invveh);
            //numofcurrentinvestors.clear();
            //numofhistinvestors.clear();
        }  
        System.debug('lstUpdateInvVehicle : ' + lstUpdateInvVehicle.size());
       
       /*************************************************************************************
       *  SS: 7/18/18 - End of SOQL 101 issue fix code  
       ************************************************************************************/
        try
        {
            if(lstUpdateInvVehicle.size() > 0)
            {
                update lstUpdateInvVehicle; 
            }
                
        }
        catch(exception ex)
        {
            for (Investor_Position__c obj : trigger.new) 
            {         
                obj.addError(ex.getmessage());        
            } 
        }      
    //}   
    
}

    if(Trigger.isInsert){
        ConfigurableRollup.rollup(trigger.new);
    }
    if(Trigger.isUpdate){
        system.debug('when is update------');
        ConfigurableRollup.rollup(trigger.new, Trigger.OldMap);
    }
    if(Trigger.isDelete){
        ConfigurableRollup.rollup(trigger.old);
    }
}
Test Class: 
@isTest(SeeAllData=false)
private class Test_InvestorPositionTrigger {
        
    static testMethod void myUnitTest() {
    	
       		Account account = new Account(Name='Test' );
    		insert account;
    		Account account1 = new Account(Name='Test1' );
    		insert account1;
    		Investment_Vehicle__c invvehicle = new Investment_Vehicle__c(Name='TestInvestmentVehicle');
    		insert invvehicle;
        //SS: 7/18/18 added following line of code for code coverage
        Opportunity opt = new Opportunity(Name = 'NewTestOpportunity', StageName ='2 - Initiated General Contact', CloseDate = system.today() , Investment_Vehicle__c = invvehicle.id, AccountId = account.id,  Consultant__c = account.id  );
        insert opt;
        //Opportunity opt1 = new Opportunity(Name = 'NewTestOpportunity1', StageName ='2 - Initiated General Contact', CloseDate = system.today() , Investment_Vehicle__c = invvehicle.id, AccountId = account.id,  Consultant__c = account.id  );
        //insert opt1;
    		Investor_Position__c invposition = new Investor_Position__c(As_of__c= System.Today() - 89 , Current_Commitments_Functional__c = 100000, Investor_Position_Account__c = account.Id, Investment_Vehicle__c = invvehicle.Id, Name='TestInvestorPosition', Source_of_Capital__c = 'Operating Partner', Is_Active__c=true, Opportunity_Name__c = opt.id);
    		insert invposition;
    		Investor_Position__c invposition1 = new Investor_Position__c(As_of__c= System.Today() -89 , Investor_Position_Account__c = account1.Id, Investment_Vehicle__c = invvehicle.Id, Name='TestInvestorPosition', Source_of_Capital__c = 'Operating Partner', Is_Active__c=true, Opportunity_Name__c = opt.id);
    		insert invposition1;
        //SS: 7/18/18 end of the change.
        test.startTest();
        
        //SS: 7/18/18 updated following line of code : From: As_of_Last_quater_text__c TO: As_of_Is_last_quater__c
        List<Investor_Position__c> InvPositionlst = [Select Id,As_of_Is_last_quater__c,As_of__c from Investor_Position__c where Investment_Vehicle__c =: invvehicle.Id];
        for(Investor_Position__c inv : InvPositionlst)
        {
        	 System.debug( 'test2323' + inv.As_of_Is_last_quater__c);
        	 System.debug('test2323' + inv.As_of__c);
       }
       system.debug('Test Investment Positions: ' + InvPositionlst.size());
        // SS: 7/18/18 end of change. 
        System.assertequals(InvPositionlst.size(),2);
      
       List<Investment_Vehicle__c> TestInvestmentVehicle = [Select Number_of_Historical_Investors__c, Number_of_Current_Investors__c from Investment_Vehicle__c where Id =: invvehicle.Id];
      System.assertequals(TestInvestmentVehicle.size(),1);
      //
      System.debug('....Historical Investor -1 .......'+TestInvestmentVehicle[0].Number_of_Historical_Investors__c);
      System.debug('....Current Investor -1 .......'+TestInvestmentVehicle[0].Number_of_Current_Investors__c);
       //
     	System.assertequals(TestInvestmentVehicle[0].Number_of_Historical_Investors__c,2);
       System.assertequals(TestInvestmentVehicle[0].Number_of_Current_Investors__c,1); 
       
       delete invposition;
       
         List<Investment_Vehicle__c> TestInvestmentVehicle1 = [Select Number_of_Historical_Investors__c, Number_of_Current_Investors__c from Investment_Vehicle__c where Id =: invvehicle.Id];
      System.assertequals(TestInvestmentVehicle1.size(),1);
      System.debug('....Historical Investor -2 .......'+TestInvestmentVehicle1[0].Number_of_Historical_Investors__c);
      System.debug('....Current Investor -2 .......'+TestInvestmentVehicle1[0].Number_of_Current_Investors__c);
     	System.assertequals(TestInvestmentVehicle1[0].Number_of_Historical_Investors__c,1);
      System.assertequals(TestInvestmentVehicle1[0].Number_of_Current_Investors__c,0);
       
       
        
        test.stopTest();

    }
   
    
}


 
Best Answer chosen by Sunny Solanki 11
Sunny Solanki 11Sunny Solanki 11
Thank you to these users who has invested time to isolate my issue. 

I have found the solution. Code working fine when you have multiple records it will update count correctly for Historical Investor and Current Investor. The situation comes when Map is null it will not execute the IF statement (# 073 and # 078) and the result will remind as the last iteration which means 1 every time.

Added ELSE statement as below to fix this issue.
 
if(numofhistinvestorsMap.containsKey(id)){
                invveh.Number_of_Historical_Investors__c = numofhistinvestorsMap.get(id);
                 System.debug('invveh.Number_of_Historical_Investors__c: ' + invveh.Number_of_Historical_Investors__c);
            } else {
                invveh.Number_of_Historical_Investors__c = 0;
            }
            
            if(numofcurrentinvestorsMap.containsKey(id)){
                invveh.Number_of_Current_Investors__c = numofcurrentinvestorsMap.get(id);
                 System.debug('invveh.Number_of_Current_Investors__c: ' + invveh.Number_of_Current_Investors__c);
            }else {
                invveh.Number_of_Current_Investors__c = 0;
            }