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
cool_codingcool_coding 

Duplicate id in list

Can anyone help me for fixing this error please, Duplicate id in a list. Below is my piece of code. The error is occurring when I am trying to update this list: cddListUpdate.add(cdd);
 
global class Batch_ApplicationDesPrix4 implements Database.Batchable<sObject>, Database.AllowsCallouts, Database.Stateful {
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        
        /*Etape 1 : Récupérer l'ensemble des enregistrements suivis TDM qui répondent aux critères suivants : 
        
            > Application des prix : Décoché 
            > Traitemement = Reconduction ou révision ou Reconduction avant révision 
            > Etape = Terminé            
            Sur la PC renseignée dans le champ Réf PC, il faut que : 
            Date du jour - 7 < Date de fin de prestation < Date du jour           
            Et            
            Statut = Signée - Validée 
        */
        String query = null;

        Set<String> traitementSet = new Set<String>{'Reconduction', 'Reconduction avant révision'};
       // Date BelowRange = Date.Today().addDays(-7);
        //Date todayDate = Date.today();
        
        query = 'SELECT Id';
        query += ', Traitement__r.Name, Ref_PC__r.Date_fin_prestation__c';
        query += ', Ref_PC__c, ID_Simulation__c,Ref_PC__r.Simulation_Offre__c';
        query += ' FROM Suivi_TDM__c';
        query += ' WHERE Application_des_prix__c = false';
        query += ' AND Etape__c = \'Terminé\'';
        query += ' AND Traitement__r.Name =: traitementSet';        
        query += ' AND Ref_PC__r.StageName = \'Signée - validée\'';
       // query += ' AND Ref_PC__r.Date_fin_prestation__c > BelowRange';
       // query += ' AND Ref_PC__r.Date_fin_prestation__c < todayDate';
      
        System.debug(query);
        
        return Database.getQueryLocator(query);
      
    }

    global void execute(Database.BatchableContext BC, List<Suivi_TDM__c> aStdList){   
        try{
            
        Set<Id> oppIdSet = new Set<Id>();
        map<id,opportunity> oppToUpdateMap = new map<id,opportunity> ();
        map<id,Simulations__c> simToUpdateMap = new map<id,Simulations__c> ();
        Date BelowRange = Date.Today().addDays(-7);
        system.debug('cddList values'+BelowRange);
		List<Collectes_des_donnees__c> cddListUpdate = new List<Collectes_des_donnees__c>();
		List<Sollicitation__c> sollicitationListUpdate = new List<Sollicitation__c>();
		List<opportunity> oppListUpdate = new List<opportunity>();
		Map<Id, CallOut_Statut_Traitement> mapObjectStatutTrt = new Map<Id, CallOut_Statut_Traitement>();
        Map<Id, Id> objectIdEchangeIdMap = new Map<Id, Id>();
        FeedItem post = new FeedItem();

       /*Etape 2 : Constituer une liste de l'ensemble des PC contenues dans le 
       champ "Réf PC" des Suivi TDM répondant aux critères ci-dessus */

        for(Suivi_TDM__c std : aStdList){
            system.debug('testinf code1');  
			
            if(std.Ref_PC__r.Date_fin_prestation__c > BelowRange
               && std.Ref_PC__r.Date_fin_prestation__c < Date.today()){	
                   system.debug('date in if ');
                if(std.Ref_PC__c != null){
                    oppIdSet.add(std.Ref_PC__c);
                    system.debug('oppIdSet values'+oppIdSet);
                    System.debug('std.Ref_PC__c values: ' + std.Ref_PC__c);
                }          
            }   
        }
         //System.debug('std.Ref_PC__c values: ' + std.Ref_PC__c);      
        System.debug('oppIdSet : ' + oppIdSet);
        System.debug('aStdList : ' + aStdList);
        
        /*Passer à "Inactive" le statut de la simulation offre initialement 
        liée à la PC (Champ "Simulation Offre" sur la proposition commerciale)*/ 
		
        List<Simulations__c> simOffreList = [SELECT Id, Statut__c FROM Simulations__c 
                                                WHERE Id =: oppIdSet
                                                AND (RecordType.DeveloperName =: Label.CL00125_SIM_RT_Simulation_Offre)];
												
        if(!oppIdSet.isEmpty()){
           
            if(!simOffreList.isEmpty()){
                for(Simulations__c simoffre :simOffreList)
                {
                    simoffre.Statut__c = Label.CL00129_SIM_SimulationOffreStageInActive;
                    system.debug('simoffre.Statut__c'+simoffre.Statut__c);
                }
             }
            
                                       
           
           // Etape 3 : Activation/Inactivation des simulations 
           // --> Remplacer la simulation offre renseignée sur la PC (champ "Simulation Offre") par la simulation renvoyée par le pricer (ID Simulation sur le suivi TDM) 
           //--> Passer à "Active" le statut de cette simulation
          
            for (Suivi_TDM__c suivi_TDM :aStdList) {
                if (suivi_TDM.Ref_PC__c != null) {
                    oppToUpdateMap.put(suivi_TDM.Ref_PC__c, 
                                       new opportunity( id = suivi_TDM.Ref_PC__c, Simulation_Offre__c = suivi_TDM.ID_Simulation__c));
                    
                    if (suivi_TDM.Ref_PC__r.Simulation_Offre__c != null) {
                        simToUpdateMap.put(suivi_TDM.Ref_PC__r.Simulation_Offre__c, 
                                           new Simulations__c( id = suivi_TDM.Ref_PC__r.Simulation_Offre__c, Statut__c =Label.CL00126_SIM_PLV_Active));
                    }
                }
            }
            system.debug('oppToUpdateMap.values() before'+oppToUpdateMap.values());
            system.debug('simToUpdateMap.values() before'+simToUpdateMap.values());
            UtilsBypass.SKIP_STRIGGER_MAP.put('OpportunityAfterInsert', 'skip trigger');
            UtilsBypass.SKIP_STRIGGER_MAP.put('OpportunityAfterUpdate', 'skip trigger');
            UtilsBypass.SKIP_STRIGGER_MAP.put('OpportunityBeforeUpdate', 'skip trigger');
            Database.update(oppToUpdateMap.values());
            Database.update(simToUpdateMap.values());
            UtilsBypass.SKIP_STRIGGER_MAP.remove('OpportunityAfterInsert');
            UtilsBypass.SKIP_STRIGGER_MAP.remove('OpportunityAfterUpdate');
            UtilsBypass.SKIP_STRIGGER_MAP.remove('OpportunityBeforeUpdate');

            system.debug('oppToUpdateMap.values() after'+oppToUpdateMap.values());
            system.debug('simToUpdateMap.values() after'+simToUpdateMap.values());
           
        }
        
       /*Passer à "Inactive" le statut des simulations sites liées à des contrats dont le statut est différent de "Prise en compte RV" ou 
       dont la date de résiliation souhaitée est < Date de fin de prestation (si renseignée) */
            
 
		List<Simulations__c> simSiteList = [SELECT Id,Statut__c, Contrat__c, Contrat__r.Statut__c,
                                            Contrat__r.Date_resiliation_souhaitee__c, Contrat__r.Date_fin_prestation__c FROM Simulations__c 
                                            WHERE (RecordType.DeveloperName =: Label.CL00127_SIM_RT_Simulation_Site)
                                            AND (Contrat__r.Statut__c !=: Label.CL00535_CON_PriseEnCompteRV)];
											
        System.debug('simSiteList values '+simSiteList);
     
        Set<Id> conIdSet = new Set<Id>();
        
        if(!simSiteList.isEmpty()){
            
            for(Simulations__c simSite : simSiteList){
                if(simSite.Contrat__c != null){
                    if(simSite.Contrat__r.Date_fin_prestation__c !=null || simSite.Contrat__r.Date_resiliation_souhaitee__c < simSite.Contrat__r.Date_fin_prestation__c ){
                         conIdSet.add(simSite.Contrat__c);
                         simSite.Statut__c = Label.CL00132_SIM_Staut_Inactive;
                         system.debug('conIdSet values'+conIdSet);
                         system.debug('simSite values'+simSite);
                         system.debug('simSite.Contrat__r.Date_fin_prestation__c '+simSite.Contrat__r.Date_fin_prestation__c );
                    }                   
                }             
            }
        }
         //Etape 4 : Mise à jour des informations sur les contrats 
        
		List<Simulations__c> simSiteActiveList = [SELECT Id,Statut__c,Date_de_r_vision__c,Collecte_de_donnees__c, Contrat__c, Contrat__r.Statut__c,Date_fin_prestation__c,Contrat__r.Date_de_r_vision__c,Contrat__r.Site__c,
                                            Contrat__r.Date_resiliation_souhaitee__c,Mensualite_Indicative_TTC__c, Contrat__r.Date_fin_prestation__c,
                                            Contrat__r.Produit__c,Contrat__r.Reference_contrat_display__c, Date_fin_de_prestation_site__c FROM Simulations__c 
                                            WHERE (RecordType.DeveloperName =: Label.CL00127_SIM_RT_Simulation_Site)
                                            AND (Contrat__r.Statut__c =: Label.CL00535_CON_PriseEnCompteRV)
                                            AND (Statut__c =: Label.CL00126_SIM_PLV_Active)];
											
        System.debug('simSiteActiveList values'+simSiteActiveList);
        Map<id,Contrat__c> conToUpdateMap = new Map<id,Contrat__c> ();
        
        if(!simSiteActiveList.isEmpty()){
            UtilsBypass.setBypassValidationRuleONOFF(true);
			for (Suivi_TDM__c suiviTDMSite :aStdList){ 
				for(Simulations__c simSiteActive : simSiteActiveList){
                
                //creation sollicitation
					Sollicitation__c solCon = new Sollicitation__c();
                
					if(simSiteActive.Contrat__c != null){
						if(simSiteActive.Contrat__r.Date_resiliation_souhaitee__c ==null || simSiteActive.Contrat__r.Date_resiliation_souhaitee__c > simSiteActive.Contrat__r.Date_fin_prestation__c ){  
                         
                        conToUpdateMap.put(simSiteActive.Contrat__c, new Contrat__c( id = simSiteActive.Contrat__c, Date_fin_prestation__c = simSiteActive.Date_fin_de_prestation_site__c));
                        }   
                        
                    //simSiteActive.Contrat__r.Date_fin_prestation__c = simSiteActive.Date_fin_prestation__c;
                                          
                    
                    if(Label.CL00892_Trt_TDM_Trt_Reconduction.equalsIgnoreCase(suiviTDMSite.Traitement__r.Name)||Label.CL00892_Trt_TDM_Trt_ReconductionAvantRevision.equalsIgnoreCase(suiviTDMSite.Traitement__r.Name)){
                        if(simSiteActive.Date_de_r_vision__c!=null){
                            
                        System.debug('Dirish 1');
                        conToUpdateMap.put(simSiteActive.Contrat__c, new Contrat__c( id = simSiteActive.Contrat__c, Date_de_r_vision__c = simSiteActive.Date_de_r_vision__c));
                        System.debug('conToUpdateMap'+conToUpdateMap);
                        System.debug('Dirish 2');
                        }
                    }
                  
                    if(Label.CL00892_Trt_TDM_Trt_Reconduction.equalsIgnoreCase(suiviTDMSite.Traitement__r.Name) 
                       || Label.CL00892_Trt_TDM_Trt_ReconductionAvantRevision.equalsIgnoreCase(suiviTDMSite.Traitement__r.Name)
                       || Label.CL_STD_TYPE_PRICING_REVISION.equalsIgnoreCase(suiviTDMSite.Traitement__r.Name)){
                        //simSiteActive.Contrat__r.Date_de_r_vision__c = simSiteActive.Date_de_r_vision__c ;
                        solCon.Automatisable__c = true;
                        solCon.Sous_famille_Synapse__c = Label.CL_Sous_famille_Synapse_sollicitation;
                        solCon.Famille__c  = Label.CL_Famille_Synapse_MISE_A_JOUR_CONTRAT;
                        solCon.Date_Echeance__c = date.today();
                        solCon.Produit__c = simSiteActive.Contrat__r.Produit__c;
                        solCon.Type_de_demande__c = Label.CL00892_Trt_TDM_Trt_Reconduction; 
                       // solCon.Contrats__c = simSiteActive.Contrat__r.Reference_contrat_display__c;
                        solCon.Site__c = simSiteActive.Contrat__r.Site__c;
                        system.debug('solCon test1'+solCon);
                      }  
                        
                    if(Label.CL_STD_TYPE_PRICING_REVISION.equalsIgnoreCase(suiviTDMSite.Traitement__r.Name)){
                       solCon.Sous_famille_Synapse__c = Label.CL_STD_TYPE_PRICING_REVISION;
                       //solCon.Type_de_demande__c = Label.CL_STD_TYPE_PRICING_REVISION;
                        system.debug('solCon test2'+solCon);
                    }                  
                       
                       
                        system.debug('simSiteActive values'+simSiteActive);
                    
                        system.debug('solCon To Insert' + solCon);
                        sollicitationListUpdate.add(solCon);
                    }    
			    }         
		    
			}    
			system.debug('conToUpdateMapvalues before insert'+conToUpdateMap);
			UtilsBypass.SKIP_STRIGGER_MAP.put('ContractBeforeUpdate','skip trigger');
			Database.update(conToUpdateMap.values());
			UtilsBypass.SKIP_STRIGGER_MAP.remove('ContractBeforeUpdate');
                    
			system.debug('conToUpdateMapvalues after insert'+conToUpdateMap);
			Database.insert(sollicitationListUpdate);
                  
            system.debug('sollicitationListUpdate values after insert'+sollicitationListUpdate);
			
                //Etape 6 : Mise à jour des informations sur la collecte 
                        List<Collectes_des_donnees__c> cddList = [SELECT id,name,Contrat__c,Mensualit_indicative_TTC__c
                                                 FROM Collectes_des_donnees__c
                                                 WHERE Contrat__r.Statut__c =: Label.CL00535_CON_PriseEnCompteRV];

						System.debug('cddList values'+cddList);
						
                    for(Collectes_des_donnees__c cdd : cddList){
                        for(Simulations__c simSiteActiveCdd : simSiteActiveList){
							
                        if(simSiteActiveCdd.Contrat__r.Date_fin_prestation__c!=null ){
                			if(simSiteActiveCdd.Contrat__r.Date_resiliation_souhaitee__c ==null || simSiteActiveCdd.Contrat__r.Date_resiliation_souhaitee__c > simSiteActiveCdd.Contrat__r.Date_fin_prestation__c )  
                    	
               		    	{   cdd.Mensualit_indicative_TTC__c = simSiteActiveCdd.Mensualite_Indicative_TTC__c;     			
                    			system.debug('test3');
               				}  
                        }
                        system.debug('simSiteActiveCdd.Mensualite_Indicative_TTC__c'+simSiteActiveCdd.Mensualite_Indicative_TTC__c);
                               
                                     
                            cddListUpdate.add(cdd);         
                        
                    }
					}
					Database.update(cddListUpdate); 
					system.debug('cddListUpdate in database'+cddListUpdate);
					            
				
			
        }
        system.debug('test test test oppToUpdateMap'+oppToUpdateMap.values());
        /*
            Etape 7 : Mise à jour des informations sur la proposition commerciale : 
            
            Type de prix	= Type de prix de la simulation offre 
            Date de fin de prestation = Date de fin de prestation de la simulation offre 
            Type de flexibilité (%)	= Type de flexibilité de la simulation offre 
            Seuil Haut flexibilité (%) =	Seuil Haut flexibilité (%) de la simulation offre 
            Seuil Bas flexibilité (%) = Seuil Bas flexibilité (%) de la simulation offre 
            Borne Haute	= Borne Haute de la simulation offre 
            Borne Basse	= Borne Basse de la simulation offre 
		*/
        Set<Id> objectsIds = new Set<Id>();
        
       for(Opportunity opp : oppToUpdateMap.values()){ 
           objectsIds.add(opp.Id);
            for(Simulations__c sim : simToUpdateMap.values()){
             //check if the current sim is related to the current opp via lookup
                if (opp.Simulation_Offre__c  == sim.id)
                {
                    opp.Type_prix__c = sim.Type_prix__c;
                    opp.Date_fin_prestation__c = sim.Date_fin_prestation__c;
                    opp.Type_de_flexibilite__c = sim.Type_de_flexibilit__c;
                    opp.Seuil_Haut__c = sim.Seuil_haut_flexibilite__c;
                    opp.Seuil_Bas__c = sim.Seuil_bas_flexibilite__c;
                    opp.Borne_haute__c = sim.Borne_haute__c;
                    opp.Borne_basse__c = sim.Borne_basse__c;                 
               }

            }
                oppListUpdate.add(opp);				
          }
            UtilsBypass.SKIP_STRIGGER_MAP.put('OpportunityAfterInsert', 'skip trigger');
            UtilsBypass.SKIP_STRIGGER_MAP.put('OpportunityAfterUpdate', 'skip trigger');
            UtilsBypass.SKIP_STRIGGER_MAP.put('OpportunityBeforeUpdate', 'skip trigger');
            Database.update(oppListUpdate);
            UtilsBypass.SKIP_STRIGGER_MAP.remove('OpportunityAfterInsert');
            UtilsBypass.SKIP_STRIGGER_MAP.remove('OpportunityAfterUpdate');
            UtilsBypass.SKIP_STRIGGER_MAP.remove('OpportunityBeforeUpdate');
           
            system.debug('oppListUpdate values in db'+oppListUpdate);
				
          //Etape 8 : Synchro OPTEAM 
       
            // Appel SYNCHRONE synaps
            //System.debug('--#### Appel Synchrone callOutOpteamModeSynchrone.');
            objectIdEchangeIdMap = CallOut_Utils.createEchangesRecords(objectsIds);
            mapObjectStatutTrt = CallOut_Opteam.executeActionsWS(objectsIds);
            CallOut_Utils.updateEchanges(objectIdEchangeIdMap, mapObjectStatutTrt);              
        UtilsBypass.setBypassValidationRuleONOFF(false);
          //Etape 9 : Indiquer que les prix ont été appliqués 
            
            for (Suivi_TDM__c suiviFinish :aStdList){
               for (opportunity oppToUpdateFinish :oppListUpdate){
        
            	if(Label.CL00892_Trt_TDM_Trt_Reconduction.equalsIgnoreCase(suiviFinish.Traitement__r.Name) 
               		|| Label.CL00892_Trt_TDM_Trt_ReconductionAvantRevision.equalsIgnoreCase(suiviFinish.Traitement__r.Name)){
                   	suiviFinish.Application_des_prix__c = true;
                        
                        post.Body = 'Cette offre a été reconduite automatiquement';
                        post.ParentId = oppToUpdateFinish.Id;
                }
                   if (Label.CL_STD_TYPE_PRICING_REVISION.equalsIgnoreCase(suiviFinish.Traitement__r.Name)){
                       	suiviFinish.Application_des_prix__c = true;
                        post.Body = 'Cette offre a été révisée';
                        post.ParentId = oppToUpdateFinish.Id;
                   }
              }
            }
            system.debug('values of post'+post);
            Database.insert(post);
            system.debug('values of post in db'+post);
           
        }catch(Exception e){
            System.debug('Error : '+e.getMessage());
            System.debug('Error line : '+e.getLineNumber());
        }
        
      
		system.debug('end of method');
        
        
        }
    
    global void finish(Database.BatchableContext BC){

    }

}

 
Best Answer chosen by cool_coding
vinita kumari 8vinita kumari 8
Make sure that you have defined the Map propely and Apply null checks before adding any value to list or Map. 
Also appy null check for Map values 
 if(cddMapUpdate != null && cddMapUpdate.values() != null && cddMapUpdate.values().size()>0)
         Database.update(cddMapUpdate.values());
 // system.debug('cddListUpdate in database'+cddMapUpdate.values());       // comment this debug. This can also throw exception.

All Answers

vinita kumari 8vinita kumari 8
Hi,
Instead of taking list  cddListUpdate  take a Map
like : Map<id,Collectes_des_donnees__c> cddMapUpdate = new Map<id,Collectes_des_donnees__c>();

and replace the below code as
249                            cddMapUpdate .put(cdd.id,cdd);        
250                         
251                    }
252                    }
253                    Database.update(cddMapUpdate.values());
254                    system.debug('cddListUpdate in database'+cddMapUpdate.values());

Try these changes and let me know if you face any issue.
cool_codingcool_coding
I have done this. But now I have this error:
 FATAL_ERROR System.NullPointerException: Argument cannot be null.
vinita kumari 8vinita kumari 8
Make sure that you have defined the Map propely and Apply null checks before adding any value to list or Map. 
Also appy null check for Map values 
 if(cddMapUpdate != null && cddMapUpdate.values() != null && cddMapUpdate.values().size()>0)
         Database.update(cddMapUpdate.values());
 // system.debug('cddListUpdate in database'+cddMapUpdate.values());       // comment this debug. This can also throw exception.
This was selected as the best answer
cool_codingcool_coding
Thks @vinita , it works when i have checked the map.