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
Genious007Genious007 

Apex Error: INVALID_FIELD_FOR_INSERT_UPDATE, Cannot specify Id in an insert call

Hi Guys,
i am getting this error when i call the class to generate invoices. the piece of code was working fine but due to over 10,000 records i have to put records in array and since then i am getting the above insert_update error.  

qryGift[i].Item__c = itemDTL1.Id; 
above code through error when insert L; gets executed.

thanks in advance.
 
failedUpdates = 0;
         // Billing Cycle variables
        String CycleType = '';
       Integer CycleMonths = 3; 
       //Integer CycleMonths = 0;
            
        // Set start and end dates. Assumes run at start of new month for preceding quarter        
       Date t =   Date.valueOf('2017-10-03'); 
      // Date t = Date.today();
        Integer m = t.Month();
        dateEnd = t.toStartOfMonth().addDays(-1);
            
        // Determine what the billing cycle is
        List<System_Settings__c> qrySettings = new List<System_Settings__c>();
        qrySettings = Database.query('SELECT Name, Value__c FROM System_Settings__c WHERE Name LIKE \'Billing Cycle%\' ORDER BY NAME');
        for (Integer i = 0; i < qrySettings.size(); i++) 
        {
            // Set the cycle type
            if (qrySettings[i].Name == 'Billing Cycle')
            {
                CycleType = qrySettings[i].Value__c;

                // TempC Print CycleType
                System.debug('Info-01: ' + CycleType);
                
                // If monthly just set and quit
                if (CycleType == 'Monthly')
                {
                    CycleMonths = 1;
                    break; 
                }                
            }
    
            // If quarterly see if this month is a billing month
            if (CycleType == 'Quarterly')
            {
                String RunMonth = String.ValueOf(m);
                if (qrySettings[i].Value__c == RunMonth)
                {
                    CycleMonths = 3;
                    break; 
                }
            }
        }
            
		// Step 3 **** custom duration invoice generation		
    			// CycleMonths = 3;
				// CycleType = 'Quarterly';

       	// TempC Print CycleType
                System.debug('Info-02 ' + CycleType);
        // Check all okay
        if (CycleType == '')
        {
            runok = 'NO BILLING CYCLE';
            System.debug('ERROR: No Billing Cycle type found. Invoice run aborted.');
            return;
        }
        if (CycleType != 'Monthly' && CycleType != 'Quarterly')
        {
            runok = 'INVALID BILLING CYCLE';
            System.debug('ERROR: Invalid Billing Cycle type found. Invoice run aborted.');
            return;
        }
        if (CycleMonths == 0)
        {
            runok = 'QUARTERLY - NOT A RUN MONTH';
            System.debug('ERROR: Quarterly Billing Cycle but not a run month. Invoice run aborted.');
            return;
        }
            
        Date s = t.toStartOfMonth();
        dateStart = s.addMonths(-CycleMonths);
        
    }
    
    global Database.queryLocator 
                    start(Database.BatchableContext ctx){
        return Database.getQueryLocator([SELECT Id, Country__c, End_Date__c, Invoiced_Up_To__c, Orphan__c, Start_Date__c, Orphan__r.Country__r.Orphan_Invoice_Amount__c,
                                                       Orphan__r.IRP_Sponsorship_Start__c, Orphan__r.Donor__c, Orphan__r.Donor_Start_Date__c, Orphan__r.Country__r.Orphan_Transfer_Amount__c,
                                                       Country__r.Primary_PO_User__c, Orphan__r.OwnerId
                                                  FROM IRP_Sponsorship__c 
                                                 WHERE Start_Date__c < :dateEnd 
                                                 AND ((End_Date__c = NULL
                                                 AND (Invoiced_Up_To__c = NULL
                                                  OR Invoiced_Up_To__c < :dateEnd)) 
                                                  OR (End_Date__c >= :dateStart
                                                 AND (Invoiced_Up_To__c = NULL
                                                  OR Invoiced_Up_To__c < :dateEnd)) 
                                                  OR (End_Date__c < :dateStart
                                                 AND  Billable__c = 0
                                                 AND (Invoiced_Up_To__c = NULL
                                                  OR (Invoiced_Up_To__c < :dateEnd))))
                                                 AND Orphan__r.Sponsored_Directly__c = FALSE Limit 200]);
    }
    
    global void execute(Database.BatchableContext ctx, List<Sobject>
                        scope){

        List<IRP_Sponsorship__c> qrySponsors = (List<IRP_Sponsorship__c>)scope;

        // Check a run month
        if(runok != 'TRUE'){
            return;
        }
                        
        // Cycle through list and get a unique list of Partner Offices
        Map<Id,String> setPtnr = new Map<Id,String>();
        // Add the invoice headers
        List<Invoice__c> newHdr = new List<Invoice__c>();

        // Get any generated open invoice headers
        List<Invoice__c> qryInv = [SELECT Id, IRP_Country__c
                                     FROM Invoice__c 
                                    WHERE Invoice_Status__c = 'Generated'
                                      AND Invoice_Date__c >= YESTERDAY];

                            // Make sure a header appears for this country                        
        for (Integer i = 0; i < qryInv.size(); i++) {
            if(!setPtnr.containsKey(qryInv[i].IRP_Country__c)){
                setPtnr.put(qryInv[i].IRP_Country__c,'Inv Hdr');
            }
        }    
            
        //Get initial record type id for invoice
        RecordType invrt = [SELECT Id FROM RecordType WHERE Name = 'Invoice Stage 1' AND sObjectType = 'Invoice__c' LIMIT 1];
        Id hdrRT = invrt.Id;
    
        // Invoice header
        Date invDate = Date.today();
        // Get number of rows
        //recs = qrySponsors.size();
        for (Integer i = 0; i < qrySponsors.size(); i++) {

            if(!setPtnr.containsKey(qrySponsors[i].Country__c)){
                setPtnr.put(qrySponsors[i].Country__c,'Inv Hdr');
                Invoice__c itmHdr = new Invoice__c (                    
                    IRP_Country__c = qrySponsors[i].Country__c,
                    Invoice_Date__c = invDate,
                    Invoice_Status__c = 'Generated',
                    RecordTypeId = hdrRT,
                    OwnerId = qrySponsors[i].Country__r.Primary_PO_User__c
                );
                newhdr.add(itmHdr);
            }
        }

        // Get any unbilled gifts
        List<Gift__c> qryGift = [SELECT Id, Donor__c, Donor__r.IRP_Country__c, Item__c, Orphan_Id__c, Gift_Amount__c, Gift_Date__c, Invoiced_On__c,
                                        Donor__r.IRP_Country__r.Primary_PO_User__c, Orphan_Id__r.OwnerId
                                   FROM Gift__c 
                                  WHERE Gift_Date__c <= :dateEnd
                                    AND Invoiced_On__c = NULL FOR UPDATE];
                            
        // Make sure a header appears for this country                        
        for (Integer i = 0; i < qryGift.size(); i++) {

            if(!setPtnr.containsKey(qryGift[i].Donor__r.IRP_Country__c)){
                setPtnr.put(qryGift[i].Donor__r.IRP_Country__c,'Inv Hdr');
     
                    Invoice__c itmHdr1 = new Invoice__c (                    
                    IRP_Country__c = qryGift[i].Donor__r.IRP_Country__c,
                    Invoice_Date__c = invDate,
                    Invoice_Status__c = 'Generated',
                    RecordTypeId = hdrRT,
                    OwnerId = qryGift[i].Donor__r.IRP_Country__r.Primary_PO_User__c
                );
                newhdr.add(itmHdr1);
            }
        }
                 // Debug
                 for (Integer i = 0; i < newHdr.size(); i++) {
                 system.debug('New Header ' +i+ newHdr[i]);
                 }
                            insert newHdr;

        // Create a map of country and invoice id
        Map<String,Id> newHdr1 = new Map<String, Id>();
        // Get new list of generated invoices
        List<Invoice__c> qryInv1 = [SELECT Id, IRP_Country__c
                                      FROM Invoice__c 
                                     WHERE Invoice_Status__c = 'Generated'
                                       AND Invoice_Date__c >= YESTERDAY];
                
        for (Integer i = 0; i < qryInv1.size(); i++) {
            newHdr1.put(qryInv1[i].IRP_Country__c, qryInv1[i].Id);
        }        

         // Map for keeping invoice items
          //Map<integer, list<Item__c>> finalinsertlist = new Map<integer, list<Item__c>>(); 
          list<list<Item__c>> finalinsertlist = new list<list<Item__c>>();                      

        // Add the item details
        List<Item__c> newITM = new List<Item__c>();
        // Get a list of the affected orphans
        Map<Id,Date> updOrp = new Map<Id,Date>();
                
        // Now go back through the sponsorship records and add the item records
        for (Integer i = 0; i < qrySponsors.size(); i++) {
            if(newHdr1.containsKey(qrySponsors[i].Country__c)){
            
                String itmHDR1 = newHdr1.get(qrySponsors[i].Country__c);
                
                // Use donor start date if present, otherwise use IRP start date
                Date dateSpons = qrySponsors[i].Orphan__r.Donor_Start_Date__c;
                if (dateSpons == NULL){ dateSpons = qrySponsors[i].Start_Date__c; }
                
                // Work out the number of months involved
                Date billfrom = qrySponsors[i].Invoiced_Up_To__c;
                if (billfrom == NULL){ billfrom = qrySponsors[i].Start_Date__c; }
                // Adjust bill from based on 15th of month
                if (billfrom.day() >= 15){
                    Date bf = billfrom;
                    Date bf1 = bf.toStartOfMonth();
                    Date bf2 = bf1.addMonths(1);
                    billfrom = bf2;
                } 
                Integer billqty = 1;
                Date billto = dateEnd;
                if (qrySponsors[i].End_Date__c < dateEnd){billto = qrySponsors[i].End_Date__c;}
                
                if (billfrom.year() == billto.year()){
                    billqty = billto.month() - billfrom.month() + 1;
                }
                else
                {
                    billqty = billto.month() + ((billto.year() - billfrom.year()) * 12) - billfrom.month() + 1;                    
                }
                
                // Add new item record
                Item__c itemDTL = new Item__c (
                    Date_Sponsored__c = dateSpons,
                    Donor__c = qrySponsors[i].Orphan__r.Donor__c,
                    Invoice_Price__c = qrySponsors[i].Orphan__r.Country__r.Orphan_Invoice_Amount__c,
//                    Item_Status__c = 'Generated',
                    Orphan__c = qrySponsors[i].Orphan__c,
                    Item_Type__c = 'Sponsorship',
                    Payment_Cost__c = qrySponsors[i].Orphan__r.Country__r.Orphan_Transfer_Amount__c,
                    Qty__c = billqty,
                    IRP_Sponsorship_Ref__c = qrySponsors[i].Id,
                    Quarterly_Billing_Number__c = itmHDR1,
                    OwnerId = qrySponsors[i].Orphan__r.OwnerId
                );
                     if (math.mod(i, 9999)==0 && !newITM.isempty()){
                           finalinsertlist.add(newITM);   
                           newITM.clear() ; //= new list<item__c>();  
                     }

                newITM.add(itemDTL);
                
                // Make a note of the latest bill to for an orphan
                if (updOrp.containsKey(qrySponsors[i].Orphan__c)){
                    Date orpCheck = updOrp.get(qrySponsors[i].Orphan__c); 
                    if (billto > orpCheck) {
                        updOrp.put(qrySponsors[i].Orphan__c, billto);
                    }
                }
                else
                {
                    updOrp.put(qrySponsors[i].Orphan__c, billto);
                }   
                // Update IRP sponsorship record
                qrySponsors[i].Invoiced_Up_To__c = billto;
            }
        }                 

        // Now go back through the gift records and add the item records
        for (Integer i = 0; i < qryGift.size(); i++) {
            if(newHdr1.containsKey(qryGift[i].Donor__r.IRP_Country__c)){
            
                String itmHDR2 = newHdr1.get(qryGift[i].Donor__r.IRP_Country__c);

                // Add new item record
                Item__c itemDTL1 = new Item__c (
                    Donor__c = qryGift[i].Donor__c,
                    Invoice_Price__c = qryGift[i].Gift_Amount__c,
//                    Item_Status__c = 'Generated',
                    Orphan__c = qryGift[i].Orphan_Id__c,
                    Item_Type__c = 'Gift',
                    Payment_Cost__c = qryGift[i].Gift_Amount__c,
                    Qty__c = 1,
                    Quarterly_Billing_Number__c = itmHDR2,
                    OwnerId = qryGift[i].Orphan_Id__r.OwnerId                    
                );
                  if (math.mod(i, 9999)==0 && !newITM.isempty()){
                      finalinsertlist.add(newITM);   
                      newITM.clear(); // = new list<item__c>();  
                  }
              newITM.add(itemDTL1);
                // Update Gift record
                qryGift[i].Invoiced_On__c = dateEnd;
                qryGift[i].Item__c = itemDTL1.Id;
            }
        }
                
                for(list<Item__c> L:finalinsertlist){
                system.debug('Array size:' + L.size());   
                    insert L ;                 
                 }

 
Genious007Genious007
FATAL_ERROR System.DmlException: Insert failed. First exception on row 0 with id a0M2X0000117fSsUAI; first error: INVALID_FIELD_FOR_INSERT_UPDATE, cannot specify Id in an insert call: [Id]
NForceNForce
Hi Mahmood, 
This Error pops up when you're trying to insert records which are already inserted. if you want to update and create(if records don't exist) use upsert statement instead of insert.
Genious007Genious007
thanks for your reply @NForce. before i do upsert, i want to know why system asks for it. before adding code 285-287 the same code was working fine.