[SalesForce] Before Insert or Upsert list must not have two identically equal elements using Map

The error I am facing here is

Before Insert or Upsert list must not have two identically equal
elements

I am getting this error while executing my below code.
Can anyone please help me to overcome this error?

  for(sked__Job__c j : sked_Start_End_JobList){

    List_Store_Summary__c ss = new List_Store_Summary__c();
     ss = [ select Id,Merchandiser_Resource_ID__c, Store__r.Region__c from List_Store_Summary__c where Id=: j.List_Store_Summary__c];
    sked__Job_Allocation__c a = new sked__Job_Allocation__c();
    a.sked__Job__c = j.Id;
    a.sked__Status__c = 'Pending Dispatch';
    a.sked__Resource__c = (ListStoreSummaryMap.get(j.id)).Merchandiser_Resource_ID__c; 

    system.debug('Merchandiser_Resource_ID__c >>>> '+ a.sked__Resource__c);

    jobAlist.add(a);

    if(ListStoreMap.containsKey(j.List_Store_Summary__c)){
         List<List_Store__c> storeList = new List<List_Store__c>(); 
        storeList = ListStoreMap.get(j.List_Store_Summary__c); 
        system.debug('storeList >>>>>' + storeList);

        for(List_Store__c ls : storeList){

            if(listOrderMap.containsKey(ls.Id)){
                List<List_Order__c> orderList = new List<List_Order__c>();
                orderList = listOrderMap.get(ls.Id); 
                system.debug('orderList >>>>' + orderList);
                for(List_Order__c o : orderList)
                {
                    o.Job__c = j.Id;
                    system.debug('list order updated is:'+o.Name);
                }
                mainOrderList.addAll(orderList);
            }
        }
    }
}
system.debug('mainOrderList :' + mainOrderList);
upsert mainOrderList;

below is the full method

global void finish(Database.BatchableContext BC)
    {
        List<sked__Job_Allocation__c> jobAlist = new List<sked__Job_Allocation__c>();
        //List<List_Store__c> storeList; 
        List<List_Order__c> mainOrderList = new List<List_Order__c>();

        List<AggregateResult> listStoreSummary = [SELECT MerchandiserContact__r.End_of_Day_Account__c, Store__r.Address_Location__r.sked__Region__c, Store__r.Address_Location__c, MerchandiserContact__r.Start_of_Day_Account__c, MerchandiserContact__r.id , day_only(Start_Date_Time__c) day, MIN(Start_Date_Time__c) mindate, MAX(Finish_Date_Time__c) maxDate FROM List_Store_Summary__c WHERE Service_date__c >=: fromDate and Service_date__c <=: toDate group by MerchandiserContact__r.id, day_only(Start_Date_Time__c),MerchandiserContact__r.End_of_Day_Account__c, Store__r.Address_Location__r.sked__Region__c, Store__r.Address_Location__c, MerchandiserContact__r.Start_of_Day_Account__c  order by day_only(Start_Date_Time__c) asc];
        system.debug('results' + listStoreSummary);

        Set<Datetime> start_datetime = new Set<Datetime>();
        Set<Datetime> end_datetime = new Set<Datetime>();

        for(AggregateResult ag1: listStoreSummary){
            start_datetime.add((Datetime)ag1.get('mindate'));
            end_datetime.add((Datetime)ag1.get('maxDate'));
        }

        List<List_Store_Summary__c> StartResultListSS = [SELECT MerchandiserContact__c, Id FROM List_Store_Summary__c WHERE Start_Date_Time__c IN: start_datetime];

        system.debug('StartResultListSS :' + StartResultListSS);

        Map<String,String> mapStartMerchandiserAndListSS = new Map<String,String>();

        for(List_Store_Summary__c lss: StartResultListSS){
            mapStartMerchandiserAndListSS.put(lss.MerchandiserContact__c, lss.Id);
        }

        system.debug('mapStartMerchandiserAndListSS : ' + mapStartMerchandiserAndListSS);

        List<List_Store_Summary__c> EndResultListSS = [SELECT MerchandiserContact__c, Id FROM List_Store_Summary__c WHERE Finish_Date_Time__c IN: end_datetime];

        system.debug('EndResultListSS :' + EndResultListSS);

        Map<String,String> mapEndMerchandiserAndListSS = new Map<String,String>();

        for(List_Store_Summary__c lss: EndResultListSS){
            mapEndMerchandiserAndListSS.put(lss.MerchandiserContact__c, lss.Id);
        }

        system.debug('mapEndMerchandiserAndListSS : ' + mapEndMerchandiserAndListSS);

        List<sked__Job__c> sked_Start_End_JobList = new List<sked__Job__c>();

        Datetime start_time;
        Datetime end_time;

        for(AggregateResult ag: listStoreSummary){
            start_time = (Datetime)ag.get('mindate');
            sked__Job__c start_job = new sked__Job__c();
            start_job.sked__Type__c = 'Start of Day Tasks';
            start_job.sked__Start__c = start_time.addMinutes(-20);
            start_job.sked__Finish__c = start_time.addMinutes(10);
            start_job.sked__Duration__c = 10;
            start_job.sked__Estimated_Start__c = start_time.addMinutes(-20);
            start_job.sked__Estimated_End__c = start_time.addMinutes(10);
            start_job.sked__Account__c = (Id)ag.get('Start_of_Day_Account__c');
            start_job.sked__Location__c = (Id)ag.get('Address_Location__c');
            start_job.sked__Region__c = (Id)ag.get('sked__Region__c');
            start_job.sked__Urgency__c = 'Normal';
            start_job.sked__Job_Status__c = 'Queued';
            start_job.List_Store_Summary__c = mapStartMerchandiserAndListSS.get((Id)ag.get('Id'));
            sked_Start_End_JobList.add(start_job);


            end_time = (Datetime)ag.get('maxDate');
            sked__Job__c end_job = new sked__Job__c();
            end_job.sked__Type__c = 'Start of Day Tasks';
            end_job.sked__Start__c = end_time.addMinutes(20);
            end_job.sked__Finish__c = end_time.addMinutes(30);
            end_job.sked__Duration__c = 10;
            end_job.sked__Estimated_Start__c = end_time.addMinutes(20);
            end_job.sked__Estimated_End__c = end_time.addMinutes(30);
            end_job.sked__Account__c =(Id) ag.get('End_of_Day_Account__c');
            end_job.sked__Location__c =(Id) ag.get('Address_Location__c');
            end_job.sked__Region__c =(Id) ag.get('sked__Region__c');
            end_job.sked__Urgency__c = 'Normal';
            end_job.sked__Job_Status__c = 'Queued';
            end_job.List_Store_Summary__c = mapEndMerchandiserAndListSS.get((Id)ag.get('Id'));
            sked_Start_End_JobList.add(end_job);

        }

        insert sked_Start_End_JobList;

        system.debug('New Jobs :' + sked_Start_End_JobList);

        Set<Id> StorySummaryIdSet = new Set<Id>();

        for (sked__Job__c job1 : sked_Start_End_JobList){
            StorySummaryIdSet.add(job1.List_Store_Summary__c);
        }

        List<List_Store_Summary__c> StorySummaryList = new List<List_Store_Summary__c>();
        StorySummaryList = [select Id,Merchandiser_Resource_ID__c, Store__r.Region__c from List_Store_Summary__c where Id IN: StorySummaryIdSet];

        Map<Id,List_Store_Summary__c> ListStoreSummaryMap = new Map<Id,List_Store_Summary__c>();

        for (sked__Job__c job : sked_Start_End_JobList){
            for(List_Store_Summary__c storeSummaryObj : StorySummaryList){
                if(job.List_Store_Summary__c == storeSummaryObj.id){   

                    ListStoreSummaryMap.put(job.id, storeSummaryObj);  
                }
            }
        }

        Set<Id> listStoreSetId = new Set<Id>();


        List<List_Store__c> listStore = [select Id,List_Store_Summary__c from List_Store__c where List_Store_Summary__c IN: StorySummaryIdSet];

        Map<Id,List<List_Store__c>> ListStoreMap = new Map<Id,List<List_Store__c>>();

        for(List_Store__c lss : listStore){
            if(ListStoreMap.containsKey(lss.List_Store_Summary__c)){
                List<List_Store__c> temp = ListStoreMap.get(lss.List_Store_Summary__c);
                temp.add(lss);
            }
            else
            {
                List<List_Store__c> temp = new List<List_Store__c>();
                temp.add(lss);
                ListStoreMap.put(lss.List_Store_Summary__c, temp);
            }

            listStoreSetId.add(lss.Id);
        }

        List<List_Order__c> listOrder = [select Id, List_Store__c from List_Order__c where List_Store__c IN: listStoreSetId];
        Map<Id, List<List_Order__c>> listOrderMap = new Map<Id, List<List_Order__c>>();

        for(List_Order__c lo : listOrder){
            if(listOrderMap.containsKey(lo.List_Store__c)){
                List<List_Order__c> temp = listOrderMap.get(lo.List_Store__c);
                temp.add(lo);
            }
            else
            {
                List<List_Order__c> temp = new List<List_Order__c>();
                temp.add(lo);
                listOrderMap.put(lo.List_Store__c, temp);
            }
        }

         for(sked__Job__c j : sked_Start_End_JobList){

            List_Store_Summary__c ss = new List_Store_Summary__c();
             ss = [ select Id,Merchandiser_Resource_ID__c, Store__r.Region__c from List_Store_Summary__c where Id=: j.List_Store_Summary__c];
            sked__Job_Allocation__c a = new sked__Job_Allocation__c();
            a.sked__Job__c = j.Id;
            a.sked__Status__c = 'Pending Dispatch';
            a.sked__Resource__c = (ListStoreSummaryMap.get(j.id)).Merchandiser_Resource_ID__c; 

            system.debug('Merchandiser_Resource_ID__c >>>> '+ a.sked__Resource__c);

            jobAlist.add(a);

            if(ListStoreMap.containsKey(j.List_Store_Summary__c)){
                 List<List_Store__c> storeList = new List<List_Store__c>(); 
                storeList = ListStoreMap.get(j.List_Store_Summary__c); 
                system.debug('storeList >>>>>' + storeList);

                for(List_Store__c ls : storeList){

                    if(listOrderMap.containsKey(ls.Id)){
                        List<List_Order__c> orderList = new List<List_Order__c>();
                        orderList = listOrderMap.get(ls.Id); 
                        system.debug('orderList >>>>' + orderList);
                        for(List_Order__c o : orderList)
                        {
                            o.Job__c = j.Id;
                            system.debug('list order updated is:'+o.Name);
                        }
                        mainOrderList.addAll(orderList);
                    }
                }
            }
        }
        system.debug('mainOrderList :' + mainOrderList);
        upsert mainOrderList;

        System.debug('jobAlist'+jobAlist);
        insert jobAlist;

        system.debug('inside finish method-------------------------->');
        // Get the AsyncApexJob that represents the Batch job using the Id from the BatchableContext  
        AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,  
                          TotalJobItems, CreatedBy.Email, ExtendedStatus  
                          from AsyncApexJob where Id = :BC.getJobId()];  
        if(a.NumberOfErrors> 0 || a.Status=='Failed')
        {
            // Email the Batch Job's submitter that the Job is finished.  
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();  
            system.debug('label ->'+Label.Batch_Job_Error_Email);
            String[] toAddresses = new String[] {Label.Batch_Job_Error_Email};  
                mail.setToAddresses(toAddresses);  
            mail.setSubject('Skedulo Batch Job Creation Status: ' + a.Status);  
            mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +  
                                  ' batches with '+ a.NumberOfErrors + ' failures. ExtendedStatus: ' + a.ExtendedStatus);  

            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });  
            system.debug('mail'+mail);
        }


    }

Best Answer

This error is coming because of this line

 mainOrderList.addAll(orderList);

You are adding the same value again.

Move this code outside loop because its not related to outer loop

for(List_Order__c o : orderList)
{
       o.Job__c = j.Id;
       system.debug('list order updated is:'+o.Name);
 }
 mainOrderList.addAll(orderList);

or else make this mainOrderList a Set to remove duplicate records.

Related Topic