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
Jake BullardJake Bullard 

Help with some code, Apex class not running when I think it should.

Hey guys I have an issue I'm hoping you can help with. I'm a little new to Apex but figuring it out (I think). I have a really awesome unmanaged package that assigns leads/cases (link) and it works great on the lead but I wanted to use it on a custom object. So I thought now problem, I'll just add a trigger for the custom object and modify the other bits to work. 

So I built the trigger and it works great and at the end it calls an apex class which should finish off what the trigger started. But the weird thing is the apex class returns nothing in to SOQL query. However when the trigger is hit again (to assign another record) the SOQL query runs and finds the previous record. It's like the apex class SOQL query is running before the trigger finishes updating. The lead assignment works in the same way and has no issues.

My questions are: 

1. Why is this happening? 

2. Why did the orginal developer build it this way? Why have the seperate APEX class? Couldn't it all be done within the trigger? Just wondering for the sake of learning. 


Here is the orginal trigger: 

 

trigger FireLeadDistribution on Lead (before insert, before update) {
    
Set<String> setLeadcriteria= new Set<String>();    
    for ( Lead objLead : Trigger.new)  {        
        setLeadcriteria.add(objLead.distributionValue__c);
    }

    Map<Id, Receiver__c>updtReceivers = new Map<Id,Receiver__c>();
    Map<Id, Distributor__c>updtDistributors = new Map<Id,Distributor__c>();
    List<Id> leadIds = new LIst<Id>();
  
    Receiver__c[] receiver = [SELECT name,distributor__r.distributioncount__c,distributorstatus__c, id,relateduser__c ,
    distributionValue__c, recordsreceived__c,LastDistributionTime__c,distributor__r.sumofquotas__c,
    first__c,last__c,position__c FROM Receiver__c WHERE distributionValue__c =: setleadcriteria 
    AND Status__c = 'Active' AND UserStatus__c = 'OK' AND DistributorStatus__c = 'Active' AND distributorObject__c = 'Lead'
    ORDER BY distributionValue__c, position__c LIMIT 1000];
        
    for(Lead lid : trigger.new){
       
        if(lid.distributionValue__c != null && lid.isDistributed__c == false && lid.isconverted == false ){
            for(integer i=0;i< receiver.size();i++){ // loop through receivers
                if(lid.distributionValue__c == receiver[i].distributionValue__c){
                 
                    Integer leadCount = integer.valueof(receiver[i].distributor__r.distributioncount__c);                  
                    Integer quotasSum = integer.valueof(receiver[i].distributor__r.sumofquotas__c);      
                    Integer remainder = math.mod(leadCount , quotasSum );
                    
                   
                   if(remainder >= receiver[i].first__c && remainder <= receiver[i].last__c ){ 
                                        
                       receiver[i].recordsreceived__c = receiver[i].recordsreceived__c+1;
                       receiver[i].distributor__r.distributioncount__c = receiver[i].distributor__r.distributioncount__c+1;

                       receiver[i].LastDistributionTime__c = system.now();

                       lid.receiverID__c = receiver[i].relateduser__c ;
                       lid.isDistributed__c = true ;
                       leadids.add(lid.id);
                                              
                       updtReceivers.put(receiver[i].id, receiver[i]);
                       updtDistributors.put(receiver[i].Distributor__c,receiver[i].distributor__r); 
                       
                       break;
                   }
                }
                
                              
            }//end for "i"
        }    
    }// end for "lid"
    if(updtReceivers.size()>0){
        update updtReceivers.values();
    }
    if(updtDistributors.size()>0){
        update updtDistributors.values();
    }
    if(leadids.size()>0){
        DistributorsAssignment.LeadAssignment(leadids);  
    }   
}


Here is my trigger:

trigger FireOrderItemDistributionPreflight on Order_Item__c (before insert, before update) {

Set<String> setOrderItemcriteria= new Set<String>();    
    for ( Order_Item__c objOrderItem : Trigger.new)  {        
        setOrderItemcriteria.add(objOrderItem.PreflightDistributionValue__c);
    }

    Map<Id, Receiver__c>updtReceivers = new Map<Id,Receiver__c>();
    Map<Id, Distributor__c>updtDistributors = new Map<Id,Distributor__c>();
    List<Id> itemids = new List<Id>();
  
    Receiver__c[] receiver = [SELECT name,distributor__r.distributioncount__c,distributorstatus__c, id,relateduser__c ,
    distributionValue__c, recordsreceived__c,LastDistributionTime__c,distributor__r.sumofquotas__c,
    first__c,last__c,position__c FROM Receiver__c WHERE DistributionValue__c =: setOrderItemcriteria
    AND Status__c = 'Active' AND UserStatus__c = 'OK' AND DistributorStatus__c = 'Active' AND distributorObject__c = 'Order Item'
    ORDER BY distributionValue__c, position__c LIMIT 1000];
        
    for(Order_Item__c oid : trigger.new){
       
        if(oid.PreflightDistributionValue__c != null && oid.isPreflightDistributed__c == false ){
            for(integer i=0;i< receiver.size();i++){ // loop through receivers
                if(oid.PreflightDistributionValue__c == receiver[i].distributionValue__c){
                 
                    Integer OrderItemCount = integer.valueof(receiver[i].distributor__r.distributioncount__c);                  
                    Integer quotasSum = integer.valueof(receiver[i].distributor__r.sumofquotas__c);      
                    Integer remainder = math.mod(OrderItemCount , quotasSum );
                    
                   
                   if(remainder >= receiver[i].first__c && remainder <= receiver[i].last__c ){ 
                                        
                       receiver[i].recordsreceived__c = receiver[i].recordsreceived__c+1;
                       receiver[i].distributor__r.distributioncount__c = receiver[i].distributor__r.distributioncount__c+1;

                       receiver[i].LastDistributionTime__c = system.now();

                       oid.PreflightReceiverID__c = receiver[i].relateduser__c ;
                       oid.isPreflightDistributed__c = true ;
                       itemids.add(oid.id);
                       
                       updtReceivers.put(receiver[i].id, receiver[i]);
                       updtDistributors.put(receiver[i].Distributor__c,receiver[i].distributor__r); 
                       
                       break;
                   }
                }
                
                              
            }//end for "i"
        }    
    }// end for "Oid"
    if(updtReceivers.size()>0){
        update updtReceivers.values();
    }
    if(updtDistributors.size()>0){
        update updtDistributors.values();
    }
    if(itemids.size()>0){
        DistributorsAssignment.ItemPreflightAssignment(itemids);  
    }   
}

Here is the class they both trigger:

public with sharing class DistributorsAssignment {
    @future 
    public static void LeadAssignment(list<id> leadids ) {
    
        List<Lead> assignWithoutNotif = new List<Lead>();
        
        Database.DMLOptions dloNoNotif = new Database.DMLOptions();           
        dloNoNotif.EmailHeader.triggerUserEmail = false;    
        dloNoNotif.EmailHeader.triggerOtherEmail = false;    
     
        for(Lead lidz : [SELECT Id,ownerid, receiverID__c FROM Lead WHERE isdistributed__c = true AND receiverID__c != NULL]){

                lidz.OwnerId = lidz.receiverID__c ; 
                lidz.receiverID__c = NULL;
                                     
                lidz.setOptions(dloNoNotif); 
                assignWithoutNotif.add(lidz);
            
        }  
       if(assignWithoutNotif.size()>0){          
            database.update(assignWithoutNotif ,dloNoNotif);
        }
        
    }
    public static void CaseAssignment(list<id> Caseids ) {
    
        List<Case> assignWithoutNotif = new List<Case>();

        
        Database.DMLOptions dloNoNotif = new Database.DMLOptions();           
        dloNoNotif.EmailHeader.triggerUserEmail = false;    
        dloNoNotif.EmailHeader.triggerOtherEmail = false;    
      
        for(Case kasz : [SELECT Id,ownerid, receiverID__c FROM Case WHERE isdistributed__c = true AND receiverID__c != NULL]){

                kasz.OwnerId = kasz.receiverID__c ; 
                kasz.receiverID__c = '';

                kasz.setOptions(dloNoNotif); 
                assignWithoutNotif.add(kasz);
           
        }  
        if(assignWithoutNotif.size()>0){          
            database.update(assignWithoutNotif ,dloNoNotif);
        }
       
    }
	public static void ItemPreflightAssignment(list<id> itemIds ) {
    
        List<Order_Item__c> assignWithoutNotif = new List<Order_Item__c>();
            
		Database.DMLOptions dloNoNotif = new Database.DMLOptions();           
        dloNoNotif.EmailHeader.triggerUserEmail = false;    
        dloNoNotif.EmailHeader.triggerOtherEmail = false;
     
        for(Order_Item__c oidz : [SELECT Id,Preflighter__c, PreflightReceiverID__c FROM Order_Item__c WHERE isPreflightDistributed__c = true AND PreflightReceiverID__c != NULL]){

                oidz.Comments__c = 'test' ;
            	oidz.Preflighter__c = oidz.PreflightReceiverID__c ;
                oidz.PreflightReceiverID__c = NULL;
				
				oidz.setOptions(dloNoNotif); 
                assignWithoutNotif.add(oidz);
            
        }
		if(assignWithoutNotif.size()>0){          
            database.update(assignWithoutNotif ,dloNoNotif);
        }
        
    }
    
	public static void ItemSenderAssignment(list<id> Itemids ) {
    
        List<Order_Item__c> assignWithoutNotif = new List<Order_Item__c>();

     
        for(Order_Item__c Oidz : [SELECT Id,Sender__c, SenderReceiverID__c FROM Order_Item__c WHERE isSenderDistributed__c = true AND SenderReceiverID__c != NULL]){

                Oidz.Sender__c = Oidz.SenderReceiverID__c ; 
                Oidz.SenderReceiverID__c = NULL;

            
        }
        
    }
    
}
Jake BullardJake Bullard
Here is a debug log as well: https://docs.google.com/document/d/1EY7-Mgd1UMrhsvh_a4Ka7xu5gSpTLJHERxjjO4kq4I4/edit?usp=sharing