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
Vishnu Kant PandeyVishnu Kant Pandey 

System.ListException: Before Insert or Upsert list must not have two identically equal elements

Hi Experts,

I am trying to insert child opportunity records details in system by clubbing all the details to its parent opportunities. Like if i have one parent opportunity and multiple child records so after some custom calculations, i want to insert single record in an other custom object under parent opportunity name.

but i am getting the same error while running this batch class on batch size of 50 but while running the same code for 1 batch size it running perfectly.
What should I do?
my code:
global class XXXXX implements Database.Batchable<sObject>,Database.Stateful {  
    private Date DT1;

    public XXXXX(Date DT) {   
        DT1 = DT;
    }
    global Database.QueryLocator start(Database.BatchableContext BC) {
       String Query = 'Select id, accountid, Name, Disbursement_Date__c, CloseDate, Actual_Maturity_Date__c, Sanction_Amount__c, Current_Face__c,StageName,LastModifiedDate, RecordType.Name, Account_Record_Type__c, Original_face__c, current_factors__c, LeadSource__c,LeadSource__r.name,Credit_Approved_Date__c,Credit_Type__c,Loan_Tenor_in_Month__c,Maturity_Date__c,Credit_Rating__c,Amortization_Type__c,Parent_Opportunity__c,Parent_Opportunity__r.Name from Opportunity where ((RecordType.Name= \'XXXXX\') and (StageName = \'XXXXX\' OR StageName = \'XXXXX\' OR StageName = \'XXXXX\' OR (LeadSource__r.name=\'XXXXX\' and StageName = \'XXXXX\')  ))';
        return Database.getQueryLocator(Query);
    }
    
    global void execute(Database.BatchableContext BC, List<Opportunity> scope) {
            system.debug('Scope  :'+ Scope);
        try{
            List<CIBIL_Reporting__c> XXXXX= new List<CIBIL_Reporting__c>();
            Set<id>accId=new Set<id>();
            Set<id>oppId=new Set<id>();
            Set<id>oppparntId=new Set<id>();
            Map<id,Opportunity>mapOpp=new Map<id,Opportunity>();
            List<Payment_Schedules__c> pslist=new List<Payment_Schedules__c>();
            Map<id,Contact> Mapcon=new Map<id,Contact>();
            Map<Id, Opportunity> oppMap =  new Map<Id, Opportunity>();
for(opportunity opp : Scope){ 
                accId.add(opp.AccountId);
                oppparntId.add(opp.id);
oppMap.put(opp.id, opp);
            }
            system.debug('==accId=='+accId);
            if(accId!=null && accId.size()>0){
                for(Contact con: [Select Id,Account.Parent.name,District_eKYC__c,Date_of_Birth_eKYC__c,Passport_Id__c,account.name,account.ParentId,
                                account.Business_Category__c,account.Industry,Account.Aadhaar_Number__c,Account.Salutation,Account.Legal_Constitution__c,account.AccountNumber,account.CIN__c,
                                Account.BillingPostalCode, accountid,Account.PAN__c, Name, Birthdate, Gender__c, PAN_ID__c, Aadhaar_Number__c,Phone, Email, Official_Email__c,
                                MobilePhone, HomePhone, Alt_Phone__c, OtherPhone, Voter_Id__c, Driving_License__c, Mailing_Address__c, Address_Category__c, 
                                Borrower_Type__c, mailingStreet, mailingState,Account.Incorporation_Date__c, mailingPostalCode, mailingCountry, mailingCity,
                                Borrower_Office_Type__c,Pin_Code_eKYC__c,Fax,Account.Phone from Contact where accountid In: accId]){
                                
                    if(con.accountid!=null)
                        Mapcon.put(con.accountid,con);                
                }
            }
            system.debug('==Mapcon=='+Mapcon);
            system.debug('==oppparntId=='+oppparntId);
            for(opportunity opp: [Select id, accountid, Name, Disbursement_Date__c, CloseDate, Actual_Maturity_Date__c, Sanction_Amount__c, Current_Face__c,StageName,LastModifiedDate, RecordType.Name, Account_Record_Type__c, Original_face__c, current_factors__c, LeadSource__c,LeadSource__r.name,Credit_Approved_Date__c,Credit_Type__c,Loan_Tenor_in_Month__c,Maturity_Date__c,Credit_Rating__c,Amortization_Type__c,Parent_Opportunity__c,Parent_Opportunity__r.Name from Opportunity where Parent_Opportunity__c IN:oppparntId]){  
                if(Mapcon.containskey(opp.accountid)){                
                    If (Opp.RecordType.Name !='XXXXX' && Opp.Parent_Opportunity__c!= null ){
                        oppId.add(opp.id);
                        mapOpp.put(opp.id,opp);
                    }

               }
            }
            
            Integer SanctionAmount = 0;
            Integer Noofday = 0;
            Decimal CF = 0.0;
            Integer AmtOverdue = 0;
            Boolean Flag = false;
            Date lastPaymentReceived;
            
            system.debug('==oppId=='+oppId);
            system.debug('OPPID SIZE =='+ oppId.size());
            system.debug('MAPOPP SIZE =='+ mapOpp.size());
            if(oppId!=null && oppId.size()>0){
                pslist= [select id, Opportunity__r.Sanction_Amount__c,Opportunity__c,Opportunity__r.AccountId,Opportunity__r.Parent_Opportunity__c,
                                                Opportunity__r.Account_Record_Type__c,Payment_Received_Date__c,ClosingPrincipalBal__c,
                                                Open_Principal__c,Clearance__c,Date__c,Net_Payment__c, Delinquent_Days__c from 
                                                Payment_Schedules__c where Opportunity__c IN: oppId and Date__c<:DT1 order by Date__c Desc];                            
            }
            system.debug('==pslist=='+pslist.size());
            
            if(pslist!=null && pslist.Size()>0){
                for(Payment_Schedules__c psch: pslist){
                     
                    if (psch.Opportunity__r.Sanction_Amount__c!=null)
                        SanctionAmount=integer.valueOf(psch.Opportunity__r.Sanction_Amount__c);       
                        
                                      
                    // if Payment is not received
                    if(psch.Clearance__c == false) {
                        flag = True;
                        if (psch.Net_Payment__c!=null) 
                            AmtOverdue+=integer.valueOf(psch.Net_Payment__c);
                            
                           // Noofday = psch.Date__c.daysBetween(DT1);
                            system.debug('No. of DPD: From ' + psch.Date__c + ' To ' + DT1 + Noofday);
                        
                            CF = psch.Open_Principal__c;
                            system.debug('Current Face: ' + CF);
                    }else{ // Payment is received
                        if(!flag){ // if all the Payment was received
                           // Noofday = psch.Date__c.daysBetween(DT1)-1;
                            
                            // if payment is received after Reported Date to CIBIL
                            if(psch.Delinquent_Days__c<=Noofday){
                              //  Noofday = Integer.Valueof(psch.Delinquent_Days__c);
                                CF = psch.ClosingPrincipalBal__c;
                            }else{
                                CF = psch.Open_Principal__c;
                            }
                            system.debug('No. of DPD: From 111: ' + psch.Date__c + ' To ' + DT1 + Noofday);                           
                            system.debug('Current Face 111: ' + CF);
                       }
                          lastPaymentReceived = psch.Payment_Received_Date__c;
                        system.debug('Last Payment Received: +' + psch.Payment_Received_Date__c);
                        
                        break;
                     }
                                
                 }
                 Map<Id,Double>mapdaycount=new Map<Id,Double>();
                AggregateResult[] groupedResults
                          = [SELECT Opportunity__c, Max(Delinquent_Days__c)
                              FROM Payment_Schedules__c where Opportunity__c IN: oppId and Opportunity__r.Parent_Opportunity__c != null and Date__c<:DT1
                              GROUP BY Opportunity__c];
                        
                for (AggregateResult ar : groupedResults)  
                {   
                Id oppId1 = (ID)ar.get('Opportunity__c');
                double temp = (Double)ar.get('expr0');
                temp=temp!=null?temp:0;
                    if(mapdaycount.containsKey(mapOpp.get(oppId1 ).Parent_Opportunity__c)){
                        double maxValue= mapdaycount.get(mapOpp.get(oppId1 ).Parent_Opportunity__c)!=null?mapdaycount.get(mapOpp.get(oppId1 ).Parent_Opportunity__c):0;
                
                        if(temp > mapdaycount.get(mapOpp.get(oppId1).Parent_Opportunity__c)){
                                mapdaycount.put(mapOpp.get(oppId1).Parent_Opportunity__c,temp);
                        }
                    
                    }
                    else{
                    mapdaycount.put(mapOpp.get(oppId1 ).Parent_Opportunity__c,temp);
                    }
                }
                system.debug('==mapdaycount=='+mapdaycount);
                 CIBIL_Reporting__c  cbp = new CIBIL_Reporting__c();
                 for(Payment_Schedules__c psch: pslist){
                     if(mapOpp.containskey(psch.Opportunity__c) && mapOpp.get(psch.Opportunity__c).Account_Record_Type__c == 'Retail Borrower Account' && Mapcon.containskey(psch.Opportunity__r.AccountId) && Mapcon.get(psch.Opportunity__r.AccountId).Borrower_Type__c == 'Borrower'){
                       
                       system.debug('==Test==');
                        cbp.Amt_Overdue__c = String.valueof(AmtOverdue);
                        cbp.Date_of_Last_Payment__c = lastPaymentReceived;
                        
                        cbp.Report_Month__c = DT1;
                        cbp.Current_Face__c = CF;
                        if(mapdaycount.containskey(psch.Opportunity__r.Parent_Opportunity__c))
                        cbp.No_of_Days_Pass_Due__c = mapdaycount.get(psch.Opportunity__r.Parent_Opportunity__c);
                        
                        cbp.Disbursement_Date__c = mapOpp.get(psch.Opportunity__c).CloseDate;
                        cbp.Actual_Maturity_Date__c = mapOpp.get(psch.Opportunity__c).Actual_Maturity_Date__c;
                        cbp.Date_closed__c = mapOpp.get(psch.Opportunity__c).Actual_Maturity_Date__c;
                        cbp.Sanction_Amount__c = mapOpp.get(psch.Opportunity__c).Sanction_Amount__c;
                        cbp.LeadSource__c = mapOpp.get(psch.Opportunity__c).LeadSource__r.name;
                        cbp.Curr_New_Account_No__c = mapOpp.get(psch.Opportunity__c).Name;
                        cbp.Opportunity_Name__c = mapOpp.get(psch.Opportunity__c).Parent_Opportunity__r.Name;
                        cbp.Account_Type__c = mapOpp.get(psch.Opportunity__c).RecordType.Name;
                        //cbp.CIBIL_Record_Type__c = mapOpp.get(psch.Opportunity__c).RecordType.Name;
                        cbp.CIBIL_Record_Type__c = 'Credit Facility Loan';
                   
                        
                        cbp.BirthDate__c = Mapcon.get(psch.Opportunity__r.AccountId).Birthdate;
                        cbp.PAN_ID__c = Mapcon.get(psch.Opportunity__r.AccountId).Account.PAN__c;
                        cbp.Aadhar_Number__c = Mapcon.get(psch.Opportunity__r.AccountId).Account.Aadhaar_Number__c;
                        cbp.Phone__c = Mapcon.get(psch.Opportunity__r.AccountId).Phone;
                        cbp.HomePhone__c = Mapcon.get(psch.Opportunity__r.AccountId).HomePhone;
                        cbp.Alt_Phone__c = Mapcon.get(psch.Opportunity__r.AccountId).Alt_Phone__c;
                        cbp.OtherPhone__c = Mapcon.get(psch.Opportunity__r.AccountId).OtherPhone;               
                        cbp.Gender__c = Mapcon.get(psch.Opportunity__r.AccountId).Gender__c;
                        cbp.Voter_ID__c = Mapcon.get(psch.Opportunity__r.AccountId).Voter_ID__c;
                        cbp.Driving_License__c = Mapcon.get(psch.Opportunity__r.AccountId).Driving_License__c;
                        cbp.Mobile_Phone__c = Mapcon.get(psch.Opportunity__r.AccountId).MobilePhone;
                        cbp.Email__c = Mapcon.get(psch.Opportunity__r.AccountId).Email;
                        cbp.Email1__c = Mapcon.get(psch.Opportunity__r.AccountId).Official_Email__c;
                        cbp.Address_Category__c = Mapcon.get(psch.Opportunity__r.AccountId).Address_Category__c;
                        cbp.Mailing_Address__c = Mapcon.get(psch.Opportunity__r.AccountId).Mailing_Address__c;
                        cbp.Street__c = Mapcon.get(psch.Opportunity__r.AccountId).mailingStreet;
                        cbp.Address_1__c = Mapcon.get(psch.Opportunity__r.AccountId).mailingStreet;
                        cbp.State__c = Mapcon.get(psch.Opportunity__r.AccountId).mailingState;
                        cbp.Postal_code__c = Mapcon.get(psch.Opportunity__r.AccountId).mailingPostalCode;
                        cbp.Country__c = Mapcon.get(psch.Opportunity__r.AccountId).mailingCountry;
                        cbp.City__c = Mapcon.get(psch.Opportunity__r.AccountId).mailingCity;
                        cbp.Account_Name__c = Mapcon.get(psch.Opportunity__r.AccountId).Accountid;               
                        cbp.Account_Id__c = Mapcon.get(psch.Opportunity__r.AccountId).Account.id;
                     }
                }           
                cibillst.add(cbp);
            }
            system.debug('==cibillst=='+cibillst.size());
            if(cibillst!=null && cibillst.size()>0)
                insert cibillst;
        }catch(Exception e){
            system.debug('==Exp=='+e);
        }
    }
    global void finish(Database.BatchableContext BC) {
    }
}

Ashish KumarAshish Kumar
Hi Nishkam,

The error says that the list you are inserting i.e. cibillst must not have two identically equal elements.
That is the "cibillst" is having the same elements again and again..There are two possible solutions of that.
1. Reinitialise "cibillst" for every iteration of batch.
2. You will have to put debug points in your code. probably on 'Mapcon" or "MapOpp" that for every iteration of batch they are not holding the same version of data. Since they are the souce of data you are adding in "cibillst".

Please let me if it helps.

Regards,
Ashish Kr.
Vishnu Kant PandeyVishnu Kant Pandey
Hi Ashish,

I searched on internet and found a solution by initilizing the object with in the FOR loop. I did the same but all the records got duplicated.
 
Ashish KumarAshish Kumar
Hi Nishkam,

Since I am not able to visualise the data and hence not able to find the duplicacy,
Could you change insert DML to upsert  and try again?
Please use "upsert cibillst".

Regards,
Ashish Kr.