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
SaravaSarava 

Salesforce CPQ QuoteDocumentController inside a FOR loop

There are four templates. I want to generate Quote document for each Template whenever the Status on the SBQQ__Quote__c object changes. I have the  
generateDocument(String language, String quoteId, String templateId, String documentName, String outputFormat, List documentIds) and  saveProposal(String language, String quoteId, String templateId, String documentName, String outputFormat, List documentIds) class inside the template loop but only one document is getting saved.
The loop is running four times.
I assume the value for SBQQ__key__c is holding the same ID since the second loop runs before the 1st job gets completed.
Below is my code and the error on APEX job
list<SBQQ__QuoteTemplate__c> templateLst = [SELECT Name, id 
                                                    from SBQQ__QuoteTemplate__c     ];                                          
        
        for (SBQQ__Quote__c QuoteRec : QuoteLst)
        {
            for (SBQQ__QuoteTemplate__c TemplateRec :templateLst ) // Four Records from Template object
            {
                List<id> documentIds 	= new List<id>(); 
                id jobId = SBQQ.QuoteDocumentController.generateDocument ('en_US', 
                                                                          QuoteRec.Id, 
                                                                          TemplateRec.id, 
                                                                          'DocumentName', 
                                                                          'PDF', 
                                                                          documentIds);
                system.debug('Doc Id size: '+documentIds.size()); //Size 0 for all 4 loops
                documentIds.add(QuoteRec.Id);
                system.debug('Doc Id size: '+documentIds.size()); //Size 1 for all 4 loops
                
                jobId = SBQQ.QuoteDocumentController.saveProposal ('en_US', QuoteRec.Id, TemplateRec.id, 'DocumentName', 'PDF', documentIds);
            }
        }

Error I am getting for the second Document : Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: SBQQ__Key__c duplicates value on record with id: XXXXXXXXXXXXXX: []

How can I overcome this problem? 

Thanks!
Best Answer chosen by Sarava
SaravaSarava
I am able to resolve the issue.
I have created a beforeInsert trigger on 'quote document' and manually passing a unique value for SBQQ__key__c and then Inserting the document. So the duplication of the key is avoided.