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
Carter85Carter85 

Need help with a Map

I have part of a method which governs record creation for a webservice I'm trying to improve.  The snippet in question is below:
if( contractItemList != null && contractItemList.size() != 0 )
               {
                   // Build Query List
                   List<String> dealerNumList        = new List<String>();
                   List<String> batchNameList        = new List<String>();
                   List<String> productGroupNameList = new List<String>();
                   
                   List<Date> effactiveDates = new List<Date>();
                   List<String> vinNumbers   = new List<String>();

                   for( ContractItem ci : contractItemList )
                   {
                       dealerNumList.add( ci.dealerNum );
                       productGroupNameList.add( ci.productGroup );
                       effactiveDates.add(ci.contract.effective_date__c);
                       vinNumbers.add(ci.contract.vin_number__c);
                   }
                   
                   // select contracts from database for product group,effactive date and vin number
                   
                   List<MG_Contract_Holder__c> existingContracts = [
                                                                        select ID, Name,
                                                                        Vin_Number__c,
                                                                        Product_Group__c,
                                                                        Effective_Date__c,
                                                                        Contract_Number__c
                                                                        from MG_Contract_Holder__c
                                                                        where Vin_Number__c IN:vinNumbers
                                                                        and Effective_Date__c IN:effactiveDates
                                                                        and Product_Group__c IN: productGroupNameList
                                                                        and Contract_Status__c !=:MG_CommonConstant.STATUS_VOID
                                                                    ];
                   Map<String,MG_Contract_Holder__c> existContractsMap = new Map<String,MG_Contract_Holder__c>();                                       
                   for(MG_Contract_Holder__c existingContract : existingContracts)
                   {
                        existContractsMap.put(      existingContract.Vin_Number__c + 
                                                    MG_CommonConstant.PLUS_SEPRATOR + 
                                                    existingContract.Product_Group__c +
                                                    MG_CommonConstant.PLUS_SEPRATOR+
                                                    existingContract.Effective_Date__c ,
                                                    existingContract
                                                );
                   }
                   
                   system.debug('Product Group Name List : '+productGroupNameList);
                                   
                   // Lookup dealer information
                   Map<String,Account>       dealerMap        = new Map<String,Account>();
                   Map<String,MG_Cost__c>    dealerCostMap    = new Map<String,MG_Cost__c>();                   
                   Map<String,MG_Product_Group__c> 
                                             productGroupMap  = new Map<String,MG_Product_Group__c>();                   
                   
                   // Build cache list based on contract items
                   getDealerCache      ( dealerNumList, dealerMap );                   
                   getDealerCostCache  ( dealerNumList, dealerCostMap );
                   getProductGroupCache( productGroupNameList, productGroupMap );

                   // Lookup Batch information by constructing the
                   // Name of the batch of the fly
                   List<MG_Batch__c>       batchList = new List<MG_Batch__c>();
                   Map<String,MG_Batch__c> batchMap  = new Map<String,MG_Batch__c>();
                   
                   Set<String> contractNumbers = new Set<String>();
                   Map<String,MG_Contract_Holder__c> contractHolderMap = new Map<String,MG_Contract_Holder__c>(); 

                   for( ContractItem ci : contractItemList )
                   {
                       // Assign or Create a batch for New Contract
                       Date current = System.today();
                       
                       String batchName = current.year()  + '-' + 
                                          current.month() + '-' +
                                          ci.productGroup + '-' +
                                          dealerMap.get(ci.dealernum).name;                                          
                                
                       System.debug('NEW Batch Name [' + batchName + ']');
                       
                       String dateKey = System.now().format('yyMM');
                       String productPrefix = productGroupMap.get(ci.productGroup).product_prefix__c;
                       
                       String contractNumber =
                                          productPrefix +
                                          dateKey +
                                          ci.contract.Vin_Number__c.substring( ci.contract.Vin_Number__c.length()-6 );
                                          
                       System.debug('New Contract Number' + contractNumber );                   
                       contractNumbers.add(contractNumber);
                       // Fetch dealer cost info
                       String dealerGUID = getDealerGUID( ci, dealerCostMap );
                       system.debug('dealerGUID : '+dealerGUID);
                       system.debug('dealer Cost Map : '+JSON.serialize(dealerCostMap.keySet()));
                       MG_Cost__c dealerCost = dealerCostMap.get( dealerGUID );
                             
                       // Update contract information
                       ci.batchName = batchName;
                       ci.contract.contract_number__c = contractNumber;
                       ci.contract.agent__c           = dealerCost.agent__c;
                                
                       batchNameList.add( batchName );
                   }                        
                   
                   // Search for latest batch
                   try {
                       batchList = [  select id, name, 
                                              product_group__c, 
                                              product_group__r.name,
                                              alias__c 
                                       from MG_Batch__c
                                       where alias__c in :batchNameList ];
                                       
                   } 
                   catch( Exception e ) 
                   {
                       System.debug('EXISTING BATCH NOT FOUND'); 
                   }                                 
                   System.debug('Batch List ' + batchList );
                   
                   // Build Batch Map                  
                   for( MG_Batch__c batch : batchList )
                   {
                      batchMap.put( batch.alias__c, batch );
                   }
                   
                   /*// get existing contract for contract numbers
                   List<MG_Contract_Holder__c> existingContractHolders = getContractHoldersByContractNum(contractNumbers);
                   
                   for(MG_Contract_Holder__c contractHolder : existingContractHolders)
                   {
                       contractHolderMap.put(contractHolder.Contract_Number__c,contractHolder);
                   }*/
                                  
                   // Make sure we found correct dealer
                   Set<String> keySet = new Set<String>();
                   for( ContractItem ci : contractItemList )
                   {
                       
                       String key = ci.contract.Vin_Number__c + 
                                    MG_CommonConstant.PLUS_SEPRATOR + 
                                    ci.productGroup +
                                    MG_CommonConstant.PLUS_SEPRATOR+
                                    ci.contract.Effective_Date__c;
                        system.debug('Key : '+key);
                       // check contract already exist or not
                       if(!existContractsMap.containsKey(key) && keySet.add(key))
                       {
                           // Assign Dealer info                                           
                           ci.contract.Dealer__c = dealerMap.get(ci.dealerNum).id;
                           
                           // Check if new batch exist
                           MG_Batch__c batch = batchMap.get( ci.batchName );
                           
                           if( batch == null )
                           {
                               System.debug('Creating New Batch');
    
                               batch                  = new MG_Batch__c();
                               batch.Alias__c         = ci.batchName;
                               batch.Received_Date__c = System.now().date();
                               batch.Dealer__c        = ci.contract.Dealer__c; 
                               batch.Product_Group__c = productGroupMap.get( ci.productGroup ).id;
                               batch.Insurer__c       = getInsurer( ci, dealerCostMap );
                               batch.Agent__c         = ci.contract.agent__c;
                               if(partnerOID != null)
                               {
                                batch.partner__c       = partnerOID;
                               }
                                                                                     
                               insert batch;
                                                       
                               // Add new batch to map for future use
                               batchMap.put( ci.batchName, batch );
                           }
                           
                           // Assign contract id to batch                                          
                           ci.contract.batch__c = batch.id;
                           
                           // Build new Contract Holder List to insert
                           //if(!contractHolderMap.containsKey(ci.contract.contract_number__c))
                           //{
                                contractHolderList.add( ci.contract );
                           //}
                       }
                       else
                       {
                           String contractNumber = ci.contract.contract_number__c;
                           if(existContractsMap.containsKey(key))
                           {
                               MG_Contract_Holder__c existContractHolder = existContractsMap.get(key);
                               contractNumber = existContractHolder.contract_number__c;
                           }
                           Datetime effectiveDate = datetime.newInstance(ci.contract.Effective_Date__c.year(), ci.contract.Effective_Date__c.month(),ci.contract.Effective_Date__c.day()) ;
                               errorList.add('Contract (['+ci.contract.Vin_Number__c+'] ['+ci.productGroup+'] ['+effectiveDate.format('MM/dd/yyyy')+']) has already been submitted under contract number '+contractNumber+'. You need to void the initial contract before submitting this one or, if you think this is in error, please call us for assistance.');
                       }
                   }
It works for the most part as intended.  However, I'd like for the validation to also look for effective dates similar to the one which has been included in the record trying to be created.  At the moment all it does is block records where the effective eate exactly matches an existing record, but will let others through, and I'm a bit stuck on how to get that right.  I'm open to also removing the date filter from consideration entirely since the only important factors are really the VIN number and Product Groups, but I haven't been able to do that successfully either.