Read each numbered source line with the explanation beside it. Method headings name the job of the whole method; nearby rows explain its individual steps.
1/**Starts a developer comment describing the code below.
2 * Creates a CPQ quote from a confirmed PS Quote Analysis.Part of the surrounding declaration or expression; read it with the adjacent lines.
3 * Required analysis fields are listed in README.md.Part of the surrounding declaration or expression; read it with the adjacent lines.
4 * CPQ work is split across queueable transactions so the quote header existsPart of the surrounding declaration or expression; read it with the adjacent lines.
5 * before quote lines are saved and before calculation is requested.Part of the surrounding declaration or expression; read it with the adjacent lines.
6 */Ends the comment.
7public with sharing class PsQuoteCpqController {Declares a class or trigger. The braces contain its members and behavior.
8 private static final Id SERVICES_PRICEBOOK_ID = '01sSu00000532iLIAQ';Creates or assigns a typed value for the steps that follow.
9 @TestVisible private static Id testServicesPricebookId;Allows a test class to access this normally private member.
10 private static final Map<String, String> PRODUCT_CODES = new Map<String, String>{Opens a block; the indented lines below execute or belong together.
11 'TIME_MATERIAL' => '863',Maps the value on the left to the value on the right.
12 'PREPAID_TIME_MATERIAL' => '875',Maps the value on the left to the value on the right.
13 'MILESTONE' => '885',Maps the value on the left to the value on the right.
14 'MILESTONE_TIME_MATERIAL' => '886'Maps the value on the left to the value on the right.
15 };Closes the current block or declaration.
16 Spacing separates related steps.
17 public class PrimaryAmendmentQuote {Declares a class or trigger. The braces contain its members and behavior.
18 @AuraEnabled public Id quoteId;Exposes this Apex method or value to a Lightning component, or marks the next declaration when the annotation is on its own line.
19 @AuraEnabled public String quoteName;Exposes this Apex method or value to a Lightning component, or marks the next declaration when the annotation is on its own line.
20 @AuraEnabled public Id contractId;Exposes this Apex method or value to a Lightning component, or marks the next declaration when the annotation is on its own line.
21 @AuraEnabled public String contractName;Exposes this Apex method or value to a Lightning component, or marks the next declaration when the annotation is on its own line.
22 @AuraEnabled public Date startDate;Exposes this Apex method or value to a Lightning component, or marks the next declaration when the annotation is on its own line.
23 }Closes the current block or declaration.
24 Spacing separates related steps.
25 @AuraEnabled(cacheable=true)Exposes this Apex method or value to a Lightning component, or marks the next declaration when the annotation is on its own line.
26 public static PrimaryAmendmentQuote getPrimaryAmendmentQuote(Id opportunityId) {Method declaration: Find the primary amendment Quote and return details to the screen. The parentheses define its inputs; the type before the name defines its return value.
27 if (opportunityId == null) {Guard or branch: the following block runs only when this condition is true.
28 return null;Returns this value to the caller and ends the method.
29 }Closes the current block or declaration.
30 List<Opportunity> opportunities = [Creates or assigns a typed value for the steps that follow.
31 SELECT Id, AccountId FROM OpportunitySOQL field list: identifies data to read from Salesforce.
32 WHERE Id = :opportunityId WITH USER_MODE LIMIT 1SOQL filter: narrows the records returned by this query.
33 ];Completes the statement begun on this line or the preceding lines.
34 if (opportunities.isEmpty() || opportunities[0].AccountId == null) {Guard or branch: the following block runs only when this condition is true.
35 return null;Returns this value to the caller and ends the method.
36 }Closes the current block or declaration.
37 Id opportunityAccountId = opportunities[0].AccountId;Creates or assigns a typed value for the steps that follow.
38 List<SBQQ__Quote__c> quotes = [Creates or assigns a typed value for the steps that follow.
39 SELECT Id, Name, SBQQ__MasterContract__c,SOQL field list: identifies data to read from Salesforce.
40 SBQQ__MasterContract__r.Name, SBQQ__StartDate__cPart of the surrounding declaration or expression; read it with the adjacent lines.
41 FROM SBQQ__Quote__cSOQL source: identifies which Salesforce object to read.
42 WHERE SBQQ__Opportunity2__c = :opportunityIdSOQL filter: narrows the records returned by this query.
43 AND SBQQ__Account__c = :opportunityAccountIdSOQL filter: narrows the records returned by this query.
44 AND SBQQ__Primary__c = trueSOQL filter: narrows the records returned by this query.
45 AND SBQQ__Type__c = 'Amendment'SOQL filter: narrows the records returned by this query.
46 AND SBQQ__MasterContract__c != nullSOQL filter: narrows the records returned by this query.
47 WITH USER_MODERuns this read using the current user’s data and field permissions.
48 ORDER BY CreatedDate DESC LIMIT 1Sorts the records returned by this query.
49 ];Completes the statement begun on this line or the preceding lines.
50 if (quotes.isEmpty()) {Guard or branch: the following block runs only when this condition is true.
51 return null;Returns this value to the caller and ends the method.
52 }Closes the current block or declaration.
53 PrimaryAmendmentQuote result = new PrimaryAmendmentQuote();Creates or assigns a typed value for the steps that follow.
54 result.quoteId = quotes[0].Id;Creates or assigns a typed value for the steps that follow.
55 result.quoteName = quotes[0].Name;Assigns or configures the value on the left using the expression on the right.
56 result.contractId = quotes[0].SBQQ__MasterContract__c;Assigns or configures the value on the left using the expression on the right.
57 result.contractName = quotes[0].SBQQ__MasterContract__r.Name;Assigns or configures the value on the left using the expression on the right.
58 result.startDate = quotes[0].SBQQ__StartDate__c;Assigns or configures the value on the left using the expression on the right.
59 return result;Returns this value to the caller and ends the method.
60 }Closes the current block or declaration.
61 Spacing separates related steps.
62 @AuraEnabledExposes this Apex method or value to a Lightning component, or marks the next declaration when the annotation is on its own line.
63 public static Id createQuote(Id analysisId, Date quoteStartDate) {Method declaration: Validate a New Services analysis and enqueue the HEADER job. The parentheses define its inputs; the type before the name defines its return value.
64 if (analysisId == null) {Guard or branch: the following block runs only when this condition is true.
65 throw new AuraHandledException('Select a confirmed analysis.');Stops this path and reports an error to the caller.
66 }Closes the current block or declaration.
67 Spacing separates related steps.
68 PS_Quote_Analysis__c analysis = [Assigns or configures the value on the left using the expression on the right.
69 SELECT Id, Status__c, Quote_Type__c, Effective_Date__c,SOQL field list: identifies data to read from Salesforce.
70 Amended_Contract__c, Reviewed_Proposal_JSON__c,Continues the argument list or condition on the next line.
71 Created_Quote__c, Quote_Creation_Status__cPart of the surrounding declaration or expression; read it with the adjacent lines.
72 FROM PS_Quote_Analysis__cSOQL source: identifies which Salesforce object to read.
73 WHERE Id = :analysisIdSOQL filter: narrows the records returned by this query.
74 LIMIT 1 FOR UPDATECaps the number of records returned by this query.
75 ];Completes the statement begun on this line or the preceding lines.
76 if (analysis.Status__c != 'Confirmed' ||Guard or branch: the following block runs only when this condition is true.
77 String.isBlank(analysis.Reviewed_Proposal_JSON__c)) {Opens a block; the indented lines below execute or belong together.
78 throw new AuraHandledException('Confirm the breakdown before creating a quote.');Stops this path and reports an error to the caller.
79 }Closes the current block or declaration.
80 if (analysis.Created_Quote__c != null ||Guard or branch: the following block runs only when this condition is true.
81 (analysis.Quote_Creation_Status__c != null &&Assigns or configures the value on the left using the expression on the right.
82 analysis.Quote_Creation_Status__c != 'Failed')) {Opens a block; the indented lines below execute or belong together.
83 throw new AuraHandledException('A quote has already been requested for this analysis.');Stops this path and reports an error to the caller.
84 }Closes the current block or declaration.
85 if (analysis.Quote_Type__c != 'New Services') {Guard or branch: the following block runs only when this condition is true.
86 throw new AuraHandledException(Stops this path and reports an error to the caller.
87 'Change orders use the primary amendment quote already on this Opportunity.'Part of the surrounding declaration or expression; read it with the adjacent lines.
88 );Opens or closes the expression begun on the surrounding lines.
89 }Closes the current block or declaration.
90 if (quoteStartDate == null) {Guard or branch: the following block runs only when this condition is true.
91 throw new AuraHandledException('Enter the quote start date before creating the quote.');Stops this path and reports an error to the caller.
92 }Closes the current block or declaration.
93 Spacing separates related steps.
94 // Validate the saved review, not client-supplied lines.Developer comment: Validate the saved review, not client-supplied lines.
95 parseAndValidate(analysis.Reviewed_Proposal_JSON__c);Calls parseAndValidate(): Check the saved proposal JSON and approved total.
96 analysis.Quote_Creation_Status__c = 'Queued';Assigns or configures the value on the left using the expression on the right.
97 analysis.Quote_Creation_Error__c = null;Assigns or configures the value on the left using the expression on the right.
98 update analysis;DML write: saves changes to the specified Salesforce record or records.
99 System.enqueueJob(new BuildJob(analysisId, quoteStartDate, 'HEADER'));Queues a separate Apex transaction; the current request does not wait for all queued work to finish.
100 return analysisId;Returns this value to the caller and ends the method.
101 }Closes the current block or declaration.
102 Spacing separates related steps.
103 @AuraEnabledExposes this Apex method or value to a Lightning component, or marks the next declaration when the annotation is on its own line.
104 public static Id useNativeAmendmentQuote(Id analysisId) {Method declaration: Validate a CPQ amendment Quote and enqueue the LINES job. The parentheses define its inputs; the type before the name defines its return value.
105 if (analysisId == null) {Guard or branch: the following block runs only when this condition is true.
106 throw new AuraHandledException('Select a confirmed change-order analysis.');Stops this path and reports an error to the caller.
107 }Closes the current block or declaration.
108 PS_Quote_Analysis__c analysis = [Assigns or configures the value on the left using the expression on the right.
109 SELECT Id, Opportunity__c, Status__c, Quote_Type__c,SOQL field list: identifies data to read from Salesforce.
110 Amended_Contract__c, Effective_Date__c, CurrencyIsoCode,Continues the argument list or condition on the next line.
111 Reviewed_Proposal_JSON__c, Created_Quote__c,Continues the argument list or condition on the next line.
112 Quote_Creation_Status__cPart of the surrounding declaration or expression; read it with the adjacent lines.
113 FROM PS_Quote_Analysis__c WHERE Id = :analysisId LIMIT 1 FOR UPDATESOQL source: identifies which Salesforce object to read.
114 ];Completes the statement begun on this line or the preceding lines.
115 if (analysis.Status__c != 'Confirmed' ||Guard or branch: the following block runs only when this condition is true.
116 analysis.Quote_Type__c != 'Change Order' ||Assigns or configures the value on the left using the expression on the right.
117 String.isBlank(analysis.Reviewed_Proposal_JSON__c)) {Opens a block; the indented lines below execute or belong together.
118 throw new AuraHandledException('Confirm the change-order breakdown first.');Stops this path and reports an error to the caller.
119 }Closes the current block or declaration.
120 if (analysis.Amended_Contract__c == null) {Guard or branch: the following block runs only when this condition is true.
121 throw new AuraHandledException('The analysis has no amended contract.');Stops this path and reports an error to the caller.
122 }Closes the current block or declaration.
123 parseAndValidate(analysis.Reviewed_Proposal_JSON__c);Calls parseAndValidate(): Check the saved proposal JSON and approved total.
124 Opportunity sourceOpportunity = [Assigns or configures the value on the left using the expression on the right.
125 SELECT Id, AccountId, CurrencyIsoCodeSOQL field list: identifies data to read from Salesforce.
126 FROM Opportunity WHERE Id = :analysis.Opportunity__c LIMIT 1SOQL source: identifies which Salesforce object to read.
127 ];Completes the statement begun on this line or the preceding lines.
128 Contract selectedContract = [Assigns or configures the value on the left using the expression on the right.
129 SELECT Id, AccountId FROM ContractSOQL field list: identifies data to read from Salesforce.
130 WHERE Id = :analysis.Amended_Contract__c LIMIT 1SOQL filter: narrows the records returned by this query.
131 ];Completes the statement begun on this line or the preceding lines.
132 if (sourceOpportunity.AccountId == null ||Guard or branch: the following block runs only when this condition is true.
133 sourceOpportunity.AccountId != selectedContract.AccountId ||Assigns or configures the value on the left using the expression on the right.
134 sourceOpportunity.CurrencyIsoCode != analysis.CurrencyIsoCode) {Opens a block; the indented lines below execute or belong together.
135 throw new AuraHandledException(Stops this path and reports an error to the caller.
136 'Check the Opportunity and contract Account, and the analysis currency.'Part of the surrounding declaration or expression; read it with the adjacent lines.
137 );Opens or closes the expression begun on the surrounding lines.
138 }Closes the current block or declaration.
139 List<SBQQ__Quote__c> primaryAmendments = [Creates or assigns a typed value for the steps that follow.
140 SELECT Id, SBQQ__Opportunity2__c, SBQQ__Account__c,SOQL field list: identifies data to read from Salesforce.
141 SBQQ__MasterContract__c,Continues the argument list or condition on the next line.
142 SBQQ__Type__c, SBQQ__StartDate__c, CurrencyIsoCodePart of the surrounding declaration or expression; read it with the adjacent lines.
143 FROM SBQQ__Quote__cSOQL source: identifies which Salesforce object to read.
144 WHERE SBQQ__Opportunity2__c = :analysis.Opportunity__cSOQL filter: narrows the records returned by this query.
145 AND SBQQ__Primary__c = trueSOQL filter: narrows the records returned by this query.
146 AND SBQQ__Type__c = 'Amendment'SOQL filter: narrows the records returned by this query.
147 AND SBQQ__MasterContract__c != nullSOQL filter: narrows the records returned by this query.
148 ORDER BY CreatedDate DESC LIMIT 1Sorts the records returned by this query.
149 ];Completes the statement begun on this line or the preceding lines.
150 if (primaryAmendments.isEmpty()) {Guard or branch: the following block runs only when this condition is true.
151 throw new AuraHandledException('This Opportunity has no primary CPQ amendment quote.');Stops this path and reports an error to the caller.
152 }Closes the current block or declaration.
153 SBQQ__Quote__c quoteRecord = primaryAmendments[0];Assigns or configures the value on the left using the expression on the right.
154 Id quoteId = quoteRecord.Id;Creates or assigns a typed value for the steps that follow.
155 if (quoteRecord.SBQQ__Opportunity2__c != analysis.Opportunity__c ||Guard or branch: the following block runs only when this condition is true.
156 quoteRecord.SBQQ__Account__c != sourceOpportunity.AccountId ||Assigns or configures the value on the left using the expression on the right.
157 quoteRecord.SBQQ__MasterContract__c != analysis.Amended_Contract__c ||Assigns or configures the value on the left using the expression on the right.
158 quoteRecord.SBQQ__Type__c != 'Amendment' ||Assigns or configures the value on the left using the expression on the right.
159 quoteRecord.CurrencyIsoCode != analysis.CurrencyIsoCode) {Opens a block; the indented lines below execute or belong together.
160 throw new AuraHandledException(Stops this path and reports an error to the caller.
161 'The primary amendment quote does not match this analysis, contract, or currency.'Part of the surrounding declaration or expression; read it with the adjacent lines.
162 );Opens or closes the expression begun on the surrounding lines.
163 }Closes the current block or declaration.
164 if (quoteRecord.SBQQ__StartDate__c != analysis.Effective_Date__c) {Guard or branch: the following block runs only when this condition is true.
165 throw new AuraHandledException(Stops this path and reports an error to the caller.
166 'The CPQ quote starts ' + String.valueOf(quoteRecord.SBQQ__StartDate__c) +Part of the surrounding declaration or expression; read it with the adjacent lines.
167 ', but the confirmed effective date is ' + String.valueOf(analysis.Effective_Date__c) +Part of the surrounding declaration or expression; read it with the adjacent lines.
168 '. Correct the native amendment date before adding products.'Part of the surrounding declaration or expression; read it with the adjacent lines.
169 );Opens or closes the expression begun on the surrounding lines.
170 }Closes the current block or declaration.
171 List<SBQQ__QuoteLine__c> existingAmendedLines = [Creates or assigns a typed value for the steps that follow.
172 SELECT Id FROM SBQQ__QuoteLine__cSOQL field list: identifies data to read from Salesforce.
173 WHERE SBQQ__Quote__c = :quoteId ANDSOQL filter: narrows the records returned by this query.
174 (SBQQ__UpgradedSubscription__c != null ORAssigns or configures the value on the left using the expression on the right.
175 SBQQ__UpgradedAsset__c != null)Assigns or configures the value on the left using the expression on the right.
176 LIMIT 1Caps the number of records returned by this query.
177 ];Completes the statement begun on this line or the preceding lines.
178 if (existingAmendedLines.isEmpty()) {Guard or branch: the following block runs only when this condition is true.
179 throw new AuraHandledException(Stops this path and reports an error to the caller.
180 'This quote has no existing contract lines. Create it with the standard Amend Contract action.'Part of the surrounding declaration or expression; read it with the adjacent lines.
181 );Opens or closes the expression begun on the surrounding lines.
182 }Closes the current block or declaration.
183 if (analysis.Created_Quote__c == quoteId) {Guard or branch: the following block runs only when this condition is true.
184 throw new AuraHandledException('This amendment quote is already linked to this analysis.');Stops this path and reports an error to the caller.
185 }Closes the current block or declaration.
186 if (analysis.Created_Quote__c != null) {Guard or branch: the following block runs only when this condition is true.
187 List<SBQQ__QuoteLine__c> oldNativeLines = [Creates or assigns a typed value for the steps that follow.
188 SELECT Id FROM SBQQ__QuoteLine__cSOQL field list: identifies data to read from Salesforce.
189 WHERE SBQQ__Quote__c = :analysis.Created_Quote__c ANDSOQL filter: narrows the records returned by this query.
190 (SBQQ__UpgradedSubscription__c != null ORAssigns or configures the value on the left using the expression on the right.
191 SBQQ__UpgradedAsset__c != null)Assigns or configures the value on the left using the expression on the right.
192 LIMIT 1Caps the number of records returned by this query.
193 ];Completes the statement begun on this line or the preceding lines.
194 if (!oldNativeLines.isEmpty()) {Guard or branch: the following block runs only when this condition is true.
195 throw new AuraHandledException('This analysis is already linked to a native amendment quote.');Stops this path and reports an error to the caller.
196 }Closes the current block or declaration.
197 }Closes the current block or declaration.
198 List<PS_Quote_Analysis__c> otherAnalyses = [Creates or assigns a typed value for the steps that follow.
199 SELECT Id FROM PS_Quote_Analysis__cSOQL field list: identifies data to read from Salesforce.
200 WHERE Created_Quote__c = :quoteId AND Id != :analysisId LIMIT 1SOQL filter: narrows the records returned by this query.
201 ];Completes the statement begun on this line or the preceding lines.
202 if (!otherAnalyses.isEmpty()) {Guard or branch: the following block runs only when this condition is true.
203 throw new AuraHandledException('Another analysis is already using this amendment quote.');Stops this path and reports an error to the caller.
204 }Closes the current block or declaration.
205 update new PS_Quote_Analysis__c(DML write: saves changes to the specified Salesforce record or records.
206 Id = analysisId,Creates or assigns a typed value for the steps that follow.
207 Created_Quote__c = quoteId,Assigns or configures the value on the left using the expression on the right.
208 Quote_Creation_Status__c = 'Adding Lines',Assigns or configures the value on the left using the expression on the right.
209 Quote_Creation_Error__c = nullAssigns or configures the value on the left using the expression on the right.
210 );Opens or closes the expression begun on the surrounding lines.
211 System.enqueueJob(new BuildJob(analysisId, quoteRecord.SBQQ__StartDate__c, 'LINES'));Queues a separate Apex transaction; the current request does not wait for all queued work to finish.
212 return analysisId;Returns this value to the caller and ends the method.
213 }Closes the current block or declaration.
214 Spacing separates related steps.
215 @AuraEnabledExposes this Apex method or value to a Lightning component, or marks the next declaration when the annotation is on its own line.
216 public static PS_Quote_Analysis__c getQuoteCreation(Id analysisId) {Method declaration: Return progress and error fields to the component. The parentheses define its inputs; the type before the name defines its return value.
217 if (analysisId == null) {Guard or branch: the following block runs only when this condition is true.
218 throw new AuraHandledException('Select an analysis.');Stops this path and reports an error to the caller.
219 }Closes the current block or declaration.
220 return [Returns this value to the caller and ends the method.
221 SELECT Id, Created_Quote__c, Quote_Creation_Status__c,SOQL field list: identifies data to read from Salesforce.
222 Quote_Creation_Error__cPart of the surrounding declaration or expression; read it with the adjacent lines.
223 FROM PS_Quote_Analysis__c WHERE Id = :analysisId LIMIT 1SOQL source: identifies which Salesforce object to read.
224 ];Completes the statement begun on this line or the preceding lines.
225 }Closes the current block or declaration.
226 Spacing separates related steps.
227 public class BuildJob implements Queueable, Database.AllowsCallouts {Declares a class or trigger. The braces contain its members and behavior.
228 private Id analysisId;Completes the statement begun on this line or the preceding lines.
229 private Date startDate;Completes the statement begun on this line or the preceding lines.
230 private String stage;Completes the statement begun on this line or the preceding lines.
231 Spacing separates related steps.
232 public BuildJob(Id analysisId, Date startDate, String stage) {Opens a block; the indented lines below execute or belong together.
233 this.analysisId = analysisId;Updates component state; the template may show the new value on rerender.
234 this.startDate = startDate;Updates component state; the template may show the new value on rerender.
235 this.stage = stage;Updates component state; the template may show the new value on rerender.
236 }Closes the current block or declaration.
237 Spacing separates related steps.
238 public void execute(QueueableContext context) {Method declaration: Choose HEADER, LINES, or CALCULATE; record failures. The parentheses define its inputs; the type before the name defines its return value.
239 try {Starts an operation whose exception can be handled below.
240 if (stage == 'HEADER') {Guard or branch: the following block runs only when this condition is true.
241 createHeader();Calls createHeader(): Check the configured price book and insert a Quote header.
242 } else if (stage == 'LINES') {Opens a block; the indented lines below execute or belong together.
243 addLines();Calls addLines(): Find Products and price book entries; ask CPQ to add priced lines.
244 } else if (stage == 'CALCULATE') {Opens a block; the indented lines below execute or belong together.
245 calculate();Calls calculate(): Ask CPQ to calculate and invoke the callback.
246 } else {Opens a block; the indented lines below execute or belong together.
247 throw new QuoteBuildException('Unknown quote creation stage.');Stops this path and reports an error to the caller.
248 }Closes the current block or declaration.
249 } catch (Exception ex) {Opens a block; the indented lines below execute or belong together.
250 PS_Quote_Analysis__c failed = new PS_Quote_Analysis__c(Creates or assigns a typed value for the steps that follow.
251 Id = analysisId,Creates or assigns a typed value for the steps that follow.
252 Quote_Creation_Status__c = 'Failed',Assigns or configures the value on the left using the expression on the right.
253 Quote_Creation_Error__c = ex.getMessage().left(1000)Assigns or configures the value on the left using the expression on the right.
254 );Opens or closes the expression begun on the surrounding lines.
255 update failed;DML write: saves changes to the specified Salesforce record or records.
256 }Closes the current block or declaration.
257 }Closes the current block or declaration.
258 Spacing separates related steps.
259 private void createHeader() {Method declaration: Check the configured price book and insert a Quote header. The parentheses define its inputs; the type before the name defines its return value.
260 Id servicesPricebookId = Test.isRunningTest() &&Creates or assigns a typed value for the steps that follow.
261 PsQuoteCpqController.testServicesPricebookId != nullAssigns or configures the value on the left using the expression on the right.
262 ? PsQuoteCpqController.testServicesPricebookId : SERVICES_PRICEBOOK_ID;Completes the statement begun on this line or the preceding lines.
263 PS_Quote_Analysis__c analysis = [Assigns or configures the value on the left using the expression on the right.
264 SELECT Id, Opportunity__c, Quote_Type__c, Amended_Contract__c,SOQL field list: identifies data to read from Salesforce.
265 Effective_Date__c, CurrencyIsoCode, Created_Quote__cPart of the surrounding declaration or expression; read it with the adjacent lines.
266 FROM PS_Quote_Analysis__c WHERE Id = :analysisId LIMIT 1SOQL source: identifies which Salesforce object to read.
267 ];Completes the statement begun on this line or the preceding lines.
268 if (analysis.Created_Quote__c != null) {Guard or branch: the following block runs only when this condition is true.
269 throw new QuoteBuildException('This analysis already has a quote.');Stops this path and reports an error to the caller.
270 }Closes the current block or declaration.
271 if (analysis.Quote_Type__c != 'New Services') {Guard or branch: the following block runs only when this condition is true.
272 throw new QuoteBuildException('Only new-services quote headers are created here.');Stops this path and reports an error to the caller.
273 }Closes the current block or declaration.
274 Opportunity opportunityRecord = [Assigns or configures the value on the left using the expression on the right.
275 SELECT Id, AccountId, Pricebook2Id, CurrencyIsoCodeSOQL field list: identifies data to read from Salesforce.
276 FROM Opportunity WHERE Id = :analysis.Opportunity__c LIMIT 1SOQL source: identifies which Salesforce object to read.
277 ];Completes the statement begun on this line or the preceding lines.
278 if (opportunityRecord.AccountId == null ||Guard or branch: the following block runs only when this condition is true.
279 opportunityRecord.CurrencyIsoCode != analysis.CurrencyIsoCode) {Opens a block; the indented lines below execute or belong together.
280 throw new QuoteBuildException('Check the Opportunity account and currency.');Stops this path and reports an error to the caller.
281 }Closes the current block or declaration.
282 Spacing separates related steps.
283 List<Pricebook2> books = [Creates or assigns a typed value for the steps that follow.
284 SELECT Id, IsActive FROM Pricebook2SOQL field list: identifies data to read from Salesforce.
285 WHERE Id = :servicesPricebookId LIMIT 1SOQL filter: narrows the records returned by this query.
286 ];Completes the statement begun on this line or the preceding lines.
287 if (books.isEmpty() || !books[0].IsActive) {Guard or branch: the following block runs only when this condition is true.
288 throw new QuoteBuildException('The Professional Services price book is not active.');Stops this path and reports an error to the caller.
289 }Closes the current block or declaration.
290 if (opportunityRecord.Pricebook2Id == null) {Guard or branch: the following block runs only when this condition is true.
291 update new Opportunity(DML write: saves changes to the specified Salesforce record or records.
292 Id = opportunityRecord.Id,Creates or assigns a typed value for the steps that follow.
293 Pricebook2Id = servicesPricebookIdAssigns or configures the value on the left using the expression on the right.
294 );Opens or closes the expression begun on the surrounding lines.
295 } else if (opportunityRecord.Pricebook2Id != servicesPricebookId) {Opens a block; the indented lines below execute or belong together.
296 throw new QuoteBuildException(Stops this path and reports an error to the caller.
297 'Opportunity price book ' + String.valueOf(opportunityRecord.Pricebook2Id) +Part of the surrounding declaration or expression; read it with the adjacent lines.
298 ' differs from the configured Professional Services price book ' +Part of the surrounding declaration or expression; read it with the adjacent lines.
299 String.valueOf(servicesPricebookId) + '.'Part of the surrounding declaration or expression; read it with the adjacent lines.
300 );Opens or closes the expression begun on the surrounding lines.
301 }Closes the current block or declaration.
302 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(Creates or assigns a typed value for the steps that follow.
303 SBQQ__Opportunity2__c = opportunityRecord.Id,Creates or assigns a typed value for the steps that follow.
304 SBQQ__Account__c = opportunityRecord.AccountId,Assigns or configures the value on the left using the expression on the right.
305 SBQQ__PricebookId__c = servicesPricebookId,Assigns or configures the value on the left using the expression on the right.
306 SBQQ__StartDate__c = startDate,Assigns or configures the value on the left using the expression on the right.
307 SBQQ__SubscriptionTerm__c = 24,Assigns or configures the value on the left using the expression on the right.
308 CurrencyIsoCode = analysis.CurrencyIsoCodeAssigns or configures the value on the left using the expression on the right.
309 );Opens or closes the expression begun on the surrounding lines.
310 insert quoteRecord;DML write: creates the specified Salesforce record or records.
311 Id quoteId = quoteRecord.Id;Creates or assigns a typed value for the steps that follow.
312 update new PS_Quote_Analysis__c(DML write: saves changes to the specified Salesforce record or records.
313 Id = analysisId, Created_Quote__c = quoteId,Creates or assigns a typed value for the steps that follow.
314 Quote_Creation_Status__c = 'Adding Lines'Assigns or configures the value on the left using the expression on the right.
315 );Opens or closes the expression begun on the surrounding lines.
316 System.enqueueJob(new BuildJob(analysisId, startDate, 'LINES'));Queues a separate Apex transaction; the current request does not wait for all queued work to finish.
317 }Closes the current block or declaration.
318 Spacing separates related steps.
319 private void addLines() {Method declaration: Find Products and price book entries; ask CPQ to add priced lines. The parentheses define its inputs; the type before the name defines its return value.
320 PS_Quote_Analysis__c analysis = [Assigns or configures the value on the left using the expression on the right.
321 SELECT Id, Created_Quote__c, Reviewed_Proposal_JSON__c,SOQL field list: identifies data to read from Salesforce.
322 CurrencyIsoCodePart of the surrounding declaration or expression; read it with the adjacent lines.
323 FROM PS_Quote_Analysis__c WHERE Id = :analysisId LIMIT 1SOQL source: identifies which Salesforce object to read.
324 ];Completes the statement begun on this line or the preceding lines.
325 if (analysis.Created_Quote__c == null) {Guard or branch: the following block runs only when this condition is true.
326 throw new QuoteBuildException('The CPQ quote has not been created.');Stops this path and reports an error to the caller.
327 }Closes the current block or declaration.
328 SBQQ__Quote__c quoteRecord = [Assigns or configures the value on the left using the expression on the right.
329 SELECT Id, SBQQ__PricebookId__c, CurrencyIsoCode,SOQL field list: identifies data to read from Salesforce.
330 SBQQ__StartDate__cPart of the surrounding declaration or expression; read it with the adjacent lines.
331 FROM SBQQ__Quote__c WHERE Id = :analysis.Created_Quote__c LIMIT 1SOQL source: identifies which Salesforce object to read.
332 ];Completes the statement begun on this line or the preceding lines.
333 if (quoteRecord.SBQQ__PricebookId__c == null ||Guard or branch: the following block runs only when this condition is true.
334 quoteRecord.CurrencyIsoCode != analysis.CurrencyIsoCode ||Assigns or configures the value on the left using the expression on the right.
335 quoteRecord.SBQQ__StartDate__c == null) {Opens a block; the indented lines below execute or belong together.
336 throw new QuoteBuildException('Check the quote price book, currency, and start date.');Stops this path and reports an error to the caller.
337 }Closes the current block or declaration.
338 List<Map<String, Object>> lines = parseAndValidate(Calls parseAndValidate(): Check the saved proposal JSON and approved total.
339 analysis.Reviewed_Proposal_JSON__cPart of the surrounding declaration or expression; read it with the adjacent lines.
340 );Opens or closes the expression begun on the surrounding lines.
341 Set<String> codes = new Set<String>();Creates or assigns a typed value for the steps that follow.
342 for (Map<String, Object> line : lines) {Loop: repeats the following block for each matching item.
343 codes.add(PRODUCT_CODES.get((String) line.get('category')));Completes the statement begun on this line or the preceding lines.
344 }Closes the current block or declaration.
345 Map<String, Id> productsByCode = new Map<String, Id>();Creates or assigns a typed value for the steps that follow.
346 for (Product2 product : [Loop: repeats the following block for each matching item.
347 SELECT Id, ProductCode FROM Product2SOQL field list: identifies data to read from Salesforce.
348 WHERE ProductCode IN :codes AND IsActive = trueSOQL filter: narrows the records returned by this query.
349 AND CurrencyIsoCode = :analysis.CurrencyIsoCodeSOQL filter: narrows the records returned by this query.
350 ]) {Opens a block; the indented lines below execute or belong together.
351 if (productsByCode.containsKey(product.ProductCode)) {Guard or branch: the following block runs only when this condition is true.
352 throw new QuoteBuildException('Duplicate active product code ' + product.ProductCode);Stops this path and reports an error to the caller.
353 }Closes the current block or declaration.
354 productsByCode.put(product.ProductCode, product.Id);Completes the statement begun on this line or the preceding lines.
355 }Closes the current block or declaration.
356 if (productsByCode.size() != codes.size()) {Guard or branch: the following block runs only when this condition is true.
357 throw new QuoteBuildException('One or more service products are inactive or missing.');Stops this path and reports an error to the caller.
358 }Closes the current block or declaration.
359 Set<Id> productIds = new Set<Id>(productsByCode.values());Creates or assigns a typed value for the steps that follow.
360 Set<Id> pricedIds = new Set<Id>();Creates or assigns a typed value for the steps that follow.
361 for (PricebookEntry entry : [Loop: repeats the following block for each matching item.
362 SELECT Product2Id FROM PricebookEntrySOQL field list: identifies data to read from Salesforce.
363 WHERE Pricebook2Id = :quoteRecord.SBQQ__PricebookId__cSOQL filter: narrows the records returned by this query.
364 AND CurrencyIsoCode = :analysis.CurrencyIsoCodeSOQL filter: narrows the records returned by this query.
365 AND Product2Id IN :productIds AND IsActive = trueSOQL filter: narrows the records returned by this query.
366 ]) {Opens a block; the indented lines below execute or belong together.
367 pricedIds.add(entry.Product2Id);Completes the statement begun on this line or the preceding lines.
368 }Closes the current block or declaration.
369 if (pricedIds.size() != productIds.size()) {Guard or branch: the following block runs only when this condition is true.
370 throw new QuoteBuildException('Add active price book entries for all service products.');Stops this path and reports an error to the caller.
371 }Closes the current block or declaration.
372 Spacing separates related steps.
373 String quoteJson = SBQQ.ServiceRouter.read(Calls the Salesforce CPQ managed package API for the named operation.
374 'SBQQ.QuoteAPI.QuoteReader', String.valueOf(quoteRecord.Id)Part of the surrounding declaration or expression; read it with the adjacent lines.
375 );Opens or closes the expression begun on the surrounding lines.
376 for (Map<String, Object> line : lines) {Loop: repeats the following block for each matching item.
377 String code = PRODUCT_CODES.get((String) line.get('category'));Creates or assigns a typed value for the steps that follow.
378 Id productId = productsByCode.get(code);Creates or assigns a typed value for the steps that follow.
379 String productJson = SBQQ.ServiceRouter.load(Calls the Salesforce CPQ managed package API for the named operation.
380 'SBQQ.ProductAPI.ProductLoader', String.valueOf(productId),Continues the argument list or condition on the next line.
381 JSON.serialize(new Map<String, Object>{Converts Apex values into JSON text for another API or saved field.
382 'pricebookId' => String.valueOf(quoteRecord.SBQQ__PricebookId__c),Maps the value on the left to the value on the right.
383 'currencyCode' => analysis.CurrencyIsoCodeMaps the value on the left to the value on the right.
384 })Part of the surrounding declaration or expression; read it with the adjacent lines.
385 );Opens or closes the expression begun on the surrounding lines.
386 Map<String, Object> before = asMap(JSON.deserializeUntyped(quoteJson));Parses JSON text into Apex values that the following code can inspect.
387 Set<String> previousKeys = lineKeys(before);Calls lineKeys(): Collect keys that existed before CPQ adds a Product.
388 String addedJson = SBQQ.ServiceRouter.load(Calls the Salesforce CPQ managed package API for the named operation.
389 'SBQQ.QuoteAPI.QuoteProductAdder', null,Continues the argument list or condition on the next line.
390 '{"quote":' + quoteJson + ',"products":[' + productJson +Part of the surrounding declaration or expression; read it with the adjacent lines.
391 '],"ignoreCalculate":true}'Part of the surrounding declaration or expression; read it with the adjacent lines.
392 );Opens or closes the expression begun on the surrounding lines.
393 Map<String, Object> added = asMap(JSON.deserializeUntyped(addedJson));Parses JSON text into Apex values that the following code can inspect.
394 Map<String, Object> newLine = findAddedLine(added, previousKeys);Calls findAddedLine(): Identify exactly one newly added CPQ line.
395 Map<String, Object> lineRecord = asMap(newLine.get('record'));Creates or assigns a typed value for the steps that follow.
396 lineRecord.put('SBQQ__Quantity__c', 1);Completes the statement begun on this line or the preceding lines.
397 lineRecord.put('SBQQ__ListPrice__c', line.get('amount'));Completes the statement begun on this line or the preceding lines.
398 // Feed the approved amount into CPQ's pricing waterfall as aDeveloper comment: Feed the approved amount into CPQ's pricing waterfall as a
399 // custom price. CPQ still calculates Net Total, TCV, and theDeveloper comment: custom price. CPQ still calculates Net Total, TCV, and the
400 // org's configured calculator plugin; Apex does not set them.Developer comment: org's configured calculator plugin; Apex does not set them.
401 lineRecord.put('SBQQ__SpecialPrice__c', line.get('amount'));Completes the statement begun on this line or the preceding lines.
402 lineRecord.put('SBQQ__SpecialPriceType__c', 'Custom');Completes the statement begun on this line or the preceding lines.
403 lineRecord.put('SBQQ__Description__c', line.get('label'));Completes the statement begun on this line or the preceding lines.
404 quoteJson = JSON.serialize(added);Converts Apex values into JSON text for another API or saved field.
405 }Closes the current block or declaration.
406 Spacing separates related steps.
407 SBQQ.ServiceRouter.save('SBQQ.QuoteAPI.QuoteSaver', quoteJson);Calls the Salesforce CPQ managed package API for the named operation.
408 update new PS_Quote_Analysis__c(DML write: saves changes to the specified Salesforce record or records.
409 Id = analysisId, Quote_Creation_Status__c = 'Calculating'Creates or assigns a typed value for the steps that follow.
410 );Opens or closes the expression begun on the surrounding lines.
411 System.enqueueJob(new BuildJob(analysisId, startDate, 'CALCULATE'));Queues a separate Apex transaction; the current request does not wait for all queued work to finish.
412 }Closes the current block or declaration.
413 Spacing separates related steps.
414 private void calculate() {Method declaration: Ask CPQ to calculate and invoke the callback. The parentheses define its inputs; the type before the name defines its return value.
415 PS_Quote_Analysis__c analysis = [Assigns or configures the value on the left using the expression on the right.
416 SELECT Created_Quote__c FROM PS_Quote_Analysis__cSOQL field list: identifies data to read from Salesforce.
417 WHERE Id = :analysisId LIMIT 1SOQL filter: narrows the records returned by this query.
418 ];Completes the statement begun on this line or the preceding lines.
419 String quoteJson = SBQQ.ServiceRouter.read(Calls the Salesforce CPQ managed package API for the named operation.
420 'SBQQ.QuoteAPI.QuoteReader', String.valueOf(analysis.Created_Quote__c)Part of the surrounding declaration or expression; read it with the adjacent lines.
421 );Opens or closes the expression begun on the surrounding lines.
422 SBQQ.ServiceRouter.load(Calls the Salesforce CPQ managed package API for the named operation.
423 'SBQQ.QuoteAPI.QuoteCalculator', null,Continues the argument list or condition on the next line.
424 '{"quote":' + quoteJson +Part of the surrounding declaration or expression; read it with the adjacent lines.
425 ',"callbackClass":"PsQuoteCpqCalculateCallback"}'Part of the surrounding declaration or expression; read it with the adjacent lines.
426 );Opens or closes the expression begun on the surrounding lines.
427 // The callback saves the calculated model and marks it Ready.Developer comment: The callback saves the calculated model and marks it Ready.
428 }Closes the current block or declaration.
429 }Closes the current block or declaration.
430 Spacing separates related steps.
431 @TestVisibleAllows a test class to access this normally private member.
432 private static List<Map<String, Object>> parseAndValidate(String reviewedJson) {Method declaration: Check the saved proposal JSON and approved total. The parentheses define its inputs; the type before the name defines its return value.
433 Map<String, Object> proposal;Completes the statement begun on this line or the preceding lines.
434 List<Object> rawLines;Completes the statement begun on this line or the preceding lines.
435 try {Starts an operation whose exception can be handled below.
436 proposal = asMap(JSON.deserializeUntyped(reviewedJson));Parses JSON text into Apex values that the following code can inspect.
437 rawLines = (List<Object>) proposal.get('lines');Creates or assigns a typed value for the steps that follow.
438 } catch (Exception ex) {Opens a block; the indented lines below execute or belong together.
439 throw new QuoteBuildException('The saved breakdown is not valid JSON.');Stops this path and reports an error to the caller.
440 }Closes the current block or declaration.
441 if (rawLines == null || rawLines.isEmpty() || rawLines.size() > 100) {Guard or branch: the following block runs only when this condition is true.
442 throw new QuoteBuildException('The breakdown must contain 1 to 100 lines.');Stops this path and reports an error to the caller.
443 }Closes the current block or declaration.
444 List<Map<String, Object>> result = new List<Map<String, Object>>();Creates or assigns a typed value for the steps that follow.
445 Decimal sum = 0;Creates or assigns a typed value for the steps that follow.
446 for (Object rawLine : rawLines) {Loop: repeats the following block for each matching item.
447 Map<String, Object> line = asMap(rawLine);Creates or assigns a typed value for the steps that follow.
448 String category = (String) line.get('category');Creates or assigns a typed value for the steps that follow.
449 String label = (String) line.get('label');Creates or assigns a typed value for the steps that follow.
450 if (!PRODUCT_CODES.containsKey(category) || String.isBlank(label)) {Guard or branch: the following block runs only when this condition is true.
451 throw new QuoteBuildException('Each line needs a valid category and label.');Stops this path and reports an error to the caller.
452 }Closes the current block or declaration.
453 Decimal amount;Completes the statement begun on this line or the preceding lines.
454 try {Starts an operation whose exception can be handled below.
455 amount = Decimal.valueOf(String.valueOf(line.get('amount')));Creates or assigns a typed value for the steps that follow.
456 } catch (Exception ex) {Opens a block; the indented lines below execute or belong together.
457 throw new QuoteBuildException('Each line needs a valid amount.');Stops this path and reports an error to the caller.
458 }Closes the current block or declaration.
459 if (amount <= 0 || amount != amount.setScale(2, RoundingMode.HALF_UP)) {Guard or branch: the following block runs only when this condition is true.
460 throw new QuoteBuildException('Line amounts must be positive with two decimal places.');Stops this path and reports an error to the caller.
461 }Closes the current block or declaration.
462 sum += amount;Assigns or configures the value on the left using the expression on the right.
463 result.add(line);Completes the statement begun on this line or the preceding lines.
464 }Closes the current block or declaration.
465 Decimal proposedTotal;Completes the statement begun on this line or the preceding lines.
466 try {Starts an operation whose exception can be handled below.
467 proposedTotal = Decimal.valueOf(String.valueOf(proposal.get('quote_total')));Creates or assigns a typed value for the steps that follow.
468 } catch (Exception ex) {Opens a block; the indented lines below execute or belong together.
469 throw new QuoteBuildException('The saved breakdown has no total.');Stops this path and reports an error to the caller.
470 }Closes the current block or declaration.
471 if (sum != proposedTotal) {Guard or branch: the following block runs only when this condition is true.
472 throw new QuoteBuildException('The saved line amounts do not equal the approved total.');Stops this path and reports an error to the caller.
473 }Closes the current block or declaration.
474 return result;Returns this value to the caller and ends the method.
475 }Closes the current block or declaration.
476 Spacing separates related steps.
477 @TestVisibleAllows a test class to access this normally private member.
478 private static Map<String, Object> asMap(Object value) {Opens a block; the indented lines below execute or belong together.
479 if (value == null) {Guard or branch: the following block runs only when this condition is true.
480 throw new QuoteBuildException('CPQ returned an unexpected response.');Stops this path and reports an error to the caller.
481 }Closes the current block or declaration.
482 try {Starts an operation whose exception can be handled below.
483 return (Map<String, Object>) value;Returns this value to the caller and ends the method.
484 } catch (Exception ex) {Opens a block; the indented lines below execute or belong together.
485 throw new QuoteBuildException('CPQ returned an unexpected response.');Stops this path and reports an error to the caller.
486 }Closes the current block or declaration.
487 }Closes the current block or declaration.
488 Spacing separates related steps.
489 @TestVisibleAllows a test class to access this normally private member.
490 private static Set<String> lineKeys(Map<String, Object> model) {Method declaration: Collect keys that existed before CPQ adds a Product. The parentheses define its inputs; the type before the name defines its return value.
491 Set<String> keys = new Set<String>();Creates or assigns a typed value for the steps that follow.
492 List<Object> items = (List<Object>) model.get('lineItems');Creates or assigns a typed value for the steps that follow.
493 if (items != null) {Guard or branch: the following block runs only when this condition is true.
494 for (Object item : items) {Loop: repeats the following block for each matching item.
495 keys.add(String.valueOf(asMap(item).get('key')));Completes the statement begun on this line or the preceding lines.
496 }Closes the current block or declaration.
497 }Closes the current block or declaration.
498 return keys;Returns this value to the caller and ends the method.
499 }Closes the current block or declaration.
500 Spacing separates related steps.
501 @TestVisibleAllows a test class to access this normally private member.
502 private static Map<String, Object> findAddedLine(Method declaration: Identify exactly one newly added CPQ line. The parentheses define its inputs; the type before the name defines its return value.
503 Map<String, Object> model, Set<String> previousKeysPart of the surrounding declaration or expression; read it with the adjacent lines.
504 ) {Opens a block; the indented lines below execute or belong together.
505 List<Object> items = (List<Object>) model.get('lineItems');Creates or assigns a typed value for the steps that follow.
506 Map<String, Object> found;Completes the statement begun on this line or the preceding lines.
507 if (items != null) {Guard or branch: the following block runs only when this condition is true.
508 for (Object item : items) {Loop: repeats the following block for each matching item.
509 Map<String, Object> line = asMap(item);Creates or assigns a typed value for the steps that follow.
510 if (!previousKeys.contains(String.valueOf(line.get('key')))) {Guard or branch: the following block runs only when this condition is true.
511 if (found != null) {Guard or branch: the following block runs only when this condition is true.
512 throw new QuoteBuildException('CPQ added more than one line for a service product.');Stops this path and reports an error to the caller.
513 }Closes the current block or declaration.
514 found = line;Assigns or configures the value on the left using the expression on the right.
515 }Closes the current block or declaration.
516 }Closes the current block or declaration.
517 }Closes the current block or declaration.
518 if (found == null) {Guard or branch: the following block runs only when this condition is true.
519 throw new QuoteBuildException('CPQ did not add the requested service line.');Stops this path and reports an error to the caller.
520 }Closes the current block or declaration.
521 return found;Returns this value to the caller and ends the method.
522 }Closes the current block or declaration.
523 Spacing separates related steps.
524 private class QuoteBuildException extends Exception {}Declares a class or trigger. The braces contain its members and behavior.
525}Closes the current block or declaration.