Professional Services quote project · learning edition

Apex & Lightning,
with the code beside the explanation.

A complete local reference to the classes, tests, trigger, JavaScript, HTML, and CSS. Choose an Apex class or Lightning component on the left to open its guided source.

Download this HTML guide
18 source files3,729 lines of codeDark tinted, print friendly

Read a method from top to bottom

1 · Declaration

public static Id createQuote(Id analysisId, Date startDate) names the method, its two inputs, and the ID it returns. void means no return value.

2 · Guard checks

if statements reject missing or invalid inputs before records change. An exception exits the current path with a message.

3 · Data work

SOQL SELECT reads Salesforce records. DML insert and update save them. CPQ ServiceRouter calls invoke the managed package.

4 · Result

return sends a value to the caller. A Queueable job may return from the first request before later stages finish.

Find a method by searching for its name followed by (. A declaration defines it; a call supplies actual values. static methods are called on the class name. An instance method is called on an object created with new.

How the files connect

01 · BrowserUpload a signed PDF and start analysis in psQuoteAnalyzerTools.
02 · Apex + WorkatoValidate the file and Opportunity, save the analysis, publish the event.
03 · Human reviewPoll for proposed lines, edit them, and confirm the breakdown.
04 · CPQCreate a New Services Quote or use the native amendment Quote; add lines and calculate.
05 · ResultCallback records Ready or Failed; quote-line trigger assigns budget sequence data.

The local controller and change-order action include recent test-only hooks. The latest sandbox coverage report supplied in chat showed 62% for PsQuoteCpqController before the newest local tests. This page is a source snapshot and learning aid; it does not establish that the new tests passed or production deployed.

JavaScript versus CSS: JavaScript owns screen state, calls Apex, handles clicks, and decides what is enabled. HTML renders the fields and binds events. CSS controls spacing, color, grids, and narrow-screen layout. Trace a button as HTML event → JavaScript handler → Apex method → returned data → state update → HTML rerender → CSS appearance.

Production Apex

Start with the source head and method links. The full file is preserved below each explanation.

production · 120 lines

PsQuoteAnalyzerController

Starts document analysis, checks the Opportunity and signed PDF, saves the analysis, and publishes the event Workato receives.

  • startAnalysis() line 3Validate inputs and linked PDF, create the analysis, publish the request event, return the analysis ID.
Review and understand complete source code

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.

1public with sharing class PsQuoteAnalyzerController {Declares a class or trigger. The braces contain its members and behavior.
2 @AuraEnabledExposes this Apex method or value to a Lightning component, or marks the next declaration when the annotation is on its own line.
3 public static Id startAnalysis(Method declaration: Validate inputs and linked PDF, create the analysis, publish the request event, return the analysis ID. The parentheses define its inputs; the type before the name defines its return value.
4 Id opportunityId,Continues the argument list or condition on the next line.
5 Id contentDocumentId,Continues the argument list or condition on the next line.
6 String quoteType,Continues the argument list or condition on the next line.
7 Date effectiveDatePart of the surrounding declaration or expression; read it with the adjacent lines.
8 ) {Opens a block; the indented lines below execute or belong together.
9 if (opportunityId == null || contentDocumentId == null) {Guard or branch: the following block runs only when this condition is true.
10 throw new AuraHandledException('Select an Opportunity and upload a document.');Stops this path and reports an error to the caller.
11 }Closes the current block or declaration.
12 if (quoteType != 'new' && quoteType != 'amendment') {Guard or branch: the following block runs only when this condition is true.
13 throw new AuraHandledException('Select New services or Change order.');Stops this path and reports an error to the caller.
14 }Closes the current block or declaration.
15 Spacing separates related steps.
16 List<Opportunity> opportunities = [Creates or assigns a typed value for the steps that follow.
17 SELECT Id, AccountIdSOQL field list: identifies data to read from Salesforce.
18 FROM OpportunitySOQL source: identifies which Salesforce object to read.
19 WHERE Id = :opportunityIdSOQL filter: narrows the records returned by this query.
20 WITH USER_MODERuns this read using the current user’s data and field permissions.
21 LIMIT 1Caps the number of records returned by this query.
22 ];Completes the statement begun on this line or the preceding lines.
23 if (opportunities.isEmpty()) {Guard or branch: the following block runs only when this condition is true.
24 throw new AuraHandledException('Opportunity not found or not accessible.');Stops this path and reports an error to the caller.
25 }Closes the current block or declaration.
26 Opportunity opportunityRecord = opportunities[0];Assigns or configures the value on the left using the expression on the right.
27 Spacing separates related steps.
28 Id contractId;Completes the statement begun on this line or the preceding lines.
29 if (quoteType == 'amendment') {Guard or branch: the following block runs only when this condition is true.
30 if (effectiveDate == null) {Guard or branch: the following block runs only when this condition is true.
31 throw new AuraHandledException('Enter the change effective date.');Stops this path and reports an error to the caller.
32 }Closes the current block or declaration.
33 List<SBQQ__Quote__c> primaryAmendments = [Creates or assigns a typed value for the steps that follow.
34 SELECT Id, SBQQ__MasterContract__c, SBQQ__StartDate__cSOQL field list: identifies data to read from Salesforce.
35 FROM SBQQ__Quote__cSOQL source: identifies which Salesforce object to read.
36 WHERE SBQQ__Opportunity2__c = :opportunityIdSOQL filter: narrows the records returned by this query.
37 AND SBQQ__Account__c = :opportunityRecord.AccountIdSOQL filter: narrows the records returned by this query.
38 AND SBQQ__MasterContract__c != nullSOQL filter: narrows the records returned by this query.
39 AND SBQQ__Primary__c = trueSOQL filter: narrows the records returned by this query.
40 AND SBQQ__Type__c = 'Amendment'SOQL filter: narrows the records returned by this query.
41 WITH USER_MODE ORDER BY CreatedDate DESC LIMIT 1Runs this read using the current user’s data and field permissions.
42 ];Completes the statement begun on this line or the preceding lines.
43 if (primaryAmendments.isEmpty()) {Guard or branch: the following block runs only when this condition is true.
44 throw new AuraHandledException(Stops this path and reports an error to the caller.
45 'This Opportunity needs a primary CPQ amendment quote before analysis.'Part of the surrounding declaration or expression; read it with the adjacent lines.
46 );Opens or closes the expression begun on the surrounding lines.
47 }Closes the current block or declaration.
48 contractId = primaryAmendments[0].SBQQ__MasterContract__c;Assigns or configures the value on the left using the expression on the right.
49 if (primaryAmendments[0].SBQQ__StartDate__c != effectiveDate) {Guard or branch: the following block runs only when this condition is true.
50 throw new AuraHandledException(Stops this path and reports an error to the caller.
51 'The effective date must match the primary amendment quote start date. ' +Part of the surrounding declaration or expression; read it with the adjacent lines.
52 'Correct the CPQ amendment before starting analysis.'Part of the surrounding declaration or expression; read it with the adjacent lines.
53 );Opens or closes the expression begun on the surrounding lines.
54 }Closes the current block or declaration.
55 } else {Opens a block; the indented lines below execute or belong together.
56 effectiveDate = null;Assigns or configures the value on the left using the expression on the right.
57 }Closes the current block or declaration.
58 Spacing separates related steps.
59 List<ContentDocumentLink> fileLinks = [Creates or assigns a typed value for the steps that follow.
60 SELECT IdSOQL field list: identifies data to read from Salesforce.
61 FROM ContentDocumentLinkSOQL source: identifies which Salesforce object to read.
62 WHERE ContentDocumentId = :contentDocumentIdSOQL filter: narrows the records returned by this query.
63 AND LinkedEntityId = :opportunityIdSOQL filter: narrows the records returned by this query.
64 WITH USER_MODERuns this read using the current user’s data and field permissions.
65 LIMIT 1Caps the number of records returned by this query.
66 ];Completes the statement begun on this line or the preceding lines.
67 if (fileLinks.isEmpty()) {Guard or branch: the following block runs only when this condition is true.
68 throw new AuraHandledException('The uploaded file is not linked to this Opportunity.');Stops this path and reports an error to the caller.
69 }Closes the current block or declaration.
70 Spacing separates related steps.
71 List<ContentDocument> documents = [Creates or assigns a typed value for the steps that follow.
72 SELECT Id, LatestPublishedVersionIdSOQL field list: identifies data to read from Salesforce.
73 FROM ContentDocumentSOQL source: identifies which Salesforce object to read.
74 WHERE Id = :contentDocumentIdSOQL filter: narrows the records returned by this query.
75 WITH USER_MODERuns this read using the current user’s data and field permissions.
76 LIMIT 1Caps the number of records returned by this query.
77 ];Completes the statement begun on this line or the preceding lines.
78 if (documents.isEmpty() || documents[0].LatestPublishedVersionId == null) {Guard or branch: the following block runs only when this condition is true.
79 throw new AuraHandledException('The uploaded file version is unavailable.');Stops this path and reports an error to the caller.
80 }Closes the current block or declaration.
81 Spacing separates related steps.
82 Id latestVersionId = documents[0].LatestPublishedVersionId;Creates or assigns a typed value for the steps that follow.
83 List<ContentVersion> versions = [Creates or assigns a typed value for the steps that follow.
84 SELECT Id, FileExtensionSOQL field list: identifies data to read from Salesforce.
85 FROM ContentVersionSOQL source: identifies which Salesforce object to read.
86 WHERE Id = :latestVersionIdSOQL filter: narrows the records returned by this query.
87 WITH USER_MODERuns this read using the current user’s data and field permissions.
88 LIMIT 1Caps the number of records returned by this query.
89 ];Completes the statement begun on this line or the preceding lines.
90 if (versions.isEmpty() || versions[0].FileExtension == null) {Guard or branch: the following block runs only when this condition is true.
91 throw new AuraHandledException('The uploaded file version is unavailable.');Stops this path and reports an error to the caller.
92 }Closes the current block or declaration.
93 String extension = versions[0].FileExtension.toLowerCase();Creates or assigns a typed value for the steps that follow.
94 if (extension != 'pdf') {Guard or branch: the following block runs only when this condition is true.
95 throw new AuraHandledException('Upload a signed PDF file.');Stops this path and reports an error to the caller.
96 }Closes the current block or declaration.
97 Spacing separates related steps.
98 PS_Quote_Analysis__c analysis = new PS_Quote_Analysis__c(Creates or assigns a typed value for the steps that follow.
99 Opportunity__c = opportunityId,Assigns or configures the value on the left using the expression on the right.
100 Content_Document_Id__c = String.valueOf(contentDocumentId),Creates or assigns a typed value for the steps that follow.
101 Content_Version_Id__c = String.valueOf(versions[0].Id),Creates or assigns a typed value for the steps that follow.
102 Quote_Type__c = quoteType == 'new' ? 'New Services' : 'Change Order',Creates or assigns a typed value for the steps that follow.
103 Amended_Contract__c = contractId,Assigns or configures the value on the left using the expression on the right.
104 Effective_Date__c = effectiveDate,Assigns or configures the value on the left using the expression on the right.
105 Status__c = 'Queued'Assigns or configures the value on the left using the expression on the right.
106 );Opens or closes the expression begun on the surrounding lines.
107 Database.insert(analysis, AccessLevel.USER_MODE);DML write: creates the specified Salesforce record or records.
108 Spacing separates related steps.
109 PS_Quote_Analysis_Requested__e requestEvent =Assigns or configures the value on the left using the expression on the right.
110 new PS_Quote_Analysis_Requested__e(Part of the surrounding declaration or expression; read it with the adjacent lines.
111 Analysis_Id__c = String.valueOf(analysis.Id)Creates or assigns a typed value for the steps that follow.
112 );Opens or closes the expression begun on the surrounding lines.
113 Database.SaveResult publishResult = EventBus.publish(requestEvent);Assigns or configures the value on the left using the expression on the right.
114 if (!publishResult.isSuccess()) {Guard or branch: the following block runs only when this condition is true.
115 throw new AuraHandledException('The analysis request could not be published.');Stops this path and reports an error to the caller.
116 }Closes the current block or declaration.
117 Spacing separates related steps.
118 return analysis.Id;Returns this value to the caller and ends the method.
119 }Closes the current block or declaration.
120}Closes the current block or declaration.
View complete source code
1public with sharing class PsQuoteAnalyzerController {
2 @AuraEnabled
3 public static Id startAnalysis(
4 Id opportunityId,
5 Id contentDocumentId,
6 String quoteType,
7 Date effectiveDate
8 ) {
9 if (opportunityId == null || contentDocumentId == null) {
10 throw new AuraHandledException('Select an Opportunity and upload a document.');
11 }
12 if (quoteType != 'new' && quoteType != 'amendment') {
13 throw new AuraHandledException('Select New services or Change order.');
14 }
15
16 List<Opportunity> opportunities = [
17 SELECT Id, AccountId
18 FROM Opportunity
19 WHERE Id = :opportunityId
20 WITH USER_MODE
21 LIMIT 1
22 ];
23 if (opportunities.isEmpty()) {
24 throw new AuraHandledException('Opportunity not found or not accessible.');
25 }
26 Opportunity opportunityRecord = opportunities[0];
27
28 Id contractId;
29 if (quoteType == 'amendment') {
30 if (effectiveDate == null) {
31 throw new AuraHandledException('Enter the change effective date.');
32 }
33 List<SBQQ__Quote__c> primaryAmendments = [
34 SELECT Id, SBQQ__MasterContract__c, SBQQ__StartDate__c
35 FROM SBQQ__Quote__c
36 WHERE SBQQ__Opportunity2__c = :opportunityId
37 AND SBQQ__Account__c = :opportunityRecord.AccountId
38 AND SBQQ__MasterContract__c != null
39 AND SBQQ__Primary__c = true
40 AND SBQQ__Type__c = 'Amendment'
41 WITH USER_MODE ORDER BY CreatedDate DESC LIMIT 1
42 ];
43 if (primaryAmendments.isEmpty()) {
44 throw new AuraHandledException(
45 'This Opportunity needs a primary CPQ amendment quote before analysis.'
46 );
47 }
48 contractId = primaryAmendments[0].SBQQ__MasterContract__c;
49 if (primaryAmendments[0].SBQQ__StartDate__c != effectiveDate) {
50 throw new AuraHandledException(
51 'The effective date must match the primary amendment quote start date. ' +
52 'Correct the CPQ amendment before starting analysis.'
53 );
54 }
55 } else {
56 effectiveDate = null;
57 }
58
59 List<ContentDocumentLink> fileLinks = [
60 SELECT Id
61 FROM ContentDocumentLink
62 WHERE ContentDocumentId = :contentDocumentId
63 AND LinkedEntityId = :opportunityId
64 WITH USER_MODE
65 LIMIT 1
66 ];
67 if (fileLinks.isEmpty()) {
68 throw new AuraHandledException('The uploaded file is not linked to this Opportunity.');
69 }
70
71 List<ContentDocument> documents = [
72 SELECT Id, LatestPublishedVersionId
73 FROM ContentDocument
74 WHERE Id = :contentDocumentId
75 WITH USER_MODE
76 LIMIT 1
77 ];
78 if (documents.isEmpty() || documents[0].LatestPublishedVersionId == null) {
79 throw new AuraHandledException('The uploaded file version is unavailable.');
80 }
81
82 Id latestVersionId = documents[0].LatestPublishedVersionId;
83 List<ContentVersion> versions = [
84 SELECT Id, FileExtension
85 FROM ContentVersion
86 WHERE Id = :latestVersionId
87 WITH USER_MODE
88 LIMIT 1
89 ];
90 if (versions.isEmpty() || versions[0].FileExtension == null) {
91 throw new AuraHandledException('The uploaded file version is unavailable.');
92 }
93 String extension = versions[0].FileExtension.toLowerCase();
94 if (extension != 'pdf') {
95 throw new AuraHandledException('Upload a signed PDF file.');
96 }
97
98 PS_Quote_Analysis__c analysis = new PS_Quote_Analysis__c(
99 Opportunity__c = opportunityId,
100 Content_Document_Id__c = String.valueOf(contentDocumentId),
101 Content_Version_Id__c = String.valueOf(versions[0].Id),
102 Quote_Type__c = quoteType == 'new' ? 'New Services' : 'Change Order',
103 Amended_Contract__c = contractId,
104 Effective_Date__c = effectiveDate,
105 Status__c = 'Queued'
106 );
107 Database.insert(analysis, AccessLevel.USER_MODE);
108
109 PS_Quote_Analysis_Requested__e requestEvent =
110 new PS_Quote_Analysis_Requested__e(
111 Analysis_Id__c = String.valueOf(analysis.Id)
112 );
113 Database.SaveResult publishResult = EventBus.publish(requestEvent);
114 if (!publishResult.isSuccess()) {
115 throw new AuraHandledException('The analysis request could not be published.');
116 }
117
118 return analysis.Id;
119 }
120}
production · 122 lines

PsQuoteAnalysisReviewController

Reads the latest analysis and normalizes a person’s reviewed lines before saving a confirmed breakdown.

Review and understand complete source code

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.

1public with sharing class PsQuoteAnalysisReviewController {Declares a class or trigger. The braces contain its members and behavior.
2 private static final Set<String> ALLOWED_CATEGORIES = new Set<String>{Opens a block; the indented lines below execute or belong together.
3 'TIME_MATERIAL',Continues the argument list or condition on the next line.
4 'PREPAID_TIME_MATERIAL',Continues the argument list or condition on the next line.
5 'MILESTONE',Continues the argument list or condition on the next line.
6 'MILESTONE_TIME_MATERIAL'Part of the surrounding declaration or expression; read it with the adjacent lines.
7 };Closes the current block or declaration.
8 Spacing separates related steps.
9 @AuraEnabledExposes this Apex method or value to a Lightning component, or marks the next declaration when the annotation is on its own line.
10 public static PS_Quote_Analysis__c getLatestAnalysis(Id opportunityId) {Method declaration: Read the newest analysis for the Opportunity. The parentheses define its inputs; the type before the name defines its return value.
11 if (opportunityId == null) {Guard or branch: the following block runs only when this condition is true.
12 throw new AuraHandledException('Open an Opportunity to view its analysis.');Stops this path and reports an error to the caller.
13 }Closes the current block or declaration.
14 Spacing separates related steps.
15 List<PS_Quote_Analysis__c> analyses = [Creates or assigns a typed value for the steps that follow.
16 SELECT Id, Name, Status__c, CurrencyIsoCode, Quote_Type__c,SOQL field list: identifies data to read from Salesforce.
17 Effective_Date__c, AI_Proposal_JSON__c, Reviewed_Proposal_JSON__c,Continues the argument list or condition on the next line.
18 Created_Quote__c, Quote_Creation_Status__c, Quote_Creation_Error__cPart of the surrounding declaration or expression; read it with the adjacent lines.
19 FROM PS_Quote_Analysis__cSOQL source: identifies which Salesforce object to read.
20 WHERE Opportunity__c = :opportunityIdSOQL filter: narrows the records returned by this query.
21 WITH USER_MODERuns this read using the current user’s data and field permissions.
22 ORDER BY CreatedDate DESCSorts the records returned by this query.
23 LIMIT 1Caps the number of records returned by this query.
24 ];Completes the statement begun on this line or the preceding lines.
25 return analyses.isEmpty() ? null : analyses[0];Returns this value to the caller and ends the method.
26 }Closes the current block or declaration.
27 Spacing separates related steps.
28 @AuraEnabledExposes this Apex method or value to a Lightning component, or marks the next declaration when the annotation is on its own line.
29 public static void confirmBreakdown(Id analysisId, String reviewedJson) {Method declaration: Save the reviewed and normalized lines as Confirmed. The parentheses define its inputs; the type before the name defines its return value.
30 if (analysisId == null || String.isBlank(reviewedJson)) {Guard or branch: the following block runs only when this condition is true.
31 throw new AuraHandledException('No breakdown was provided.');Stops this path and reports an error to the caller.
32 }Closes the current block or declaration.
33 Spacing separates related steps.
34 List<PS_Quote_Analysis__c> analyses = [Creates or assigns a typed value for the steps that follow.
35 SELECT Id, Status__c, CurrencyIsoCode, AI_Proposal_JSON__cSOQL field list: identifies data to read from Salesforce.
36 FROM PS_Quote_Analysis__cSOQL source: identifies which Salesforce object to read.
37 WHERE Id = :analysisIdSOQL filter: narrows the records returned by this query.
38 WITH USER_MODERuns this read using the current user’s data and field permissions.
39 LIMIT 1Caps the number of records returned by this query.
40 ];Completes the statement begun on this line or the preceding lines.
41 if (analyses.isEmpty() || analyses[0].Status__c != 'Needs Review' ||Guard or branch: the following block runs only when this condition is true.
42 String.isBlank(analyses[0].AI_Proposal_JSON__c)) {Opens a block; the indented lines below execute or belong together.
43 throw new AuraHandledException('This analysis is not ready for review.');Stops this path and reports an error to the caller.
44 }Closes the current block or declaration.
45 Spacing separates related steps.
46 String normalizedJson = normalizeBreakdown(Calls normalizeBreakdown(): Check currency, categories, labels, amounts, line count, and total.
47 reviewedJson, analyses[0].CurrencyIsoCodePart of the surrounding declaration or expression; read it with the adjacent lines.
48 );Opens or closes the expression begun on the surrounding lines.
49 PS_Quote_Analysis__c updateRecord = new PS_Quote_Analysis__c(Creates or assigns a typed value for the steps that follow.
50 Id = analysisId,Creates or assigns a typed value for the steps that follow.
51 Reviewed_Proposal_JSON__c = normalizedJson,Assigns or configures the value on the left using the expression on the right.
52 Status__c = 'Confirmed'Assigns or configures the value on the left using the expression on the right.
53 );Opens or closes the expression begun on the surrounding lines.
54 Database.update(updateRecord, AccessLevel.USER_MODE);DML write: saves changes to the specified Salesforce record or records.
55 }Closes the current block or declaration.
56 Spacing separates related steps.
57 @TestVisibleAllows a test class to access this normally private member.
58 private static String normalizeBreakdown(String reviewedJson, String analysisCurrency) {Method declaration: Check currency, categories, labels, amounts, line count, and total. The parentheses define its inputs; the type before the name defines its return value.
59 Map<String, Object> proposal;Completes the statement begun on this line or the preceding lines.
60 List<Object> submittedLines;Completes the statement begun on this line or the preceding lines.
61 try {Starts an operation whose exception can be handled below.
62 proposal = (Map<String, Object>) JSON.deserializeUntyped(reviewedJson);Parses JSON text into Apex values that the following code can inspect.
63 submittedLines = (List<Object>) proposal.get('lines');Creates or assigns a typed value for the steps that follow.
64 } catch (Exception parsingError) {Opens a block; the indented lines below execute or belong together.
65 throw new AuraHandledException('The reviewed breakdown is not valid JSON.');Stops this path and reports an error to the caller.
66 }Closes the current block or declaration.
67 if (submittedLines == null || submittedLines.isEmpty() || submittedLines.size() > 100) {Guard or branch: the following block runs only when this condition is true.
68 throw new AuraHandledException('Add between 1 and 100 quote lines.');Stops this path and reports an error to the caller.
69 }Closes the current block or declaration.
70 Spacing separates related steps.
71 String currencyCode = (String) proposal.get('currency_code');Creates or assigns a typed value for the steps that follow.
72 if (String.isBlank(currencyCode) ||Guard or branch: the following block runs only when this condition is true.
73 currencyCode != analysisCurrency) {Opens a block; the indented lines below execute or belong together.
74 throw new AuraHandledException('The breakdown currency must match the Opportunity currency.');Stops this path and reports an error to the caller.
75 }Closes the current block or declaration.
76 Spacing separates related steps.
77 Decimal total = 0;Creates or assigns a typed value for the steps that follow.
78 List<Object> normalizedLines = new List<Object>();Creates or assigns a typed value for the steps that follow.
79 for (Object submittedLine : submittedLines) {Loop: repeats the following block for each matching item.
80 Map<String, Object> line;Completes the statement begun on this line or the preceding lines.
81 try {Starts an operation whose exception can be handled below.
82 line = (Map<String, Object>) submittedLine;Creates or assigns a typed value for the steps that follow.
83 } catch (Exception lineError) {Opens a block; the indented lines below execute or belong together.
84 throw new AuraHandledException('Every quote line needs a category, label, and amount.');Stops this path and reports an error to the caller.
85 }Closes the current block or declaration.
86 Spacing separates related steps.
87 String category = (String) line.get('category');Creates or assigns a typed value for the steps that follow.
88 String label = (String) line.get('label');Creates or assigns a typed value for the steps that follow.
89 if (!ALLOWED_CATEGORIES.contains(category) || String.isBlank(label) ||Guard or branch: the following block runs only when this condition is true.
90 label.length() > 255) {Opens a block; the indented lines below execute or belong together.
91 throw new AuraHandledException('Check each quote line category and label.');Stops this path and reports an error to the caller.
92 }Closes the current block or declaration.
93 Spacing separates related steps.
94 Decimal amount;Completes the statement begun on this line or the preceding lines.
95 try {Starts an operation whose exception can be handled below.
96 amount = Decimal.valueOf(String.valueOf(line.get('amount')));Creates or assigns a typed value for the steps that follow.
97 } catch (Exception amountError) {Opens a block; the indented lines below execute or belong together.
98 throw new AuraHandledException('Every quote line needs a valid amount.');Stops this path and reports an error to the caller.
99 }Closes the current block or declaration.
100 if (amount <= 0 || amount != amount.setScale(2, RoundingMode.HALF_UP)) {Guard or branch: the following block runs only when this condition is true.
101 throw new AuraHandledException('Line amounts must be positive, with at most two decimal places.');Stops this path and reports an error to the caller.
102 }Closes the current block or declaration.
103 Spacing separates related steps.
104 total += amount;Assigns or configures the value on the left using the expression on the right.
105 normalizedLines.add(new Map<String, Object>{Opens a block; the indented lines below execute or belong together.
106 'category' => category,Maps the value on the left to the value on the right.
107 'label' => label.trim(),Maps the value on the left to the value on the right.
108 'amount' => amountMaps the value on the left to the value on the right.
109 });Completes the statement begun on this line or the preceding lines.
110 }Closes the current block or declaration.
111 Spacing separates related steps.
112 Map<String, Object> normalizedBreakdown = new Map<String, Object>{Opens a block; the indented lines below execute or belong together.
113 'currency_code' => currencyCode,Maps the value on the left to the value on the right.
114 'quote_total' => total,Maps the value on the left to the value on the right.
115 'lines' => normalizedLines,Maps the value on the left to the value on the right.
116 'needs_review' => false,Maps the value on the left to the value on the right.
117 'review_reason' => ''Maps the value on the left to the value on the right.
118 };Closes the current block or declaration.
119 Spacing separates related steps.
120 return JSON.serialize(normalizedBreakdown);Returns this value to the caller and ends the method.
121 }Closes the current block or declaration.
122}Closes the current block or declaration.
View complete source code
1public with sharing class PsQuoteAnalysisReviewController {
2 private static final Set<String> ALLOWED_CATEGORIES = new Set<String>{
3 'TIME_MATERIAL',
4 'PREPAID_TIME_MATERIAL',
5 'MILESTONE',
6 'MILESTONE_TIME_MATERIAL'
7 };
8
9 @AuraEnabled
10 public static PS_Quote_Analysis__c getLatestAnalysis(Id opportunityId) {
11 if (opportunityId == null) {
12 throw new AuraHandledException('Open an Opportunity to view its analysis.');
13 }
14
15 List<PS_Quote_Analysis__c> analyses = [
16 SELECT Id, Name, Status__c, CurrencyIsoCode, Quote_Type__c,
17 Effective_Date__c, AI_Proposal_JSON__c, Reviewed_Proposal_JSON__c,
18 Created_Quote__c, Quote_Creation_Status__c, Quote_Creation_Error__c
19 FROM PS_Quote_Analysis__c
20 WHERE Opportunity__c = :opportunityId
21 WITH USER_MODE
22 ORDER BY CreatedDate DESC
23 LIMIT 1
24 ];
25 return analyses.isEmpty() ? null : analyses[0];
26 }
27
28 @AuraEnabled
29 public static void confirmBreakdown(Id analysisId, String reviewedJson) {
30 if (analysisId == null || String.isBlank(reviewedJson)) {
31 throw new AuraHandledException('No breakdown was provided.');
32 }
33
34 List<PS_Quote_Analysis__c> analyses = [
35 SELECT Id, Status__c, CurrencyIsoCode, AI_Proposal_JSON__c
36 FROM PS_Quote_Analysis__c
37 WHERE Id = :analysisId
38 WITH USER_MODE
39 LIMIT 1
40 ];
41 if (analyses.isEmpty() || analyses[0].Status__c != 'Needs Review' ||
42 String.isBlank(analyses[0].AI_Proposal_JSON__c)) {
43 throw new AuraHandledException('This analysis is not ready for review.');
44 }
45
46 String normalizedJson = normalizeBreakdown(
47 reviewedJson, analyses[0].CurrencyIsoCode
48 );
49 PS_Quote_Analysis__c updateRecord = new PS_Quote_Analysis__c(
50 Id = analysisId,
51 Reviewed_Proposal_JSON__c = normalizedJson,
52 Status__c = 'Confirmed'
53 );
54 Database.update(updateRecord, AccessLevel.USER_MODE);
55 }
56
57 @TestVisible
58 private static String normalizeBreakdown(String reviewedJson, String analysisCurrency) {
59 Map<String, Object> proposal;
60 List<Object> submittedLines;
61 try {
62 proposal = (Map<String, Object>) JSON.deserializeUntyped(reviewedJson);
63 submittedLines = (List<Object>) proposal.get('lines');
64 } catch (Exception parsingError) {
65 throw new AuraHandledException('The reviewed breakdown is not valid JSON.');
66 }
67 if (submittedLines == null || submittedLines.isEmpty() || submittedLines.size() > 100) {
68 throw new AuraHandledException('Add between 1 and 100 quote lines.');
69 }
70
71 String currencyCode = (String) proposal.get('currency_code');
72 if (String.isBlank(currencyCode) ||
73 currencyCode != analysisCurrency) {
74 throw new AuraHandledException('The breakdown currency must match the Opportunity currency.');
75 }
76
77 Decimal total = 0;
78 List<Object> normalizedLines = new List<Object>();
79 for (Object submittedLine : submittedLines) {
80 Map<String, Object> line;
81 try {
82 line = (Map<String, Object>) submittedLine;
83 } catch (Exception lineError) {
84 throw new AuraHandledException('Every quote line needs a category, label, and amount.');
85 }
86
87 String category = (String) line.get('category');
88 String label = (String) line.get('label');
89 if (!ALLOWED_CATEGORIES.contains(category) || String.isBlank(label) ||
90 label.length() > 255) {
91 throw new AuraHandledException('Check each quote line category and label.');
92 }
93
94 Decimal amount;
95 try {
96 amount = Decimal.valueOf(String.valueOf(line.get('amount')));
97 } catch (Exception amountError) {
98 throw new AuraHandledException('Every quote line needs a valid amount.');
99 }
100 if (amount <= 0 || amount != amount.setScale(2, RoundingMode.HALF_UP)) {
101 throw new AuraHandledException('Line amounts must be positive, with at most two decimal places.');
102 }
103
104 total += amount;
105 normalizedLines.add(new Map<String, Object>{
106 'category' => category,
107 'label' => label.trim(),
108 'amount' => amount
109 });
110 }
111
112 Map<String, Object> normalizedBreakdown = new Map<String, Object>{
113 'currency_code' => currencyCode,
114 'quote_total' => total,
115 'lines' => normalizedLines,
116 'needs_review' => false,
117 'review_reason' => ''
118 };
119
120 return JSON.serialize(normalizedBreakdown);
121 }
122}
production · 525 lines

PsQuoteCpqController

Creates New Services quotes in queued HEADER → LINES → CALCULATE stages, or adds approved lines to a native amendment quote.

This local source includes a recent test-only hook. Verify the current Salesforce version before copying or deploying the class.

Review and understand complete source code

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

PsQuoteCpqCalculateCallback

Receives CPQ calculation results, checks approved versus calculated amounts, and updates quote and analysis status.

Review and understand complete source code

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/** Saves the result of the asynchronous CPQ Quote Calculator. */Starts a developer comment describing the code below.
2global without sharing class PsQuoteCpqCalculateCallback implements SBQQ.CalculateCallback {Declares a class or trigger. The braces contain its members and behavior.
3 global void callback(String quoteJSON) {Method declaration: Save the calculated model and mark the analysis Ready or Failed. The parentheses define its inputs; the type before the name defines its return value.
4 String savedJson = SBQQ.ServiceRouter.save('SBQQ.QuoteAPI.QuoteSaver', quoteJSON);Calls the Salesforce CPQ managed package API for the named operation.
5 Map<String, Object> model = (Map<String, Object>) JSON.deserializeUntyped(savedJson);Parses JSON text into Apex values that the following code can inspect.
6 Map<String, Object> record = (Map<String, Object>) model.get('record');Creates or assigns a typed value for the steps that follow.
7 Id quoteId = (Id) record.get('Id');Creates or assigns a typed value for the steps that follow.
8 List<PS_Quote_Analysis__c> analyses = [Creates or assigns a typed value for the steps that follow.
9 SELECT Id, Quote_Type__c, Reviewed_Proposal_JSON__c FROM PS_Quote_Analysis__cSOQL field list: identifies data to read from Salesforce.
10 WHERE Created_Quote__c = :quoteId LIMIT 1SOQL filter: narrows the records returned by this query.
11 ];Completes the statement begun on this line or the preceding lines.
12 if (!analyses.isEmpty()) {Guard or branch: the following block runs only when this condition is true.
13 Map<String, Object> proposal = (Map<String, Object>) JSON.deserializeUntyped(Parses JSON text into Apex values that the following code can inspect.
14 analyses[0].Reviewed_Proposal_JSON__cPart of the surrounding declaration or expression; read it with the adjacent lines.
15 );Opens or closes the expression begun on the surrounding lines.
16 Decimal approvedTotal = Decimal.valueOf(Creates or assigns a typed value for the steps that follow.
17 String.valueOf(proposal.get('quote_total'))Part of the surrounding declaration or expression; read it with the adjacent lines.
18 );Opens or closes the expression begun on the surrounding lines.
19 List<SBQQ__QuoteLine__c> quoteLines = [Creates or assigns a typed value for the steps that follow.
20 SELECT SBQQ__NetTotal__c, SBQQ__Optional__c,SOQL field list: identifies data to read from Salesforce.
21 SBQQ__UpgradedSubscription__c, SBQQ__UpgradedAsset__cPart of the surrounding declaration or expression; read it with the adjacent lines.
22 FROM SBQQ__QuoteLine__c WHERE SBQQ__Quote__c = :quoteIdSOQL source: identifies which Salesforce object to read.
23 ];Completes the statement begun on this line or the preceding lines.
24 Decimal cpqTotal = sumChargeableLines(analyses[0].Quote_Type__c, quoteLines);Calls sumChargeableLines(): Exclude optional and previously upgraded lines where appropriate.
25 Boolean pricingMatches = cpqTotal.setScale(2) == approvedTotal.setScale(2);Creates or assigns a typed value for the steps that follow.
26 String primaryError = pricingMatches ? makePrimaryIfLatest(quoteId) : null;Calls makePrimaryIfLatest(): Make the latest Quote primary while preserving rollback on failure.
27 Boolean ready = pricingMatches && primaryError == null;Creates or assigns a typed value for the steps that follow.
28 update new PS_Quote_Analysis__c(DML write: saves changes to the specified Salesforce record or records.
29 Id = analyses[0].Id,Creates or assigns a typed value for the steps that follow.
30 Quote_Creation_Status__c = ready ? 'Ready' : 'Failed',Assigns or configures the value on the left using the expression on the right.
31 Quote_Creation_Error__c = primaryError != null ? primaryError :Assigns or configures the value on the left using the expression on the right.
32 (pricingMatches ? null :Part of the surrounding declaration or expression; read it with the adjacent lines.
33 'CPQ calculated ' + String.valueOf(cpqTotal.setScale(2)) +Part of the surrounding declaration or expression; read it with the adjacent lines.
34 ' but the confirmed breakdown totals ' +Part of the surrounding declaration or expression; read it with the adjacent lines.
35 String.valueOf(approvedTotal.setScale(2)) +Part of the surrounding declaration or expression; read it with the adjacent lines.
36 '. Open the quote and review pricing before using it.')Part of the surrounding declaration or expression; read it with the adjacent lines.
37 );Opens or closes the expression begun on the surrounding lines.
38 }Closes the current block or declaration.
39 }Closes the current block or declaration.
40 Spacing separates related steps.
41 @TestVisibleAllows a test class to access this normally private member.
42 private static Decimal sumChargeableLines(Method declaration: Exclude optional and previously upgraded lines where appropriate. The parentheses define its inputs; the type before the name defines its return value.
43 String quoteType, List<SBQQ__QuoteLine__c> quoteLinesPart of the surrounding declaration or expression; read it with the adjacent lines.
44 ) {Opens a block; the indented lines below execute or belong together.
45 Decimal total = 0;Creates or assigns a typed value for the steps that follow.
46 for (SBQQ__QuoteLine__c line : quoteLines) {Loop: repeats the following block for each matching item.
47 Boolean existingContractLine = quoteType == 'Change Order' &&Creates or assigns a typed value for the steps that follow.
48 (line.SBQQ__UpgradedSubscription__c != null ||Assigns or configures the value on the left using the expression on the right.
49 line.SBQQ__UpgradedAsset__c != null);Assigns or configures the value on the left using the expression on the right.
50 if (line.SBQQ__Optional__c != true && !existingContractLine) {Guard or branch: the following block runs only when this condition is true.
51 total += line.SBQQ__NetTotal__c == null ? 0 : line.SBQQ__NetTotal__c;Assigns or configures the value on the left using the expression on the right.
52 }Closes the current block or declaration.
53 }Closes the current block or declaration.
54 return total;Returns this value to the caller and ends the method.
55 }Closes the current block or declaration.
56 Spacing separates related steps.
57 private static String makePrimaryIfLatest(Id quoteId) {Method declaration: Make the latest Quote primary while preserving rollback on failure. The parentheses define its inputs; the type before the name defines its return value.
58 SBQQ__Quote__c quote = [Assigns or configures the value on the left using the expression on the right.
59 SELECT Id, SBQQ__Opportunity2__c, SBQQ__Primary__cSOQL field list: identifies data to read from Salesforce.
60 FROM SBQQ__Quote__c WHERE Id = :quoteId LIMIT 1SOQL source: identifies which Salesforce object to read.
61 ];Completes the statement begun on this line or the preceding lines.
62 if (quote.SBQQ__Opportunity2__c == null) {Guard or branch: the following block runs only when this condition is true.
63 return 'The calculated quote has no Opportunity, so it could not be made primary.';Returns this value to the caller and ends the method.
64 }Closes the current block or declaration.
65 Spacing separates related steps.
66 // Lock the Opportunity to serialize competing quote calculations.Developer comment: Lock the Opportunity to serialize competing quote calculations.
67 Opportunity opportunityRecord = [Assigns or configures the value on the left using the expression on the right.
68 SELECT Id FROM OpportunitySOQL field list: identifies data to read from Salesforce.
69 WHERE Id = :quote.SBQQ__Opportunity2__c LIMIT 1 FOR UPDATESOQL filter: narrows the records returned by this query.
70 ];Completes the statement begun on this line or the preceding lines.
71 SBQQ__Quote__c newest = [Assigns or configures the value on the left using the expression on the right.
72 SELECT Id FROM SBQQ__Quote__cSOQL field list: identifies data to read from Salesforce.
73 WHERE SBQQ__Opportunity2__c = :opportunityRecord.IdSOQL filter: narrows the records returned by this query.
74 ORDER BY CreatedDate DESC, Id DESC LIMIT 1Sorts the records returned by this query.
75 ];Completes the statement begun on this line or the preceding lines.
76 if (newest.Id != quoteId || quote.SBQQ__Primary__c == true) {Guard or branch: the following block runs only when this condition is true.
77 return null;Returns this value to the caller and ends the method.
78 }Closes the current block or declaration.
79 Spacing separates related steps.
80 Savepoint beforePrimaryChange = Database.setSavepoint();Assigns or configures the value on the left using the expression on the right.
81 try {Starts an operation whose exception can be handled below.
82 List<SBQQ__Quote__c> previousPrimaries = [Creates or assigns a typed value for the steps that follow.
83 SELECT Id, SBQQ__Primary__c FROM SBQQ__Quote__cSOQL field list: identifies data to read from Salesforce.
84 WHERE SBQQ__Opportunity2__c = :opportunityRecord.IdSOQL filter: narrows the records returned by this query.
85 AND SBQQ__Primary__c = true AND Id != :quoteIdSOQL filter: narrows the records returned by this query.
86 ];Completes the statement begun on this line or the preceding lines.
87 for (SBQQ__Quote__c previous : previousPrimaries) {Loop: repeats the following block for each matching item.
88 previous.SBQQ__Primary__c = false;Assigns or configures the value on the left using the expression on the right.
89 }Closes the current block or declaration.
90 if (!previousPrimaries.isEmpty()) {Guard or branch: the following block runs only when this condition is true.
91 update previousPrimaries;DML write: saves changes to the specified Salesforce record or records.
92 }Closes the current block or declaration.
93 update new SBQQ__Quote__c(Id = quoteId, SBQQ__Primary__c = true);DML write: saves changes to the specified Salesforce record or records.
94 } catch (DmlException ex) {Opens a block; the indented lines below execute or belong together.
95 Database.rollback(beforePrimaryChange);Completes the statement begun on this line or the preceding lines.
96 return 'The quote was priced, but CPQ could not make it the primary quote: ' +Returns this value to the caller and ends the method.
97 ex.getDmlMessage(0).left(800);Completes the statement begun on this line or the preceding lines.
98 }Closes the current block or declaration.
99 return null;Returns this value to the caller and ends the method.
100 }Closes the current block or declaration.
101}Closes the current block or declaration.
View complete source code
1/** Saves the result of the asynchronous CPQ Quote Calculator. */
2global without sharing class PsQuoteCpqCalculateCallback implements SBQQ.CalculateCallback {
3 global void callback(String quoteJSON) {
4 String savedJson = SBQQ.ServiceRouter.save('SBQQ.QuoteAPI.QuoteSaver', quoteJSON);
5 Map<String, Object> model = (Map<String, Object>) JSON.deserializeUntyped(savedJson);
6 Map<String, Object> record = (Map<String, Object>) model.get('record');
7 Id quoteId = (Id) record.get('Id');
8 List<PS_Quote_Analysis__c> analyses = [
9 SELECT Id, Quote_Type__c, Reviewed_Proposal_JSON__c FROM PS_Quote_Analysis__c
10 WHERE Created_Quote__c = :quoteId LIMIT 1
11 ];
12 if (!analyses.isEmpty()) {
13 Map<String, Object> proposal = (Map<String, Object>) JSON.deserializeUntyped(
14 analyses[0].Reviewed_Proposal_JSON__c
15 );
16 Decimal approvedTotal = Decimal.valueOf(
17 String.valueOf(proposal.get('quote_total'))
18 );
19 List<SBQQ__QuoteLine__c> quoteLines = [
20 SELECT SBQQ__NetTotal__c, SBQQ__Optional__c,
21 SBQQ__UpgradedSubscription__c, SBQQ__UpgradedAsset__c
22 FROM SBQQ__QuoteLine__c WHERE SBQQ__Quote__c = :quoteId
23 ];
24 Decimal cpqTotal = sumChargeableLines(analyses[0].Quote_Type__c, quoteLines);
25 Boolean pricingMatches = cpqTotal.setScale(2) == approvedTotal.setScale(2);
26 String primaryError = pricingMatches ? makePrimaryIfLatest(quoteId) : null;
27 Boolean ready = pricingMatches && primaryError == null;
28 update new PS_Quote_Analysis__c(
29 Id = analyses[0].Id,
30 Quote_Creation_Status__c = ready ? 'Ready' : 'Failed',
31 Quote_Creation_Error__c = primaryError != null ? primaryError :
32 (pricingMatches ? null :
33 'CPQ calculated ' + String.valueOf(cpqTotal.setScale(2)) +
34 ' but the confirmed breakdown totals ' +
35 String.valueOf(approvedTotal.setScale(2)) +
36 '. Open the quote and review pricing before using it.')
37 );
38 }
39 }
40
41 @TestVisible
42 private static Decimal sumChargeableLines(
43 String quoteType, List<SBQQ__QuoteLine__c> quoteLines
44 ) {
45 Decimal total = 0;
46 for (SBQQ__QuoteLine__c line : quoteLines) {
47 Boolean existingContractLine = quoteType == 'Change Order' &&
48 (line.SBQQ__UpgradedSubscription__c != null ||
49 line.SBQQ__UpgradedAsset__c != null);
50 if (line.SBQQ__Optional__c != true && !existingContractLine) {
51 total += line.SBQQ__NetTotal__c == null ? 0 : line.SBQQ__NetTotal__c;
52 }
53 }
54 return total;
55 }
56
57 private static String makePrimaryIfLatest(Id quoteId) {
58 SBQQ__Quote__c quote = [
59 SELECT Id, SBQQ__Opportunity2__c, SBQQ__Primary__c
60 FROM SBQQ__Quote__c WHERE Id = :quoteId LIMIT 1
61 ];
62 if (quote.SBQQ__Opportunity2__c == null) {
63 return 'The calculated quote has no Opportunity, so it could not be made primary.';
64 }
65
66 // Lock the Opportunity to serialize competing quote calculations.
67 Opportunity opportunityRecord = [
68 SELECT Id FROM Opportunity
69 WHERE Id = :quote.SBQQ__Opportunity2__c LIMIT 1 FOR UPDATE
70 ];
71 SBQQ__Quote__c newest = [
72 SELECT Id FROM SBQQ__Quote__c
73 WHERE SBQQ__Opportunity2__c = :opportunityRecord.Id
74 ORDER BY CreatedDate DESC, Id DESC LIMIT 1
75 ];
76 if (newest.Id != quoteId || quote.SBQQ__Primary__c == true) {
77 return null;
78 }
79
80 Savepoint beforePrimaryChange = Database.setSavepoint();
81 try {
82 List<SBQQ__Quote__c> previousPrimaries = [
83 SELECT Id, SBQQ__Primary__c FROM SBQQ__Quote__c
84 WHERE SBQQ__Opportunity2__c = :opportunityRecord.Id
85 AND SBQQ__Primary__c = true AND Id != :quoteId
86 ];
87 for (SBQQ__Quote__c previous : previousPrimaries) {
88 previous.SBQQ__Primary__c = false;
89 }
90 if (!previousPrimaries.isEmpty()) {
91 update previousPrimaries;
92 }
93 update new SBQQ__Quote__c(Id = quoteId, SBQQ__Primary__c = true);
94 } catch (DmlException ex) {
95 Database.rollback(beforePrimaryChange);
96 return 'The quote was priced, but CPQ could not make it the primary quote: ' +
97 ex.getDmlMessage(0).left(800);
98 }
99 return null;
100 }
101}
production · 161 lines

PsServicesChangeOrderAction

Flow action that asks CPQ to amend a Contract, then updates the generated Opportunity, Contact Role, and primary Quote.

This local source includes a recent test-only hook. Verify the current Salesforce version before copying or deploying the class.

Review and understand complete source code

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 * Flow action for a Contact's Create Services Change Order button.Part of the surrounding declaration or expression; read it with the adjacent lines.
3 * CPQ creates the amendment Opportunity and Quote; this class does notDeclares a class or trigger. The braces contain its members and behavior.
4 * manufacture amendment lines or move a quote between Opportunities.Part of the surrounding declaration or expression; read it with the adjacent lines.
5 */Ends the comment.
6public with sharing class PsServicesChangeOrderAction {Declares a class or trigger. The braces contain its members and behavior.
7 @TestVisible private static String testAmenderResponse;Allows a test class to access this normally private member.
8 public class Request {Declares a class or trigger. The braces contain its members and behavior.
9 @InvocableVariable(required=true label='Contact ID')Assigns or configures the value on the left using the expression on the right.
10 public Id contactId;Completes the statement begun on this line or the preceding lines.
11 @InvocableVariable(required=true label='Contract ID')Assigns or configures the value on the left using the expression on the right.
12 public Id contractId;Completes the statement begun on this line or the preceding lines.
13 @InvocableVariable(required=true label='Stage')Assigns or configures the value on the left using the expression on the right.
14 public String stageName;Completes the statement begun on this line or the preceding lines.
15 @InvocableVariable(required=true label='Type')Assigns or configures the value on the left using the expression on the right.
16 public String opportunityType;Completes the statement begun on this line or the preceding lines.
17 @InvocableVariable(required=true label='Close date')Assigns or configures the value on the left using the expression on the right.
18 public Date closeDate;Completes the statement begun on this line or the preceding lines.
19 @InvocableVariable(required=true label='Services Opportunity record type ID')Assigns or configures the value on the left using the expression on the right.
20 public Id servicesRecordTypeId;Completes the statement begun on this line or the preceding lines.
21 }Closes the current block or declaration.
22 Spacing separates related steps.
23 public class Result {Declares a class or trigger. The braces contain its members and behavior.
24 @InvocableVariable(label='Amendment Opportunity ID')Assigns or configures the value on the left using the expression on the right.
25 public Id opportunityId;Completes the statement begun on this line or the preceding lines.
26 @InvocableVariable(label='Amendment quote ID')Assigns or configures the value on the left using the expression on the right.
27 public Id quoteId;Completes the statement begun on this line or the preceding lines.
28 @InvocableVariable(label='CPQ quote start date')Assigns or configures the value on the left using the expression on the right.
29 public Date quoteStartDate;Completes the statement begun on this line or the preceding lines.
30 }Closes the current block or declaration.
31 Spacing separates related steps.
32 @InvocableMethod(label='Create Services Change Order Opportunity'Assigns or configures the value on the left using the expression on the right.
33 description='Create a native CPQ amendment Opportunity and Quote from the selected Contract.')Assigns or configures the value on the left using the expression on the right.
34 public static List<Result> create(List<Request> requests) {Method declaration: Validate Flow input; call CPQ; update Opportunity, Contact Role, Quote; return IDs. The parentheses define its inputs; the type before the name defines its return value.
35 if (requests == null || requests.size() != 1 || requests[0] == null) {Guard or branch: the following block runs only when this condition is true.
36 throw new ChangeOrderException('Submit one change order at a time.');Stops this path and reports an error to the caller.
37 }Closes the current block or declaration.
38 Request request = requests[0];Assigns or configures the value on the left using the expression on the right.
39 if (request.contactId == null || request.contractId == null ||Guard or branch: the following block runs only when this condition is true.
40 request.servicesRecordTypeId == null || request.closeDate == null ||Assigns or configures the value on the left using the expression on the right.
41 String.isBlank(request.stageName) ||Continues the argument list or condition on the next line.
42 String.isBlank(request.opportunityType)) {Opens a block; the indented lines below execute or belong together.
43 throw new ChangeOrderException('Complete all change-order fields.');Stops this path and reports an error to the caller.
44 }Closes the current block or declaration.
45 Spacing separates related steps.
46 Contact contact = [Assigns or configures the value on the left using the expression on the right.
47 SELECT Id, AccountId FROM Contact WHERE Id = :request.contactIdSOQL field list: identifies data to read from Salesforce.
48 WITH USER_MODE LIMIT 1Runs this read using the current user’s data and field permissions.
49 ];Completes the statement begun on this line or the preceding lines.
50 Contract selectedContract = [Assigns or configures the value on the left using the expression on the right.
51 SELECT Id, AccountId, Status FROM ContractSOQL field list: identifies data to read from Salesforce.
52 WHERE Id = :request.contractId WITH USER_MODE LIMIT 1SOQL filter: narrows the records returned by this query.
53 ];Completes the statement begun on this line or the preceding lines.
54 if (contact.AccountId == null ||Guard or branch: the following block runs only when this condition is true.
55 contact.AccountId != selectedContract.AccountId) {Opens a block; the indented lines below execute or belong together.
56 throw new ChangeOrderException(Stops this path and reports an error to the caller.
57 'Choose a contract belonging to the Contact account.'Part of the surrounding declaration or expression; read it with the adjacent lines.
58 );Opens or closes the expression begun on the surrounding lines.
59 }Closes the current block or declaration.
60 if (String.isBlank(selectedContract.Status) ||Guard or branch: the following block runs only when this condition is true.
61 !selectedContract.Status.startsWith('Activated')) {Opens a block; the indented lines below execute or belong together.
62 throw new ChangeOrderException('Choose an activated contract.');Stops this path and reports an error to the caller.
63 }Closes the current block or declaration.
64 List<RecordType> servicesTypes = [Creates or assigns a typed value for the steps that follow.
65 SELECT Id FROM RecordTypeSOQL field list: identifies data to read from Salesforce.
66 WHERE Id = :request.servicesRecordTypeId AND SObjectType = 'Opportunity'SOQL filter: narrows the records returned by this query.
67 AND IsActive = true WITH USER_MODE LIMIT 1SOQL filter: narrows the records returned by this query.
68 ];Completes the statement begun on this line or the preceding lines.
69 if (servicesTypes.isEmpty()) {Guard or branch: the following block runs only when this condition is true.
70 throw new ChangeOrderException('Choose an active Opportunity record type.');Stops this path and reports an error to the caller.
71 }Closes the current block or declaration.
72 Spacing separates related steps.
73 // No Opportunity is inserted here. CPQ's amender creates both nativeDeveloper comment: No Opportunity is inserted here. CPQ's amender creates both native
74 // records and their existing subscription / asset amendment lines.Developer comment: records and their existing subscription / asset amendment lines.
75 String cpqResponse = Test.isRunningTest() && testAmenderResponse != nullCreates or assigns a typed value for the steps that follow.
76 ? testAmenderResponsePart of the surrounding declaration or expression; read it with the adjacent lines.
77 : SBQQ.ServiceRouter.load(Calls the Salesforce CPQ managed package API for the named operation.
78 'SBQQ.ContractManipulationAPI.ContractAmender',Continues the argument list or condition on the next line.
79 String.valueOf(selectedContract.Id), nullPart of the surrounding declaration or expression; read it with the adjacent lines.
80 );Opens or closes the expression begun on the surrounding lines.
81 Id quoteId = quoteIdFromModel(cpqResponse);Calls quoteIdFromModel(): Extract a Quote ID from CPQ JSON or reject an invalid response.
82 SBQQ__Quote__c quoteRecord = [Assigns or configures the value on the left using the expression on the right.
83 SELECT Id, SBQQ__Opportunity2__c, SBQQ__Account__c,SOQL field list: identifies data to read from Salesforce.
84 SBQQ__MasterContract__c, SBQQ__Type__c, SBQQ__Primary__c,Continues the argument list or condition on the next line.
85 SBQQ__StartDate__cPart of the surrounding declaration or expression; read it with the adjacent lines.
86 FROM SBQQ__Quote__c WHERE Id = :quoteId WITH USER_MODE LIMIT 1SOQL source: identifies which Salesforce object to read.
87 ];Completes the statement begun on this line or the preceding lines.
88 if (quoteRecord.SBQQ__Opportunity2__c == null ||Guard or branch: the following block runs only when this condition is true.
89 quoteRecord.SBQQ__Account__c != contact.AccountId ||Assigns or configures the value on the left using the expression on the right.
90 quoteRecord.SBQQ__MasterContract__c != selectedContract.Id ||Creates or assigns a typed value for the steps that follow.
91 quoteRecord.SBQQ__Type__c != 'Amendment') {Opens a block; the indented lines below execute or belong together.
92 throw new ChangeOrderException(Stops this path and reports an error to the caller.
93 'CPQ did not return an amendment quote for the selected contract and account.'Part of the surrounding declaration or expression; read it with the adjacent lines.
94 );Opens or closes the expression begun on the surrounding lines.
95 }Closes the current block or declaration.
96 Spacing separates related steps.
97 Opportunity amendment = new Opportunity(Creates or assigns a typed value for the steps that follow.
98 Id = quoteRecord.SBQQ__Opportunity2__c,Creates or assigns a typed value for the steps that follow.
99 StageName = request.stageName,Assigns or configures the value on the left using the expression on the right.
100 Type = request.opportunityType,Assigns or configures the value on the left using the expression on the right.
101 CloseDate = request.closeDate,Assigns or configures the value on the left using the expression on the right.
102 RecordTypeId = request.servicesRecordTypeIdAssigns or configures the value on the left using the expression on the right.
103 );Opens or closes the expression begun on the surrounding lines.
104 Database.update(amendment, AccessLevel.USER_MODE);DML write: saves changes to the specified Salesforce record or records.
105 Spacing separates related steps.
106 List<OpportunityContactRole> existingRoles = [Creates or assigns a typed value for the steps that follow.
107 SELECT Id, ContactId, IsPrimary FROM OpportunityContactRoleSOQL field list: identifies data to read from Salesforce.
108 WHERE OpportunityId = :amendment.Id WITH USER_MODESOQL filter: narrows the records returned by this query.
109 ];Completes the statement begun on this line or the preceding lines.
110 Boolean hasContactRole = false;Creates or assigns a typed value for the steps that follow.
111 Boolean hasPrimaryRole = false;Creates or assigns a typed value for the steps that follow.
112 for (OpportunityContactRole role : existingRoles) {Loop: repeats the following block for each matching item.
113 hasContactRole = hasContactRole || role.ContactId == contact.Id;Creates or assigns a typed value for the steps that follow.
114 hasPrimaryRole = hasPrimaryRole || role.IsPrimary;Assigns or configures the value on the left using the expression on the right.
115 }Closes the current block or declaration.
116 if (!hasContactRole) {Guard or branch: the following block runs only when this condition is true.
117 Database.insert(new OpportunityContactRole(DML write: creates the specified Salesforce record or records.
118 OpportunityId = amendment.Id,Creates or assigns a typed value for the steps that follow.
119 ContactId = contact.Id,Creates or assigns a typed value for the steps that follow.
120 IsPrimary = !hasPrimaryRoleAssigns or configures the value on the left using the expression on the right.
121 ), AccessLevel.USER_MODE);Completes the statement begun on this line or the preceding lines.
122 }Closes the current block or declaration.
123 Spacing separates related steps.
124 // The newly generated Opportunity has one CPQ quote. Make it theDeveloper comment: The newly generated Opportunity has one CPQ quote. Make it the
125 // default for the analyzer and downstream order creation.Developer comment: default for the analyzer and downstream order creation.
126 if (quoteRecord.SBQQ__Primary__c != true) {Guard or branch: the following block runs only when this condition is true.
127 Database.update(new SBQQ__Quote__c(DML write: saves changes to the specified Salesforce record or records.
128 Id = quoteRecord.Id,Creates or assigns a typed value for the steps that follow.
129 SBQQ__Primary__c = trueAssigns or configures the value on the left using the expression on the right.
130 ), AccessLevel.USER_MODE);Completes the statement begun on this line or the preceding lines.
131 }Closes the current block or declaration.
132 Spacing separates related steps.
133 Result result = new Result();Creates or assigns a typed value for the steps that follow.
134 result.opportunityId = amendment.Id;Creates or assigns a typed value for the steps that follow.
135 result.quoteId = quoteId;Assigns or configures the value on the left using the expression on the right.
136 result.quoteStartDate = quoteRecord.SBQQ__StartDate__c;Assigns or configures the value on the left using the expression on the right.
137 return new List<Result>{ result };Returns this value to the caller and ends the method.
138 }Closes the current block or declaration.
139 Spacing separates related steps.
140 @TestVisibleAllows a test class to access this normally private member.
141 private static Id quoteIdFromModel(String response) {Method declaration: Extract a Quote ID from CPQ JSON or reject an invalid response. The parentheses define its inputs; the type before the name defines its return value.
142 if (String.isBlank(response)) {Guard or branch: the following block runs only when this condition is true.
143 throw new ChangeOrderException('CPQ returned no amendment quote.');Stops this path and reports an error to the caller.
144 }Closes the current block or declaration.
145 Object parsed = JSON.deserializeUntyped(response);Parses JSON text into Apex values that the following code can inspect.
146 if (!(parsed instanceof Map<String, Object>)) {Guard or branch: the following block runs only when this condition is true.
147 throw new ChangeOrderException('CPQ returned an unexpected amendment response.');Stops this path and reports an error to the caller.
148 }Closes the current block or declaration.
149 Map<String, Object> model = (Map<String, Object>) parsed;Creates or assigns a typed value for the steps that follow.
150 if (!(model.get('record') instanceof Map<String, Object>)) {Guard or branch: the following block runs only when this condition is true.
151 throw new ChangeOrderException('CPQ returned no quote record.');Stops this path and reports an error to the caller.
152 }Closes the current block or declaration.
153 Map<String, Object> record = (Map<String, Object>) model.get('record');Creates or assigns a typed value for the steps that follow.
154 if (record.get('Id') == null) {Guard or branch: the following block runs only when this condition is true.
155 throw new ChangeOrderException('CPQ returned no quote ID.');Stops this path and reports an error to the caller.
156 }Closes the current block or declaration.
157 return (Id) String.valueOf(record.get('Id'));Returns this value to the caller and ends the method.
158 }Closes the current block or declaration.
159 Spacing separates related steps.
160 public class ChangeOrderException extends Exception {}Declares a class or trigger. The braces contain its members and behavior.
161}Closes the current block or declaration.
View complete source code
1/**
2 * Flow action for a Contact's Create Services Change Order button.
3 * CPQ creates the amendment Opportunity and Quote; this class does not
4 * manufacture amendment lines or move a quote between Opportunities.
5 */
6public with sharing class PsServicesChangeOrderAction {
7 @TestVisible private static String testAmenderResponse;
8 public class Request {
9 @InvocableVariable(required=true label='Contact ID')
10 public Id contactId;
11 @InvocableVariable(required=true label='Contract ID')
12 public Id contractId;
13 @InvocableVariable(required=true label='Stage')
14 public String stageName;
15 @InvocableVariable(required=true label='Type')
16 public String opportunityType;
17 @InvocableVariable(required=true label='Close date')
18 public Date closeDate;
19 @InvocableVariable(required=true label='Services Opportunity record type ID')
20 public Id servicesRecordTypeId;
21 }
22
23 public class Result {
24 @InvocableVariable(label='Amendment Opportunity ID')
25 public Id opportunityId;
26 @InvocableVariable(label='Amendment quote ID')
27 public Id quoteId;
28 @InvocableVariable(label='CPQ quote start date')
29 public Date quoteStartDate;
30 }
31
32 @InvocableMethod(label='Create Services Change Order Opportunity'
33 description='Create a native CPQ amendment Opportunity and Quote from the selected Contract.')
34 public static List<Result> create(List<Request> requests) {
35 if (requests == null || requests.size() != 1 || requests[0] == null) {
36 throw new ChangeOrderException('Submit one change order at a time.');
37 }
38 Request request = requests[0];
39 if (request.contactId == null || request.contractId == null ||
40 request.servicesRecordTypeId == null || request.closeDate == null ||
41 String.isBlank(request.stageName) ||
42 String.isBlank(request.opportunityType)) {
43 throw new ChangeOrderException('Complete all change-order fields.');
44 }
45
46 Contact contact = [
47 SELECT Id, AccountId FROM Contact WHERE Id = :request.contactId
48 WITH USER_MODE LIMIT 1
49 ];
50 Contract selectedContract = [
51 SELECT Id, AccountId, Status FROM Contract
52 WHERE Id = :request.contractId WITH USER_MODE LIMIT 1
53 ];
54 if (contact.AccountId == null ||
55 contact.AccountId != selectedContract.AccountId) {
56 throw new ChangeOrderException(
57 'Choose a contract belonging to the Contact account.'
58 );
59 }
60 if (String.isBlank(selectedContract.Status) ||
61 !selectedContract.Status.startsWith('Activated')) {
62 throw new ChangeOrderException('Choose an activated contract.');
63 }
64 List<RecordType> servicesTypes = [
65 SELECT Id FROM RecordType
66 WHERE Id = :request.servicesRecordTypeId AND SObjectType = 'Opportunity'
67 AND IsActive = true WITH USER_MODE LIMIT 1
68 ];
69 if (servicesTypes.isEmpty()) {
70 throw new ChangeOrderException('Choose an active Opportunity record type.');
71 }
72
73 // No Opportunity is inserted here. CPQ's amender creates both native
74 // records and their existing subscription / asset amendment lines.
75 String cpqResponse = Test.isRunningTest() && testAmenderResponse != null
76 ? testAmenderResponse
77 : SBQQ.ServiceRouter.load(
78 'SBQQ.ContractManipulationAPI.ContractAmender',
79 String.valueOf(selectedContract.Id), null
80 );
81 Id quoteId = quoteIdFromModel(cpqResponse);
82 SBQQ__Quote__c quoteRecord = [
83 SELECT Id, SBQQ__Opportunity2__c, SBQQ__Account__c,
84 SBQQ__MasterContract__c, SBQQ__Type__c, SBQQ__Primary__c,
85 SBQQ__StartDate__c
86 FROM SBQQ__Quote__c WHERE Id = :quoteId WITH USER_MODE LIMIT 1
87 ];
88 if (quoteRecord.SBQQ__Opportunity2__c == null ||
89 quoteRecord.SBQQ__Account__c != contact.AccountId ||
90 quoteRecord.SBQQ__MasterContract__c != selectedContract.Id ||
91 quoteRecord.SBQQ__Type__c != 'Amendment') {
92 throw new ChangeOrderException(
93 'CPQ did not return an amendment quote for the selected contract and account.'
94 );
95 }
96
97 Opportunity amendment = new Opportunity(
98 Id = quoteRecord.SBQQ__Opportunity2__c,
99 StageName = request.stageName,
100 Type = request.opportunityType,
101 CloseDate = request.closeDate,
102 RecordTypeId = request.servicesRecordTypeId
103 );
104 Database.update(amendment, AccessLevel.USER_MODE);
105
106 List<OpportunityContactRole> existingRoles = [
107 SELECT Id, ContactId, IsPrimary FROM OpportunityContactRole
108 WHERE OpportunityId = :amendment.Id WITH USER_MODE
109 ];
110 Boolean hasContactRole = false;
111 Boolean hasPrimaryRole = false;
112 for (OpportunityContactRole role : existingRoles) {
113 hasContactRole = hasContactRole || role.ContactId == contact.Id;
114 hasPrimaryRole = hasPrimaryRole || role.IsPrimary;
115 }
116 if (!hasContactRole) {
117 Database.insert(new OpportunityContactRole(
118 OpportunityId = amendment.Id,
119 ContactId = contact.Id,
120 IsPrimary = !hasPrimaryRole
121 ), AccessLevel.USER_MODE);
122 }
123
124 // The newly generated Opportunity has one CPQ quote. Make it the
125 // default for the analyzer and downstream order creation.
126 if (quoteRecord.SBQQ__Primary__c != true) {
127 Database.update(new SBQQ__Quote__c(
128 Id = quoteRecord.Id,
129 SBQQ__Primary__c = true
130 ), AccessLevel.USER_MODE);
131 }
132
133 Result result = new Result();
134 result.opportunityId = amendment.Id;
135 result.quoteId = quoteId;
136 result.quoteStartDate = quoteRecord.SBQQ__StartDate__c;
137 return new List<Result>{ result };
138 }
139
140 @TestVisible
141 private static Id quoteIdFromModel(String response) {
142 if (String.isBlank(response)) {
143 throw new ChangeOrderException('CPQ returned no amendment quote.');
144 }
145 Object parsed = JSON.deserializeUntyped(response);
146 if (!(parsed instanceof Map<String, Object>)) {
147 throw new ChangeOrderException('CPQ returned an unexpected amendment response.');
148 }
149 Map<String, Object> model = (Map<String, Object>) parsed;
150 if (!(model.get('record') instanceof Map<String, Object>)) {
151 throw new ChangeOrderException('CPQ returned no quote record.');
152 }
153 Map<String, Object> record = (Map<String, Object>) model.get('record');
154 if (record.get('Id') == null) {
155 throw new ChangeOrderException('CPQ returned no quote ID.');
156 }
157 return (Id) String.valueOf(record.get('Id'));
158 }
159
160 public class ChangeOrderException extends Exception {}
161}
production · 315 lines

QuoteLineBudgetSequenceHandler

Assigns budget sequence numbers and dates to newly inserted CPQ quote lines.

Review and understand complete source code

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 * QuoteLineBudgetSequenceHandlerPart of the surrounding declaration or expression; read it with the adjacent lines.
3 *Part of the surrounding declaration or expression; read it with the adjacent lines.
4 * Auto-assigns Budget_Sequence__c and Budget_Start_Date__c on SBQQ__QuoteLine__cPart of the surrounding declaration or expression; read it with the adjacent lines.
5 * when a new line is inserted, based on product code → block rules in custom metadata.Part of the surrounding declaration or expression; read it with the adjacent lines.
6 *Part of the surrounding declaration or expression; read it with the adjacent lines.
7 * BLOCK RULES (configured in Budget_Sequence_Config__mdt):Part of the surrounding declaration or expression; read it with the adjacent lines.
8 * Block 1 → T&M Prepaid → sequences 1000-1999 (activates first in Teamwork)Part of the surrounding declaration or expression; read it with the adjacent lines.
9 * Block 2 → Middle products → sequences 2000-2999 (Fixed Fee, Milestone, FTE)Part of the surrounding declaration or expression; read it with the adjacent lines.
10 * Block 3 → T&M → sequences 3000-3999 (activates last in Teamwork)Part of the surrounding declaration or expression; read it with the adjacent lines.
11 *Part of the surrounding declaration or expression; read it with the adjacent lines.
12 * ORDERING NOTE: Within a block, lines are sequenced in the order they are addedPart of the surrounding declaration or expression; read it with the adjacent lines.
13 * to the quote (ascending line number = lower sequence = activates sooner within that block).Assigns or configures the value on the left using the expression on the right.
14 *Part of the surrounding declaration or expression; read it with the adjacent lines.
15 * MANUAL OVERRIDE: Fires only on after insert, and only sets sequence when it is null.Part of the surrounding declaration or expression; read it with the adjacent lines.
16 * Edit the sequence number directly on the quote line — it will never be overwrittenPart of the surrounding declaration or expression; read it with the adjacent lines.
17 * by this trigger after the initial assignment.Declares a class or trigger. The braces contain its members and behavior.
18 *Part of the surrounding declaration or expression; read it with the adjacent lines.
19 * DATE FIELD: Budget_Start_Date__c = Quote start date + (dense rank - 1 days).Assigns or configures the value on the left using the expression on the right.
20 * Dense rank = this line's position when ALL tracked lines on the quote are sortedAssigns or configures the value on the left using the expression on the right.
21 * by sequence number ascending.Part of the surrounding declaration or expression; read it with the adjacent lines.
22 *Part of the surrounding declaration or expression; read it with the adjacent lines.
23 * SOURCE DATE: SBQQ__Quote__r.SBQQ__StartDate__c. Falls back to today if null.Part of the surrounding declaration or expression; read it with the adjacent lines.
24 *Part of the surrounding declaration or expression; read it with the adjacent lines.
25 * NOTE: SBQQ__ProductCode__c is a cross-object formula field and is not reliablyPart of the surrounding declaration or expression; read it with the adjacent lines.
26 * populated in Trigger.new. This handler queries it via SBQQ__Product__r.ProductCode.Part of the surrounding declaration or expression; read it with the adjacent lines.
27 */Ends the comment.
28public class QuoteLineBudgetSequenceHandler {Declares a class or trigger. The braces contain its members and behavior.
29 Spacing separates related steps.
30 @TestVisibleAllows a test class to access this normally private member.
31 private static final Map<Integer, Integer> BLOCK_BASE = new Map<Integer, Integer>{Opens a block; the indented lines below execute or belong together.
32 1 => 1000,Maps the value on the left to the value on the right.
33 2 => 2000,Maps the value on the left to the value on the right.
34 3 => 3000Maps the value on the left to the value on the right.
35 };Closes the current block or declaration.
36 Spacing separates related steps.
37 private static Boolean isRunning = false;Creates or assigns a typed value for the steps that follow.
38 Spacing separates related steps.
39 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
40 // Entry point called from the triggerDeveloper comment: Entry point called from the trigger
41 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
42 public static void assignSequences(List<SBQQ__QuoteLine__c> newLines) {Method declaration: Find inserted lines needing budget data and update them in bulk. The parentheses define its inputs; the type before the name defines its return value.
43 if (isRunning) return;Guard or branch: the following block runs only when this condition is true.
44 Spacing separates related steps.
45 Map<String, Integer> productBlockMap = loadProductBlockMap();Calls loadProductBlockMap(): Read Product Code → sequence block configuration.
46 if (productBlockMap.isEmpty()) return;Guard or branch: the following block runs only when this condition is true.
47 Spacing separates related steps.
48 // Query product codes — SBQQ__ProductCode__c is a formula field and isDeveloper comment: Query product codes — SBQQ__ProductCode__c is a formula field and is
49 // not reliably present in Trigger.new; query via relationship instead.Developer comment: not reliably present in Trigger.new; query via relationship instead.
50 Set<Id> allLineIds = new Map<Id, SBQQ__QuoteLine__c>(newLines).keySet();Creates or assigns a typed value for the steps that follow.
51 Map<Id, String> lineToCode = queryProductCodes(allLineIds);Calls queryProductCodes(): Resolve Product Codes for the new lines.
52 Spacing separates related steps.
53 List<SBQQ__QuoteLine__c> linesToAssign = new List<SBQQ__QuoteLine__c>();Creates or assigns a typed value for the steps that follow.
54 Set<Id> quoteIds = new Set<Id>();Creates or assigns a typed value for the steps that follow.
55 Spacing separates related steps.
56 for (SBQQ__QuoteLine__c ql : newLines) {Loop: repeats the following block for each matching item.
57 String code = lineToCode.get(ql.Id);Creates or assigns a typed value for the steps that follow.
58 if (ql.Budget_Sequence__c == nullGuard or branch: the following block runs only when this condition is true.
59 && code != nullAssigns or configures the value on the left using the expression on the right.
60 && productBlockMap.containsKey(code)) {Opens a block; the indented lines below execute or belong together.
61 linesToAssign.add(ql);Completes the statement begun on this line or the preceding lines.
62 quoteIds.add(ql.SBQQ__Quote__c);Completes the statement begun on this line or the preceding lines.
63 }Closes the current block or declaration.
64 }Closes the current block or declaration.
65 Spacing separates related steps.
66 if (linesToAssign.isEmpty()) return;Guard or branch: the following block runs only when this condition is true.
67 Spacing separates related steps.
68 Map<Id, Date> quoteStartDates = getQuoteStartDates(quoteIds);Calls getQuoteStartDates(): Get dates used for budget scheduling.
69 ExistingLineData existing = queryExistingLines(quoteIds, allLineIds, productBlockMap);Calls queryExistingLines(): Find numbers already assigned.
70 Spacing separates related steps.
71 List<SBQQ__QuoteLine__c> toUpdate = buildUpdates(Calls buildUpdates(): Compute sequence numbers and dates.
72 linesToAssign, quoteStartDates, existing, productBlockMap, lineToCodePart of the surrounding declaration or expression; read it with the adjacent lines.
73 );Opens or closes the expression begun on the surrounding lines.
74 Spacing separates related steps.
75 if (!toUpdate.isEmpty()) {Guard or branch: the following block runs only when this condition is true.
76 isRunning = true;Assigns or configures the value on the left using the expression on the right.
77 try {Starts an operation whose exception can be handled below.
78 update toUpdate;DML write: saves changes to the specified Salesforce record or records.
79 } finally {Opens a block; the indented lines below execute or belong together.
80 isRunning = false;Assigns or configures the value on the left using the expression on the right.
81 }Closes the current block or declaration.
82 }Closes the current block or declaration.
83 }Closes the current block or declaration.
84 Spacing separates related steps.
85 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
86 // Query product codes via the parent Product2 lookupDeveloper comment: Query product codes via the parent Product2 lookup
87 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
88 private static Map<Id, String> queryProductCodes(Set<Id> lineIds) {Method declaration: Resolve Product Codes for the new lines. The parentheses define its inputs; the type before the name defines its return value.
89 Map<Id, String> result = new Map<Id, String>();Creates or assigns a typed value for the steps that follow.
90 for (SBQQ__QuoteLine__c ql : [Loop: repeats the following block for each matching item.
91 SELECT Id, SBQQ__Product__r.ProductCodeSOQL field list: identifies data to read from Salesforce.
92 FROM SBQQ__QuoteLine__cSOQL source: identifies which Salesforce object to read.
93 WHERE Id IN :lineIdsSOQL filter: narrows the records returned by this query.
94 ]) {Opens a block; the indented lines below execute or belong together.
95 if (ql.SBQQ__Product__r != null && ql.SBQQ__Product__r.ProductCode != null) {Guard or branch: the following block runs only when this condition is true.
96 result.put(ql.Id, ql.SBQQ__Product__r.ProductCode);Completes the statement begun on this line or the preceding lines.
97 }Closes the current block or declaration.
98 }Closes the current block or declaration.
99 return result;Returns this value to the caller and ends the method.
100 }Closes the current block or declaration.
101 Spacing separates related steps.
102 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
103 // Core assignment logicDeveloper comment: Core assignment logic
104 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
105 @TestVisibleAllows a test class to access this normally private member.
106 private static List<SBQQ__QuoteLine__c> buildUpdates(Method declaration: Compute sequence numbers and dates. The parentheses define its inputs; the type before the name defines its return value.
107 List<SBQQ__QuoteLine__c> linesToAssign,Continues the argument list or condition on the next line.
108 Map<Id, Date> quoteStartDates,Continues the argument list or condition on the next line.
109 ExistingLineData existing,Continues the argument list or condition on the next line.
110 Map<String, Integer> productBlockMap,Continues the argument list or condition on the next line.
111 Map<Id, String> lineToCodePart of the surrounding declaration or expression; read it with the adjacent lines.
112 ) {Opens a block; the indented lines below execute or belong together.
113 List<SBQQ__QuoteLine__c> toUpdate = new List<SBQQ__QuoteLine__c>();Creates or assigns a typed value for the steps that follow.
114 Spacing separates related steps.
115 Map<Id, List<SBQQ__QuoteLine__c>> byQuote = new Map<Id, List<SBQQ__QuoteLine__c>>();Creates or assigns a typed value for the steps that follow.
116 for (SBQQ__QuoteLine__c ql : linesToAssign) {Loop: repeats the following block for each matching item.
117 if (!byQuote.containsKey(ql.SBQQ__Quote__c)) {Guard or branch: the following block runs only when this condition is true.
118 byQuote.put(ql.SBQQ__Quote__c, new List<SBQQ__QuoteLine__c>());Completes the statement begun on this line or the preceding lines.
119 }Closes the current block or declaration.
120 byQuote.get(ql.SBQQ__Quote__c).add(ql);Completes the statement begun on this line or the preceding lines.
121 }Closes the current block or declaration.
122 Spacing separates related steps.
123 for (Id quoteId : byQuote.keySet()) {Loop: repeats the following block for each matching item.
124 Date startDate = quoteStartDates.containsKey(quoteId)Creates or assigns a typed value for the steps that follow.
125 ? quoteStartDates.get(quoteId)Part of the surrounding declaration or expression; read it with the adjacent lines.
126 : Date.today();Completes the statement begun on this line or the preceding lines.
127 Map<Integer, Integer> blockMax = existing.quoteBlockMax.containsKey(quoteId)Creates or assigns a typed value for the steps that follow.
128 ? existing.quoteBlockMax.get(quoteId)Part of the surrounding declaration or expression; read it with the adjacent lines.
129 : new Map<Integer, Integer>();Completes the statement begun on this line or the preceding lines.
130 List<Integer> existingSeqs = existing.quoteSeqs.containsKey(quoteId)Creates or assigns a typed value for the steps that follow.
131 ? existing.quoteSeqs.get(quoteId)Part of the surrounding declaration or expression; read it with the adjacent lines.
132 : new List<Integer>();Completes the statement begun on this line or the preceding lines.
133 Spacing separates related steps.
134 List<SBQQ__QuoteLine__c> sorted = groupAndSort(Creates or assigns a typed value for the steps that follow.
135 byQuote.get(quoteId), productBlockMap, lineToCodePart of the surrounding declaration or expression; read it with the adjacent lines.
136 );Opens or closes the expression begun on the surrounding lines.
137 Spacing separates related steps.
138 Map<Id, Integer> newSeqs = new Map<Id, Integer>();Creates or assigns a typed value for the steps that follow.
139 for (SBQQ__QuoteLine__c ql : sorted) {Loop: repeats the following block for each matching item.
140 Integer block = productBlockMap.get(lineToCode.get(ql.Id));Creates or assigns a typed value for the steps that follow.
141 Integer base = BLOCK_BASE.get(block);Creates or assigns a typed value for the steps that follow.
142 Integer nextSeq = blockMax.containsKey(block) ? blockMax.get(block) + 1 : base;Creates or assigns a typed value for the steps that follow.
143 newSeqs.put(ql.Id, nextSeq);Completes the statement begun on this line or the preceding lines.
144 blockMax.put(block, nextSeq);Completes the statement begun on this line or the preceding lines.
145 }Closes the current block or declaration.
146 Spacing separates related steps.
147 List<Integer> allSeqs = new List<Integer>(existingSeqs);Creates or assigns a typed value for the steps that follow.
148 allSeqs.addAll(newSeqs.values());Completes the statement begun on this line or the preceding lines.
149 allSeqs.sort();Completes the statement begun on this line or the preceding lines.
150 Spacing separates related steps.
151 Map<Integer, Integer> seqToRank = new Map<Integer, Integer>();Creates or assigns a typed value for the steps that follow.
152 Integer rank = 0;Creates or assigns a typed value for the steps that follow.
153 Integer previousSeq;Completes the statement begun on this line or the preceding lines.
154 for (Integer seq : allSeqs) {Loop: repeats the following block for each matching item.
155 if (previousSeq == null || seq != previousSeq) {Guard or branch: the following block runs only when this condition is true.
156 rank++;Completes the statement begun on this line or the preceding lines.
157 }Closes the current block or declaration.
158 seqToRank.put(seq, rank);Completes the statement begun on this line or the preceding lines.
159 previousSeq = seq;Assigns or configures the value on the left using the expression on the right.
160 }Closes the current block or declaration.
161 Spacing separates related steps.
162 for (SBQQ__QuoteLine__c ql : byQuote.get(quoteId)) {Loop: repeats the following block for each matching item.
163 Integer seq = newSeqs.get(ql.Id);Creates or assigns a typed value for the steps that follow.
164 Integer lineRank = seqToRank.get(seq);Creates or assigns a typed value for the steps that follow.
165 toUpdate.add(new SBQQ__QuoteLine__c(Part of the surrounding declaration or expression; read it with the adjacent lines.
166 Id = ql.Id,Creates or assigns a typed value for the steps that follow.
167 Budget_Sequence__c = seq,Assigns or configures the value on the left using the expression on the right.
168 Budget_Start_Date__c = startDate.addDays(lineRank - 1)Assigns or configures the value on the left using the expression on the right.
169 ));Completes the statement begun on this line or the preceding lines.
170 }Closes the current block or declaration.
171 Spacing separates related steps.
172 // CPQ may insert lines in multiple DML batches, so existing lines may haveDeveloper comment: CPQ may insert lines in multiple DML batches, so existing lines may have
173 // stale start dates if a new line was inserted with a lower sequence number.Developer comment: stale start dates if a new line was inserted with a lower sequence number.
174 // Recalculate start dates for all existing tracked lines on this quote.Developer comment: Recalculate start dates for all existing tracked lines on this quote.
175 Map<Id, Integer> existingLineSeqMap = existing.quoteLineSeqs.containsKey(quoteId)Creates or assigns a typed value for the steps that follow.
176 ? existing.quoteLineSeqs.get(quoteId)Part of the surrounding declaration or expression; read it with the adjacent lines.
177 : new Map<Id, Integer>();Completes the statement begun on this line or the preceding lines.
178 for (Id existLineId : existingLineSeqMap.keySet()) {Loop: repeats the following block for each matching item.
179 Integer existSeq = existingLineSeqMap.get(existLineId);Creates or assigns a typed value for the steps that follow.
180 Integer existRank = seqToRank.get(existSeq);Creates or assigns a typed value for the steps that follow.
181 if (existRank != null) {Guard or branch: the following block runs only when this condition is true.
182 toUpdate.add(new SBQQ__QuoteLine__c(Part of the surrounding declaration or expression; read it with the adjacent lines.
183 Id = existLineId,Creates or assigns a typed value for the steps that follow.
184 Budget_Start_Date__c = startDate.addDays(existRank - 1)Assigns or configures the value on the left using the expression on the right.
185 ));Completes the statement begun on this line or the preceding lines.
186 }Closes the current block or declaration.
187 }Closes the current block or declaration.
188 }Closes the current block or declaration.
189 Spacing separates related steps.
190 return toUpdate;Returns this value to the caller and ends the method.
191 }Closes the current block or declaration.
192 Spacing separates related steps.
193 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
194 // Sort lines: block ascending, then line number ascending within blockDeveloper comment: Sort lines: block ascending, then line number ascending within block
195 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
196 private static List<SBQQ__QuoteLine__c> groupAndSort(Part of the surrounding declaration or expression; read it with the adjacent lines.
197 List<SBQQ__QuoteLine__c> lines,Continues the argument list or condition on the next line.
198 Map<String, Integer> productBlockMap,Continues the argument list or condition on the next line.
199 Map<Id, String> lineToCodePart of the surrounding declaration or expression; read it with the adjacent lines.
200 ) {Opens a block; the indented lines below execute or belong together.
201 List<LineWrapper> wrappers = new List<LineWrapper>();Creates or assigns a typed value for the steps that follow.
202 for (SBQQ__QuoteLine__c ql : lines) {Loop: repeats the following block for each matching item.
203 Integer block = productBlockMap.get(lineToCode.get(ql.Id));Creates or assigns a typed value for the steps that follow.
204 wrappers.add(new LineWrapper(ql, block));Completes the statement begun on this line or the preceding lines.
205 }Closes the current block or declaration.
206 wrappers.sort();Completes the statement begun on this line or the preceding lines.
207 Spacing separates related steps.
208 List<SBQQ__QuoteLine__c> sorted = new List<SBQQ__QuoteLine__c>();Creates or assigns a typed value for the steps that follow.
209 for (LineWrapper w : wrappers) sorted.add(w.line);Loop: repeats the following block for each matching item.
210 return sorted;Returns this value to the caller and ends the method.
211 }Closes the current block or declaration.
212 Spacing separates related steps.
213 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
214 // Query helpersDeveloper comment: Query helpers
215 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
216 private static Map<Id, Date> getQuoteStartDates(Set<Id> quoteIds) {Method declaration: Get dates used for budget scheduling. The parentheses define its inputs; the type before the name defines its return value.
217 Map<Id, Date> result = new Map<Id, Date>();Creates or assigns a typed value for the steps that follow.
218 for (SBQQ__Quote__c q : [Loop: repeats the following block for each matching item.
219 SELECT Id, SBQQ__StartDate__cSOQL field list: identifies data to read from Salesforce.
220 FROM SBQQ__Quote__cSOQL source: identifies which Salesforce object to read.
221 WHERE Id IN :quoteIdsSOQL filter: narrows the records returned by this query.
222 ]) {Opens a block; the indented lines below execute or belong together.
223 result.put(q.Id, q.SBQQ__StartDate__c != null ? q.SBQQ__StartDate__c : Date.today());Creates or assigns a typed value for the steps that follow.
224 }Closes the current block or declaration.
225 return result;Returns this value to the caller and ends the method.
226 }Closes the current block or declaration.
227 Spacing separates related steps.
228 private static ExistingLineData queryExistingLines(Method declaration: Find numbers already assigned. The parentheses define its inputs; the type before the name defines its return value.
229 Set<Id> quoteIds,Continues the argument list or condition on the next line.
230 Set<Id> newLineIds,Continues the argument list or condition on the next line.
231 Map<String, Integer> productBlockMapPart of the surrounding declaration or expression; read it with the adjacent lines.
232 ) {Opens a block; the indented lines below execute or belong together.
233 ExistingLineData data = new ExistingLineData();Creates or assigns a typed value for the steps that follow.
234 Spacing separates related steps.
235 for (SBQQ__QuoteLine__c ql : [Loop: repeats the following block for each matching item.
236 SELECT Id, SBQQ__Quote__c, Budget_Sequence__cSOQL field list: identifies data to read from Salesforce.
237 FROM SBQQ__QuoteLine__cSOQL source: identifies which Salesforce object to read.
238 WHERE SBQQ__Quote__c IN :quoteIdsSOQL filter: narrows the records returned by this query.
239 AND Budget_Sequence__c != nullSOQL filter: narrows the records returned by this query.
240 AND Id NOT IN :newLineIdsSOQL filter: narrows the records returned by this query.
241 ]) {Opens a block; the indented lines below execute or belong together.
242 Id qId = ql.SBQQ__Quote__c;Creates or assigns a typed value for the steps that follow.
243 Integer seq = Integer.valueOf(ql.Budget_Sequence__c);Creates or assigns a typed value for the steps that follow.
244 Spacing separates related steps.
245 if (!data.quoteSeqs.containsKey(qId)) data.quoteSeqs.put(qId, new List<Integer>());Guard or branch: the following block runs only when this condition is true.
246 data.quoteSeqs.get(qId).add(seq);Completes the statement begun on this line or the preceding lines.
247 Spacing separates related steps.
248 if (!data.quoteLineSeqs.containsKey(qId)) data.quoteLineSeqs.put(qId, new Map<Id, Integer>());Guard or branch: the following block runs only when this condition is true.
249 data.quoteLineSeqs.get(qId).put(ql.Id, seq);Completes the statement begun on this line or the preceding lines.
250 Spacing separates related steps.
251 if (!data.quoteBlockMax.containsKey(qId)) data.quoteBlockMax.put(qId, new Map<Integer, Integer>());Guard or branch: the following block runs only when this condition is true.
252 Map<Integer, Integer> blockMax = data.quoteBlockMax.get(qId);Creates or assigns a typed value for the steps that follow.
253 for (Integer block : BLOCK_BASE.keySet()) {Loop: repeats the following block for each matching item.
254 Integer base = BLOCK_BASE.get(block);Creates or assigns a typed value for the steps that follow.
255 if (seq >= base && seq < base + 1000) {Guard or branch: the following block runs only when this condition is true.
256 Integer curr = blockMax.containsKey(block) ? blockMax.get(block) : base - 1;Creates or assigns a typed value for the steps that follow.
257 if (seq > curr) blockMax.put(block, seq);Guard or branch: the following block runs only when this condition is true.
258 break;Completes the statement begun on this line or the preceding lines.
259 }Closes the current block or declaration.
260 }Closes the current block or declaration.
261 }Closes the current block or declaration.
262 Spacing separates related steps.
263 return data;Returns this value to the caller and ends the method.
264 }Closes the current block or declaration.
265 Spacing separates related steps.
266 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
267 // Load Custom Metadata: productCode → block numberDeveloper comment: Load Custom Metadata: productCode → block number
268 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
269 @TestVisibleAllows a test class to access this normally private member.
270 static Map<String, Integer> productBlockMapOverride;Completes the statement begun on this line or the preceding lines.
271 Spacing separates related steps.
272 private static Map<String, Integer> loadProductBlockMap() {Method declaration: Read Product Code → sequence block configuration. The parentheses define its inputs; the type before the name defines its return value.
273 if (productBlockMapOverride != null) return productBlockMapOverride;Guard or branch: the following block runs only when this condition is true.
274 Spacing separates related steps.
275 Map<String, Integer> result = new Map<String, Integer>();Creates or assigns a typed value for the steps that follow.
276 for (Budget_Sequence_Config__mdt cfg : [Loop: repeats the following block for each matching item.
277 SELECT Product_Code__c, Sequence_Block__cSOQL field list: identifies data to read from Salesforce.
278 FROM Budget_Sequence_Config__mdtSOQL source: identifies which Salesforce object to read.
279 ]) {Opens a block; the indented lines below execute or belong together.
280 if (cfg.Product_Code__c != null && cfg.Sequence_Block__c != null) {Guard or branch: the following block runs only when this condition is true.
281 result.put(cfg.Product_Code__c, Integer.valueOf(cfg.Sequence_Block__c));Completes the statement begun on this line or the preceding lines.
282 }Closes the current block or declaration.
283 }Closes the current block or declaration.
284 return result;Returns this value to the caller and ends the method.
285 }Closes the current block or declaration.
286 Spacing separates related steps.
287 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
288 // Inner classesDeveloper comment: Inner classes
289 // ─────────────────────────────────────────────────────────────────────────Developer comment: ─────────────────────────────────────────────────────────────────────────
290 @TestVisibleAllows a test class to access this normally private member.
291 private class ExistingLineData {Declares a class or trigger. The braces contain its members and behavior.
292 @TestVisible Map<Id, Map<Integer, Integer>> quoteBlockMax = new Map<Id, Map<Integer, Integer>>();Allows a test class to access this normally private member.
293 @TestVisible Map<Id, List<Integer>> quoteSeqs = new Map<Id, List<Integer>>();Allows a test class to access this normally private member.
294 // lineId → sequence for existing lines, so we can recalculate their start datesDeveloper comment: lineId → sequence for existing lines, so we can recalculate their start dates
295 @TestVisible Map<Id, Map<Id, Integer>> quoteLineSeqs = new Map<Id, Map<Id, Integer>>();Allows a test class to access this normally private member.
296 }Closes the current block or declaration.
297 Spacing separates related steps.
298 private class LineWrapper implements Comparable {Declares a class or trigger. The braces contain its members and behavior.
299 SBQQ__QuoteLine__c line;Completes the statement begun on this line or the preceding lines.
300 Integer block;Completes the statement begun on this line or the preceding lines.
301 Decimal lineNumber;Completes the statement begun on this line or the preceding lines.
302 Spacing separates related steps.
303 LineWrapper(SBQQ__QuoteLine__c l, Integer b) {Opens a block; the indented lines below execute or belong together.
304 line = l;Assigns or configures the value on the left using the expression on the right.
305 block = b;Assigns or configures the value on the left using the expression on the right.
306 lineNumber = l.SBQQ__Number__c != null ? l.SBQQ__Number__c : 9999;Assigns or configures the value on the left using the expression on the right.
307 }Closes the current block or declaration.
308 Spacing separates related steps.
309 public Integer compareTo(Object other) {Opens a block; the indented lines below execute or belong together.
310 LineWrapper o = (LineWrapper) other;Assigns or configures the value on the left using the expression on the right.
311 if (block != o.block) return block - o.block;Guard or branch: the following block runs only when this condition is true.
312 return lineNumber > o.lineNumber ? 1 : (lineNumber < o.lineNumber ? -1 : 0);Returns this value to the caller and ends the method.
313 }Closes the current block or declaration.
314 }Closes the current block or declaration.
315}Closes the current block or declaration.
View complete source code
1/**
2 * QuoteLineBudgetSequenceHandler
3 *
4 * Auto-assigns Budget_Sequence__c and Budget_Start_Date__c on SBQQ__QuoteLine__c
5 * when a new line is inserted, based on product code → block rules in custom metadata.
6 *
7 * BLOCK RULES (configured in Budget_Sequence_Config__mdt):
8 * Block 1 → T&M Prepaid → sequences 1000-1999 (activates first in Teamwork)
9 * Block 2 → Middle products → sequences 2000-2999 (Fixed Fee, Milestone, FTE)
10 * Block 3 → T&M → sequences 3000-3999 (activates last in Teamwork)
11 *
12 * ORDERING NOTE: Within a block, lines are sequenced in the order they are added
13 * to the quote (ascending line number = lower sequence = activates sooner within that block).
14 *
15 * MANUAL OVERRIDE: Fires only on after insert, and only sets sequence when it is null.
16 * Edit the sequence number directly on the quote line — it will never be overwritten
17 * by this trigger after the initial assignment.
18 *
19 * DATE FIELD: Budget_Start_Date__c = Quote start date + (dense rank - 1 days).
20 * Dense rank = this line's position when ALL tracked lines on the quote are sorted
21 * by sequence number ascending.
22 *
23 * SOURCE DATE: SBQQ__Quote__r.SBQQ__StartDate__c. Falls back to today if null.
24 *
25 * NOTE: SBQQ__ProductCode__c is a cross-object formula field and is not reliably
26 * populated in Trigger.new. This handler queries it via SBQQ__Product__r.ProductCode.
27 */
28public class QuoteLineBudgetSequenceHandler {
29
30 @TestVisible
31 private static final Map<Integer, Integer> BLOCK_BASE = new Map<Integer, Integer>{
32 1 => 1000,
33 2 => 2000,
34 3 => 3000
35 };
36
37 private static Boolean isRunning = false;
38
39 // ─────────────────────────────────────────────────────────────────────────
40 // Entry point called from the trigger
41 // ─────────────────────────────────────────────────────────────────────────
42 public static void assignSequences(List<SBQQ__QuoteLine__c> newLines) {
43 if (isRunning) return;
44
45 Map<String, Integer> productBlockMap = loadProductBlockMap();
46 if (productBlockMap.isEmpty()) return;
47
48 // Query product codes — SBQQ__ProductCode__c is a formula field and is
49 // not reliably present in Trigger.new; query via relationship instead.
50 Set<Id> allLineIds = new Map<Id, SBQQ__QuoteLine__c>(newLines).keySet();
51 Map<Id, String> lineToCode = queryProductCodes(allLineIds);
52
53 List<SBQQ__QuoteLine__c> linesToAssign = new List<SBQQ__QuoteLine__c>();
54 Set<Id> quoteIds = new Set<Id>();
55
56 for (SBQQ__QuoteLine__c ql : newLines) {
57 String code = lineToCode.get(ql.Id);
58 if (ql.Budget_Sequence__c == null
59 && code != null
60 && productBlockMap.containsKey(code)) {
61 linesToAssign.add(ql);
62 quoteIds.add(ql.SBQQ__Quote__c);
63 }
64 }
65
66 if (linesToAssign.isEmpty()) return;
67
68 Map<Id, Date> quoteStartDates = getQuoteStartDates(quoteIds);
69 ExistingLineData existing = queryExistingLines(quoteIds, allLineIds, productBlockMap);
70
71 List<SBQQ__QuoteLine__c> toUpdate = buildUpdates(
72 linesToAssign, quoteStartDates, existing, productBlockMap, lineToCode
73 );
74
75 if (!toUpdate.isEmpty()) {
76 isRunning = true;
77 try {
78 update toUpdate;
79 } finally {
80 isRunning = false;
81 }
82 }
83 }
84
85 // ─────────────────────────────────────────────────────────────────────────
86 // Query product codes via the parent Product2 lookup
87 // ─────────────────────────────────────────────────────────────────────────
88 private static Map<Id, String> queryProductCodes(Set<Id> lineIds) {
89 Map<Id, String> result = new Map<Id, String>();
90 for (SBQQ__QuoteLine__c ql : [
91 SELECT Id, SBQQ__Product__r.ProductCode
92 FROM SBQQ__QuoteLine__c
93 WHERE Id IN :lineIds
94 ]) {
95 if (ql.SBQQ__Product__r != null && ql.SBQQ__Product__r.ProductCode != null) {
96 result.put(ql.Id, ql.SBQQ__Product__r.ProductCode);
97 }
98 }
99 return result;
100 }
101
102 // ─────────────────────────────────────────────────────────────────────────
103 // Core assignment logic
104 // ─────────────────────────────────────────────────────────────────────────
105 @TestVisible
106 private static List<SBQQ__QuoteLine__c> buildUpdates(
107 List<SBQQ__QuoteLine__c> linesToAssign,
108 Map<Id, Date> quoteStartDates,
109 ExistingLineData existing,
110 Map<String, Integer> productBlockMap,
111 Map<Id, String> lineToCode
112 ) {
113 List<SBQQ__QuoteLine__c> toUpdate = new List<SBQQ__QuoteLine__c>();
114
115 Map<Id, List<SBQQ__QuoteLine__c>> byQuote = new Map<Id, List<SBQQ__QuoteLine__c>>();
116 for (SBQQ__QuoteLine__c ql : linesToAssign) {
117 if (!byQuote.containsKey(ql.SBQQ__Quote__c)) {
118 byQuote.put(ql.SBQQ__Quote__c, new List<SBQQ__QuoteLine__c>());
119 }
120 byQuote.get(ql.SBQQ__Quote__c).add(ql);
121 }
122
123 for (Id quoteId : byQuote.keySet()) {
124 Date startDate = quoteStartDates.containsKey(quoteId)
125 ? quoteStartDates.get(quoteId)
126 : Date.today();
127 Map<Integer, Integer> blockMax = existing.quoteBlockMax.containsKey(quoteId)
128 ? existing.quoteBlockMax.get(quoteId)
129 : new Map<Integer, Integer>();
130 List<Integer> existingSeqs = existing.quoteSeqs.containsKey(quoteId)
131 ? existing.quoteSeqs.get(quoteId)
132 : new List<Integer>();
133
134 List<SBQQ__QuoteLine__c> sorted = groupAndSort(
135 byQuote.get(quoteId), productBlockMap, lineToCode
136 );
137
138 Map<Id, Integer> newSeqs = new Map<Id, Integer>();
139 for (SBQQ__QuoteLine__c ql : sorted) {
140 Integer block = productBlockMap.get(lineToCode.get(ql.Id));
141 Integer base = BLOCK_BASE.get(block);
142 Integer nextSeq = blockMax.containsKey(block) ? blockMax.get(block) + 1 : base;
143 newSeqs.put(ql.Id, nextSeq);
144 blockMax.put(block, nextSeq);
145 }
146
147 List<Integer> allSeqs = new List<Integer>(existingSeqs);
148 allSeqs.addAll(newSeqs.values());
149 allSeqs.sort();
150
151 Map<Integer, Integer> seqToRank = new Map<Integer, Integer>();
152 Integer rank = 0;
153 Integer previousSeq;
154 for (Integer seq : allSeqs) {
155 if (previousSeq == null || seq != previousSeq) {
156 rank++;
157 }
158 seqToRank.put(seq, rank);
159 previousSeq = seq;
160 }
161
162 for (SBQQ__QuoteLine__c ql : byQuote.get(quoteId)) {
163 Integer seq = newSeqs.get(ql.Id);
164 Integer lineRank = seqToRank.get(seq);
165 toUpdate.add(new SBQQ__QuoteLine__c(
166 Id = ql.Id,
167 Budget_Sequence__c = seq,
168 Budget_Start_Date__c = startDate.addDays(lineRank - 1)
169 ));
170 }
171
172 // CPQ may insert lines in multiple DML batches, so existing lines may have
173 // stale start dates if a new line was inserted with a lower sequence number.
174 // Recalculate start dates for all existing tracked lines on this quote.
175 Map<Id, Integer> existingLineSeqMap = existing.quoteLineSeqs.containsKey(quoteId)
176 ? existing.quoteLineSeqs.get(quoteId)
177 : new Map<Id, Integer>();
178 for (Id existLineId : existingLineSeqMap.keySet()) {
179 Integer existSeq = existingLineSeqMap.get(existLineId);
180 Integer existRank = seqToRank.get(existSeq);
181 if (existRank != null) {
182 toUpdate.add(new SBQQ__QuoteLine__c(
183 Id = existLineId,
184 Budget_Start_Date__c = startDate.addDays(existRank - 1)
185 ));
186 }
187 }
188 }
189
190 return toUpdate;
191 }
192
193 // ─────────────────────────────────────────────────────────────────────────
194 // Sort lines: block ascending, then line number ascending within block
195 // ─────────────────────────────────────────────────────────────────────────
196 private static List<SBQQ__QuoteLine__c> groupAndSort(
197 List<SBQQ__QuoteLine__c> lines,
198 Map<String, Integer> productBlockMap,
199 Map<Id, String> lineToCode
200 ) {
201 List<LineWrapper> wrappers = new List<LineWrapper>();
202 for (SBQQ__QuoteLine__c ql : lines) {
203 Integer block = productBlockMap.get(lineToCode.get(ql.Id));
204 wrappers.add(new LineWrapper(ql, block));
205 }
206 wrappers.sort();
207
208 List<SBQQ__QuoteLine__c> sorted = new List<SBQQ__QuoteLine__c>();
209 for (LineWrapper w : wrappers) sorted.add(w.line);
210 return sorted;
211 }
212
213 // ─────────────────────────────────────────────────────────────────────────
214 // Query helpers
215 // ─────────────────────────────────────────────────────────────────────────
216 private static Map<Id, Date> getQuoteStartDates(Set<Id> quoteIds) {
217 Map<Id, Date> result = new Map<Id, Date>();
218 for (SBQQ__Quote__c q : [
219 SELECT Id, SBQQ__StartDate__c
220 FROM SBQQ__Quote__c
221 WHERE Id IN :quoteIds
222 ]) {
223 result.put(q.Id, q.SBQQ__StartDate__c != null ? q.SBQQ__StartDate__c : Date.today());
224 }
225 return result;
226 }
227
228 private static ExistingLineData queryExistingLines(
229 Set<Id> quoteIds,
230 Set<Id> newLineIds,
231 Map<String, Integer> productBlockMap
232 ) {
233 ExistingLineData data = new ExistingLineData();
234
235 for (SBQQ__QuoteLine__c ql : [
236 SELECT Id, SBQQ__Quote__c, Budget_Sequence__c
237 FROM SBQQ__QuoteLine__c
238 WHERE SBQQ__Quote__c IN :quoteIds
239 AND Budget_Sequence__c != null
240 AND Id NOT IN :newLineIds
241 ]) {
242 Id qId = ql.SBQQ__Quote__c;
243 Integer seq = Integer.valueOf(ql.Budget_Sequence__c);
244
245 if (!data.quoteSeqs.containsKey(qId)) data.quoteSeqs.put(qId, new List<Integer>());
246 data.quoteSeqs.get(qId).add(seq);
247
248 if (!data.quoteLineSeqs.containsKey(qId)) data.quoteLineSeqs.put(qId, new Map<Id, Integer>());
249 data.quoteLineSeqs.get(qId).put(ql.Id, seq);
250
251 if (!data.quoteBlockMax.containsKey(qId)) data.quoteBlockMax.put(qId, new Map<Integer, Integer>());
252 Map<Integer, Integer> blockMax = data.quoteBlockMax.get(qId);
253 for (Integer block : BLOCK_BASE.keySet()) {
254 Integer base = BLOCK_BASE.get(block);
255 if (seq >= base && seq < base + 1000) {
256 Integer curr = blockMax.containsKey(block) ? blockMax.get(block) : base - 1;
257 if (seq > curr) blockMax.put(block, seq);
258 break;
259 }
260 }
261 }
262
263 return data;
264 }
265
266 // ─────────────────────────────────────────────────────────────────────────
267 // Load Custom Metadata: productCode → block number
268 // ─────────────────────────────────────────────────────────────────────────
269 @TestVisible
270 static Map<String, Integer> productBlockMapOverride;
271
272 private static Map<String, Integer> loadProductBlockMap() {
273 if (productBlockMapOverride != null) return productBlockMapOverride;
274
275 Map<String, Integer> result = new Map<String, Integer>();
276 for (Budget_Sequence_Config__mdt cfg : [
277 SELECT Product_Code__c, Sequence_Block__c
278 FROM Budget_Sequence_Config__mdt
279 ]) {
280 if (cfg.Product_Code__c != null && cfg.Sequence_Block__c != null) {
281 result.put(cfg.Product_Code__c, Integer.valueOf(cfg.Sequence_Block__c));
282 }
283 }
284 return result;
285 }
286
287 // ─────────────────────────────────────────────────────────────────────────
288 // Inner classes
289 // ─────────────────────────────────────────────────────────────────────────
290 @TestVisible
291 private class ExistingLineData {
292 @TestVisible Map<Id, Map<Integer, Integer>> quoteBlockMax = new Map<Id, Map<Integer, Integer>>();
293 @TestVisible Map<Id, List<Integer>> quoteSeqs = new Map<Id, List<Integer>>();
294 // lineId → sequence for existing lines, so we can recalculate their start dates
295 @TestVisible Map<Id, Map<Id, Integer>> quoteLineSeqs = new Map<Id, Map<Id, Integer>>();
296 }
297
298 private class LineWrapper implements Comparable {
299 SBQQ__QuoteLine__c line;
300 Integer block;
301 Decimal lineNumber;
302
303 LineWrapper(SBQQ__QuoteLine__c l, Integer b) {
304 line = l;
305 block = b;
306 lineNumber = l.SBQQ__Number__c != null ? l.SBQQ__Number__c : 9999;
307 }
308
309 public Integer compareTo(Object other) {
310 LineWrapper o = (LineWrapper) other;
311 if (block != o.block) return block - o.block;
312 return lineNumber > o.lineNumber ? 1 : (lineNumber < o.lineNumber ? -1 : 0);
313 }
314 }
315}
trigger · 3 lines

QuoteLineBudgetSequenceTrigger

Entry point that invokes the budget sequence handler after quote lines are inserted.

Review and understand complete source code

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.

1trigger QuoteLineBudgetSequenceTrigger on SBQQ__QuoteLine__c (after insert) {Declares a class or trigger. The braces contain its members and behavior.
2 QuoteLineBudgetSequenceHandler.assignSequences(Trigger.new);Completes the statement begun on this line or the preceding lines.
3}Closes the current block or declaration.
View complete source code
1trigger QuoteLineBudgetSequenceTrigger on SBQQ__QuoteLine__c (after insert) {
2 QuoteLineBudgetSequenceHandler.assignSequences(Trigger.new);
3}

Tests and shared fixture

Read each test as arrange → act → assert: create isolated data, call production code, then check a saved value or expected error. A passing test does not prove paths it never executed.

test · 105 lines

PsQuoteAnalyzerControllerTest

Tests document-analysis inputs, signed PDF linking, and the change-order setup rules.

Review and understand complete source code

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@IsTestMarks the following class or method as test code.
2private class PsQuoteAnalyzerControllerTest {Declares a class or trigger. The braces contain its members and behavior.
3 @IsTestMarks the following class or method as test code.
4 static void rejectsMissingOrUnknownInputs() {Method declaration: Tests rejects missing or unknown inputs. The parentheses define its inputs; the type before the name defines its return value.
5 try {Starts an operation whose exception can be handled below.
6 PsQuoteAnalyzerController.startAnalysis(null, null, 'new', null);Completes the statement begun on this line or the preceding lines.
7 System.assert(false, 'An Opportunity and PDF are required.');Test assertion: fails the test when the expected behavior is absent.
8 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
9 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
10 }Closes the current block or declaration.
11 try {Starts an operation whose exception can be handled below.
12 PsQuoteAnalyzerController.startAnalysis(Part of the surrounding declaration or expression; read it with the adjacent lines.
13 (Id) '006000000000001', (Id) '069000000000001', 'unknown', nullPart of the surrounding declaration or expression; read it with the adjacent lines.
14 );Opens or closes the expression begun on the surrounding lines.
15 System.assert(false, 'Unknown request types must be rejected.');Test assertion: fails the test when the expected behavior is absent.
16 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
17 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
18 }Closes the current block or declaration.
19 }Closes the current block or declaration.
20 Spacing separates related steps.
21 @IsTestMarks the following class or method as test code.
22 static void createsNewServicesAnalysisFromLinkedPdf() {Method declaration: Tests creates new services analysis from linked pdf. The parentheses define its inputs; the type before the name defines its return value.
23 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
24 Id documentId = PsQuoteTestData.pdfOnOpportunity(opportunityRecord.Id);Creates or assigns a typed value for the steps that follow.
25 Test.startTest();Starts the test’s measured execution section and resets governor limits.
26 Id analysisId = PsQuoteAnalyzerController.startAnalysis(Creates or assigns a typed value for the steps that follow.
27 opportunityRecord.Id, documentId, 'new', nullPart of the surrounding declaration or expression; read it with the adjacent lines.
28 );Opens or closes the expression begun on the surrounding lines.
29 Test.stopTest();Ends that section and runs queued asynchronous test work.
30 PS_Quote_Analysis__c saved = [Assigns or configures the value on the left using the expression on the right.
31 SELECT Opportunity__c, Content_Document_Id__c, Content_Version_Id__c,SOQL field list: identifies data to read from Salesforce.
32 Quote_Type__c, Amended_Contract__c, Effective_Date__c, Status__cPart of the surrounding declaration or expression; read it with the adjacent lines.
33 FROM PS_Quote_Analysis__c WHERE Id = :analysisIdSOQL source: identifies which Salesforce object to read.
34 ];Completes the statement begun on this line or the preceding lines.
35 System.assertEquals(opportunityRecord.Id, saved.Opportunity__c);Test assertion: fails the test when the expected behavior is absent.
36 System.assertEquals(String.valueOf(documentId), saved.Content_Document_Id__c);Test assertion: fails the test when the expected behavior is absent.
37 System.assertNotEquals(null, saved.Content_Version_Id__c);Test assertion: fails the test when the expected behavior is absent.
38 System.assertEquals('New Services', saved.Quote_Type__c);Test assertion: fails the test when the expected behavior is absent.
39 System.assertEquals(null, saved.Amended_Contract__c);Test assertion: fails the test when the expected behavior is absent.
40 System.assertEquals(null, saved.Effective_Date__c);Test assertion: fails the test when the expected behavior is absent.
41 System.assertEquals('Queued', saved.Status__c);Test assertion: fails the test when the expected behavior is absent.
42 }Closes the current block or declaration.
43 Spacing separates related steps.
44 @IsTestMarks the following class or method as test code.
45 static void changeOrderRequiresDateAndPrimaryAmendmentQuote() {Method declaration: Tests change order requires date and primary amendment quote. The parentheses define its inputs; the type before the name defines its return value.
46 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
47 Id documentId = PsQuoteTestData.pdfOnOpportunity(opportunityRecord.Id);Creates or assigns a typed value for the steps that follow.
48 try {Starts an operation whose exception can be handled below.
49 PsQuoteAnalyzerController.startAnalysis(Part of the surrounding declaration or expression; read it with the adjacent lines.
50 opportunityRecord.Id, documentId, 'amendment', nullPart of the surrounding declaration or expression; read it with the adjacent lines.
51 );Opens or closes the expression begun on the surrounding lines.
52 System.assert(false, 'An effective date is required.');Test assertion: fails the test when the expected behavior is absent.
53 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
54 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
55 }Closes the current block or declaration.
56 try {Starts an operation whose exception can be handled below.
57 PsQuoteAnalyzerController.startAnalysis(Part of the surrounding declaration or expression; read it with the adjacent lines.
58 opportunityRecord.Id, documentId, 'amendment', Date.today()Part of the surrounding declaration or expression; read it with the adjacent lines.
59 );Opens or closes the expression begun on the surrounding lines.
60 System.assert(false, 'A primary CPQ amendment quote is required.');Test assertion: fails the test when the expected behavior is absent.
61 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
62 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
63 }Closes the current block or declaration.
64 System.assertEquals(0, [SELECT COUNT() FROM PS_Quote_Analysis__c]);Test assertion: fails the test when the expected behavior is absent.
65 }Closes the current block or declaration.
66 Spacing separates related steps.
67 @IsTestMarks the following class or method as test code.
68 static void rejectsNonPdfAndUnlinkedFiles() {Method declaration: Tests rejects non pdf and unlinked files. The parentheses define its inputs; the type before the name defines its return value.
69 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
70 ContentVersion textFile = new ContentVersion(Creates or assigns a typed value for the steps that follow.
71 Title='notes', PathOnClient='notes.txt',Assigns or configures the value on the left using the expression on the right.
72 VersionData=Blob.valueOf('not a PDF'),Assigns or configures the value on the left using the expression on the right.
73 FirstPublishLocationId=opportunityRecord.IdCreates or assigns a typed value for the steps that follow.
74 );Opens or closes the expression begun on the surrounding lines.
75 insert textFile;DML write: creates the specified Salesforce record or records.
76 Id documentId = [SELECT ContentDocumentId FROM ContentVersionCreates or assigns a typed value for the steps that follow.
77 WHERE Id = :textFile.Id].ContentDocumentId;SOQL filter: narrows the records returned by this query.
78 try {Starts an operation whose exception can be handled below.
79 PsQuoteAnalyzerController.startAnalysis(Part of the surrounding declaration or expression; read it with the adjacent lines.
80 opportunityRecord.Id, documentId, 'new', nullPart of the surrounding declaration or expression; read it with the adjacent lines.
81 );Opens or closes the expression begun on the surrounding lines.
82 System.assert(false, 'Only PDFs are accepted.');Test assertion: fails the test when the expected behavior is absent.
83 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
84 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
85 }Closes the current block or declaration.
86 Account unrelated = new Account(Name='Unrelated file owner');Creates or assigns a typed value for the steps that follow.
87 insert unrelated;DML write: creates the specified Salesforce record or records.
88 ContentVersion otherFile = new ContentVersion(Creates or assigns a typed value for the steps that follow.
89 Title='other', PathOnClient='other.pdf',Assigns or configures the value on the left using the expression on the right.
90 VersionData=Blob.valueOf('%PDF-1.4\n%%EOF'),Assigns or configures the value on the left using the expression on the right.
91 FirstPublishLocationId=unrelated.IdCreates or assigns a typed value for the steps that follow.
92 );Opens or closes the expression begun on the surrounding lines.
93 insert otherFile;DML write: creates the specified Salesforce record or records.
94 Id otherDocumentId = [SELECT ContentDocumentId FROM ContentVersionCreates or assigns a typed value for the steps that follow.
95 WHERE Id = :otherFile.Id].ContentDocumentId;SOQL filter: narrows the records returned by this query.
96 try {Starts an operation whose exception can be handled below.
97 PsQuoteAnalyzerController.startAnalysis(Part of the surrounding declaration or expression; read it with the adjacent lines.
98 opportunityRecord.Id, otherDocumentId, 'new', nullPart of the surrounding declaration or expression; read it with the adjacent lines.
99 );Opens or closes the expression begun on the surrounding lines.
100 System.assert(false, 'The PDF must be linked to this Opportunity.');Test assertion: fails the test when the expected behavior is absent.
101 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
102 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
103 }Closes the current block or declaration.
104 }Closes the current block or declaration.
105}Closes the current block or declaration.
View complete source code
1@IsTest
2private class PsQuoteAnalyzerControllerTest {
3 @IsTest
4 static void rejectsMissingOrUnknownInputs() {
5 try {
6 PsQuoteAnalyzerController.startAnalysis(null, null, 'new', null);
7 System.assert(false, 'An Opportunity and PDF are required.');
8 } catch (AuraHandledException expected) {
9 System.assertNotEquals(null, expected);
10 }
11 try {
12 PsQuoteAnalyzerController.startAnalysis(
13 (Id) '006000000000001', (Id) '069000000000001', 'unknown', null
14 );
15 System.assert(false, 'Unknown request types must be rejected.');
16 } catch (AuraHandledException expected) {
17 System.assertNotEquals(null, expected);
18 }
19 }
20
21 @IsTest
22 static void createsNewServicesAnalysisFromLinkedPdf() {
23 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
24 Id documentId = PsQuoteTestData.pdfOnOpportunity(opportunityRecord.Id);
25 Test.startTest();
26 Id analysisId = PsQuoteAnalyzerController.startAnalysis(
27 opportunityRecord.Id, documentId, 'new', null
28 );
29 Test.stopTest();
30 PS_Quote_Analysis__c saved = [
31 SELECT Opportunity__c, Content_Document_Id__c, Content_Version_Id__c,
32 Quote_Type__c, Amended_Contract__c, Effective_Date__c, Status__c
33 FROM PS_Quote_Analysis__c WHERE Id = :analysisId
34 ];
35 System.assertEquals(opportunityRecord.Id, saved.Opportunity__c);
36 System.assertEquals(String.valueOf(documentId), saved.Content_Document_Id__c);
37 System.assertNotEquals(null, saved.Content_Version_Id__c);
38 System.assertEquals('New Services', saved.Quote_Type__c);
39 System.assertEquals(null, saved.Amended_Contract__c);
40 System.assertEquals(null, saved.Effective_Date__c);
41 System.assertEquals('Queued', saved.Status__c);
42 }
43
44 @IsTest
45 static void changeOrderRequiresDateAndPrimaryAmendmentQuote() {
46 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
47 Id documentId = PsQuoteTestData.pdfOnOpportunity(opportunityRecord.Id);
48 try {
49 PsQuoteAnalyzerController.startAnalysis(
50 opportunityRecord.Id, documentId, 'amendment', null
51 );
52 System.assert(false, 'An effective date is required.');
53 } catch (AuraHandledException expected) {
54 System.assertNotEquals(null, expected);
55 }
56 try {
57 PsQuoteAnalyzerController.startAnalysis(
58 opportunityRecord.Id, documentId, 'amendment', Date.today()
59 );
60 System.assert(false, 'A primary CPQ amendment quote is required.');
61 } catch (AuraHandledException expected) {
62 System.assertNotEquals(null, expected);
63 }
64 System.assertEquals(0, [SELECT COUNT() FROM PS_Quote_Analysis__c]);
65 }
66
67 @IsTest
68 static void rejectsNonPdfAndUnlinkedFiles() {
69 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
70 ContentVersion textFile = new ContentVersion(
71 Title='notes', PathOnClient='notes.txt',
72 VersionData=Blob.valueOf('not a PDF'),
73 FirstPublishLocationId=opportunityRecord.Id
74 );
75 insert textFile;
76 Id documentId = [SELECT ContentDocumentId FROM ContentVersion
77 WHERE Id = :textFile.Id].ContentDocumentId;
78 try {
79 PsQuoteAnalyzerController.startAnalysis(
80 opportunityRecord.Id, documentId, 'new', null
81 );
82 System.assert(false, 'Only PDFs are accepted.');
83 } catch (AuraHandledException expected) {
84 System.assertNotEquals(null, expected);
85 }
86 Account unrelated = new Account(Name='Unrelated file owner');
87 insert unrelated;
88 ContentVersion otherFile = new ContentVersion(
89 Title='other', PathOnClient='other.pdf',
90 VersionData=Blob.valueOf('%PDF-1.4\n%%EOF'),
91 FirstPublishLocationId=unrelated.Id
92 );
93 insert otherFile;
94 Id otherDocumentId = [SELECT ContentDocumentId FROM ContentVersion
95 WHERE Id = :otherFile.Id].ContentDocumentId;
96 try {
97 PsQuoteAnalyzerController.startAnalysis(
98 opportunityRecord.Id, otherDocumentId, 'new', null
99 );
100 System.assert(false, 'The PDF must be linked to this Opportunity.');
101 } catch (AuraHandledException expected) {
102 System.assertNotEquals(null, expected);
103 }
104 }
105}
test · 121 lines

PsQuoteAnalysisReviewControllerTest

Tests review confirmation, normalized breakdowns, and rejection of invalid data.

Review and understand complete source code

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@IsTestMarks the following class or method as test code.
2private class PsQuoteAnalysisReviewControllerTest {Declares a class or trigger. The braces contain its members and behavior.
3 private static PS_Quote_Analysis__c readyAnalysis() {Opens a block; the indented lines below execute or belong together.
4 Account account = new Account(Name = 'Review test account');Creates or assigns a typed value for the steps that follow.
5 insert account;DML write: creates the specified Salesforce record or records.
6 Spacing separates related steps.
7 String stageName;Completes the statement begun on this line or the preceding lines.
8 for (Schema.PicklistEntry entry : Opportunity.StageName.getDescribe().getPicklistValues()) {Loop: repeats the following block for each matching item.
9 if (entry.isActive()) {Guard or branch: the following block runs only when this condition is true.
10 stageName = entry.getValue();Assigns or configures the value on the left using the expression on the right.
11 break;Completes the statement begun on this line or the preceding lines.
12 }Closes the current block or declaration.
13 }Closes the current block or declaration.
14 System.assertNotEquals(null, stageName, 'An active Opportunity stage is required.');Test assertion: fails the test when the expected behavior is absent.
15 Opportunity opportunityRecord = new Opportunity(Creates or assigns a typed value for the steps that follow.
16 Name = 'Review test opportunity', AccountId = account.Id,Creates or assigns a typed value for the steps that follow.
17 StageName = stageName, CloseDate = Date.today().addDays(30)Creates or assigns a typed value for the steps that follow.
18 );Opens or closes the expression begun on the surrounding lines.
19 insert opportunityRecord;DML write: creates the specified Salesforce record or records.
20 Spacing separates related steps.
21 ContentVersion fileVersion = new ContentVersion(Creates or assigns a typed value for the steps that follow.
22 Title = 'Signed SOW', PathOnClient = 'signed.pdf',Assigns or configures the value on the left using the expression on the right.
23 VersionData = Blob.valueOf('%PDF-1.4\n%%EOF'),Assigns or configures the value on the left using the expression on the right.
24 FirstPublishLocationId = opportunityRecord.IdCreates or assigns a typed value for the steps that follow.
25 );Opens or closes the expression begun on the surrounding lines.
26 insert fileVersion;DML write: creates the specified Salesforce record or records.
27 fileVersion = [Assigns or configures the value on the left using the expression on the right.
28 SELECT ContentDocumentId FROM ContentVersion WHERE Id = :fileVersion.Id LIMIT 1SOQL field list: identifies data to read from Salesforce.
29 ];Completes the statement begun on this line or the preceding lines.
30 Spacing separates related steps.
31 String currencyCode = [Creates or assigns a typed value for the steps that follow.
32 SELECT CurrencyIsoCode FROM Opportunity WHERE Id = :opportunityRecord.Id LIMIT 1SOQL field list: identifies data to read from Salesforce.
33 ].CurrencyIsoCode;Completes the statement begun on this line or the preceding lines.
34 String proposal = '{"currency_code":"' + currencyCode + '",' +Creates or assigns a typed value for the steps that follow.
35 '"quote_total":25,"lines":[{"category":"MILESTONE",' +Part of the surrounding declaration or expression; read it with the adjacent lines.
36 '"label":"Design","amount":25}]}';Completes the statement begun on this line or the preceding lines.
37 PS_Quote_Analysis__c analysis = new PS_Quote_Analysis__c(Creates or assigns a typed value for the steps that follow.
38 Opportunity__c = opportunityRecord.Id,Creates or assigns a typed value for the steps that follow.
39 Status__c = 'Needs Review',Assigns or configures the value on the left using the expression on the right.
40 Quote_Type__c = 'New Services',Assigns or configures the value on the left using the expression on the right.
41 Content_Document_Id__c = String.valueOf(fileVersion.ContentDocumentId),Creates or assigns a typed value for the steps that follow.
42 Content_Version_Id__c = String.valueOf(fileVersion.Id),Creates or assigns a typed value for the steps that follow.
43 AI_Proposal_JSON__c = proposalAssigns or configures the value on the left using the expression on the right.
44 );Opens or closes the expression begun on the surrounding lines.
45 insert analysis;DML write: creates the specified Salesforce record or records.
46 return [Returns this value to the caller and ends the method.
47 SELECT Id, Opportunity__c, CurrencyIsoCode, Status__cSOQL field list: identifies data to read from Salesforce.
48 FROM PS_Quote_Analysis__c WHERE Id = :analysis.Id LIMIT 1SOQL source: identifies which Salesforce object to read.
49 ];Completes the statement begun on this line or the preceding lines.
50 }Closes the current block or declaration.
51 Spacing separates related steps.
52 @IsTestMarks the following class or method as test code.
53 static void confirmsAndRetrievesReviewedBreakdown() {Method declaration: Tests confirms and retrieves reviewed breakdown. The parentheses define its inputs; the type before the name defines its return value.
54 PS_Quote_Analysis__c analysis = readyAnalysis();Assigns or configures the value on the left using the expression on the right.
55 String reviewedJson = '{"currency_code":"' + analysis.CurrencyIsoCode + '",' +Creates or assigns a typed value for the steps that follow.
56 '"lines":[{"category":"MILESTONE","label":" Design sign off ",' +Part of the surrounding declaration or expression; read it with the adjacent lines.
57 '"amount":22.50},{"category":"TIME_MATERIAL","label":"Delivery",' +Part of the surrounding declaration or expression; read it with the adjacent lines.
58 '"amount":10.00}]}';Completes the statement begun on this line or the preceding lines.
59 Spacing separates related steps.
60 Test.startTest();Starts the test’s measured execution section and resets governor limits.
61 PsQuoteAnalysisReviewController.confirmBreakdown(analysis.Id, reviewedJson);Completes the statement begun on this line or the preceding lines.
62 PS_Quote_Analysis__c latest =Assigns or configures the value on the left using the expression on the right.
63 PsQuoteAnalysisReviewController.getLatestAnalysis(analysis.Opportunity__c);Completes the statement begun on this line or the preceding lines.
64 Test.stopTest();Ends that section and runs queued asynchronous test work.
65 Spacing separates related steps.
66 System.assertEquals(analysis.Id, latest.Id);Test assertion: fails the test when the expected behavior is absent.
67 System.assertEquals('Confirmed', latest.Status__c);Test assertion: fails the test when the expected behavior is absent.
68 Map<String, Object> saved = (Map<String, Object>) JSON.deserializeUntyped(Parses JSON text into Apex values that the following code can inspect.
69 latest.Reviewed_Proposal_JSON__cPart of the surrounding declaration or expression; read it with the adjacent lines.
70 );Opens or closes the expression begun on the surrounding lines.
71 System.assertEquals(32.5, (Decimal) saved.get('quote_total'));Test assertion: fails the test when the expected behavior is absent.
72 List<Object> lines = (List<Object>) saved.get('lines');Creates or assigns a typed value for the steps that follow.
73 System.assertEquals(2, lines.size());Test assertion: fails the test when the expected behavior is absent.
74 System.assertEquals('Design sign off',Test assertion: fails the test when the expected behavior is absent.
75 ((Map<String, Object>) lines[0]).get('label'));Completes the statement begun on this line or the preceding lines.
76 }Closes the current block or declaration.
77 Spacing separates related steps.
78 @IsTestMarks the following class or method as test code.
79 static void rejectsBadInputsAndKeepsAnalysisUnconfirmed() {Method declaration: Tests rejects bad inputs and keeps analysis unconfirmed. The parentheses define its inputs; the type before the name defines its return value.
80 PS_Quote_Analysis__c analysis = readyAnalysis();Assigns or configures the value on the left using the expression on the right.
81 String otherCurrency = analysis.CurrencyIsoCode == 'USD' ? 'EUR' : 'USD';Creates or assigns a typed value for the steps that follow.
82 List<String> invalidReviews = new List<String>{Opens a block; the indented lines below execute or belong together.
83 '{"currency_code":"' + otherCurrency + '","lines":[' +Part of the surrounding declaration or expression; read it with the adjacent lines.
84 '{"category":"MILESTONE","label":"Design","amount":25}]}',Continues the argument list or condition on the next line.
85 '{"currency_code":"' + analysis.CurrencyIsoCode + '","lines":[' +Part of the surrounding declaration or expression; read it with the adjacent lines.
86 '{"category":"MILESTONE","label":"Design","amount":-1}]}'Part of the surrounding declaration or expression; read it with the adjacent lines.
87 };Closes the current block or declaration.
88 Spacing separates related steps.
89 for (String invalidReview : invalidReviews) {Loop: repeats the following block for each matching item.
90 Boolean rejected = false;Creates or assigns a typed value for the steps that follow.
91 try {Starts an operation whose exception can be handled below.
92 PsQuoteAnalysisReviewController.confirmBreakdown(analysis.Id, invalidReview);Completes the statement begun on this line or the preceding lines.
93 } catch (AuraHandledException expectedError) {Opens a block; the indented lines below execute or belong together.
94 rejected = true;Assigns or configures the value on the left using the expression on the right.
95 }Closes the current block or declaration.
96 System.assert(rejected, 'Invalid breakdown should be rejected.');Test assertion: fails the test when the expected behavior is absent.
97 }Closes the current block or declaration.
98 System.assertEquals('Needs Review', [Test assertion: fails the test when the expected behavior is absent.
99 SELECT Status__c FROM PS_Quote_Analysis__c WHERE Id = :analysis.IdSOQL field list: identifies data to read from Salesforce.
100 ].Status__c);Completes the statement begun on this line or the preceding lines.
101 }Closes the current block or declaration.
102 Spacing separates related steps.
103 @IsTestMarks the following class or method as test code.
104 static void rejectsMissingIdentifiers() {Method declaration: Tests rejects missing identifiers. The parentheses define its inputs; the type before the name defines its return value.
105 Boolean lookupRejected = false;Creates or assigns a typed value for the steps that follow.
106 try {Starts an operation whose exception can be handled below.
107 PsQuoteAnalysisReviewController.getLatestAnalysis(null);Completes the statement begun on this line or the preceding lines.
108 } catch (AuraHandledException expectedError) {Opens a block; the indented lines below execute or belong together.
109 lookupRejected = true;Assigns or configures the value on the left using the expression on the right.
110 }Closes the current block or declaration.
111 System.assert(lookupRejected, 'An Opportunity ID is required.');Test assertion: fails the test when the expected behavior is absent.
112 Spacing separates related steps.
113 Boolean confirmationRejected = false;Creates or assigns a typed value for the steps that follow.
114 try {Starts an operation whose exception can be handled below.
115 PsQuoteAnalysisReviewController.confirmBreakdown(null, null);Completes the statement begun on this line or the preceding lines.
116 } catch (AuraHandledException expectedError) {Opens a block; the indented lines below execute or belong together.
117 confirmationRejected = true;Assigns or configures the value on the left using the expression on the right.
118 }Closes the current block or declaration.
119 System.assert(confirmationRejected, 'An analysis ID and breakdown are required.');Test assertion: fails the test when the expected behavior is absent.
120 }Closes the current block or declaration.
121}Closes the current block or declaration.
View complete source code
1@IsTest
2private class PsQuoteAnalysisReviewControllerTest {
3 private static PS_Quote_Analysis__c readyAnalysis() {
4 Account account = new Account(Name = 'Review test account');
5 insert account;
6
7 String stageName;
8 for (Schema.PicklistEntry entry : Opportunity.StageName.getDescribe().getPicklistValues()) {
9 if (entry.isActive()) {
10 stageName = entry.getValue();
11 break;
12 }
13 }
14 System.assertNotEquals(null, stageName, 'An active Opportunity stage is required.');
15 Opportunity opportunityRecord = new Opportunity(
16 Name = 'Review test opportunity', AccountId = account.Id,
17 StageName = stageName, CloseDate = Date.today().addDays(30)
18 );
19 insert opportunityRecord;
20
21 ContentVersion fileVersion = new ContentVersion(
22 Title = 'Signed SOW', PathOnClient = 'signed.pdf',
23 VersionData = Blob.valueOf('%PDF-1.4\n%%EOF'),
24 FirstPublishLocationId = opportunityRecord.Id
25 );
26 insert fileVersion;
27 fileVersion = [
28 SELECT ContentDocumentId FROM ContentVersion WHERE Id = :fileVersion.Id LIMIT 1
29 ];
30
31 String currencyCode = [
32 SELECT CurrencyIsoCode FROM Opportunity WHERE Id = :opportunityRecord.Id LIMIT 1
33 ].CurrencyIsoCode;
34 String proposal = '{"currency_code":"' + currencyCode + '",' +
35 '"quote_total":25,"lines":[{"category":"MILESTONE",' +
36 '"label":"Design","amount":25}]}';
37 PS_Quote_Analysis__c analysis = new PS_Quote_Analysis__c(
38 Opportunity__c = opportunityRecord.Id,
39 Status__c = 'Needs Review',
40 Quote_Type__c = 'New Services',
41 Content_Document_Id__c = String.valueOf(fileVersion.ContentDocumentId),
42 Content_Version_Id__c = String.valueOf(fileVersion.Id),
43 AI_Proposal_JSON__c = proposal
44 );
45 insert analysis;
46 return [
47 SELECT Id, Opportunity__c, CurrencyIsoCode, Status__c
48 FROM PS_Quote_Analysis__c WHERE Id = :analysis.Id LIMIT 1
49 ];
50 }
51
52 @IsTest
53 static void confirmsAndRetrievesReviewedBreakdown() {
54 PS_Quote_Analysis__c analysis = readyAnalysis();
55 String reviewedJson = '{"currency_code":"' + analysis.CurrencyIsoCode + '",' +
56 '"lines":[{"category":"MILESTONE","label":" Design sign off ",' +
57 '"amount":22.50},{"category":"TIME_MATERIAL","label":"Delivery",' +
58 '"amount":10.00}]}';
59
60 Test.startTest();
61 PsQuoteAnalysisReviewController.confirmBreakdown(analysis.Id, reviewedJson);
62 PS_Quote_Analysis__c latest =
63 PsQuoteAnalysisReviewController.getLatestAnalysis(analysis.Opportunity__c);
64 Test.stopTest();
65
66 System.assertEquals(analysis.Id, latest.Id);
67 System.assertEquals('Confirmed', latest.Status__c);
68 Map<String, Object> saved = (Map<String, Object>) JSON.deserializeUntyped(
69 latest.Reviewed_Proposal_JSON__c
70 );
71 System.assertEquals(32.5, (Decimal) saved.get('quote_total'));
72 List<Object> lines = (List<Object>) saved.get('lines');
73 System.assertEquals(2, lines.size());
74 System.assertEquals('Design sign off',
75 ((Map<String, Object>) lines[0]).get('label'));
76 }
77
78 @IsTest
79 static void rejectsBadInputsAndKeepsAnalysisUnconfirmed() {
80 PS_Quote_Analysis__c analysis = readyAnalysis();
81 String otherCurrency = analysis.CurrencyIsoCode == 'USD' ? 'EUR' : 'USD';
82 List<String> invalidReviews = new List<String>{
83 '{"currency_code":"' + otherCurrency + '","lines":[' +
84 '{"category":"MILESTONE","label":"Design","amount":25}]}',
85 '{"currency_code":"' + analysis.CurrencyIsoCode + '","lines":[' +
86 '{"category":"MILESTONE","label":"Design","amount":-1}]}'
87 };
88
89 for (String invalidReview : invalidReviews) {
90 Boolean rejected = false;
91 try {
92 PsQuoteAnalysisReviewController.confirmBreakdown(analysis.Id, invalidReview);
93 } catch (AuraHandledException expectedError) {
94 rejected = true;
95 }
96 System.assert(rejected, 'Invalid breakdown should be rejected.');
97 }
98 System.assertEquals('Needs Review', [
99 SELECT Status__c FROM PS_Quote_Analysis__c WHERE Id = :analysis.Id
100 ].Status__c);
101 }
102
103 @IsTest
104 static void rejectsMissingIdentifiers() {
105 Boolean lookupRejected = false;
106 try {
107 PsQuoteAnalysisReviewController.getLatestAnalysis(null);
108 } catch (AuraHandledException expectedError) {
109 lookupRejected = true;
110 }
111 System.assert(lookupRejected, 'An Opportunity ID is required.');
112
113 Boolean confirmationRejected = false;
114 try {
115 PsQuoteAnalysisReviewController.confirmBreakdown(null, null);
116 } catch (AuraHandledException expectedError) {
117 confirmationRejected = true;
118 }
119 System.assert(confirmationRejected, 'An analysis ID and breakdown are required.');
120 }
121}
test · 474 lines

PsQuoteCpqControllerTest

Tests quote and amendment guards, JSON validation, queue stages, price book behavior, and CPQ line helpers. Recent local additions are not verified in Salesforce.

This is the newer local test source. Recent additions still need a Salesforce test run.

Review and understand complete source code

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@IsTestMarks the following class or method as test code.
2private class PsQuoteCpqControllerTest {Declares a class or trigger. The braces contain its members and behavior.
3 @IsTestMarks the following class or method as test code.
4 static void findsPrimaryAmendmentAndRejectsMissingNativeLines() {Method declaration: Tests finds primary amendment and rejects missing native lines. The parentheses define its inputs; the type before the name defines its return value.
5 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
6 List<ContractStatus> draftStatuses = [Creates or assigns a typed value for the steps that follow.
7 SELECT ApiName FROM ContractStatusSOQL field list: identifies data to read from Salesforce.
8 WHERE StatusCode = 'Draft'SOQL filter: narrows the records returned by this query.
9 ORDER BY IsDefault DESC LIMIT 1Sorts the records returned by this query.
10 ];Completes the statement begun on this line or the preceding lines.
11 System.assert(!draftStatuses.isEmpty(),Test assertion: fails the test when the expected behavior is absent.
12 'This test needs a Contract status in the Draft category.');Completes the statement begun on this line or the preceding lines.
13 Contract contractRecord = new Contract(Creates or assigns a typed value for the steps that follow.
14 Name = 'Amended services contract',Assigns or configures the value on the left using the expression on the right.
15 AccountId = opportunityRecord.AccountId,Assigns or configures the value on the left using the expression on the right.
16 Status = draftStatuses[0].ApiName,Assigns or configures the value on the left using the expression on the right.
17 StartDate = Date.today().addMonths(-1), ContractTerm = 12Creates or assigns a typed value for the steps that follow.
18 );Opens or closes the expression begun on the surrounding lines.
19 insert contractRecord;DML write: creates the specified Salesforce record or records.
20 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(Creates or assigns a typed value for the steps that follow.
21 SBQQ__Opportunity2__c = opportunityRecord.Id,Creates or assigns a typed value for the steps that follow.
22 SBQQ__Account__c = opportunityRecord.AccountId,Assigns or configures the value on the left using the expression on the right.
23 SBQQ__MasterContract__c = contractRecord.Id,Creates or assigns a typed value for the steps that follow.
24 SBQQ__Type__c = 'Amendment', SBQQ__Primary__c = true,Assigns or configures the value on the left using the expression on the right.
25 SBQQ__StartDate__c = Date.today()Creates or assigns a typed value for the steps that follow.
26 );Opens or closes the expression begun on the surrounding lines.
27 insert quoteRecord;DML write: creates the specified Salesforce record or records.
28 PsQuoteCpqController.PrimaryAmendmentQuote found =Assigns or configures the value on the left using the expression on the right.
29 PsQuoteCpqController.getPrimaryAmendmentQuote(opportunityRecord.Id);Completes the statement begun on this line or the preceding lines.
30 System.assertNotEquals(null, found);Test assertion: fails the test when the expected behavior is absent.
31 System.assertEquals(quoteRecord.Id, found.quoteId);Test assertion: fails the test when the expected behavior is absent.
32 System.assertEquals(contractRecord.Id, found.contractId);Test assertion: fails the test when the expected behavior is absent.
33 Spacing separates related steps.
34 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(Assigns or configures the value on the left using the expression on the right.
35 opportunityRecord.Id, 'Confirmed', 'Change Order'Part of the surrounding declaration or expression; read it with the adjacent lines.
36 );Opens or closes the expression begun on the surrounding lines.
37 update new PS_Quote_Analysis__c(DML write: saves changes to the specified Salesforce record or records.
38 Id = analysis.Id,Creates or assigns a typed value for the steps that follow.
39 Amended_Contract__c = contractRecord.Id,Creates or assigns a typed value for the steps that follow.
40 Effective_Date__c = Date.today()Creates or assigns a typed value for the steps that follow.
41 );Opens or closes the expression begun on the surrounding lines.
42 try {Starts an operation whose exception can be handled below.
43 PsQuoteCpqController.useNativeAmendmentQuote(analysis.Id);Completes the statement begun on this line or the preceding lines.
44 System.assert(false, 'The quote has no existing contract lines.');Test assertion: fails the test when the expected behavior is absent.
45 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
46 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
47 }Closes the current block or declaration.
48 }Closes the current block or declaration.
49 @IsTestMarks the following class or method as test code.
50 static void rejectsMissingAnalysisAndQuoteIds() {Method declaration: Tests rejects missing analysis and quote ids. The parentheses define its inputs; the type before the name defines its return value.
51 try {Starts an operation whose exception can be handled below.
52 PsQuoteCpqController.createQuote(null, Date.today());Completes the statement begun on this line or the preceding lines.
53 System.assert(false, 'Missing analysis must stop quote creation.');Test assertion: fails the test when the expected behavior is absent.
54 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
55 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
56 }Closes the current block or declaration.
57 try {Starts an operation whose exception can be handled below.
58 PsQuoteCpqController.useNativeAmendmentQuote(null);Completes the statement begun on this line or the preceding lines.
59 System.assert(false, 'Missing IDs must stop amendment use.');Test assertion: fails the test when the expected behavior is absent.
60 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
61 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
62 }Closes the current block or declaration.
63 System.assertEquals(null, PsQuoteCpqController.getPrimaryAmendmentQuote(null));Test assertion: fails the test when the expected behavior is absent.
64 }Closes the current block or declaration.
65 Spacing separates related steps.
66 @IsTestMarks the following class or method as test code.
67 static void requiresConfirmedBreakdownAndStartDate() {Method declaration: Tests requires confirmed breakdown and start date. The parentheses define its inputs; the type before the name defines its return value.
68 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
69 System.assertEquals(null,Test assertion: fails the test when the expected behavior is absent.
70 PsQuoteCpqController.getPrimaryAmendmentQuote(opportunityRecord.Id));Completes the statement begun on this line or the preceding lines.
71 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(Assigns or configures the value on the left using the expression on the right.
72 opportunityRecord.Id, 'Needs Review', 'New Services'Part of the surrounding declaration or expression; read it with the adjacent lines.
73 );Opens or closes the expression begun on the surrounding lines.
74 try {Starts an operation whose exception can be handled below.
75 PsQuoteCpqController.createQuote(analysis.Id, Date.today());Completes the statement begun on this line or the preceding lines.
76 System.assert(false, 'An unconfirmed analysis cannot create a quote.');Test assertion: fails the test when the expected behavior is absent.
77 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
78 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
79 }Closes the current block or declaration.
80 update new PS_Quote_Analysis__c(DML write: saves changes to the specified Salesforce record or records.
81 Id = analysis.Id, Status__c = 'Confirmed',Creates or assigns a typed value for the steps that follow.
82 Reviewed_Proposal_JSON__c =Assigns or configures the value on the left using the expression on the right.
83 '{"quote_total":25,"lines":[{"category":"MILESTONE",' +Part of the surrounding declaration or expression; read it with the adjacent lines.
84 '"label":"Design","amount":25}]}'Part of the surrounding declaration or expression; read it with the adjacent lines.
85 );Opens or closes the expression begun on the surrounding lines.
86 try {Starts an operation whose exception can be handled below.
87 PsQuoteCpqController.createQuote(analysis.Id, null);Completes the statement begun on this line or the preceding lines.
88 System.assert(false, 'A start date is required.');Test assertion: fails the test when the expected behavior is absent.
89 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
90 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
91 }Closes the current block or declaration.
92 update new PS_Quote_Analysis__c(DML write: saves changes to the specified Salesforce record or records.
93 Id = analysis.Id, Quote_Creation_Status__c = 'Queued'Creates or assigns a typed value for the steps that follow.
94 );Opens or closes the expression begun on the surrounding lines.
95 try {Starts an operation whose exception can be handled below.
96 PsQuoteCpqController.createQuote(analysis.Id, Date.today());Completes the statement begun on this line or the preceding lines.
97 System.assert(false, 'A queued analysis cannot create a duplicate quote.');Test assertion: fails the test when the expected behavior is absent.
98 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
99 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
100 }Closes the current block or declaration.
101 System.assertEquals('Queued',Test assertion: fails the test when the expected behavior is absent.
102 PsQuoteCpqController.getQuoteCreation(analysis.Id).Quote_Creation_Status__c);Completes the statement begun on this line or the preceding lines.
103 }Closes the current block or declaration.
104 Spacing separates related steps.
105 @IsTestMarks the following class or method as test code.
106 static void validatesReviewedAmountsAndTotal() {Method declaration: Tests validates reviewed amounts and total. The parentheses define its inputs; the type before the name defines its return value.
107 String valid = '{"quote_total":30.00,"lines":[' +Creates or assigns a typed value for the steps that follow.
108 '{"category":"MILESTONE","label":"First","amount":10.00},' +Part of the surrounding declaration or expression; read it with the adjacent lines.
109 '{"category":"TIME_MATERIAL","label":"Second","amount":20.00}]}';Completes the statement begun on this line or the preceding lines.
110 System.assertEquals(2, PsQuoteCpqController.parseAndValidate(valid).size());Test assertion: fails the test when the expected behavior is absent.
111 Spacing separates related steps.
112 String invalid = '{"quote_total":31.00,"lines":[' +Creates or assigns a typed value for the steps that follow.
113 '{"category":"MILESTONE","label":"First","amount":10.00},' +Part of the surrounding declaration or expression; read it with the adjacent lines.
114 '{"category":"TIME_MATERIAL","label":"Second","amount":20.00}]}';Completes the statement begun on this line or the preceding lines.
115 Boolean rejected = false;Creates or assigns a typed value for the steps that follow.
116 try {Starts an operation whose exception can be handled below.
117 PsQuoteCpqController.parseAndValidate(invalid);Completes the statement begun on this line or the preceding lines.
118 } catch (Exception expected) {Opens a block; the indented lines below execute or belong together.
119 rejected = true;Assigns or configures the value on the left using the expression on the right.
120 }Closes the current block or declaration.
121 System.assert(rejected, 'Approved total must equal the lines.');Test assertion: fails the test when the expected behavior is absent.
122 }Closes the current block or declaration.
123 Spacing separates related steps.
124 @IsTestMarks the following class or method as test code.
125 static void rejectsMissingLinesBadCategoryAndTooManyDecimals() {Method declaration: Tests rejects missing lines bad category and too many decimals. The parentheses define its inputs; the type before the name defines its return value.
126 for (String jsonValue : new List<String>{Loop: repeats the following block for each matching item.
127 '{"quote_total":0,"lines":[]}',Continues the argument list or condition on the next line.
128 '{"quote_total":10,"lines":[{"category":"OTHER","label":"X","amount":10}]}',Continues the argument list or condition on the next line.
129 '{"quote_total":10.001,"lines":[{"category":"MILESTONE","label":"X","amount":10.001}]}'Part of the surrounding declaration or expression; read it with the adjacent lines.
130 }) {Opens a block; the indented lines below execute or belong together.
131 Boolean rejected = false;Creates or assigns a typed value for the steps that follow.
132 try {Starts an operation whose exception can be handled below.
133 PsQuoteCpqController.parseAndValidate(jsonValue);Completes the statement begun on this line or the preceding lines.
134 } catch (Exception expected) {Opens a block; the indented lines below execute or belong together.
135 rejected = true;Assigns or configures the value on the left using the expression on the right.
136 }Closes the current block or declaration.
137 System.assert(rejected, 'Invalid saved review must be rejected: ' + jsonValue);Test assertion: fails the test when the expected behavior is absent.
138 }Closes the current block or declaration.
139 }Closes the current block or declaration.
140 Spacing separates related steps.
141 @IsTestMarks the following class or method as test code.
142 static void queuesConfirmedNewServicesOnlyOnce() {Method declaration: Tests queues confirmed new services only once. The parentheses define its inputs; the type before the name defines its return value.
143 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
144 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(Assigns or configures the value on the left using the expression on the right.
145 opportunityRecord.Id, 'Confirmed', 'New Services'Part of the surrounding declaration or expression; read it with the adjacent lines.
146 );Opens or closes the expression begun on the surrounding lines.
147 update new PS_Quote_Analysis__c(DML write: saves changes to the specified Salesforce record or records.
148 Id=analysis.Id,Creates or assigns a typed value for the steps that follow.
149 Reviewed_Proposal_JSON__c =Assigns or configures the value on the left using the expression on the right.
150 '{"quote_total":25,"lines":[{"category":"MILESTONE",' +Part of the surrounding declaration or expression; read it with the adjacent lines.
151 '"label":"Design","amount":25}]}'Part of the surrounding declaration or expression; read it with the adjacent lines.
152 );Opens or closes the expression begun on the surrounding lines.
153 System.assertEquals(analysis.Id,Test assertion: fails the test when the expected behavior is absent.
154 PsQuoteCpqController.createQuote(analysis.Id, Date.today()));Completes the statement begun on this line or the preceding lines.
155 System.assertEquals('Queued',Test assertion: fails the test when the expected behavior is absent.
156 PsQuoteCpqController.getQuoteCreation(analysis.Id).Quote_Creation_Status__c);Completes the statement begun on this line or the preceding lines.
157 try {Starts an operation whose exception can be handled below.
158 PsQuoteCpqController.createQuote(analysis.Id, Date.today());Completes the statement begun on this line or the preceding lines.
159 System.assert(false, 'A second request must not be queued.');Test assertion: fails the test when the expected behavior is absent.
160 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
161 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
162 }Closes the current block or declaration.
163 }Closes the current block or declaration.
164 Spacing separates related steps.
165 @IsTestMarks the following class or method as test code.
166 static void unknownBackgroundStageRecordsFailure() {Method declaration: Tests unknown background stage records failure. The parentheses define its inputs; the type before the name defines its return value.
167 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
168 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(Assigns or configures the value on the left using the expression on the right.
169 opportunityRecord.Id, 'Confirmed', 'New Services'Part of the surrounding declaration or expression; read it with the adjacent lines.
170 );Opens or closes the expression begun on the surrounding lines.
171 Test.startTest();Starts the test’s measured execution section and resets governor limits.
172 System.enqueueJob(new PsQuoteCpqController.BuildJob(Queues a separate Apex transaction; the current request does not wait for all queued work to finish.
173 analysis.Id, Date.today(), 'UNKNOWN'Part of the surrounding declaration or expression; read it with the adjacent lines.
174 ));Completes the statement begun on this line or the preceding lines.
175 Test.stopTest();Ends that section and runs queued asynchronous test work.
176 PS_Quote_Analysis__c saved = PsQuoteCpqController.getQuoteCreation(analysis.Id);Creates or assigns a typed value for the steps that follow.
177 System.assertEquals('Failed', saved.Quote_Creation_Status__c);Test assertion: fails the test when the expected behavior is absent.
178 System.assert(saved.Quote_Creation_Error__c.contains('Unknown quote creation stage'));Test assertion: fails the test when the expected behavior is absent.
179 }Closes the current block or declaration.
180 Spacing separates related steps.
181 @IsTestMarks the following class or method as test code.
182 static void linesStageRecordsMissingServiceProduct() {Method declaration: Tests lines stage records missing service product. The parentheses define its inputs; the type before the name defines its return value.
183 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
184 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(Creates or assigns a typed value for the steps that follow.
185 SBQQ__Opportunity2__c = opportunityRecord.Id,Creates or assigns a typed value for the steps that follow.
186 SBQQ__Account__c = opportunityRecord.AccountId,Assigns or configures the value on the left using the expression on the right.
187 SBQQ__PricebookId__c = Test.getStandardPricebookId(),Assigns or configures the value on the left using the expression on the right.
188 SBQQ__StartDate__c = Date.today(),Creates or assigns a typed value for the steps that follow.
189 SBQQ__SubscriptionTerm__c = 12Assigns or configures the value on the left using the expression on the right.
190 );Opens or closes the expression begun on the surrounding lines.
191 insert quoteRecord;DML write: creates the specified Salesforce record or records.
192 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(Assigns or configures the value on the left using the expression on the right.
193 opportunityRecord.Id, 'Confirmed', 'New Services'Part of the surrounding declaration or expression; read it with the adjacent lines.
194 );Opens or closes the expression begun on the surrounding lines.
195 update new PS_Quote_Analysis__c(DML write: saves changes to the specified Salesforce record or records.
196 Id = analysis.Id,Creates or assigns a typed value for the steps that follow.
197 Created_Quote__c = quoteRecord.Id,Creates or assigns a typed value for the steps that follow.
198 Quote_Creation_Status__c = 'Adding Lines'Assigns or configures the value on the left using the expression on the right.
199 );Opens or closes the expression begun on the surrounding lines.
200 Spacing separates related steps.
201 Test.startTest();Starts the test’s measured execution section and resets governor limits.
202 System.enqueueJob(new PsQuoteCpqController.BuildJob(Queues a separate Apex transaction; the current request does not wait for all queued work to finish.
203 analysis.Id, Date.today(), 'LINES'Part of the surrounding declaration or expression; read it with the adjacent lines.
204 ));Completes the statement begun on this line or the preceding lines.
205 Test.stopTest();Ends that section and runs queued asynchronous test work.
206 Spacing separates related steps.
207 PS_Quote_Analysis__c saved = PsQuoteCpqController.getQuoteCreation(analysis.Id);Creates or assigns a typed value for the steps that follow.
208 System.assertEquals('Failed', saved.Quote_Creation_Status__c);Test assertion: fails the test when the expected behavior is absent.
209 System.assert(saved.Quote_Creation_Error__c.contains('service products'),Test assertion: fails the test when the expected behavior is absent.
210 'The job should explain that its required product is missing.');Completes the statement begun on this line or the preceding lines.
211 }Closes the current block or declaration.
212 Spacing separates related steps.
213 @IsTestMarks the following class or method as test code.
214 static void rejectsMalformedBreakdownAndUnexpectedLineTypes() {Method declaration: Tests rejects malformed breakdown and unexpected line types. The parentheses define its inputs; the type before the name defines its return value.
215 for (String invalidJson : new List<String>{Loop: repeats the following block for each matching item.
216 '{bad json',Continues the argument list or condition on the next line.
217 '{"quote_total":10,"lines":[10]}'Part of the surrounding declaration or expression; read it with the adjacent lines.
218 }) {Opens a block; the indented lines below execute or belong together.
219 Boolean rejected = false;Creates or assigns a typed value for the steps that follow.
220 try {Starts an operation whose exception can be handled below.
221 PsQuoteCpqController.parseAndValidate(invalidJson);Completes the statement begun on this line or the preceding lines.
222 } catch (Exception expected) {Opens a block; the indented lines below execute or belong together.
223 rejected = true;Assigns or configures the value on the left using the expression on the right.
224 }Closes the current block or declaration.
225 System.assert(rejected, 'Invalid breakdown should be rejected: ' + invalidJson);Test assertion: fails the test when the expected behavior is absent.
226 }Closes the current block or declaration.
227 }Closes the current block or declaration.
228 Spacing separates related steps.
229 @IsTestMarks the following class or method as test code.
230 static void identifiesExactlyOneAddedCpqLine() {Method declaration: Tests identifies exactly one added cpq line. The parentheses define its inputs; the type before the name defines its return value.
231 Map<String, Object> previous = new Map<String, Object>{Opens a block; the indented lines below execute or belong together.
232 'lineItems' => new List<Object>{Maps the value on the left to the value on the right.
233 new Map<String, Object>{'key' => 1}Maps the value on the left to the value on the right.
234 }Closes the current block or declaration.
235 };Closes the current block or declaration.
236 Set<String> previousKeys = PsQuoteCpqController.lineKeys(previous);Creates or assigns a typed value for the steps that follow.
237 System.assertEquals(new Set<String>{'1'}, previousKeys);Test assertion: fails the test when the expected behavior is absent.
238 System.assertEquals(0, PsQuoteCpqController.lineKeys(Test assertion: fails the test when the expected behavior is absent.
239 new Map<String, Object>()Part of the surrounding declaration or expression; read it with the adjacent lines.
240 ).size());Completes the statement begun on this line or the preceding lines.
241 Spacing separates related steps.
242 Map<String, Object> oneAdded = new Map<String, Object>{Opens a block; the indented lines below execute or belong together.
243 'lineItems' => new List<Object>{Maps the value on the left to the value on the right.
244 new Map<String, Object>{'key' => 1},Maps the value on the left to the value on the right.
245 new Map<String, Object>{'key' => 2}Maps the value on the left to the value on the right.
246 }Closes the current block or declaration.
247 };Closes the current block or declaration.
248 System.assertEquals('2', String.valueOf(Test assertion: fails the test when the expected behavior is absent.
249 PsQuoteCpqController.findAddedLine(oneAdded, previousKeys).get('key')Part of the surrounding declaration or expression; read it with the adjacent lines.
250 ));Completes the statement begun on this line or the preceding lines.
251 Spacing separates related steps.
252 for (Map<String, Object> model : new List<Map<String, Object>>{Loop: repeats the following block for each matching item.
253 previous,Continues the argument list or condition on the next line.
254 new Map<String, Object>(),Continues the argument list or condition on the next line.
255 new Map<String, Object>{Opens a block; the indented lines below execute or belong together.
256 'lineItems' => new List<Object>{Maps the value on the left to the value on the right.
257 new Map<String, Object>{'key' => 2},Maps the value on the left to the value on the right.
258 new Map<String, Object>{'key' => 3}Maps the value on the left to the value on the right.
259 }Closes the current block or declaration.
260 }Closes the current block or declaration.
261 }) {Opens a block; the indented lines below execute or belong together.
262 Boolean rejected = false;Creates or assigns a typed value for the steps that follow.
263 try {Starts an operation whose exception can be handled below.
264 PsQuoteCpqController.findAddedLine(model, previousKeys);Completes the statement begun on this line or the preceding lines.
265 } catch (Exception expected) {Opens a block; the indented lines below execute or belong together.
266 rejected = true;Assigns or configures the value on the left using the expression on the right.
267 }Closes the current block or declaration.
268 System.assert(rejected, 'CPQ must add exactly one new line.');Test assertion: fails the test when the expected behavior is absent.
269 }Closes the current block or declaration.
270 }Closes the current block or declaration.
271 Spacing separates related steps.
272 @IsTestMarks the following class or method as test code.
273 static void rejectsUnexpectedCpqResponseShapes() {Method declaration: Tests rejects unexpected cpq response shapes. The parentheses define its inputs; the type before the name defines its return value.
274 for (Object unexpected : new List<Object>{Loop: repeats the following block for each matching item.
275 null, new List<Object>{'not a map'}Closes the current block after this expression.
276 }) {Opens a block; the indented lines below execute or belong together.
277 Boolean rejected = false;Creates or assigns a typed value for the steps that follow.
278 try {Starts an operation whose exception can be handled below.
279 PsQuoteCpqController.asMap(unexpected);Completes the statement begun on this line or the preceding lines.
280 } catch (Exception expected) {Opens a block; the indented lines below execute or belong together.
281 rejected = true;Assigns or configures the value on the left using the expression on the right.
282 }Closes the current block or declaration.
283 System.assert(rejected, 'CPQ data must be a map.');Test assertion: fails the test when the expected behavior is absent.
284 }Closes the current block or declaration.
285 }Closes the current block or declaration.
286 Spacing separates related steps.
287 @IsTestMarks the following class or method as test code.
288 static void createsHeaderUsingAnIsolatedTestPricebook() {Method declaration: Tests creates header using an isolated test pricebook. The parentheses define its inputs; the type before the name defines its return value.
289 Id bookId = Test.getStandardPricebookId();Creates or assigns a typed value for the steps that follow.
290 update new Pricebook2(Id = bookId, IsActive = true);DML write: saves changes to the specified Salesforce record or records.
291 PsQuoteCpqController.testServicesPricebookId = bookId;Assigns or configures the value on the left using the expression on the right.
292 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
293 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(Assigns or configures the value on the left using the expression on the right.
294 opportunityRecord.Id, 'Confirmed', 'New Services'Part of the surrounding declaration or expression; read it with the adjacent lines.
295 );Opens or closes the expression begun on the surrounding lines.
296 Spacing separates related steps.
297 new PsQuoteCpqController.BuildJob(Part of the surrounding declaration or expression; read it with the adjacent lines.
298 analysis.Id, Date.today(), 'HEADER'Part of the surrounding declaration or expression; read it with the adjacent lines.
299 ).execute(null);Completes the statement begun on this line or the preceding lines.
300 Spacing separates related steps.
301 PS_Quote_Analysis__c saved = PsQuoteCpqController.getQuoteCreation(analysis.Id);Creates or assigns a typed value for the steps that follow.
302 System.assertEquals('Adding Lines', saved.Quote_Creation_Status__c,Test assertion: fails the test when the expected behavior is absent.
303 'The header job should create a quote and advance to lines.');Completes the statement begun on this line or the preceding lines.
304 System.assertNotEquals(null, saved.Created_Quote__c);Test assertion: fails the test when the expected behavior is absent.
305 System.assertEquals(bookId, [Test assertion: fails the test when the expected behavior is absent.
306 SELECT SBQQ__PricebookId__c FROM SBQQ__Quote__cSOQL field list: identifies data to read from Salesforce.
307 WHERE Id = :saved.Created_Quote__cSOQL filter: narrows the records returned by this query.
308 ].SBQQ__PricebookId__c);Completes the statement begun on this line or the preceding lines.
309 System.assertEquals(bookId, [Test assertion: fails the test when the expected behavior is absent.
310 SELECT Pricebook2Id FROM Opportunity WHERE Id = :opportunityRecord.IdSOQL field list: identifies data to read from Salesforce.
311 ].Pricebook2Id);Completes the statement begun on this line or the preceding lines.
312 }Closes the current block or declaration.
313 Spacing separates related steps.
314 @IsTestMarks the following class or method as test code.
315 static void headerRejectsOpportunityWithAnotherPricebook() {Method declaration: Tests header rejects opportunity with another pricebook. The parentheses define its inputs; the type before the name defines its return value.
316 Id servicesBookId = Test.getStandardPricebookId();Creates or assigns a typed value for the steps that follow.
317 update new Pricebook2(Id = servicesBookId, IsActive = true);DML write: saves changes to the specified Salesforce record or records.
318 PsQuoteCpqController.testServicesPricebookId = servicesBookId;Assigns or configures the value on the left using the expression on the right.
319 Pricebook2 otherBook = new Pricebook2(Creates or assigns a typed value for the steps that follow.
320 Name = 'Other test price book', IsActive = trueAssigns or configures the value on the left using the expression on the right.
321 );Opens or closes the expression begun on the surrounding lines.
322 insert otherBook;DML write: creates the specified Salesforce record or records.
323 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
324 update new Opportunity(DML write: saves changes to the specified Salesforce record or records.
325 Id = opportunityRecord.Id, Pricebook2Id = otherBook.IdCreates or assigns a typed value for the steps that follow.
326 );Opens or closes the expression begun on the surrounding lines.
327 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(Assigns or configures the value on the left using the expression on the right.
328 opportunityRecord.Id, 'Confirmed', 'New Services'Part of the surrounding declaration or expression; read it with the adjacent lines.
329 );Opens or closes the expression begun on the surrounding lines.
330 Spacing separates related steps.
331 new PsQuoteCpqController.BuildJob(Part of the surrounding declaration or expression; read it with the adjacent lines.
332 analysis.Id, Date.today(), 'HEADER'Part of the surrounding declaration or expression; read it with the adjacent lines.
333 ).execute(null);Completes the statement begun on this line or the preceding lines.
334 Spacing separates related steps.
335 PS_Quote_Analysis__c saved = PsQuoteCpqController.getQuoteCreation(analysis.Id);Creates or assigns a typed value for the steps that follow.
336 System.assertEquals('Failed', saved.Quote_Creation_Status__c);Test assertion: fails the test when the expected behavior is absent.
337 System.assert(saved.Quote_Creation_Error__c.contains('differs from'),Test assertion: fails the test when the expected behavior is absent.
338 'The job should reject a different Opportunity price book.');Completes the statement begun on this line or the preceding lines.
339 }Closes the current block or declaration.
340 Spacing separates related steps.
341 @IsTestMarks the following class or method as test code.
342 static void rejectsChangeOrderInNewQuotePathAndMissingAmendmentContract() {Method declaration: Tests rejects change order in new quote path and missing amendment contract. The parentheses define its inputs; the type before the name defines its return value.
343 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
344 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(Assigns or configures the value on the left using the expression on the right.
345 opportunityRecord.Id, 'Confirmed', 'Change Order'Part of the surrounding declaration or expression; read it with the adjacent lines.
346 );Opens or closes the expression begun on the surrounding lines.
347 Boolean newQuoteRejected = false;Creates or assigns a typed value for the steps that follow.
348 try {Starts an operation whose exception can be handled below.
349 PsQuoteCpqController.createQuote(analysis.Id, Date.today());Completes the statement begun on this line or the preceding lines.
350 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
351 newQuoteRejected = true;Assigns or configures the value on the left using the expression on the right.
352 }Closes the current block or declaration.
353 System.assert(newQuoteRejected, 'Change orders use native amendment quotes.');Test assertion: fails the test when the expected behavior is absent.
354 Spacing separates related steps.
355 Boolean amendmentRejected = false;Creates or assigns a typed value for the steps that follow.
356 try {Starts an operation whose exception can be handled below.
357 PsQuoteCpqController.useNativeAmendmentQuote(analysis.Id);Completes the statement begun on this line or the preceding lines.
358 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
359 amendmentRejected = true;Assigns or configures the value on the left using the expression on the right.
360 }Closes the current block or declaration.
361 System.assert(amendmentRejected, 'An amended contract is required.');Test assertion: fails the test when the expected behavior is absent.
362 }Closes the current block or declaration.
363 Spacing separates related steps.
364 @IsTestMarks the following class or method as test code.
365 static void rejectsMissingTotalAndNonNumericAmounts() {Method declaration: Tests rejects missing total and non numeric amounts. The parentheses define its inputs; the type before the name defines its return value.
366 for (String invalidJson : new List<String>{Loop: repeats the following block for each matching item.
367 '{"lines":[{"category":"MILESTONE","label":"Work","amount":25}]}',Continues the argument list or condition on the next line.
368 '{"quote_total":25,"lines":[{"category":"MILESTONE","label":"Work","amount":"abc"}]}'Part of the surrounding declaration or expression; read it with the adjacent lines.
369 }) {Opens a block; the indented lines below execute or belong together.
370 Boolean rejected = false;Creates or assigns a typed value for the steps that follow.
371 try {Starts an operation whose exception can be handled below.
372 PsQuoteCpqController.parseAndValidate(invalidJson);Completes the statement begun on this line or the preceding lines.
373 } catch (Exception expected) {Opens a block; the indented lines below execute or belong together.
374 rejected = true;Assigns or configures the value on the left using the expression on the right.
375 }Closes the current block or declaration.
376 System.assert(rejected, 'The amount and total must be numeric.');Test assertion: fails the test when the expected behavior is absent.
377 }Closes the current block or declaration.
378 }Closes the current block or declaration.
379 Spacing separates related steps.
380 @IsTestMarks the following class or method as test code.
381 static void amendmentRequiresPrimaryQuoteAndMatchingStartDate() {Method declaration: Tests amendment requires primary quote and matching start date. The parentheses define its inputs; the type before the name defines its return value.
382 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
383 List<ContractStatus> draftStatuses = [Creates or assigns a typed value for the steps that follow.
384 SELECT ApiName FROM ContractStatus WHERE StatusCode = 'Draft'SOQL field list: identifies data to read from Salesforce.
385 ORDER BY IsDefault DESC LIMIT 1Sorts the records returned by this query.
386 ];Completes the statement begun on this line or the preceding lines.
387 System.assert(!draftStatuses.isEmpty(), 'A Draft contract status is required.');Test assertion: fails the test when the expected behavior is absent.
388 Contract contractRecord = new Contract(Creates or assigns a typed value for the steps that follow.
389 Name = 'Amendment test contract',Assigns or configures the value on the left using the expression on the right.
390 AccountId = opportunityRecord.AccountId,Assigns or configures the value on the left using the expression on the right.
391 Status = draftStatuses[0].ApiName,Assigns or configures the value on the left using the expression on the right.
392 StartDate = Date.today(), ContractTerm = 12Creates or assigns a typed value for the steps that follow.
393 );Opens or closes the expression begun on the surrounding lines.
394 insert contractRecord;DML write: creates the specified Salesforce record or records.
395 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(Assigns or configures the value on the left using the expression on the right.
396 opportunityRecord.Id, 'Confirmed', 'Change Order'Part of the surrounding declaration or expression; read it with the adjacent lines.
397 );Opens or closes the expression begun on the surrounding lines.
398 update new PS_Quote_Analysis__c(DML write: saves changes to the specified Salesforce record or records.
399 Id = analysis.Id, Amended_Contract__c = contractRecord.Id,Creates or assigns a typed value for the steps that follow.
400 Effective_Date__c = Date.today()Creates or assigns a typed value for the steps that follow.
401 );Opens or closes the expression begun on the surrounding lines.
402 Boolean missingQuoteRejected = false;Creates or assigns a typed value for the steps that follow.
403 try {Starts an operation whose exception can be handled below.
404 PsQuoteCpqController.useNativeAmendmentQuote(analysis.Id);Completes the statement begun on this line or the preceding lines.
405 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
406 missingQuoteRejected = true;Assigns or configures the value on the left using the expression on the right.
407 }Closes the current block or declaration.
408 System.assert(missingQuoteRejected, 'A primary amendment quote is required.');Test assertion: fails the test when the expected behavior is absent.
409 Spacing separates related steps.
410 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(Creates or assigns a typed value for the steps that follow.
411 SBQQ__Opportunity2__c = opportunityRecord.Id,Creates or assigns a typed value for the steps that follow.
412 SBQQ__Account__c = opportunityRecord.AccountId,Assigns or configures the value on the left using the expression on the right.
413 SBQQ__MasterContract__c = contractRecord.Id,Creates or assigns a typed value for the steps that follow.
414 SBQQ__Type__c = 'Amendment', SBQQ__Primary__c = true,Assigns or configures the value on the left using the expression on the right.
415 SBQQ__StartDate__c = Date.today().addDays(1)Creates or assigns a typed value for the steps that follow.
416 );Opens or closes the expression begun on the surrounding lines.
417 insert quoteRecord;DML write: creates the specified Salesforce record or records.
418 Boolean wrongDateRejected = false;Creates or assigns a typed value for the steps that follow.
419 try {Starts an operation whose exception can be handled below.
420 PsQuoteCpqController.useNativeAmendmentQuote(analysis.Id);Completes the statement begun on this line or the preceding lines.
421 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
422 wrongDateRejected = true;Assigns or configures the value on the left using the expression on the right.
423 }Closes the current block or declaration.
424 System.assert(wrongDateRejected, 'The quote start date must match the analysis.');Test assertion: fails the test when the expected behavior is absent.
425 }Closes the current block or declaration.
426 Spacing separates related steps.
427 @IsTestMarks the following class or method as test code.
428 static void linesStageRequiresPricebookEntry() {Method declaration: Tests lines stage requires pricebook entry. The parentheses define its inputs; the type before the name defines its return value.
429 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
430 String currencyCode = [Creates or assigns a typed value for the steps that follow.
431 SELECT CurrencyIsoCode FROM Opportunity WHERE Id = :opportunityRecord.IdSOQL field list: identifies data to read from Salesforce.
432 ].CurrencyIsoCode;Completes the statement begun on this line or the preceding lines.
433 Product2 serviceProduct = new Product2(Creates or assigns a typed value for the steps that follow.
434 Name = 'Test milestone service', ProductCode = '885',Assigns or configures the value on the left using the expression on the right.
435 IsActive = true, CurrencyIsoCode = currencyCodeAssigns or configures the value on the left using the expression on the right.
436 );Opens or closes the expression begun on the surrounding lines.
437 insert serviceProduct;DML write: creates the specified Salesforce record or records.
438 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(Creates or assigns a typed value for the steps that follow.
439 SBQQ__Opportunity2__c = opportunityRecord.Id,Creates or assigns a typed value for the steps that follow.
440 SBQQ__Account__c = opportunityRecord.AccountId,Assigns or configures the value on the left using the expression on the right.
441 SBQQ__PricebookId__c = Test.getStandardPricebookId(),Assigns or configures the value on the left using the expression on the right.
442 SBQQ__StartDate__c = Date.today(),Creates or assigns a typed value for the steps that follow.
443 SBQQ__SubscriptionTerm__c = 12Assigns or configures the value on the left using the expression on the right.
444 );Opens or closes the expression begun on the surrounding lines.
445 insert quoteRecord;DML write: creates the specified Salesforce record or records.
446 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(Assigns or configures the value on the left using the expression on the right.
447 opportunityRecord.Id, 'Confirmed', 'New Services'Part of the surrounding declaration or expression; read it with the adjacent lines.
448 );Opens or closes the expression begun on the surrounding lines.
449 update new PS_Quote_Analysis__c(DML write: saves changes to the specified Salesforce record or records.
450 Id = analysis.Id, Created_Quote__c = quoteRecord.Id,Creates or assigns a typed value for the steps that follow.
451 Quote_Creation_Status__c = 'Adding Lines'Assigns or configures the value on the left using the expression on the right.
452 );Opens or closes the expression begun on the surrounding lines.
453 Spacing separates related steps.
454 new PsQuoteCpqController.BuildJob(Part of the surrounding declaration or expression; read it with the adjacent lines.
455 analysis.Id, Date.today(), 'LINES'Part of the surrounding declaration or expression; read it with the adjacent lines.
456 ).execute(null);Completes the statement begun on this line or the preceding lines.
457 Spacing separates related steps.
458 PS_Quote_Analysis__c saved = PsQuoteCpqController.getQuoteCreation(analysis.Id);Creates or assigns a typed value for the steps that follow.
459 System.assertEquals('Failed', saved.Quote_Creation_Status__c);Test assertion: fails the test when the expected behavior is absent.
460 System.assert(saved.Quote_Creation_Error__c.contains('price book entries'),Test assertion: fails the test when the expected behavior is absent.
461 'The job should identify the missing price book entry.');Completes the statement begun on this line or the preceding lines.
462 }Closes the current block or declaration.
463 Spacing separates related steps.
464 @IsTestMarks the following class or method as test code.
465 static void getQuoteCreationRejectsMissingId() {Method declaration: Tests get quote creation rejects missing id. The parentheses define its inputs; the type before the name defines its return value.
466 Boolean rejected = false;Creates or assigns a typed value for the steps that follow.
467 try {Starts an operation whose exception can be handled below.
468 PsQuoteCpqController.getQuoteCreation(null);Completes the statement begun on this line or the preceding lines.
469 } catch (AuraHandledException expected) {Opens a block; the indented lines below execute or belong together.
470 rejected = true;Assigns or configures the value on the left using the expression on the right.
471 }Closes the current block or declaration.
472 System.assert(rejected, 'An analysis ID is required.');Test assertion: fails the test when the expected behavior is absent.
473 }Closes the current block or declaration.
474}Closes the current block or declaration.
View complete source code
1@IsTest
2private class PsQuoteCpqControllerTest {
3 @IsTest
4 static void findsPrimaryAmendmentAndRejectsMissingNativeLines() {
5 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
6 List<ContractStatus> draftStatuses = [
7 SELECT ApiName FROM ContractStatus
8 WHERE StatusCode = 'Draft'
9 ORDER BY IsDefault DESC LIMIT 1
10 ];
11 System.assert(!draftStatuses.isEmpty(),
12 'This test needs a Contract status in the Draft category.');
13 Contract contractRecord = new Contract(
14 Name = 'Amended services contract',
15 AccountId = opportunityRecord.AccountId,
16 Status = draftStatuses[0].ApiName,
17 StartDate = Date.today().addMonths(-1), ContractTerm = 12
18 );
19 insert contractRecord;
20 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(
21 SBQQ__Opportunity2__c = opportunityRecord.Id,
22 SBQQ__Account__c = opportunityRecord.AccountId,
23 SBQQ__MasterContract__c = contractRecord.Id,
24 SBQQ__Type__c = 'Amendment', SBQQ__Primary__c = true,
25 SBQQ__StartDate__c = Date.today()
26 );
27 insert quoteRecord;
28 PsQuoteCpqController.PrimaryAmendmentQuote found =
29 PsQuoteCpqController.getPrimaryAmendmentQuote(opportunityRecord.Id);
30 System.assertNotEquals(null, found);
31 System.assertEquals(quoteRecord.Id, found.quoteId);
32 System.assertEquals(contractRecord.Id, found.contractId);
33
34 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(
35 opportunityRecord.Id, 'Confirmed', 'Change Order'
36 );
37 update new PS_Quote_Analysis__c(
38 Id = analysis.Id,
39 Amended_Contract__c = contractRecord.Id,
40 Effective_Date__c = Date.today()
41 );
42 try {
43 PsQuoteCpqController.useNativeAmendmentQuote(analysis.Id);
44 System.assert(false, 'The quote has no existing contract lines.');
45 } catch (AuraHandledException expected) {
46 System.assertNotEquals(null, expected);
47 }
48 }
49 @IsTest
50 static void rejectsMissingAnalysisAndQuoteIds() {
51 try {
52 PsQuoteCpqController.createQuote(null, Date.today());
53 System.assert(false, 'Missing analysis must stop quote creation.');
54 } catch (AuraHandledException expected) {
55 System.assertNotEquals(null, expected);
56 }
57 try {
58 PsQuoteCpqController.useNativeAmendmentQuote(null);
59 System.assert(false, 'Missing IDs must stop amendment use.');
60 } catch (AuraHandledException expected) {
61 System.assertNotEquals(null, expected);
62 }
63 System.assertEquals(null, PsQuoteCpqController.getPrimaryAmendmentQuote(null));
64 }
65
66 @IsTest
67 static void requiresConfirmedBreakdownAndStartDate() {
68 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
69 System.assertEquals(null,
70 PsQuoteCpqController.getPrimaryAmendmentQuote(opportunityRecord.Id));
71 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(
72 opportunityRecord.Id, 'Needs Review', 'New Services'
73 );
74 try {
75 PsQuoteCpqController.createQuote(analysis.Id, Date.today());
76 System.assert(false, 'An unconfirmed analysis cannot create a quote.');
77 } catch (AuraHandledException expected) {
78 System.assertNotEquals(null, expected);
79 }
80 update new PS_Quote_Analysis__c(
81 Id = analysis.Id, Status__c = 'Confirmed',
82 Reviewed_Proposal_JSON__c =
83 '{"quote_total":25,"lines":[{"category":"MILESTONE",' +
84 '"label":"Design","amount":25}]}'
85 );
86 try {
87 PsQuoteCpqController.createQuote(analysis.Id, null);
88 System.assert(false, 'A start date is required.');
89 } catch (AuraHandledException expected) {
90 System.assertNotEquals(null, expected);
91 }
92 update new PS_Quote_Analysis__c(
93 Id = analysis.Id, Quote_Creation_Status__c = 'Queued'
94 );
95 try {
96 PsQuoteCpqController.createQuote(analysis.Id, Date.today());
97 System.assert(false, 'A queued analysis cannot create a duplicate quote.');
98 } catch (AuraHandledException expected) {
99 System.assertNotEquals(null, expected);
100 }
101 System.assertEquals('Queued',
102 PsQuoteCpqController.getQuoteCreation(analysis.Id).Quote_Creation_Status__c);
103 }
104
105 @IsTest
106 static void validatesReviewedAmountsAndTotal() {
107 String valid = '{"quote_total":30.00,"lines":[' +
108 '{"category":"MILESTONE","label":"First","amount":10.00},' +
109 '{"category":"TIME_MATERIAL","label":"Second","amount":20.00}]}';
110 System.assertEquals(2, PsQuoteCpqController.parseAndValidate(valid).size());
111
112 String invalid = '{"quote_total":31.00,"lines":[' +
113 '{"category":"MILESTONE","label":"First","amount":10.00},' +
114 '{"category":"TIME_MATERIAL","label":"Second","amount":20.00}]}';
115 Boolean rejected = false;
116 try {
117 PsQuoteCpqController.parseAndValidate(invalid);
118 } catch (Exception expected) {
119 rejected = true;
120 }
121 System.assert(rejected, 'Approved total must equal the lines.');
122 }
123
124 @IsTest
125 static void rejectsMissingLinesBadCategoryAndTooManyDecimals() {
126 for (String jsonValue : new List<String>{
127 '{"quote_total":0,"lines":[]}',
128 '{"quote_total":10,"lines":[{"category":"OTHER","label":"X","amount":10}]}',
129 '{"quote_total":10.001,"lines":[{"category":"MILESTONE","label":"X","amount":10.001}]}'
130 }) {
131 Boolean rejected = false;
132 try {
133 PsQuoteCpqController.parseAndValidate(jsonValue);
134 } catch (Exception expected) {
135 rejected = true;
136 }
137 System.assert(rejected, 'Invalid saved review must be rejected: ' + jsonValue);
138 }
139 }
140
141 @IsTest
142 static void queuesConfirmedNewServicesOnlyOnce() {
143 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
144 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(
145 opportunityRecord.Id, 'Confirmed', 'New Services'
146 );
147 update new PS_Quote_Analysis__c(
148 Id=analysis.Id,
149 Reviewed_Proposal_JSON__c =
150 '{"quote_total":25,"lines":[{"category":"MILESTONE",' +
151 '"label":"Design","amount":25}]}'
152 );
153 System.assertEquals(analysis.Id,
154 PsQuoteCpqController.createQuote(analysis.Id, Date.today()));
155 System.assertEquals('Queued',
156 PsQuoteCpqController.getQuoteCreation(analysis.Id).Quote_Creation_Status__c);
157 try {
158 PsQuoteCpqController.createQuote(analysis.Id, Date.today());
159 System.assert(false, 'A second request must not be queued.');
160 } catch (AuraHandledException expected) {
161 System.assertNotEquals(null, expected);
162 }
163 }
164
165 @IsTest
166 static void unknownBackgroundStageRecordsFailure() {
167 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
168 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(
169 opportunityRecord.Id, 'Confirmed', 'New Services'
170 );
171 Test.startTest();
172 System.enqueueJob(new PsQuoteCpqController.BuildJob(
173 analysis.Id, Date.today(), 'UNKNOWN'
174 ));
175 Test.stopTest();
176 PS_Quote_Analysis__c saved = PsQuoteCpqController.getQuoteCreation(analysis.Id);
177 System.assertEquals('Failed', saved.Quote_Creation_Status__c);
178 System.assert(saved.Quote_Creation_Error__c.contains('Unknown quote creation stage'));
179 }
180
181 @IsTest
182 static void linesStageRecordsMissingServiceProduct() {
183 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
184 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(
185 SBQQ__Opportunity2__c = opportunityRecord.Id,
186 SBQQ__Account__c = opportunityRecord.AccountId,
187 SBQQ__PricebookId__c = Test.getStandardPricebookId(),
188 SBQQ__StartDate__c = Date.today(),
189 SBQQ__SubscriptionTerm__c = 12
190 );
191 insert quoteRecord;
192 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(
193 opportunityRecord.Id, 'Confirmed', 'New Services'
194 );
195 update new PS_Quote_Analysis__c(
196 Id = analysis.Id,
197 Created_Quote__c = quoteRecord.Id,
198 Quote_Creation_Status__c = 'Adding Lines'
199 );
200
201 Test.startTest();
202 System.enqueueJob(new PsQuoteCpqController.BuildJob(
203 analysis.Id, Date.today(), 'LINES'
204 ));
205 Test.stopTest();
206
207 PS_Quote_Analysis__c saved = PsQuoteCpqController.getQuoteCreation(analysis.Id);
208 System.assertEquals('Failed', saved.Quote_Creation_Status__c);
209 System.assert(saved.Quote_Creation_Error__c.contains('service products'),
210 'The job should explain that its required product is missing.');
211 }
212
213 @IsTest
214 static void rejectsMalformedBreakdownAndUnexpectedLineTypes() {
215 for (String invalidJson : new List<String>{
216 '{bad json',
217 '{"quote_total":10,"lines":[10]}'
218 }) {
219 Boolean rejected = false;
220 try {
221 PsQuoteCpqController.parseAndValidate(invalidJson);
222 } catch (Exception expected) {
223 rejected = true;
224 }
225 System.assert(rejected, 'Invalid breakdown should be rejected: ' + invalidJson);
226 }
227 }
228
229 @IsTest
230 static void identifiesExactlyOneAddedCpqLine() {
231 Map<String, Object> previous = new Map<String, Object>{
232 'lineItems' => new List<Object>{
233 new Map<String, Object>{'key' => 1}
234 }
235 };
236 Set<String> previousKeys = PsQuoteCpqController.lineKeys(previous);
237 System.assertEquals(new Set<String>{'1'}, previousKeys);
238 System.assertEquals(0, PsQuoteCpqController.lineKeys(
239 new Map<String, Object>()
240 ).size());
241
242 Map<String, Object> oneAdded = new Map<String, Object>{
243 'lineItems' => new List<Object>{
244 new Map<String, Object>{'key' => 1},
245 new Map<String, Object>{'key' => 2}
246 }
247 };
248 System.assertEquals('2', String.valueOf(
249 PsQuoteCpqController.findAddedLine(oneAdded, previousKeys).get('key')
250 ));
251
252 for (Map<String, Object> model : new List<Map<String, Object>>{
253 previous,
254 new Map<String, Object>(),
255 new Map<String, Object>{
256 'lineItems' => new List<Object>{
257 new Map<String, Object>{'key' => 2},
258 new Map<String, Object>{'key' => 3}
259 }
260 }
261 }) {
262 Boolean rejected = false;
263 try {
264 PsQuoteCpqController.findAddedLine(model, previousKeys);
265 } catch (Exception expected) {
266 rejected = true;
267 }
268 System.assert(rejected, 'CPQ must add exactly one new line.');
269 }
270 }
271
272 @IsTest
273 static void rejectsUnexpectedCpqResponseShapes() {
274 for (Object unexpected : new List<Object>{
275 null, new List<Object>{'not a map'}
276 }) {
277 Boolean rejected = false;
278 try {
279 PsQuoteCpqController.asMap(unexpected);
280 } catch (Exception expected) {
281 rejected = true;
282 }
283 System.assert(rejected, 'CPQ data must be a map.');
284 }
285 }
286
287 @IsTest
288 static void createsHeaderUsingAnIsolatedTestPricebook() {
289 Id bookId = Test.getStandardPricebookId();
290 update new Pricebook2(Id = bookId, IsActive = true);
291 PsQuoteCpqController.testServicesPricebookId = bookId;
292 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
293 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(
294 opportunityRecord.Id, 'Confirmed', 'New Services'
295 );
296
297 new PsQuoteCpqController.BuildJob(
298 analysis.Id, Date.today(), 'HEADER'
299 ).execute(null);
300
301 PS_Quote_Analysis__c saved = PsQuoteCpqController.getQuoteCreation(analysis.Id);
302 System.assertEquals('Adding Lines', saved.Quote_Creation_Status__c,
303 'The header job should create a quote and advance to lines.');
304 System.assertNotEquals(null, saved.Created_Quote__c);
305 System.assertEquals(bookId, [
306 SELECT SBQQ__PricebookId__c FROM SBQQ__Quote__c
307 WHERE Id = :saved.Created_Quote__c
308 ].SBQQ__PricebookId__c);
309 System.assertEquals(bookId, [
310 SELECT Pricebook2Id FROM Opportunity WHERE Id = :opportunityRecord.Id
311 ].Pricebook2Id);
312 }
313
314 @IsTest
315 static void headerRejectsOpportunityWithAnotherPricebook() {
316 Id servicesBookId = Test.getStandardPricebookId();
317 update new Pricebook2(Id = servicesBookId, IsActive = true);
318 PsQuoteCpqController.testServicesPricebookId = servicesBookId;
319 Pricebook2 otherBook = new Pricebook2(
320 Name = 'Other test price book', IsActive = true
321 );
322 insert otherBook;
323 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
324 update new Opportunity(
325 Id = opportunityRecord.Id, Pricebook2Id = otherBook.Id
326 );
327 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(
328 opportunityRecord.Id, 'Confirmed', 'New Services'
329 );
330
331 new PsQuoteCpqController.BuildJob(
332 analysis.Id, Date.today(), 'HEADER'
333 ).execute(null);
334
335 PS_Quote_Analysis__c saved = PsQuoteCpqController.getQuoteCreation(analysis.Id);
336 System.assertEquals('Failed', saved.Quote_Creation_Status__c);
337 System.assert(saved.Quote_Creation_Error__c.contains('differs from'),
338 'The job should reject a different Opportunity price book.');
339 }
340
341 @IsTest
342 static void rejectsChangeOrderInNewQuotePathAndMissingAmendmentContract() {
343 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
344 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(
345 opportunityRecord.Id, 'Confirmed', 'Change Order'
346 );
347 Boolean newQuoteRejected = false;
348 try {
349 PsQuoteCpqController.createQuote(analysis.Id, Date.today());
350 } catch (AuraHandledException expected) {
351 newQuoteRejected = true;
352 }
353 System.assert(newQuoteRejected, 'Change orders use native amendment quotes.');
354
355 Boolean amendmentRejected = false;
356 try {
357 PsQuoteCpqController.useNativeAmendmentQuote(analysis.Id);
358 } catch (AuraHandledException expected) {
359 amendmentRejected = true;
360 }
361 System.assert(amendmentRejected, 'An amended contract is required.');
362 }
363
364 @IsTest
365 static void rejectsMissingTotalAndNonNumericAmounts() {
366 for (String invalidJson : new List<String>{
367 '{"lines":[{"category":"MILESTONE","label":"Work","amount":25}]}',
368 '{"quote_total":25,"lines":[{"category":"MILESTONE","label":"Work","amount":"abc"}]}'
369 }) {
370 Boolean rejected = false;
371 try {
372 PsQuoteCpqController.parseAndValidate(invalidJson);
373 } catch (Exception expected) {
374 rejected = true;
375 }
376 System.assert(rejected, 'The amount and total must be numeric.');
377 }
378 }
379
380 @IsTest
381 static void amendmentRequiresPrimaryQuoteAndMatchingStartDate() {
382 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
383 List<ContractStatus> draftStatuses = [
384 SELECT ApiName FROM ContractStatus WHERE StatusCode = 'Draft'
385 ORDER BY IsDefault DESC LIMIT 1
386 ];
387 System.assert(!draftStatuses.isEmpty(), 'A Draft contract status is required.');
388 Contract contractRecord = new Contract(
389 Name = 'Amendment test contract',
390 AccountId = opportunityRecord.AccountId,
391 Status = draftStatuses[0].ApiName,
392 StartDate = Date.today(), ContractTerm = 12
393 );
394 insert contractRecord;
395 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(
396 opportunityRecord.Id, 'Confirmed', 'Change Order'
397 );
398 update new PS_Quote_Analysis__c(
399 Id = analysis.Id, Amended_Contract__c = contractRecord.Id,
400 Effective_Date__c = Date.today()
401 );
402 Boolean missingQuoteRejected = false;
403 try {
404 PsQuoteCpqController.useNativeAmendmentQuote(analysis.Id);
405 } catch (AuraHandledException expected) {
406 missingQuoteRejected = true;
407 }
408 System.assert(missingQuoteRejected, 'A primary amendment quote is required.');
409
410 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(
411 SBQQ__Opportunity2__c = opportunityRecord.Id,
412 SBQQ__Account__c = opportunityRecord.AccountId,
413 SBQQ__MasterContract__c = contractRecord.Id,
414 SBQQ__Type__c = 'Amendment', SBQQ__Primary__c = true,
415 SBQQ__StartDate__c = Date.today().addDays(1)
416 );
417 insert quoteRecord;
418 Boolean wrongDateRejected = false;
419 try {
420 PsQuoteCpqController.useNativeAmendmentQuote(analysis.Id);
421 } catch (AuraHandledException expected) {
422 wrongDateRejected = true;
423 }
424 System.assert(wrongDateRejected, 'The quote start date must match the analysis.');
425 }
426
427 @IsTest
428 static void linesStageRequiresPricebookEntry() {
429 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
430 String currencyCode = [
431 SELECT CurrencyIsoCode FROM Opportunity WHERE Id = :opportunityRecord.Id
432 ].CurrencyIsoCode;
433 Product2 serviceProduct = new Product2(
434 Name = 'Test milestone service', ProductCode = '885',
435 IsActive = true, CurrencyIsoCode = currencyCode
436 );
437 insert serviceProduct;
438 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(
439 SBQQ__Opportunity2__c = opportunityRecord.Id,
440 SBQQ__Account__c = opportunityRecord.AccountId,
441 SBQQ__PricebookId__c = Test.getStandardPricebookId(),
442 SBQQ__StartDate__c = Date.today(),
443 SBQQ__SubscriptionTerm__c = 12
444 );
445 insert quoteRecord;
446 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(
447 opportunityRecord.Id, 'Confirmed', 'New Services'
448 );
449 update new PS_Quote_Analysis__c(
450 Id = analysis.Id, Created_Quote__c = quoteRecord.Id,
451 Quote_Creation_Status__c = 'Adding Lines'
452 );
453
454 new PsQuoteCpqController.BuildJob(
455 analysis.Id, Date.today(), 'LINES'
456 ).execute(null);
457
458 PS_Quote_Analysis__c saved = PsQuoteCpqController.getQuoteCreation(analysis.Id);
459 System.assertEquals('Failed', saved.Quote_Creation_Status__c);
460 System.assert(saved.Quote_Creation_Error__c.contains('price book entries'),
461 'The job should identify the missing price book entry.');
462 }
463
464 @IsTest
465 static void getQuoteCreationRejectsMissingId() {
466 Boolean rejected = false;
467 try {
468 PsQuoteCpqController.getQuoteCreation(null);
469 } catch (AuraHandledException expected) {
470 rejected = true;
471 }
472 System.assert(rejected, 'An analysis ID is required.');
473 }
474}
test · 101 lines

PsQuoteCpqCalculateCallbackTest

Tests CPQ total comparison, optional and upgraded line handling, and primary quote behavior.

This is the newer local test source. Recent additions still need a Salesforce test run.

Review and understand complete source code

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@IsTestMarks the following class or method as test code.
2private class PsQuoteCpqCalculateCallbackTest {Declares a class or trigger. The braces contain its members and behavior.
3 @IsTestMarks the following class or method as test code.
4 static void callbackRecordsMismatchFromRealCpqQuoteModel() {Method declaration: Tests callback records mismatch from real cpq quote model. The parentheses define its inputs; the type before the name defines its return value.
5 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
6 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(Creates or assigns a typed value for the steps that follow.
7 SBQQ__Opportunity2__c = opportunityRecord.Id,Creates or assigns a typed value for the steps that follow.
8 SBQQ__Account__c = opportunityRecord.AccountId,Assigns or configures the value on the left using the expression on the right.
9 SBQQ__PricebookId__c = Test.getStandardPricebookId(),Assigns or configures the value on the left using the expression on the right.
10 SBQQ__StartDate__c = Date.today(),Creates or assigns a typed value for the steps that follow.
11 SBQQ__SubscriptionTerm__c = 12Assigns or configures the value on the left using the expression on the right.
12 );Opens or closes the expression begun on the surrounding lines.
13 insert quoteRecord;DML write: creates the specified Salesforce record or records.
14 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(Assigns or configures the value on the left using the expression on the right.
15 opportunityRecord.Id, 'Confirmed', 'New Services'Part of the surrounding declaration or expression; read it with the adjacent lines.
16 );Opens or closes the expression begun on the surrounding lines.
17 update new PS_Quote_Analysis__c(DML write: saves changes to the specified Salesforce record or records.
18 Id = analysis.Id, Created_Quote__c = quoteRecord.Id,Creates or assigns a typed value for the steps that follow.
19 Quote_Creation_Status__c = 'Calculating'Assigns or configures the value on the left using the expression on the right.
20 );Opens or closes the expression begun on the surrounding lines.
21 String quoteModel = SBQQ.ServiceRouter.read(Calls the Salesforce CPQ managed package API for the named operation.
22 'SBQQ.QuoteAPI.QuoteReader', String.valueOf(quoteRecord.Id)Part of the surrounding declaration or expression; read it with the adjacent lines.
23 );Opens or closes the expression begun on the surrounding lines.
24 Spacing separates related steps.
25 new PsQuoteCpqCalculateCallback().callback(quoteModel);Completes the statement begun on this line or the preceding lines.
26 Spacing separates related steps.
27 PS_Quote_Analysis__c saved = [Assigns or configures the value on the left using the expression on the right.
28 SELECT Quote_Creation_Status__c, Quote_Creation_Error__cSOQL field list: identifies data to read from Salesforce.
29 FROM PS_Quote_Analysis__c WHERE Id = :analysis.IdSOQL source: identifies which Salesforce object to read.
30 ];Completes the statement begun on this line or the preceding lines.
31 System.assertEquals('Failed', saved.Quote_Creation_Status__c);Test assertion: fails the test when the expected behavior is absent.
32 System.assert(saved.Quote_Creation_Error__c.contains('CPQ calculated'));Test assertion: fails the test when the expected behavior is absent.
33 }Closes the current block or declaration.
34 Spacing separates related steps.
35 @IsTestMarks the following class or method as test code.
36 static void callbackMakesMatchingQuotePrimary() {Method declaration: Tests callback makes matching quote primary. The parentheses define its inputs; the type before the name defines its return value.
37 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
38 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(Creates or assigns a typed value for the steps that follow.
39 SBQQ__Opportunity2__c = opportunityRecord.Id,Creates or assigns a typed value for the steps that follow.
40 SBQQ__Account__c = opportunityRecord.AccountId,Assigns or configures the value on the left using the expression on the right.
41 SBQQ__PricebookId__c = Test.getStandardPricebookId(),Assigns or configures the value on the left using the expression on the right.
42 SBQQ__StartDate__c = Date.today(),Creates or assigns a typed value for the steps that follow.
43 SBQQ__SubscriptionTerm__c = 12,Assigns or configures the value on the left using the expression on the right.
44 SBQQ__Primary__c = falseAssigns or configures the value on the left using the expression on the right.
45 );Opens or closes the expression begun on the surrounding lines.
46 insert quoteRecord;DML write: creates the specified Salesforce record or records.
47 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(Assigns or configures the value on the left using the expression on the right.
48 opportunityRecord.Id, 'Confirmed', 'New Services'Part of the surrounding declaration or expression; read it with the adjacent lines.
49 );Opens or closes the expression begun on the surrounding lines.
50 update new PS_Quote_Analysis__c(DML write: saves changes to the specified Salesforce record or records.
51 Id = analysis.Id, Created_Quote__c = quoteRecord.Id,Creates or assigns a typed value for the steps that follow.
52 Quote_Creation_Status__c = 'Calculating',Assigns or configures the value on the left using the expression on the right.
53 Reviewed_Proposal_JSON__c = '{"quote_total":0,"lines":[]}'Assigns or configures the value on the left using the expression on the right.
54 );Opens or closes the expression begun on the surrounding lines.
55 String quoteModel = SBQQ.ServiceRouter.read(Calls the Salesforce CPQ managed package API for the named operation.
56 'SBQQ.QuoteAPI.QuoteReader', String.valueOf(quoteRecord.Id)Part of the surrounding declaration or expression; read it with the adjacent lines.
57 );Opens or closes the expression begun on the surrounding lines.
58 Spacing separates related steps.
59 new PsQuoteCpqCalculateCallback().callback(quoteModel);Completes the statement begun on this line or the preceding lines.
60 Spacing separates related steps.
61 PS_Quote_Analysis__c saved = [Assigns or configures the value on the left using the expression on the right.
62 SELECT Quote_Creation_Status__c, Quote_Creation_Error__cSOQL field list: identifies data to read from Salesforce.
63 FROM PS_Quote_Analysis__c WHERE Id = :analysis.IdSOQL source: identifies which Salesforce object to read.
64 ];Completes the statement begun on this line or the preceding lines.
65 System.assertEquals('Ready', saved.Quote_Creation_Status__c,Test assertion: fails the test when the expected behavior is absent.
66 'The matching quote should be ready. Error: ' +Part of the surrounding declaration or expression; read it with the adjacent lines.
67 String.valueOf(saved.Quote_Creation_Error__c));Completes the statement begun on this line or the preceding lines.
68 System.assertEquals(null, saved.Quote_Creation_Error__c,Test assertion: fails the test when the expected behavior is absent.
69 'A ready quote should have no creation error.');Completes the statement begun on this line or the preceding lines.
70 System.assertEquals(true, [Test assertion: fails the test when the expected behavior is absent.
71 SELECT SBQQ__Primary__c FROM SBQQ__Quote__c WHERE Id = :quoteRecord.IdSOQL field list: identifies data to read from Salesforce.
72 ].SBQQ__Primary__c);Completes the statement begun on this line or the preceding lines.
73 }Closes the current block or declaration.
74 @IsTestMarks the following class or method as test code.
75 static void excludesOptionalLinesAndIncludesNewAmendmentLines() {Method declaration: Tests excludes optional lines and includes new amendment lines. The parentheses define its inputs; the type before the name defines its return value.
76 String subscriptionId = SBQQ__Subscription__c.SObjectType.getDescribe()Creates or assigns a typed value for the steps that follow.
77 .getKeyPrefix() + '000000000001';Completes the statement begun on this line or the preceding lines.
78 List<SBQQ__QuoteLine__c> lines =Creates or assigns a typed value for the steps that follow.
79 (List<SBQQ__QuoteLine__c>) JSON.deserialize(Parses JSON text into Apex values that the following code can inspect.
80 '[{"SBQQ__NetTotal__c":100},' +Part of the surrounding declaration or expression; read it with the adjacent lines.
81 '{"SBQQ__NetTotal__c":50,"SBQQ__Optional__c":true},' +Part of the surrounding declaration or expression; read it with the adjacent lines.
82 '{"SBQQ__NetTotal__c":200,"SBQQ__UpgradedAsset__c":"02i000000000001"},' +Part of the surrounding declaration or expression; read it with the adjacent lines.
83 '{"SBQQ__NetTotal__c":70,"SBQQ__UpgradedSubscription__c":"' +Part of the surrounding declaration or expression; read it with the adjacent lines.
84 subscriptionId + '"},' +Part of the surrounding declaration or expression; read it with the adjacent lines.
85 '{"SBQQ__NetTotal__c":null}]',Continues the argument list or condition on the next line.
86 List<SBQQ__QuoteLine__c>.classPart of the surrounding declaration or expression; read it with the adjacent lines.
87 );Opens or closes the expression begun on the surrounding lines.
88 System.assertEquals(Test assertion: fails the test when the expected behavior is absent.
89 Decimal.valueOf('100'),Continues the argument list or condition on the next line.
90 PsQuoteCpqCalculateCallback.sumChargeableLines('Change Order', lines)Part of the surrounding declaration or expression; read it with the adjacent lines.
91 );Opens or closes the expression begun on the surrounding lines.
92 System.assertEquals(Test assertion: fails the test when the expected behavior is absent.
93 Decimal.valueOf('370'),Continues the argument list or condition on the next line.
94 PsQuoteCpqCalculateCallback.sumChargeableLines('New Services', lines)Part of the surrounding declaration or expression; read it with the adjacent lines.
95 );Opens or closes the expression begun on the surrounding lines.
96 System.assertEquals(Decimal.valueOf('0'),Test assertion: fails the test when the expected behavior is absent.
97 PsQuoteCpqCalculateCallback.sumChargeableLines(Part of the surrounding declaration or expression; read it with the adjacent lines.
98 'Change Order', new List<SBQQ__QuoteLine__c>()Part of the surrounding declaration or expression; read it with the adjacent lines.
99 ));Completes the statement begun on this line or the preceding lines.
100 }Closes the current block or declaration.
101}Closes the current block or declaration.
View complete source code
1@IsTest
2private class PsQuoteCpqCalculateCallbackTest {
3 @IsTest
4 static void callbackRecordsMismatchFromRealCpqQuoteModel() {
5 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
6 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(
7 SBQQ__Opportunity2__c = opportunityRecord.Id,
8 SBQQ__Account__c = opportunityRecord.AccountId,
9 SBQQ__PricebookId__c = Test.getStandardPricebookId(),
10 SBQQ__StartDate__c = Date.today(),
11 SBQQ__SubscriptionTerm__c = 12
12 );
13 insert quoteRecord;
14 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(
15 opportunityRecord.Id, 'Confirmed', 'New Services'
16 );
17 update new PS_Quote_Analysis__c(
18 Id = analysis.Id, Created_Quote__c = quoteRecord.Id,
19 Quote_Creation_Status__c = 'Calculating'
20 );
21 String quoteModel = SBQQ.ServiceRouter.read(
22 'SBQQ.QuoteAPI.QuoteReader', String.valueOf(quoteRecord.Id)
23 );
24
25 new PsQuoteCpqCalculateCallback().callback(quoteModel);
26
27 PS_Quote_Analysis__c saved = [
28 SELECT Quote_Creation_Status__c, Quote_Creation_Error__c
29 FROM PS_Quote_Analysis__c WHERE Id = :analysis.Id
30 ];
31 System.assertEquals('Failed', saved.Quote_Creation_Status__c);
32 System.assert(saved.Quote_Creation_Error__c.contains('CPQ calculated'));
33 }
34
35 @IsTest
36 static void callbackMakesMatchingQuotePrimary() {
37 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
38 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(
39 SBQQ__Opportunity2__c = opportunityRecord.Id,
40 SBQQ__Account__c = opportunityRecord.AccountId,
41 SBQQ__PricebookId__c = Test.getStandardPricebookId(),
42 SBQQ__StartDate__c = Date.today(),
43 SBQQ__SubscriptionTerm__c = 12,
44 SBQQ__Primary__c = false
45 );
46 insert quoteRecord;
47 PS_Quote_Analysis__c analysis = PsQuoteTestData.analysis(
48 opportunityRecord.Id, 'Confirmed', 'New Services'
49 );
50 update new PS_Quote_Analysis__c(
51 Id = analysis.Id, Created_Quote__c = quoteRecord.Id,
52 Quote_Creation_Status__c = 'Calculating',
53 Reviewed_Proposal_JSON__c = '{"quote_total":0,"lines":[]}'
54 );
55 String quoteModel = SBQQ.ServiceRouter.read(
56 'SBQQ.QuoteAPI.QuoteReader', String.valueOf(quoteRecord.Id)
57 );
58
59 new PsQuoteCpqCalculateCallback().callback(quoteModel);
60
61 PS_Quote_Analysis__c saved = [
62 SELECT Quote_Creation_Status__c, Quote_Creation_Error__c
63 FROM PS_Quote_Analysis__c WHERE Id = :analysis.Id
64 ];
65 System.assertEquals('Ready', saved.Quote_Creation_Status__c,
66 'The matching quote should be ready. Error: ' +
67 String.valueOf(saved.Quote_Creation_Error__c));
68 System.assertEquals(null, saved.Quote_Creation_Error__c,
69 'A ready quote should have no creation error.');
70 System.assertEquals(true, [
71 SELECT SBQQ__Primary__c FROM SBQQ__Quote__c WHERE Id = :quoteRecord.Id
72 ].SBQQ__Primary__c);
73 }
74 @IsTest
75 static void excludesOptionalLinesAndIncludesNewAmendmentLines() {
76 String subscriptionId = SBQQ__Subscription__c.SObjectType.getDescribe()
77 .getKeyPrefix() + '000000000001';
78 List<SBQQ__QuoteLine__c> lines =
79 (List<SBQQ__QuoteLine__c>) JSON.deserialize(
80 '[{"SBQQ__NetTotal__c":100},' +
81 '{"SBQQ__NetTotal__c":50,"SBQQ__Optional__c":true},' +
82 '{"SBQQ__NetTotal__c":200,"SBQQ__UpgradedAsset__c":"02i000000000001"},' +
83 '{"SBQQ__NetTotal__c":70,"SBQQ__UpgradedSubscription__c":"' +
84 subscriptionId + '"},' +
85 '{"SBQQ__NetTotal__c":null}]',
86 List<SBQQ__QuoteLine__c>.class
87 );
88 System.assertEquals(
89 Decimal.valueOf('100'),
90 PsQuoteCpqCalculateCallback.sumChargeableLines('Change Order', lines)
91 );
92 System.assertEquals(
93 Decimal.valueOf('370'),
94 PsQuoteCpqCalculateCallback.sumChargeableLines('New Services', lines)
95 );
96 System.assertEquals(Decimal.valueOf('0'),
97 PsQuoteCpqCalculateCallback.sumChargeableLines(
98 'Change Order', new List<SBQQ__QuoteLine__c>()
99 ));
100 }
101}
test · 251 lines

PsServicesChangeOrderActionTest

Tests Flow request checks and the downstream actions after a CPQ-shaped amendment response. The latest local test is not verified in Salesforce.

This is the newer local test source. Recent additions still need a Salesforce test run.

Review and understand complete source code

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@IsTestMarks the following class or method as test code.
2private class PsServicesChangeOrderActionTest {Declares a class or trigger. The braces contain its members and behavior.
3 @IsTestMarks the following class or method as test code.
4 static void rejectsInactiveContractAndUnknownOpportunityRecordType() {Method declaration: Tests rejects inactive contract and unknown opportunity record type. The parentheses define its inputs; the type before the name defines its return value.
5 Account accountRecord = new Account(Name = 'Services account');Creates or assigns a typed value for the steps that follow.
6 insert accountRecord;DML write: creates the specified Salesforce record or records.
7 Contact contactRecord = new Contact(Creates or assigns a typed value for the steps that follow.
8 FirstName = 'Services', LastName = 'Contact',Assigns or configures the value on the left using the expression on the right.
9 AccountId = accountRecord.Id,Creates or assigns a typed value for the steps that follow.
10 Email = 'services.test@example.com'Assigns or configures the value on the left using the expression on the right.
11 );Opens or closes the expression begun on the surrounding lines.
12 insert contactRecord;DML write: creates the specified Salesforce record or records.
13 List<ContractStatus> draftStatuses = [Creates or assigns a typed value for the steps that follow.
14 SELECT ApiName FROM ContractStatusSOQL field list: identifies data to read from Salesforce.
15 WHERE StatusCode = 'Draft'SOQL filter: narrows the records returned by this query.
16 ORDER BY IsDefault DESC LIMIT 1Sorts the records returned by this query.
17 ];Completes the statement begun on this line or the preceding lines.
18 System.assert(!draftStatuses.isEmpty(),Test assertion: fails the test when the expected behavior is absent.
19 'This test needs a Contract status in the Draft category.');Completes the statement begun on this line or the preceding lines.
20 Contract contractRecord = new Contract(Creates or assigns a typed value for the steps that follow.
21 Name = 'Services contract', AccountId = accountRecord.Id,Creates or assigns a typed value for the steps that follow.
22 Status = draftStatuses[0].ApiName,Assigns or configures the value on the left using the expression on the right.
23 StartDate = Date.today(), ContractTerm = 12Creates or assigns a typed value for the steps that follow.
24 );Opens or closes the expression begun on the surrounding lines.
25 insert contractRecord;DML write: creates the specified Salesforce record or records.
26 PsServicesChangeOrderAction.Request request =Assigns or configures the value on the left using the expression on the right.
27 new PsServicesChangeOrderAction.Request();Completes the statement begun on this line or the preceding lines.
28 request.contactId = contactRecord.Id;Creates or assigns a typed value for the steps that follow.
29 request.contractId = contractRecord.Id;Creates or assigns a typed value for the steps that follow.
30 request.stageName = 'Stage 1';Assigns or configures the value on the left using the expression on the right.
31 request.opportunityType = 'Change Order';Assigns or configures the value on the left using the expression on the right.
32 request.closeDate = Date.today().addDays(30);Creates or assigns a typed value for the steps that follow.
33 request.servicesRecordTypeId = (Id) '012000000000001';Creates or assigns a typed value for the steps that follow.
34 Spacing separates related steps.
35 try {Starts an operation whose exception can be handled below.
36 PsServicesChangeOrderAction.create(Part of the surrounding declaration or expression; read it with the adjacent lines.
37 new List<PsServicesChangeOrderAction.Request>{request}Closes the current block after this expression.
38 );Opens or closes the expression begun on the surrounding lines.
39 System.assert(false, 'An inactive contract must be rejected.');Test assertion: fails the test when the expected behavior is absent.
40 } catch (PsServicesChangeOrderAction.ChangeOrderException expected) {Opens a block; the indented lines below execute or belong together.
41 System.assert(expected.getMessage().contains('activated contract'));Test assertion: fails the test when the expected behavior is absent.
42 }Closes the current block or declaration.
43 Spacing separates related steps.
44 String activatedStatus;Completes the statement begun on this line or the preceding lines.
45 for (Schema.PicklistEntry value : Contract.Status.getDescribe().getPicklistValues()) {Loop: repeats the following block for each matching item.
46 if (value.isActive() && value.getValue().startsWith('Activated')) {Guard or branch: the following block runs only when this condition is true.
47 activatedStatus = value.getValue();Assigns or configures the value on the left using the expression on the right.
48 break;Completes the statement begun on this line or the preceding lines.
49 }Closes the current block or declaration.
50 }Closes the current block or declaration.
51 System.assertNotEquals(null, activatedStatus,Test assertion: fails the test when the expected behavior is absent.
52 'This test needs an active Contract status beginning with Activated.');Completes the statement begun on this line or the preceding lines.
53 contractRecord.Status = activatedStatus;Assigns or configures the value on the left using the expression on the right.
54 update contractRecord;DML write: saves changes to the specified Salesforce record or records.
55 try {Starts an operation whose exception can be handled below.
56 PsServicesChangeOrderAction.create(Part of the surrounding declaration or expression; read it with the adjacent lines.
57 new List<PsServicesChangeOrderAction.Request>{request}Closes the current block after this expression.
58 );Opens or closes the expression begun on the surrounding lines.
59 System.assert(false, 'An unknown record type must be rejected.');Test assertion: fails the test when the expected behavior is absent.
60 } catch (PsServicesChangeOrderAction.ChangeOrderException expected) {Opens a block; the indented lines below execute or belong together.
61 System.assert(expected.getMessage().contains('active Opportunity record type'));Test assertion: fails the test when the expected behavior is absent.
62 }Closes the current block or declaration.
63 }Closes the current block or declaration.
64 @IsTestMarks the following class or method as test code.
65 static void rejectsMissingRequestBeforeCallingCpq() {Method declaration: Tests rejects missing request before calling cpq. The parentheses define its inputs; the type before the name defines its return value.
66 try {Starts an operation whose exception can be handled below.
67 PsServicesChangeOrderAction.create(null);Completes the statement begun on this line or the preceding lines.
68 System.assert(false, 'Missing request must not call CPQ.');Test assertion: fails the test when the expected behavior is absent.
69 } catch (PsServicesChangeOrderAction.ChangeOrderException expected) {Opens a block; the indented lines below execute or belong together.
70 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
71 }Closes the current block or declaration.
72 Spacing separates related steps.
73 try {Starts an operation whose exception can be handled below.
74 PsServicesChangeOrderAction.create(Part of the surrounding declaration or expression; read it with the adjacent lines.
75 new List<PsServicesChangeOrderAction.Request>{Opens a block; the indented lines below execute or belong together.
76 new PsServicesChangeOrderAction.Request()Part of the surrounding declaration or expression; read it with the adjacent lines.
77 }Closes the current block or declaration.
78 );Opens or closes the expression begun on the surrounding lines.
79 System.assert(false, 'Incomplete request must not call CPQ.');Test assertion: fails the test when the expected behavior is absent.
80 } catch (PsServicesChangeOrderAction.ChangeOrderException expected) {Opens a block; the indented lines below execute or belong together.
81 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
82 }Closes the current block or declaration.
83 }Closes the current block or declaration.
84 Spacing separates related steps.
85 @IsTestMarks the following class or method as test code.
86 static void parsesNativeCpqQuoteIdAndRejectsMalformedModels() {Method declaration: Tests parses native cpq quote id and rejects malformed models. The parentheses define its inputs; the type before the name defines its return value.
87 Id quoteId = (Id) (SBQQ__Quote__c.SObjectType.getDescribe().getKeyPrefix() +Creates or assigns a typed value for the steps that follow.
88 '000000000001');Completes the statement begun on this line or the preceding lines.
89 System.assertEquals(quoteId,Test assertion: fails the test when the expected behavior is absent.
90 PsServicesChangeOrderAction.quoteIdFromModel(Part of the surrounding declaration or expression; read it with the adjacent lines.
91 '{"record":{"Id":"' + quoteId + '"}}'Part of the surrounding declaration or expression; read it with the adjacent lines.
92 ));Completes the statement begun on this line or the preceding lines.
93 for (String response : new List<String>{Loop: repeats the following block for each matching item.
94 '', '{}', '{"record":{}}', '[]'Part of the surrounding declaration or expression; read it with the adjacent lines.
95 }) {Opens a block; the indented lines below execute or belong together.
96 try {Starts an operation whose exception can be handled below.
97 PsServicesChangeOrderAction.quoteIdFromModel(response);Completes the statement begun on this line or the preceding lines.
98 System.assert(false, 'Invalid CPQ response must be rejected: ' + response);Test assertion: fails the test when the expected behavior is absent.
99 } catch (PsServicesChangeOrderAction.ChangeOrderException expected) {Opens a block; the indented lines below execute or belong together.
100 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
101 }Closes the current block or declaration.
102 }Closes the current block or declaration.
103 }Closes the current block or declaration.
104 Spacing separates related steps.
105 @IsTestMarks the following class or method as test code.
106 static void rejectsContractFromAnotherContactAccountBeforeCpqCall() {Method declaration: Tests rejects contract from another contact account before cpq call. The parentheses define its inputs; the type before the name defines its return value.
107 Account contactAccount = new Account(Name='Contact account');Creates or assigns a typed value for the steps that follow.
108 Account contractAccount = new Account(Name='Contract account');Creates or assigns a typed value for the steps that follow.
109 insert new List<Account>{contactAccount, contractAccount};DML write: creates the specified Salesforce record or records.
110 Contact contactRecord = new Contact(Creates or assigns a typed value for the steps that follow.
111 FirstName='Change Order', LastName='Contact',Assigns or configures the value on the left using the expression on the right.
112 AccountId=contactAccount.Id,Creates or assigns a typed value for the steps that follow.
113 Email='change.order.test@example.com'Assigns or configures the value on the left using the expression on the right.
114 );Opens or closes the expression begun on the surrounding lines.
115 insert contactRecord;DML write: creates the specified Salesforce record or records.
116 List<ContractStatus> draftStatuses = [Creates or assigns a typed value for the steps that follow.
117 SELECT ApiName FROM ContractStatusSOQL field list: identifies data to read from Salesforce.
118 WHERE StatusCode = 'Draft'SOQL filter: narrows the records returned by this query.
119 ORDER BY IsDefault DESC LIMIT 1Sorts the records returned by this query.
120 ];Completes the statement begun on this line or the preceding lines.
121 System.assert(!draftStatuses.isEmpty(),Test assertion: fails the test when the expected behavior is absent.
122 'This test needs a Contract status in the Draft category.');Completes the statement begun on this line or the preceding lines.
123 Contract contractRecord = new Contract(Creates or assigns a typed value for the steps that follow.
124 Name='Other account services contract',Assigns or configures the value on the left using the expression on the right.
125 AccountId=contractAccount.Id, Status=draftStatuses[0].ApiName,Creates or assigns a typed value for the steps that follow.
126 StartDate=Date.today(), ContractTerm=12Creates or assigns a typed value for the steps that follow.
127 );Opens or closes the expression begun on the surrounding lines.
128 insert contractRecord;DML write: creates the specified Salesforce record or records.
129 PsServicesChangeOrderAction.Request request =Assigns or configures the value on the left using the expression on the right.
130 new PsServicesChangeOrderAction.Request();Completes the statement begun on this line or the preceding lines.
131 request.contactId = contactRecord.Id;Creates or assigns a typed value for the steps that follow.
132 request.contractId = contractRecord.Id;Creates or assigns a typed value for the steps that follow.
133 request.stageName = 'Stage 1';Assigns or configures the value on the left using the expression on the right.
134 request.opportunityType = 'Change Order';Assigns or configures the value on the left using the expression on the right.
135 request.closeDate = Date.today().addDays(30);Creates or assigns a typed value for the steps that follow.
136 request.servicesRecordTypeId = (Id) '012000000000001';Creates or assigns a typed value for the steps that follow.
137 try {Starts an operation whose exception can be handled below.
138 PsServicesChangeOrderAction.create(Part of the surrounding declaration or expression; read it with the adjacent lines.
139 new List<PsServicesChangeOrderAction.Request>{request}Closes the current block after this expression.
140 );Opens or closes the expression begun on the surrounding lines.
141 System.assert(false, 'Contact and Contract must share an Account.');Test assertion: fails the test when the expected behavior is absent.
142 } catch (PsServicesChangeOrderAction.ChangeOrderException expected) {Opens a block; the indented lines below execute or belong together.
143 System.assertNotEquals(null, expected);Test assertion: fails the test when the expected behavior is absent.
144 }Closes the current block or declaration.
145 }Closes the current block or declaration.
146 Spacing separates related steps.
147 @IsTestMarks the following class or method as test code.
148 static void createsContactRoleAndMakesAmendmentQuotePrimary() {Method declaration: Tests creates contact role and makes amendment quote primary. The parentheses define its inputs; the type before the name defines its return value.
149 Account accountRecord = new Account(Name = 'Amendment account');Creates or assigns a typed value for the steps that follow.
150 insert accountRecord;DML write: creates the specified Salesforce record or records.
151 Contact contactRecord = new Contact(Creates or assigns a typed value for the steps that follow.
152 FirstName = 'Amendment', LastName = 'Contact',Assigns or configures the value on the left using the expression on the right.
153 AccountId = accountRecord.Id,Creates or assigns a typed value for the steps that follow.
154 Email = 'amendment.contact@example.com'Assigns or configures the value on the left using the expression on the right.
155 );Opens or closes the expression begun on the surrounding lines.
156 insert contactRecord;DML write: creates the specified Salesforce record or records.
157 List<ContractStatus> draftStatuses = [Creates or assigns a typed value for the steps that follow.
158 SELECT ApiName FROM ContractStatus WHERE StatusCode = 'Draft'SOQL field list: identifies data to read from Salesforce.
159 ORDER BY IsDefault DESC LIMIT 1Sorts the records returned by this query.
160 ];Completes the statement begun on this line or the preceding lines.
161 System.assert(!draftStatuses.isEmpty(), 'A Draft contract status is required.');Test assertion: fails the test when the expected behavior is absent.
162 Contract contractRecord = new Contract(Creates or assigns a typed value for the steps that follow.
163 Name = 'Amendment contract', AccountId = accountRecord.Id,Creates or assigns a typed value for the steps that follow.
164 Status = draftStatuses[0].ApiName,Assigns or configures the value on the left using the expression on the right.
165 StartDate = Date.today(), ContractTerm = 12Creates or assigns a typed value for the steps that follow.
166 );Opens or closes the expression begun on the surrounding lines.
167 insert contractRecord;DML write: creates the specified Salesforce record or records.
168 String activatedStatus;Completes the statement begun on this line or the preceding lines.
169 for (Schema.PicklistEntry value : Contract.Status.getDescribe().getPicklistValues()) {Loop: repeats the following block for each matching item.
170 if (value.isActive() && value.getValue().startsWith('Activated')) {Guard or branch: the following block runs only when this condition is true.
171 activatedStatus = value.getValue();Assigns or configures the value on the left using the expression on the right.
172 break;Completes the statement begun on this line or the preceding lines.
173 }Closes the current block or declaration.
174 }Closes the current block or declaration.
175 System.assertNotEquals(null, activatedStatus,Test assertion: fails the test when the expected behavior is absent.
176 'An active Contract status beginning with Activated is required.');Completes the statement begun on this line or the preceding lines.
177 contractRecord.Status = activatedStatus;Assigns or configures the value on the left using the expression on the right.
178 update contractRecord;DML write: saves changes to the specified Salesforce record or records.
179 Spacing separates related steps.
180 List<RecordType> servicesTypes = [Creates or assigns a typed value for the steps that follow.
181 SELECT Id FROM RecordTypeSOQL field list: identifies data to read from Salesforce.
182 WHERE SObjectType = 'Opportunity' AND DeveloperName = 'Services'SOQL filter: narrows the records returned by this query.
183 AND IsActive = true LIMIT 1SOQL filter: narrows the records returned by this query.
184 ];Completes the statement begun on this line or the preceding lines.
185 System.assert(!servicesTypes.isEmpty(), 'The Services record type is required.');Test assertion: fails the test when the expected behavior is absent.
186 String stageName;Completes the statement begun on this line or the preceding lines.
187 for (Schema.PicklistEntry value : Opportunity.StageName.getDescribe().getPicklistValues()) {Loop: repeats the following block for each matching item.
188 if (value.isActive()) {Guard or branch: the following block runs only when this condition is true.
189 stageName = value.getValue();Assigns or configures the value on the left using the expression on the right.
190 break;Completes the statement begun on this line or the preceding lines.
191 }Closes the current block or declaration.
192 }Closes the current block or declaration.
193 System.assertNotEquals(null, stageName, 'An active Opportunity stage is required.');Test assertion: fails the test when the expected behavior is absent.
194 String opportunityType;Completes the statement begun on this line or the preceding lines.
195 for (Schema.PicklistEntry value : Opportunity.Type.getDescribe().getPicklistValues()) {Loop: repeats the following block for each matching item.
196 if (value.isActive()) {Guard or branch: the following block runs only when this condition is true.
197 opportunityType = value.getValue();Assigns or configures the value on the left using the expression on the right.
198 break;Completes the statement begun on this line or the preceding lines.
199 }Closes the current block or declaration.
200 }Closes the current block or declaration.
201 System.assertNotEquals(null, opportunityType, 'An active Opportunity type is required.');Test assertion: fails the test when the expected behavior is absent.
202 Opportunity amendmentOpportunity = new Opportunity(Creates or assigns a typed value for the steps that follow.
203 Name = 'Native amendment test', AccountId = accountRecord.Id,Creates or assigns a typed value for the steps that follow.
204 StageName = stageName, Type = opportunityType,Assigns or configures the value on the left using the expression on the right.
205 CloseDate = Date.today().addDays(30),Creates or assigns a typed value for the steps that follow.
206 RecordTypeId = servicesTypes[0].IdCreates or assigns a typed value for the steps that follow.
207 );Opens or closes the expression begun on the surrounding lines.
208 insert amendmentOpportunity;DML write: creates the specified Salesforce record or records.
209 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(Creates or assigns a typed value for the steps that follow.
210 SBQQ__Opportunity2__c = amendmentOpportunity.Id,Creates or assigns a typed value for the steps that follow.
211 SBQQ__Account__c = accountRecord.Id,Creates or assigns a typed value for the steps that follow.
212 SBQQ__MasterContract__c = contractRecord.Id,Creates or assigns a typed value for the steps that follow.
213 SBQQ__Type__c = 'Amendment', SBQQ__Primary__c = false,Assigns or configures the value on the left using the expression on the right.
214 SBQQ__StartDate__c = Date.today()Creates or assigns a typed value for the steps that follow.
215 );Opens or closes the expression begun on the surrounding lines.
216 insert quoteRecord;DML write: creates the specified Salesforce record or records.
217 PsServicesChangeOrderAction.testAmenderResponse =Assigns or configures the value on the left using the expression on the right.
218 '{"record":{"Id":"' + String.valueOf(quoteRecord.Id) + '"}}';Completes the statement begun on this line or the preceding lines.
219 PsServicesChangeOrderAction.Request request =Assigns or configures the value on the left using the expression on the right.
220 new PsServicesChangeOrderAction.Request();Completes the statement begun on this line or the preceding lines.
221 request.contactId = contactRecord.Id;Creates or assigns a typed value for the steps that follow.
222 request.contractId = contractRecord.Id;Creates or assigns a typed value for the steps that follow.
223 request.stageName = stageName;Assigns or configures the value on the left using the expression on the right.
224 request.opportunityType = opportunityType;Assigns or configures the value on the left using the expression on the right.
225 request.closeDate = Date.today().addDays(45);Creates or assigns a typed value for the steps that follow.
226 request.servicesRecordTypeId = servicesTypes[0].Id;Creates or assigns a typed value for the steps that follow.
227 Spacing separates related steps.
228 List<PsServicesChangeOrderAction.Result> results =Creates or assigns a typed value for the steps that follow.
229 PsServicesChangeOrderAction.create(Part of the surrounding declaration or expression; read it with the adjacent lines.
230 new List<PsServicesChangeOrderAction.Request>{ request }Closes the current block after this expression.
231 );Opens or closes the expression begun on the surrounding lines.
232 Spacing separates related steps.
233 System.assertEquals(1, results.size());Test assertion: fails the test when the expected behavior is absent.
234 System.assertEquals(amendmentOpportunity.Id, results[0].opportunityId);Test assertion: fails the test when the expected behavior is absent.
235 System.assertEquals(quoteRecord.Id, results[0].quoteId);Test assertion: fails the test when the expected behavior is absent.
236 System.assertEquals(Date.today(), results[0].quoteStartDate);Test assertion: fails the test when the expected behavior is absent.
237 System.assertEquals(request.closeDate, [Test assertion: fails the test when the expected behavior is absent.
238 SELECT CloseDate FROM Opportunity WHERE Id = :amendmentOpportunity.IdSOQL field list: identifies data to read from Salesforce.
239 ].CloseDate);Completes the statement begun on this line or the preceding lines.
240 List<OpportunityContactRole> roles = [Creates or assigns a typed value for the steps that follow.
241 SELECT ContactId, IsPrimary FROM OpportunityContactRoleSOQL field list: identifies data to read from Salesforce.
242 WHERE OpportunityId = :amendmentOpportunity.IdSOQL filter: narrows the records returned by this query.
243 ];Completes the statement begun on this line or the preceding lines.
244 System.assertEquals(1, roles.size());Test assertion: fails the test when the expected behavior is absent.
245 System.assertEquals(contactRecord.Id, roles[0].ContactId);Test assertion: fails the test when the expected behavior is absent.
246 System.assertEquals(true, roles[0].IsPrimary);Test assertion: fails the test when the expected behavior is absent.
247 System.assertEquals(true, [Test assertion: fails the test when the expected behavior is absent.
248 SELECT SBQQ__Primary__c FROM SBQQ__Quote__c WHERE Id = :quoteRecord.IdSOQL field list: identifies data to read from Salesforce.
249 ].SBQQ__Primary__c);Completes the statement begun on this line or the preceding lines.
250 }Closes the current block or declaration.
251}Closes the current block or declaration.
View complete source code
1@IsTest
2private class PsServicesChangeOrderActionTest {
3 @IsTest
4 static void rejectsInactiveContractAndUnknownOpportunityRecordType() {
5 Account accountRecord = new Account(Name = 'Services account');
6 insert accountRecord;
7 Contact contactRecord = new Contact(
8 FirstName = 'Services', LastName = 'Contact',
9 AccountId = accountRecord.Id,
10 Email = 'services.test@example.com'
11 );
12 insert contactRecord;
13 List<ContractStatus> draftStatuses = [
14 SELECT ApiName FROM ContractStatus
15 WHERE StatusCode = 'Draft'
16 ORDER BY IsDefault DESC LIMIT 1
17 ];
18 System.assert(!draftStatuses.isEmpty(),
19 'This test needs a Contract status in the Draft category.');
20 Contract contractRecord = new Contract(
21 Name = 'Services contract', AccountId = accountRecord.Id,
22 Status = draftStatuses[0].ApiName,
23 StartDate = Date.today(), ContractTerm = 12
24 );
25 insert contractRecord;
26 PsServicesChangeOrderAction.Request request =
27 new PsServicesChangeOrderAction.Request();
28 request.contactId = contactRecord.Id;
29 request.contractId = contractRecord.Id;
30 request.stageName = 'Stage 1';
31 request.opportunityType = 'Change Order';
32 request.closeDate = Date.today().addDays(30);
33 request.servicesRecordTypeId = (Id) '012000000000001';
34
35 try {
36 PsServicesChangeOrderAction.create(
37 new List<PsServicesChangeOrderAction.Request>{request}
38 );
39 System.assert(false, 'An inactive contract must be rejected.');
40 } catch (PsServicesChangeOrderAction.ChangeOrderException expected) {
41 System.assert(expected.getMessage().contains('activated contract'));
42 }
43
44 String activatedStatus;
45 for (Schema.PicklistEntry value : Contract.Status.getDescribe().getPicklistValues()) {
46 if (value.isActive() && value.getValue().startsWith('Activated')) {
47 activatedStatus = value.getValue();
48 break;
49 }
50 }
51 System.assertNotEquals(null, activatedStatus,
52 'This test needs an active Contract status beginning with Activated.');
53 contractRecord.Status = activatedStatus;
54 update contractRecord;
55 try {
56 PsServicesChangeOrderAction.create(
57 new List<PsServicesChangeOrderAction.Request>{request}
58 );
59 System.assert(false, 'An unknown record type must be rejected.');
60 } catch (PsServicesChangeOrderAction.ChangeOrderException expected) {
61 System.assert(expected.getMessage().contains('active Opportunity record type'));
62 }
63 }
64 @IsTest
65 static void rejectsMissingRequestBeforeCallingCpq() {
66 try {
67 PsServicesChangeOrderAction.create(null);
68 System.assert(false, 'Missing request must not call CPQ.');
69 } catch (PsServicesChangeOrderAction.ChangeOrderException expected) {
70 System.assertNotEquals(null, expected);
71 }
72
73 try {
74 PsServicesChangeOrderAction.create(
75 new List<PsServicesChangeOrderAction.Request>{
76 new PsServicesChangeOrderAction.Request()
77 }
78 );
79 System.assert(false, 'Incomplete request must not call CPQ.');
80 } catch (PsServicesChangeOrderAction.ChangeOrderException expected) {
81 System.assertNotEquals(null, expected);
82 }
83 }
84
85 @IsTest
86 static void parsesNativeCpqQuoteIdAndRejectsMalformedModels() {
87 Id quoteId = (Id) (SBQQ__Quote__c.SObjectType.getDescribe().getKeyPrefix() +
88 '000000000001');
89 System.assertEquals(quoteId,
90 PsServicesChangeOrderAction.quoteIdFromModel(
91 '{"record":{"Id":"' + quoteId + '"}}'
92 ));
93 for (String response : new List<String>{
94 '', '{}', '{"record":{}}', '[]'
95 }) {
96 try {
97 PsServicesChangeOrderAction.quoteIdFromModel(response);
98 System.assert(false, 'Invalid CPQ response must be rejected: ' + response);
99 } catch (PsServicesChangeOrderAction.ChangeOrderException expected) {
100 System.assertNotEquals(null, expected);
101 }
102 }
103 }
104
105 @IsTest
106 static void rejectsContractFromAnotherContactAccountBeforeCpqCall() {
107 Account contactAccount = new Account(Name='Contact account');
108 Account contractAccount = new Account(Name='Contract account');
109 insert new List<Account>{contactAccount, contractAccount};
110 Contact contactRecord = new Contact(
111 FirstName='Change Order', LastName='Contact',
112 AccountId=contactAccount.Id,
113 Email='change.order.test@example.com'
114 );
115 insert contactRecord;
116 List<ContractStatus> draftStatuses = [
117 SELECT ApiName FROM ContractStatus
118 WHERE StatusCode = 'Draft'
119 ORDER BY IsDefault DESC LIMIT 1
120 ];
121 System.assert(!draftStatuses.isEmpty(),
122 'This test needs a Contract status in the Draft category.');
123 Contract contractRecord = new Contract(
124 Name='Other account services contract',
125 AccountId=contractAccount.Id, Status=draftStatuses[0].ApiName,
126 StartDate=Date.today(), ContractTerm=12
127 );
128 insert contractRecord;
129 PsServicesChangeOrderAction.Request request =
130 new PsServicesChangeOrderAction.Request();
131 request.contactId = contactRecord.Id;
132 request.contractId = contractRecord.Id;
133 request.stageName = 'Stage 1';
134 request.opportunityType = 'Change Order';
135 request.closeDate = Date.today().addDays(30);
136 request.servicesRecordTypeId = (Id) '012000000000001';
137 try {
138 PsServicesChangeOrderAction.create(
139 new List<PsServicesChangeOrderAction.Request>{request}
140 );
141 System.assert(false, 'Contact and Contract must share an Account.');
142 } catch (PsServicesChangeOrderAction.ChangeOrderException expected) {
143 System.assertNotEquals(null, expected);
144 }
145 }
146
147 @IsTest
148 static void createsContactRoleAndMakesAmendmentQuotePrimary() {
149 Account accountRecord = new Account(Name = 'Amendment account');
150 insert accountRecord;
151 Contact contactRecord = new Contact(
152 FirstName = 'Amendment', LastName = 'Contact',
153 AccountId = accountRecord.Id,
154 Email = 'amendment.contact@example.com'
155 );
156 insert contactRecord;
157 List<ContractStatus> draftStatuses = [
158 SELECT ApiName FROM ContractStatus WHERE StatusCode = 'Draft'
159 ORDER BY IsDefault DESC LIMIT 1
160 ];
161 System.assert(!draftStatuses.isEmpty(), 'A Draft contract status is required.');
162 Contract contractRecord = new Contract(
163 Name = 'Amendment contract', AccountId = accountRecord.Id,
164 Status = draftStatuses[0].ApiName,
165 StartDate = Date.today(), ContractTerm = 12
166 );
167 insert contractRecord;
168 String activatedStatus;
169 for (Schema.PicklistEntry value : Contract.Status.getDescribe().getPicklistValues()) {
170 if (value.isActive() && value.getValue().startsWith('Activated')) {
171 activatedStatus = value.getValue();
172 break;
173 }
174 }
175 System.assertNotEquals(null, activatedStatus,
176 'An active Contract status beginning with Activated is required.');
177 contractRecord.Status = activatedStatus;
178 update contractRecord;
179
180 List<RecordType> servicesTypes = [
181 SELECT Id FROM RecordType
182 WHERE SObjectType = 'Opportunity' AND DeveloperName = 'Services'
183 AND IsActive = true LIMIT 1
184 ];
185 System.assert(!servicesTypes.isEmpty(), 'The Services record type is required.');
186 String stageName;
187 for (Schema.PicklistEntry value : Opportunity.StageName.getDescribe().getPicklistValues()) {
188 if (value.isActive()) {
189 stageName = value.getValue();
190 break;
191 }
192 }
193 System.assertNotEquals(null, stageName, 'An active Opportunity stage is required.');
194 String opportunityType;
195 for (Schema.PicklistEntry value : Opportunity.Type.getDescribe().getPicklistValues()) {
196 if (value.isActive()) {
197 opportunityType = value.getValue();
198 break;
199 }
200 }
201 System.assertNotEquals(null, opportunityType, 'An active Opportunity type is required.');
202 Opportunity amendmentOpportunity = new Opportunity(
203 Name = 'Native amendment test', AccountId = accountRecord.Id,
204 StageName = stageName, Type = opportunityType,
205 CloseDate = Date.today().addDays(30),
206 RecordTypeId = servicesTypes[0].Id
207 );
208 insert amendmentOpportunity;
209 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(
210 SBQQ__Opportunity2__c = amendmentOpportunity.Id,
211 SBQQ__Account__c = accountRecord.Id,
212 SBQQ__MasterContract__c = contractRecord.Id,
213 SBQQ__Type__c = 'Amendment', SBQQ__Primary__c = false,
214 SBQQ__StartDate__c = Date.today()
215 );
216 insert quoteRecord;
217 PsServicesChangeOrderAction.testAmenderResponse =
218 '{"record":{"Id":"' + String.valueOf(quoteRecord.Id) + '"}}';
219 PsServicesChangeOrderAction.Request request =
220 new PsServicesChangeOrderAction.Request();
221 request.contactId = contactRecord.Id;
222 request.contractId = contractRecord.Id;
223 request.stageName = stageName;
224 request.opportunityType = opportunityType;
225 request.closeDate = Date.today().addDays(45);
226 request.servicesRecordTypeId = servicesTypes[0].Id;
227
228 List<PsServicesChangeOrderAction.Result> results =
229 PsServicesChangeOrderAction.create(
230 new List<PsServicesChangeOrderAction.Request>{ request }
231 );
232
233 System.assertEquals(1, results.size());
234 System.assertEquals(amendmentOpportunity.Id, results[0].opportunityId);
235 System.assertEquals(quoteRecord.Id, results[0].quoteId);
236 System.assertEquals(Date.today(), results[0].quoteStartDate);
237 System.assertEquals(request.closeDate, [
238 SELECT CloseDate FROM Opportunity WHERE Id = :amendmentOpportunity.Id
239 ].CloseDate);
240 List<OpportunityContactRole> roles = [
241 SELECT ContactId, IsPrimary FROM OpportunityContactRole
242 WHERE OpportunityId = :amendmentOpportunity.Id
243 ];
244 System.assertEquals(1, roles.size());
245 System.assertEquals(contactRecord.Id, roles[0].ContactId);
246 System.assertEquals(true, roles[0].IsPrimary);
247 System.assertEquals(true, [
248 SELECT SBQQ__Primary__c FROM SBQQ__Quote__c WHERE Id = :quoteRecord.Id
249 ].SBQQ__Primary__c);
250 }
251}
test · 128 lines

QuoteLineBudgetSequenceHandlerTest

Tests sequence blocks, order, dates, prior numbers, and manual values.

Review and understand complete source code

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@IsTestMarks the following class or method as test code.
2private class QuoteLineBudgetSequenceHandlerTest {Declares a class or trigger. The braces contain its members and behavior.
3 private static Id fakeId(Schema.SObjectType objectType, String suffix) {Opens a block; the indented lines below execute or belong together.
4 return (Id) (objectType.getDescribe().getKeyPrefix() + suffix);Returns this value to the caller and ends the method.
5 }Closes the current block or declaration.
6 Spacing separates related steps.
7 private static Map<Id, SBQQ__QuoteLine__c> byId(List<SBQQ__QuoteLine__c> lines) {Opens a block; the indented lines below execute or belong together.
8 return new Map<Id, SBQQ__QuoteLine__c>(lines);Returns this value to the caller and ends the method.
9 }Closes the current block or declaration.
10 Spacing separates related steps.
11 @IsTestMarks the following class or method as test code.
12 static void ordersBlocksAndLineNumbersFromQuoteStartDate() {Method declaration: Tests orders blocks and line numbers from quote start date. The parentheses define its inputs; the type before the name defines its return value.
13 Id quoteId = fakeId(SBQQ__Quote__c.SObjectType, '000000000001');Creates or assigns a typed value for the steps that follow.
14 Id prepaidId = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000001');Creates or assigns a typed value for the steps that follow.
15 Id milestoneEarlyId = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000002');Creates or assigns a typed value for the steps that follow.
16 Id milestoneLateId = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000003');Creates or assigns a typed value for the steps that follow.
17 Id tmId = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000004');Creates or assigns a typed value for the steps that follow.
18 List<SBQQ__QuoteLine__c> input = new List<SBQQ__QuoteLine__c>{Opens a block; the indented lines below execute or belong together.
19 new SBQQ__QuoteLine__c(Id=tmId, SBQQ__Quote__c=quoteId, SBQQ__Number__c=4),Creates or assigns a typed value for the steps that follow.
20 new SBQQ__QuoteLine__c(Id=milestoneLateId, SBQQ__Quote__c=quoteId, SBQQ__Number__c=3),Creates or assigns a typed value for the steps that follow.
21 new SBQQ__QuoteLine__c(Id=prepaidId, SBQQ__Quote__c=quoteId, SBQQ__Number__c=2),Creates or assigns a typed value for the steps that follow.
22 new SBQQ__QuoteLine__c(Id=milestoneEarlyId, SBQQ__Quote__c=quoteId, SBQQ__Number__c=1)Creates or assigns a typed value for the steps that follow.
23 };Closes the current block or declaration.
24 Date startDate = Date.newInstance(2026, 11, 18);Creates or assigns a typed value for the steps that follow.
25 Map<Id, SBQQ__QuoteLine__c> result = byId(Creates or assigns a typed value for the steps that follow.
26 QuoteLineBudgetSequenceHandler.buildUpdates(Part of the surrounding declaration or expression; read it with the adjacent lines.
27 input,Continues the argument list or condition on the next line.
28 new Map<Id, Date>{quoteId => startDate},Maps the value on the left to the value on the right.
29 new QuoteLineBudgetSequenceHandler.ExistingLineData(),Continues the argument list or condition on the next line.
30 new Map<String, Integer>{'875' => 1, '885' => 2, '863' => 3},Maps the value on the left to the value on the right.
31 new Map<Id, String>{prepaidId => '875', milestoneEarlyId => '885',Maps the value on the left to the value on the right.
32 milestoneLateId => '885', tmId => '863'}Maps the value on the left to the value on the right.
33 )Opens or closes the expression begun on the surrounding lines.
34 );Opens or closes the expression begun on the surrounding lines.
35 System.assertEquals(4, result.size());Test assertion: fails the test when the expected behavior is absent.
36 System.assertEquals(Decimal.valueOf('1000'), result.get(prepaidId).Budget_Sequence__c);Test assertion: fails the test when the expected behavior is absent.
37 System.assertEquals(startDate, result.get(prepaidId).Budget_Start_Date__c);Test assertion: fails the test when the expected behavior is absent.
38 System.assertEquals(Decimal.valueOf('2000'), result.get(milestoneEarlyId).Budget_Sequence__c);Test assertion: fails the test when the expected behavior is absent.
39 System.assertEquals(startDate.addDays(1), result.get(milestoneEarlyId).Budget_Start_Date__c);Test assertion: fails the test when the expected behavior is absent.
40 System.assertEquals(Decimal.valueOf('2001'), result.get(milestoneLateId).Budget_Sequence__c);Test assertion: fails the test when the expected behavior is absent.
41 System.assertEquals(startDate.addDays(2), result.get(milestoneLateId).Budget_Start_Date__c);Test assertion: fails the test when the expected behavior is absent.
42 System.assertEquals(Decimal.valueOf('3000'), result.get(tmId).Budget_Sequence__c);Test assertion: fails the test when the expected behavior is absent.
43 System.assertEquals(startDate.addDays(3), result.get(tmId).Budget_Start_Date__c);Test assertion: fails the test when the expected behavior is absent.
44 }Closes the current block or declaration.
45 Spacing separates related steps.
46 @IsTestMarks the following class or method as test code.
47 static void usesExistingBlockMaximumAndRecomputesDenseDates() {Method declaration: Tests uses existing block maximum and recomputes dense dates. The parentheses define its inputs; the type before the name defines its return value.
48 Id quoteId = fakeId(SBQQ__Quote__c.SObjectType, '000000000011');Creates or assigns a typed value for the steps that follow.
49 Id oldFirst = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000011');Creates or assigns a typed value for the steps that follow.
50 Id oldSecond = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000012');Creates or assigns a typed value for the steps that follow.
51 Id newPrepaid = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000013');Creates or assigns a typed value for the steps that follow.
52 Id newMilestone = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000014');Creates or assigns a typed value for the steps that follow.
53 QuoteLineBudgetSequenceHandler.ExistingLineData existing =Assigns or configures the value on the left using the expression on the right.
54 new QuoteLineBudgetSequenceHandler.ExistingLineData();Completes the statement begun on this line or the preceding lines.
55 existing.quoteBlockMax.put(quoteId, new Map<Integer, Integer>{2 => 2000});Maps the value on the left to the value on the right.
56 existing.quoteSeqs.put(quoteId, new List<Integer>{2000, 2000});Completes the statement begun on this line or the preceding lines.
57 existing.quoteLineSeqs.put(quoteId,Continues the argument list or condition on the next line.
58 new Map<Id, Integer>{oldFirst => 2000, oldSecond => 2000});Maps the value on the left to the value on the right.
59 Date startDate = Date.newInstance(2026, 12, 1);Creates or assigns a typed value for the steps that follow.
60 Map<Id, SBQQ__QuoteLine__c> result = byId(Creates or assigns a typed value for the steps that follow.
61 QuoteLineBudgetSequenceHandler.buildUpdates(Part of the surrounding declaration or expression; read it with the adjacent lines.
62 new List<SBQQ__QuoteLine__c>{Opens a block; the indented lines below execute or belong together.
63 new SBQQ__QuoteLine__c(Id=newMilestone, SBQQ__Quote__c=quoteId, SBQQ__Number__c=5),Creates or assigns a typed value for the steps that follow.
64 new SBQQ__QuoteLine__c(Id=newPrepaid, SBQQ__Quote__c=quoteId, SBQQ__Number__c=6)Creates or assigns a typed value for the steps that follow.
65 },Continues the argument list or condition on the next line.
66 new Map<Id, Date>{quoteId => startDate}, existing,Maps the value on the left to the value on the right.
67 new Map<String, Integer>{'875' => 1, '885' => 2},Maps the value on the left to the value on the right.
68 new Map<Id, String>{newPrepaid => '875', newMilestone => '885'}Maps the value on the left to the value on the right.
69 )Opens or closes the expression begun on the surrounding lines.
70 );Opens or closes the expression begun on the surrounding lines.
71 System.assertEquals(4, result.size());Test assertion: fails the test when the expected behavior is absent.
72 System.assertEquals(Decimal.valueOf('1000'), result.get(newPrepaid).Budget_Sequence__c);Test assertion: fails the test when the expected behavior is absent.
73 System.assertEquals(startDate, result.get(newPrepaid).Budget_Start_Date__c);Test assertion: fails the test when the expected behavior is absent.
74 System.assertEquals(startDate.addDays(1), result.get(oldFirst).Budget_Start_Date__c);Test assertion: fails the test when the expected behavior is absent.
75 System.assertEquals(startDate.addDays(1), result.get(oldSecond).Budget_Start_Date__c);Test assertion: fails the test when the expected behavior is absent.
76 System.assertEquals(Decimal.valueOf('2001'), result.get(newMilestone).Budget_Sequence__c);Test assertion: fails the test when the expected behavior is absent.
77 System.assertEquals(startDate.addDays(2), result.get(newMilestone).Budget_Start_Date__c);Test assertion: fails the test when the expected behavior is absent.
78 }Closes the current block or declaration.
79 Spacing separates related steps.
80 @IsTestMarks the following class or method as test code.
81 static void emptyConfigurationLeavesLinesUntouched() {Method declaration: Tests empty configuration leaves lines untouched. The parentheses define its inputs; the type before the name defines its return value.
82 QuoteLineBudgetSequenceHandler.productBlockMapOverride = new Map<String, Integer>();Creates or assigns a typed value for the steps that follow.
83 QuoteLineBudgetSequenceHandler.assignSequences(new List<SBQQ__QuoteLine__c>());Completes the statement begun on this line or the preceding lines.
84 System.assertEquals(0, Limits.getDmlStatements());Test assertion: fails the test when the expected behavior is absent.
85 }Closes the current block or declaration.
86 Spacing separates related steps.
87 @IsTestMarks the following class or method as test code.
88 static void insertTriggerAssignsDateAndLaterManualSequenceRemains() {Method declaration: Tests insert trigger assigns date and later manual sequence remains. The parentheses define its inputs; the type before the name defines its return value.
89 Opportunity opportunityRecord = PsQuoteTestData.opportunity();Assigns or configures the value on the left using the expression on the right.
90 Id standardBookId = Test.getStandardPricebookId();Creates or assigns a typed value for the steps that follow.
91 update new Pricebook2(Id=standardBookId, IsActive=true);DML write: saves changes to the specified Salesforce record or records.
92 Product2 product = new Product2(Creates or assigns a typed value for the steps that follow.
93 Name='Budget sequence test product', ProductCode='875', IsActive=trueAssigns or configures the value on the left using the expression on the right.
94 );Opens or closes the expression begun on the surrounding lines.
95 insert product;DML write: creates the specified Salesforce record or records.
96 insert new PricebookEntry(DML write: creates the specified Salesforce record or records.
97 Pricebook2Id=standardBookId, Product2Id=product.Id,Creates or assigns a typed value for the steps that follow.
98 UnitPrice=100, IsActive=trueAssigns or configures the value on the left using the expression on the right.
99 );Opens or closes the expression begun on the surrounding lines.
100 Date quoteStart = Date.today().addDays(7);Creates or assigns a typed value for the steps that follow.
101 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(Creates or assigns a typed value for the steps that follow.
102 SBQQ__Opportunity2__c=opportunityRecord.Id,Creates or assigns a typed value for the steps that follow.
103 SBQQ__Account__c=opportunityRecord.AccountId,Assigns or configures the value on the left using the expression on the right.
104 SBQQ__PricebookId__c=standardBookId,Assigns or configures the value on the left using the expression on the right.
105 SBQQ__StartDate__c=quoteStartAssigns or configures the value on the left using the expression on the right.
106 );Opens or closes the expression begun on the surrounding lines.
107 insert quoteRecord;DML write: creates the specified Salesforce record or records.
108 QuoteLineBudgetSequenceHandler.productBlockMapOverride =Assigns or configures the value on the left using the expression on the right.
109 new Map<String, Integer>{'875' => 1};Maps the value on the left to the value on the right.
110 SBQQ__QuoteLine__c line = new SBQQ__QuoteLine__c(Creates or assigns a typed value for the steps that follow.
111 SBQQ__Quote__c=quoteRecord.Id,Creates or assigns a typed value for the steps that follow.
112 SBQQ__Product__c=product.Id,Creates or assigns a typed value for the steps that follow.
113 SBQQ__Quantity__c=1,Assigns or configures the value on the left using the expression on the right.
114 SBQQ__ListPrice__c=100Assigns or configures the value on the left using the expression on the right.
115 );Opens or closes the expression begun on the surrounding lines.
116 insert line;DML write: creates the specified Salesforce record or records.
117 SBQQ__QuoteLine__c saved = [Assigns or configures the value on the left using the expression on the right.
118 SELECT Budget_Sequence__c, Budget_Start_Date__cSOQL field list: identifies data to read from Salesforce.
119 FROM SBQQ__QuoteLine__c WHERE Id=:line.IdSOQL source: identifies which Salesforce object to read.
120 ];Completes the statement begun on this line or the preceding lines.
121 System.assertEquals(Decimal.valueOf('1000'), saved.Budget_Sequence__c);Test assertion: fails the test when the expected behavior is absent.
122 System.assertEquals(quoteStart, saved.Budget_Start_Date__c);Test assertion: fails the test when the expected behavior is absent.
123 update new SBQQ__QuoteLine__c(Id=line.Id, Budget_Sequence__c=1500);DML write: saves changes to the specified Salesforce record or records.
124 System.assertEquals(Decimal.valueOf('1500'),Test assertion: fails the test when the expected behavior is absent.
125 [SELECT Budget_Sequence__c FROM SBQQ__QuoteLine__cPart of the surrounding declaration or expression; read it with the adjacent lines.
126 WHERE Id=:line.Id].Budget_Sequence__c);SOQL filter: narrows the records returned by this query.
127 }Closes the current block or declaration.
128}Closes the current block or declaration.
View complete source code
1@IsTest
2private class QuoteLineBudgetSequenceHandlerTest {
3 private static Id fakeId(Schema.SObjectType objectType, String suffix) {
4 return (Id) (objectType.getDescribe().getKeyPrefix() + suffix);
5 }
6
7 private static Map<Id, SBQQ__QuoteLine__c> byId(List<SBQQ__QuoteLine__c> lines) {
8 return new Map<Id, SBQQ__QuoteLine__c>(lines);
9 }
10
11 @IsTest
12 static void ordersBlocksAndLineNumbersFromQuoteStartDate() {
13 Id quoteId = fakeId(SBQQ__Quote__c.SObjectType, '000000000001');
14 Id prepaidId = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000001');
15 Id milestoneEarlyId = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000002');
16 Id milestoneLateId = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000003');
17 Id tmId = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000004');
18 List<SBQQ__QuoteLine__c> input = new List<SBQQ__QuoteLine__c>{
19 new SBQQ__QuoteLine__c(Id=tmId, SBQQ__Quote__c=quoteId, SBQQ__Number__c=4),
20 new SBQQ__QuoteLine__c(Id=milestoneLateId, SBQQ__Quote__c=quoteId, SBQQ__Number__c=3),
21 new SBQQ__QuoteLine__c(Id=prepaidId, SBQQ__Quote__c=quoteId, SBQQ__Number__c=2),
22 new SBQQ__QuoteLine__c(Id=milestoneEarlyId, SBQQ__Quote__c=quoteId, SBQQ__Number__c=1)
23 };
24 Date startDate = Date.newInstance(2026, 11, 18);
25 Map<Id, SBQQ__QuoteLine__c> result = byId(
26 QuoteLineBudgetSequenceHandler.buildUpdates(
27 input,
28 new Map<Id, Date>{quoteId => startDate},
29 new QuoteLineBudgetSequenceHandler.ExistingLineData(),
30 new Map<String, Integer>{'875' => 1, '885' => 2, '863' => 3},
31 new Map<Id, String>{prepaidId => '875', milestoneEarlyId => '885',
32 milestoneLateId => '885', tmId => '863'}
33 )
34 );
35 System.assertEquals(4, result.size());
36 System.assertEquals(Decimal.valueOf('1000'), result.get(prepaidId).Budget_Sequence__c);
37 System.assertEquals(startDate, result.get(prepaidId).Budget_Start_Date__c);
38 System.assertEquals(Decimal.valueOf('2000'), result.get(milestoneEarlyId).Budget_Sequence__c);
39 System.assertEquals(startDate.addDays(1), result.get(milestoneEarlyId).Budget_Start_Date__c);
40 System.assertEquals(Decimal.valueOf('2001'), result.get(milestoneLateId).Budget_Sequence__c);
41 System.assertEquals(startDate.addDays(2), result.get(milestoneLateId).Budget_Start_Date__c);
42 System.assertEquals(Decimal.valueOf('3000'), result.get(tmId).Budget_Sequence__c);
43 System.assertEquals(startDate.addDays(3), result.get(tmId).Budget_Start_Date__c);
44 }
45
46 @IsTest
47 static void usesExistingBlockMaximumAndRecomputesDenseDates() {
48 Id quoteId = fakeId(SBQQ__Quote__c.SObjectType, '000000000011');
49 Id oldFirst = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000011');
50 Id oldSecond = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000012');
51 Id newPrepaid = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000013');
52 Id newMilestone = fakeId(SBQQ__QuoteLine__c.SObjectType, '000000000014');
53 QuoteLineBudgetSequenceHandler.ExistingLineData existing =
54 new QuoteLineBudgetSequenceHandler.ExistingLineData();
55 existing.quoteBlockMax.put(quoteId, new Map<Integer, Integer>{2 => 2000});
56 existing.quoteSeqs.put(quoteId, new List<Integer>{2000, 2000});
57 existing.quoteLineSeqs.put(quoteId,
58 new Map<Id, Integer>{oldFirst => 2000, oldSecond => 2000});
59 Date startDate = Date.newInstance(2026, 12, 1);
60 Map<Id, SBQQ__QuoteLine__c> result = byId(
61 QuoteLineBudgetSequenceHandler.buildUpdates(
62 new List<SBQQ__QuoteLine__c>{
63 new SBQQ__QuoteLine__c(Id=newMilestone, SBQQ__Quote__c=quoteId, SBQQ__Number__c=5),
64 new SBQQ__QuoteLine__c(Id=newPrepaid, SBQQ__Quote__c=quoteId, SBQQ__Number__c=6)
65 },
66 new Map<Id, Date>{quoteId => startDate}, existing,
67 new Map<String, Integer>{'875' => 1, '885' => 2},
68 new Map<Id, String>{newPrepaid => '875', newMilestone => '885'}
69 )
70 );
71 System.assertEquals(4, result.size());
72 System.assertEquals(Decimal.valueOf('1000'), result.get(newPrepaid).Budget_Sequence__c);
73 System.assertEquals(startDate, result.get(newPrepaid).Budget_Start_Date__c);
74 System.assertEquals(startDate.addDays(1), result.get(oldFirst).Budget_Start_Date__c);
75 System.assertEquals(startDate.addDays(1), result.get(oldSecond).Budget_Start_Date__c);
76 System.assertEquals(Decimal.valueOf('2001'), result.get(newMilestone).Budget_Sequence__c);
77 System.assertEquals(startDate.addDays(2), result.get(newMilestone).Budget_Start_Date__c);
78 }
79
80 @IsTest
81 static void emptyConfigurationLeavesLinesUntouched() {
82 QuoteLineBudgetSequenceHandler.productBlockMapOverride = new Map<String, Integer>();
83 QuoteLineBudgetSequenceHandler.assignSequences(new List<SBQQ__QuoteLine__c>());
84 System.assertEquals(0, Limits.getDmlStatements());
85 }
86
87 @IsTest
88 static void insertTriggerAssignsDateAndLaterManualSequenceRemains() {
89 Opportunity opportunityRecord = PsQuoteTestData.opportunity();
90 Id standardBookId = Test.getStandardPricebookId();
91 update new Pricebook2(Id=standardBookId, IsActive=true);
92 Product2 product = new Product2(
93 Name='Budget sequence test product', ProductCode='875', IsActive=true
94 );
95 insert product;
96 insert new PricebookEntry(
97 Pricebook2Id=standardBookId, Product2Id=product.Id,
98 UnitPrice=100, IsActive=true
99 );
100 Date quoteStart = Date.today().addDays(7);
101 SBQQ__Quote__c quoteRecord = new SBQQ__Quote__c(
102 SBQQ__Opportunity2__c=opportunityRecord.Id,
103 SBQQ__Account__c=opportunityRecord.AccountId,
104 SBQQ__PricebookId__c=standardBookId,
105 SBQQ__StartDate__c=quoteStart
106 );
107 insert quoteRecord;
108 QuoteLineBudgetSequenceHandler.productBlockMapOverride =
109 new Map<String, Integer>{'875' => 1};
110 SBQQ__QuoteLine__c line = new SBQQ__QuoteLine__c(
111 SBQQ__Quote__c=quoteRecord.Id,
112 SBQQ__Product__c=product.Id,
113 SBQQ__Quantity__c=1,
114 SBQQ__ListPrice__c=100
115 );
116 insert line;
117 SBQQ__QuoteLine__c saved = [
118 SELECT Budget_Sequence__c, Budget_Start_Date__c
119 FROM SBQQ__QuoteLine__c WHERE Id=:line.Id
120 ];
121 System.assertEquals(Decimal.valueOf('1000'), saved.Budget_Sequence__c);
122 System.assertEquals(quoteStart, saved.Budget_Start_Date__c);
123 update new SBQQ__QuoteLine__c(Id=line.Id, Budget_Sequence__c=1500);
124 System.assertEquals(Decimal.valueOf('1500'),
125 [SELECT Budget_Sequence__c FROM SBQQ__QuoteLine__c
126 WHERE Id=:line.Id].Budget_Sequence__c);
127 }
128}
test · 62 lines

PsQuoteTestData

Shared test fixture that creates an Opportunity, a linked PDF, and an analysis record.

This is the newer local test source. Recent additions still need a Salesforce test run.

Review and understand complete source code

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@IsTestMarks the following class or method as test code.
2public class PsQuoteTestData {Declares a class or trigger. The braces contain its members and behavior.
3 public static Opportunity opportunity() {Opens a block; the indented lines below execute or belong together.
4 Account account = new Account(Name = 'PS quote test account');Creates or assigns a typed value for the steps that follow.
5 insert account;DML write: creates the specified Salesforce record or records.
6 String stage;Completes the statement begun on this line or the preceding lines.
7 for (Schema.PicklistEntry value : Opportunity.StageName.getDescribe().getPicklistValues()) {Loop: repeats the following block for each matching item.
8 if (value.isActive()) {Guard or branch: the following block runs only when this condition is true.
9 stage = value.getValue();Assigns or configures the value on the left using the expression on the right.
10 break;Completes the statement begun on this line or the preceding lines.
11 }Closes the current block or declaration.
12 }Closes the current block or declaration.
13 System.assertNotEquals(null, stage, 'The org needs an active Opportunity stage.');Test assertion: fails the test when the expected behavior is absent.
14 Opportunity result = new Opportunity(Creates or assigns a typed value for the steps that follow.
15 Name = 'PS quote test', AccountId = account.Id,Creates or assigns a typed value for the steps that follow.
16 StageName = stage, CloseDate = Date.today().addDays(30)Creates or assigns a typed value for the steps that follow.
17 );Opens or closes the expression begun on the surrounding lines.
18 List<RecordType> services = [Creates or assigns a typed value for the steps that follow.
19 SELECT Id FROM RecordTypeSOQL field list: identifies data to read from Salesforce.
20 WHERE SObjectType = 'Opportunity' AND DeveloperName = 'Services'SOQL filter: narrows the records returned by this query.
21 AND IsActive = true LIMIT 1SOQL filter: narrows the records returned by this query.
22 ];Completes the statement begun on this line or the preceding lines.
23 if (!services.isEmpty()) result.RecordTypeId = services[0].Id;Guard or branch: the following block runs only when this condition is true.
24 insert result;DML write: creates the specified Salesforce record or records.
25 return result;Returns this value to the caller and ends the method.
26 }Closes the current block or declaration.
27 Spacing separates related steps.
28 public static Id pdfOnOpportunity(Id opportunityId) {Opens a block; the indented lines below execute or belong together.
29 ContentVersion version = new ContentVersion(Creates or assigns a typed value for the steps that follow.
30 Title = 'Signed SOW', PathOnClient = 'signed.pdf',Assigns or configures the value on the left using the expression on the right.
31 VersionData = Blob.valueOf('%PDF-1.4\n%%EOF'),Assigns or configures the value on the left using the expression on the right.
32 FirstPublishLocationId = opportunityIdAssigns or configures the value on the left using the expression on the right.
33 );Opens or closes the expression begun on the surrounding lines.
34 insert version;DML write: creates the specified Salesforce record or records.
35 return [SELECT ContentDocumentId FROM ContentVersionReturns this value to the caller and ends the method.
36 WHERE Id = :version.Id LIMIT 1].ContentDocumentId;SOQL filter: narrows the records returned by this query.
37 }Closes the current block or declaration.
38 Spacing separates related steps.
39 public static PS_Quote_Analysis__c analysis(Part of the surrounding declaration or expression; read it with the adjacent lines.
40 Id opportunityId, String status, String quoteTypePart of the surrounding declaration or expression; read it with the adjacent lines.
41 ) {Opens a block; the indented lines below execute or belong together.
42 Id documentId = pdfOnOpportunity(opportunityId);Creates or assigns a typed value for the steps that follow.
43 Id versionId = [SELECT LatestPublishedVersionId FROM ContentDocumentCreates or assigns a typed value for the steps that follow.
44 WHERE Id = :documentId LIMIT 1].LatestPublishedVersionId;SOQL filter: narrows the records returned by this query.
45 String currencyCode = [SELECT CurrencyIsoCode FROM OpportunityCreates or assigns a typed value for the steps that follow.
46 WHERE Id = :opportunityId LIMIT 1].CurrencyIsoCode;SOQL filter: narrows the records returned by this query.
47 String proposal = '{"currency_code":"' + currencyCode + '",' +Creates or assigns a typed value for the steps that follow.
48 '"quote_total":25,"lines":[{"category":"MILESTONE",' +Part of the surrounding declaration or expression; read it with the adjacent lines.
49 '"label":"Design","amount":25}]}';Completes the statement begun on this line or the preceding lines.
50 PS_Quote_Analysis__c result = new PS_Quote_Analysis__c(Creates or assigns a typed value for the steps that follow.
51 Opportunity__c = opportunityId,Assigns or configures the value on the left using the expression on the right.
52 Status__c = status,Assigns or configures the value on the left using the expression on the right.
53 Quote_Type__c = quoteType,Assigns or configures the value on the left using the expression on the right.
54 Content_Document_Id__c = String.valueOf(documentId),Creates or assigns a typed value for the steps that follow.
55 Content_Version_Id__c = String.valueOf(versionId)Creates or assigns a typed value for the steps that follow.
56 );Opens or closes the expression begun on the surrounding lines.
57 if (status == 'Needs Review') result.AI_Proposal_JSON__c = proposal;Guard or branch: the following block runs only when this condition is true.
58 if (status == 'Confirmed') result.Reviewed_Proposal_JSON__c = proposal;Guard or branch: the following block runs only when this condition is true.
59 insert result;DML write: creates the specified Salesforce record or records.
60 return result;Returns this value to the caller and ends the method.
61 }Closes the current block or declaration.
62}Closes the current block or declaration.
View complete source code
1@IsTest
2public class PsQuoteTestData {
3 public static Opportunity opportunity() {
4 Account account = new Account(Name = 'PS quote test account');
5 insert account;
6 String stage;
7 for (Schema.PicklistEntry value : Opportunity.StageName.getDescribe().getPicklistValues()) {
8 if (value.isActive()) {
9 stage = value.getValue();
10 break;
11 }
12 }
13 System.assertNotEquals(null, stage, 'The org needs an active Opportunity stage.');
14 Opportunity result = new Opportunity(
15 Name = 'PS quote test', AccountId = account.Id,
16 StageName = stage, CloseDate = Date.today().addDays(30)
17 );
18 List<RecordType> services = [
19 SELECT Id FROM RecordType
20 WHERE SObjectType = 'Opportunity' AND DeveloperName = 'Services'
21 AND IsActive = true LIMIT 1
22 ];
23 if (!services.isEmpty()) result.RecordTypeId = services[0].Id;
24 insert result;
25 return result;
26 }
27
28 public static Id pdfOnOpportunity(Id opportunityId) {
29 ContentVersion version = new ContentVersion(
30 Title = 'Signed SOW', PathOnClient = 'signed.pdf',
31 VersionData = Blob.valueOf('%PDF-1.4\n%%EOF'),
32 FirstPublishLocationId = opportunityId
33 );
34 insert version;
35 return [SELECT ContentDocumentId FROM ContentVersion
36 WHERE Id = :version.Id LIMIT 1].ContentDocumentId;
37 }
38
39 public static PS_Quote_Analysis__c analysis(
40 Id opportunityId, String status, String quoteType
41 ) {
42 Id documentId = pdfOnOpportunity(opportunityId);
43 Id versionId = [SELECT LatestPublishedVersionId FROM ContentDocument
44 WHERE Id = :documentId LIMIT 1].LatestPublishedVersionId;
45 String currencyCode = [SELECT CurrencyIsoCode FROM Opportunity
46 WHERE Id = :opportunityId LIMIT 1].CurrencyIsoCode;
47 String proposal = '{"currency_code":"' + currencyCode + '",' +
48 '"quote_total":25,"lines":[{"category":"MILESTONE",' +
49 '"label":"Design","amount":25}]}';
50 PS_Quote_Analysis__c result = new PS_Quote_Analysis__c(
51 Opportunity__c = opportunityId,
52 Status__c = status,
53 Quote_Type__c = quoteType,
54 Content_Document_Id__c = String.valueOf(documentId),
55 Content_Version_Id__c = String.valueOf(versionId)
56 );
57 if (status == 'Needs Review') result.AI_Proposal_JSON__c = proposal;
58 if (status == 'Confirmed') result.Reviewed_Proposal_JSON__c = proposal;
59 insert result;
60 return result;
61 }
62}

Lightning components

JavaScript

@api recordId receives the Opportunity. Getters calculate labels and button states. Handlers call Apex and update state. async/await waits without freezing the page.

HTML

The template places controls and panels, displays JavaScript values, and binds clicks and changes to handlers.

CSS

Selectors such as .status-panel--error change the look of a state. @media stacks rows on narrower screens. CSS never saves data.

lightning · 549 lines

psQuoteAnalyzerTools.js

The component’s behavior: state, Apex calls, review editing, status polling, and user action handlers.

Review and understand complete source code

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.

1import { LightningElement, api, wire } from 'lwc';Imports a framework feature or an Apex method used by this JavaScript file.
2import { getRecord, getFieldValue } from 'lightning/uiRecordApi';Imports a framework feature or an Apex method used by this JavaScript file.
3import { ShowToastEvent } from 'lightning/platformShowToastEvent';Imports a framework feature or an Apex method used by this JavaScript file.
4import OPPORTUNITY_ACCOUNT_ID from '@salesforce/schema/Opportunity.AccountId';Imports a framework feature or an Apex method used by this JavaScript file.
5import startAnalysis from '@salesforce/apex/PsQuoteAnalyzerController.startAnalysis';Imports a framework feature or an Apex method used by this JavaScript file.
6import getLatestAnalysis from '@salesforce/apex/PsQuoteAnalysisReviewController.getLatestAnalysis';Imports a framework feature or an Apex method used by this JavaScript file.
7import confirmBreakdown from '@salesforce/apex/PsQuoteAnalysisReviewController.confirmBreakdown';Imports a framework feature or an Apex method used by this JavaScript file.
8import createQuote from '@salesforce/apex/PsQuoteCpqController.createQuote';Imports a framework feature or an Apex method used by this JavaScript file.
9import useNativeAmendmentQuote from '@salesforce/apex/PsQuoteCpqController.useNativeAmendmentQuote';Imports a framework feature or an Apex method used by this JavaScript file.
10import getPrimaryAmendmentQuote from '@salesforce/apex/PsQuoteCpqController.getPrimaryAmendmentQuote';Imports a framework feature or an Apex method used by this JavaScript file.
11 Spacing separates related steps.
12const OPPORTUNITY_FIELDS = [OPPORTUNITY_ACCOUNT_ID];Declares a JavaScript value used by this component or method.
13 Spacing separates related steps.
14export default class PsQuoteAnalyzerTools extends LightningElement {Declares the Lightning component class and the behavior it contains.
15 @api recordId;Exposes this JavaScript property or method to the component’s parent.
16 Spacing separates related steps.
17 quoteType = 'new';Creates or assigns a typed value for the steps that follow.
18 accountId;Completes the statement begun on this line or the preceding lines.
19 effectiveDate;Completes the statement begun on this line or the preceding lines.
20 uploadedFileName;Completes the statement begun on this line or the preceding lines.
21 contentDocumentId;Completes the statement begun on this line or the preceding lines.
22 loadError;Completes the statement begun on this line or the preceding lines.
23 analysisId;Completes the statement begun on this line or the preceding lines.
24 analysisStatus;Completes the statement begun on this line or the preceding lines.
25 proposalCurrency;Completes the statement begun on this line or the preceding lines.
26 proposalTotal;Completes the statement begun on this line or the preceding lines.
27 proposalReviewReason;Completes the statement begun on this line or the preceding lines.
28 reviewLines = [];Assigns or configures the value on the left using the expression on the right.
29 confirmedLines = [];Assigns or configures the value on the left using the expression on the right.
30 confirmedQuoteType;Completes the statement begun on this line or the preceding lines.
31 quoteStartDate;Completes the statement begun on this line or the preceding lines.
32 createdQuoteId;Completes the statement begun on this line or the preceding lines.
33 quoteCreationStatus;Completes the statement begun on this line or the preceding lines.
34 quoteCreationError;Completes the statement begun on this line or the preceding lines.
35 primaryAmendmentQuoteId;Completes the statement begun on this line or the preceding lines.
36 primaryAmendmentQuoteName;Completes the statement begun on this line or the preceding lines.
37 primaryAmendmentContractId;Completes the statement begun on this line or the preceding lines.
38 primaryAmendmentContractName;Completes the statement begun on this line or the preceding lines.
39 primaryAmendmentStartDate;Completes the statement begun on this line or the preceding lines.
40 isCreatingQuote = false;Assigns or configures the value on the left using the expression on the right.
41 nextRowKey = 0;Assigns or configures the value on the left using the expression on the right.
42 hasCurrentUploadQueued = false;Assigns or configures the value on the left using the expression on the right.
43 isLoadingAnalysis = false;Assigns or configures the value on the left using the expression on the right.
44 isSavingReview = false;Assigns or configures the value on the left using the expression on the right.
45 isSubmitting = false;Assigns or configures the value on the left using the expression on the right.
46 isComponentActive = false;Assigns or configures the value on the left using the expression on the right.
47 pollTimer;Completes the statement begun on this line or the preceding lines.
48 handleWindowFocus = () => {Maps the value on the left to the value on the right.
49 if (this.isComponentActive && (this.isWorking || this.isQuoteWorking)) {Guard or branch: the following block runs only when this condition is true.
50 this.refreshAnalysis();Calls refreshAnalysis(): Fetch latest status and turn JSON into display rows.
51 }Closes the current block or declaration.
52 };Closes the current block or declaration.
53 Spacing separates related steps.
54 acceptedFormats = ['.pdf'];Assigns or configures the value on the left using the expression on the right.
55 quoteTypeOptions = [Assigns or configures the value on the left using the expression on the right.
56 { label: 'New services', value: 'new' },Continues the argument list or condition on the next line.
57 { label: 'Change order / amend contract', value: 'amendment' }Closes the current block after this expression.
58 ];Completes the statement begun on this line or the preceding lines.
59 categoryOptions = [Assigns or configures the value on the left using the expression on the right.
60 { label: 'Time & Material', value: 'TIME_MATERIAL' },Continues the argument list or condition on the next line.
61 { label: 'Time & Material — Prepaid', value: 'PREPAID_TIME_MATERIAL' },Continues the argument list or condition on the next line.
62 { label: 'Milestone', value: 'MILESTONE' },Continues the argument list or condition on the next line.
63 { label: 'Milestone — Time & Material', value: 'MILESTONE_TIME_MATERIAL' }Closes the current block after this expression.
64 ];Completes the statement begun on this line or the preceding lines.
65 @wire(getRecord, { recordId: '$recordId', fields: OPPORTUNITY_FIELDS })Wires data from Salesforce into this component.
66 async loadOpportunity({ data, error }) {Method declaration: Read Opportunity data and refresh the analysis. The parentheses define its inputs; the type before the name defines its return value.
67 if (data) {Guard or branch: the following block runs only when this condition is true.
68 this.accountId = getFieldValue(data, OPPORTUNITY_ACCOUNT_ID);Updates component state; the template may show the new value on rerender.
69 this.loadError = undefined;Updates component state; the template may show the new value on rerender.
70 await this.refreshAnalysis();Calls refreshAnalysis(): Fetch latest status and turn JSON into display rows.
71 await this.loadPrimaryAmendmentQuote();Waits for this asynchronous JavaScript operation to complete.
72 } else if (error) {Opens a block; the indented lines below execute or belong together.
73 this.accountId = undefined;Updates component state; the template may show the new value on rerender.
74 this.loadError = 'Unable to read the Opportunity account.';Updates component state; the template may show the new value on rerender.
75 }Closes the current block or declaration.
76 }Closes the current block or declaration.
77 Spacing separates related steps.
78 connectedCallback() {Calls connectedCallback(): Start listeners and polling when shown.
79 this.isComponentActive = true;Updates component state; the template may show the new value on rerender.
80 window.addEventListener('focus', this.handleWindowFocus);Completes the statement begun on this line or the preceding lines.
81 this.syncPolling();Calls syncPolling(): Refresh every five seconds while work is in progress.
82 }Closes the current block or declaration.
83 Spacing separates related steps.
84 disconnectedCallback() {Calls disconnectedCallback(): Clean them up when removed.
85 this.isComponentActive = false;Updates component state; the template may show the new value on rerender.
86 window.removeEventListener('focus', this.handleWindowFocus);Completes the statement begun on this line or the preceding lines.
87 this.stopPolling();Completes the statement begun on this line or the preceding lines.
88 }Closes the current block or declaration.
89 Spacing separates related steps.
90 get isAmendment() {Opens a block; the indented lines below execute or belong together.
91 return this.quoteType === 'amendment';Returns this value to the caller and ends the method.
92 }Closes the current block or declaration.
93 Spacing separates related steps.
94 get uploadLabel() {Opens a block; the indented lines below execute or belong together.
95 return this.isAmendment ? 'Upload signed change order (PDF)' : 'Upload signed SOW (PDF)';Returns this value to the caller and ends the method.
96 }Closes the current block or declaration.
97 Spacing separates related steps.
98 get isStartDisabled() {Opens a block; the indented lines below execute or belong together.
99 return !this.recordId || !this.contentDocumentId || this.isSubmitting ||Returns this value to the caller and ends the method.
100 this.hasCurrentUploadQueued ||Continues the argument list or condition on the next line.
101 (this.isAmendment && (!this.primaryAmendmentQuoteId || !this.effectiveDate));Completes the statement begun on this line or the preceding lines.
102 }Closes the current block or declaration.
103 Spacing separates related steps.
104 get canReview() {Opens a block; the indented lines below execute or belong together.
105 return this.analysisStatus === 'Needs Review' && Boolean(this.analysisId);Returns this value to the caller and ends the method.
106 }Closes the current block or declaration.
107 Spacing separates related steps.
108 get isConfirmed() {Opens a block; the indented lines below execute or belong together.
109 return this.analysisStatus === 'Confirmed' && this.confirmedLines.length > 0;Returns this value to the caller and ends the method.
110 }Closes the current block or declaration.
111 Spacing separates related steps.
112 get isConfirmedNewServices() {Opens a block; the indented lines below execute or belong together.
113 return this.isConfirmed && this.confirmedQuoteType === 'New Services';Returns this value to the caller and ends the method.
114 }Closes the current block or declaration.
115 Spacing separates related steps.
116 get isConfirmedAmendment() {Opens a block; the indented lines below execute or belong together.
117 return this.isConfirmed && this.confirmedQuoteType === 'Change Order';Returns this value to the caller and ends the method.
118 }Closes the current block or declaration.
119 Spacing separates related steps.
120 get canCreateQuote() {Opens a block; the indented lines below execute or belong together.
121 return this.isConfirmedNewServices && !this.createdQuoteId &&Returns this value to the caller and ends the method.
122 (!this.quoteCreationStatus || this.quoteCreationStatus === 'Failed');Assigns or configures the value on the left using the expression on the right.
123 }Closes the current block or declaration.
124 Spacing separates related steps.
125 get isUseNativeAmendmentDisabled() {Opens a block; the indented lines below execute or belong together.
126 return !this.primaryAmendmentQuoteId || this.createdQuoteId || this.isCreatingQuote ||Returns this value to the caller and ends the method.
127 ['Queued', 'Adding Lines'].includes(this.quoteCreationStatus);Completes the statement begun on this line or the preceding lines.
128 }Closes the current block or declaration.
129 Spacing separates related steps.
130 get hasPrimaryAmendmentQuote() {Opens a block; the indented lines below execute or belong together.
131 return Boolean(this.primaryAmendmentQuoteId);Returns this value to the caller and ends the method.
132 }Closes the current block or declaration.
133 Spacing separates related steps.
134 get primaryAmendmentQuoteUrl() {Opens a block; the indented lines below execute or belong together.
135 return this.primaryAmendmentQuoteIdReturns this value to the caller and ends the method.
136 ? `/lightning/r/SBQQ__Quote__c/${this.primaryAmendmentQuoteId}/view`Part of the surrounding declaration or expression; read it with the adjacent lines.
137 : undefined;Completes the statement begun on this line or the preceding lines.
138 }Closes the current block or declaration.
139 Spacing separates related steps.
140 get primaryAmendmentContractUrl() {Opens a block; the indented lines below execute or belong together.
141 return this.primaryAmendmentContractIdReturns this value to the caller and ends the method.
142 ? `/lightning/r/Contract/${this.primaryAmendmentContractId}/view`Part of the surrounding declaration or expression; read it with the adjacent lines.
143 : undefined;Completes the statement begun on this line or the preceding lines.
144 }Closes the current block or declaration.
145 Spacing separates related steps.
146 async loadPrimaryAmendmentQuote() {Declares an asynchronous method that can use await.
147 if (!this.recordId) return;Guard or branch: the following block runs only when this condition is true.
148 try {Starts an operation whose exception can be handled below.
149 const primary = await getPrimaryAmendmentQuote({ opportunityId: this.recordId });Declares a JavaScript value used by this component or method.
150 this.primaryAmendmentQuoteId = primary?.quoteId;Updates component state; the template may show the new value on rerender.
151 this.primaryAmendmentQuoteName = primary?.quoteName;Updates component state; the template may show the new value on rerender.
152 this.primaryAmendmentContractId = primary?.contractId;Updates component state; the template may show the new value on rerender.
153 this.primaryAmendmentContractName = primary?.contractName;Updates component state; the template may show the new value on rerender.
154 this.primaryAmendmentStartDate = primary?.startDate;Updates component state; the template may show the new value on rerender.
155 if (primary && !this.analysisId && !this.contentDocumentId) {Guard or branch: the following block runs only when this condition is true.
156 this.quoteType = 'amendment';Updates component state; the template may show the new value on rerender.
157 }Closes the current block or declaration.
158 if (primary && !this.effectiveDate) this.effectiveDate = primary.startDate;Guard or branch: the following block runs only when this condition is true.
159 } catch (error) {Opens a block; the indented lines below execute or belong together.
160 this.loadError = error?.body?.message || error?.message ||Updates component state; the template may show the new value on rerender.
161 'Could not find the primary amendment quote.';Completes the statement begun on this line or the preceding lines.
162 }Closes the current block or declaration.
163 }Closes the current block or declaration.
164 Spacing separates related steps.
165 get isCreateQuoteDisabled() {Opens a block; the indented lines below execute or belong together.
166 return this.isCreatingQuote || (this.isConfirmedNewServices && !this.quoteStartDate);Returns this value to the caller and ends the method.
167 }Closes the current block or declaration.
168 Spacing separates related steps.
169 get isQuoteWorking() {Opens a block; the indented lines below execute or belong together.
170 return ['Queued', 'Adding Lines', 'Calculating'].includes(this.quoteCreationStatus);Returns this value to the caller and ends the method.
171 }Closes the current block or declaration.
172 Spacing separates related steps.
173 get quoteUrl() {Opens a block; the indented lines below execute or belong together.
174 return this.createdQuoteIdReturns this value to the caller and ends the method.
175 ? `/lightning/r/SBQQ__Quote__c/${this.createdQuoteId}/view`Part of the surrounding declaration or expression; read it with the adjacent lines.
176 : undefined;Completes the statement begun on this line or the preceding lines.
177 }Closes the current block or declaration.
178 Spacing separates related steps.
179 get quoteStatusTitle() {Opens a block; the indented lines below execute or belong together.
180 if (this.quoteCreationStatus === 'Queued') return 'Quote request queued';Guard or branch: the following block runs only when this condition is true.
181 if (this.quoteCreationStatus === 'Adding Lines') return 'Adding approved lines';Guard or branch: the following block runs only when this condition is true.
182 if (this.quoteCreationStatus === 'Calculating') return 'Calculating quote';Guard or branch: the following block runs only when this condition is true.
183 if (this.quoteCreationStatus === 'Ready') return 'CPQ quote ready';Guard or branch: the following block runs only when this condition is true.
184 if (this.quoteCreationStatus === 'Failed') return 'Quote creation needs attention';Guard or branch: the following block runs only when this condition is true.
185 return this.isConfirmedAmendment ? 'Add approved lines to the amendment quote' :Returns this value to the caller and ends the method.
186 'Ready to create a CPQ quote';Completes the statement begun on this line or the preceding lines.
187 }Closes the current block or declaration.
188 Spacing separates related steps.
189 get isWorking() {Opens a block; the indented lines below execute or belong together.
190 return Boolean(this.analysisId) &&Returns this value to the caller and ends the method.
191 !['needs review', 'confirmed', 'failed', 'error'].includes(Part of the surrounding declaration or expression; read it with the adjacent lines.
192 (this.analysisStatus || '').toLowerCase()Part of the surrounding declaration or expression; read it with the adjacent lines.
193 );Opens or closes the expression begun on the surrounding lines.
194 }Closes the current block or declaration.
195 Spacing separates related steps.
196 get statusTitle() {Opens a block; the indented lines below execute or belong together.
197 const status = (this.analysisStatus || '').toLowerCase();Declares a JavaScript value used by this component or method.
198 if (!this.analysisId) return 'Ready to start';Guard or branch: the following block runs only when this condition is true.
199 if (status === 'queued') return 'Waiting in queue';Guard or branch: the following block runs only when this condition is true.
200 if (status === 'needs review') return 'Ready for your review';Guard or branch: the following block runs only when this condition is true.
201 if (status === 'confirmed') return 'Breakdown confirmed';Guard or branch: the following block runs only when this condition is true.
202 if (status === 'failed' || status === 'error') return 'Analysis needs attention';Guard or branch: the following block runs only when this condition is true.
203 return 'Analyzing the document';Returns this value to the caller and ends the method.
204 }Closes the current block or declaration.
205 Spacing separates related steps.
206 get statusDescription() {Opens a block; the indented lines below execute or belong together.
207 const status = (this.analysisStatus || '').toLowerCase();Declares a JavaScript value used by this component or method.
208 if (!this.analysisId) return 'Upload a signed PDF and start an analysis.';Guard or branch: the following block runs only when this condition is true.
209 if (status === 'queued') return 'The request was sent to Workato. Analysis will begin shortly.';Guard or branch: the following block runs only when this condition is true.
210 if (status === 'needs review') return 'The proposed lines are ready. Check each amount before confirming.';Guard or branch: the following block runs only when this condition is true.
211 if (status === 'confirmed') {Guard or branch: the following block runs only when this condition is true.
212 if (this.quoteCreationStatus === 'Ready') return 'Your CPQ quote is ready to open below.';Guard or branch: the following block runs only when this condition is true.
213 if (this.isQuoteWorking) return 'Your reviewed lines are saved. Salesforce is creating the quote.';Guard or branch: the following block runs only when this condition is true.
214 if (this.quoteCreationStatus === 'Failed') return 'Your reviewed lines are saved. Check the quote creation message below.';Guard or branch: the following block runs only when this condition is true.
215 return 'Your reviewed lines are saved and ready for quote creation.';Returns this value to the caller and ends the method.
216 }Closes the current block or declaration.
217 if (status === 'failed' || status === 'error') return 'Check the Workato job or try again with a new document.';Guard or branch: the following block runs only when this condition is true.
218 return 'Workato is reading the SOW and preparing the proposed lines.';Returns this value to the caller and ends the method.
219 }Closes the current block or declaration.
220 Spacing separates related steps.
221 get statusIcon() {Opens a block; the indented lines below execute or belong together.
222 const status = (this.analysisStatus || '').toLowerCase();Declares a JavaScript value used by this component or method.
223 if (!this.analysisId) return 'utility:upload';Guard or branch: the following block runs only when this condition is true.
224 if (status === 'needs review') return 'utility:edit';Guard or branch: the following block runs only when this condition is true.
225 if (status === 'confirmed') return 'utility:success';Guard or branch: the following block runs only when this condition is true.
226 if (status === 'failed' || status === 'error') return 'utility:error';Guard or branch: the following block runs only when this condition is true.
227 return 'utility:sync';Returns this value to the caller and ends the method.
228 }Closes the current block or declaration.
229 Spacing separates related steps.
230 get statusPanelClass() {Opens a block; the indented lines below execute or belong together.
231 const status = (this.analysisStatus || '').toLowerCase();Declares a JavaScript value used by this component or method.
232 if (status === 'needs review') return 'status-panel status-panel--review';Guard or branch: the following block runs only when this condition is true.
233 if (status === 'confirmed') return 'status-panel status-panel--confirmed';Guard or branch: the following block runs only when this condition is true.
234 if (status === 'failed' || status === 'error') return 'status-panel status-panel--error';Guard or branch: the following block runs only when this condition is true.
235 return 'status-panel status-panel--waiting';Returns this value to the caller and ends the method.
236 }Closes the current block or declaration.
237 Spacing separates related steps.
238 get progressStep() {Opens a block; the indented lines below execute or belong together.
239 const status = (this.analysisStatus || '').toLowerCase();Declares a JavaScript value used by this component or method.
240 if (!this.analysisId) return 0;Guard or branch: the following block runs only when this condition is true.
241 if (status === 'confirmed') return 4;Guard or branch: the following block runs only when this condition is true.
242 if (status === 'needs review') return 3;Guard or branch: the following block runs only when this condition is true.
243 if (status === 'queued') return 1;Guard or branch: the following block runs only when this condition is true.
244 return 2;Returns this value to the caller and ends the method.
245 }Closes the current block or declaration.
246 Spacing separates related steps.
247 stageClass(step) {Opens a block; the indented lines below execute or belong together.
248 return step <= this.progressStep ? 'progress-step progress-step--active' : 'progress-step';Returns this value to the caller and ends the method.
249 }Closes the current block or declaration.
250 Spacing separates related steps.
251 get requestStageClass() { return this.stageClass(1); }Closes the current block after this expression.
252 get analysisStageClass() { return this.stageClass(2); }Closes the current block after this expression.
253 get reviewStageClass() { return this.stageClass(3); }Closes the current block after this expression.
254 get confirmedStageClass() { return this.stageClass(4); }Closes the current block after this expression.
255 Spacing separates related steps.
256 syncPolling() {Calls syncPolling(): Refresh every five seconds while work is in progress.
257 if ((this.isWorking || this.isQuoteWorking) && this.isComponentActive && !this.pollTimer) {Guard or branch: the following block runs only when this condition is true.
258 this.pollTimer = window.setInterval(() => this.refreshAnalysis(), 5000);Calls refreshAnalysis(): Fetch latest status and turn JSON into display rows.
259 } else if (!this.isComponentActive || (!this.isWorking && !this.isQuoteWorking)) {Opens a block; the indented lines below execute or belong together.
260 this.stopPolling();Completes the statement begun on this line or the preceding lines.
261 }Closes the current block or declaration.
262 }Closes the current block or declaration.
263 Spacing separates related steps.
264 stopPolling() {Opens a block; the indented lines below execute or belong together.
265 if (this.pollTimer) {Guard or branch: the following block runs only when this condition is true.
266 window.clearInterval(this.pollTimer);Completes the statement begun on this line or the preceding lines.
267 this.pollTimer = undefined;Updates component state; the template may show the new value on rerender.
268 }Closes the current block or declaration.
269 }Closes the current block or declaration.
270 Spacing separates related steps.
271 get reviewedTotal() {Opens a block; the indented lines below execute or belong together.
272 const cents = this.reviewLines.reduce(Declares a JavaScript value used by this component or method.
273 (sum, line) => sum + Math.round(Number(line.amount || 0) * 100), 0Maps the value on the left to the value on the right.
274 );Opens or closes the expression begun on the surrounding lines.
275 return cents / 100;Returns this value to the caller and ends the method.
276 }Closes the current block or declaration.
277 Spacing separates related steps.
278 get confirmedTotal() {Opens a block; the indented lines below execute or belong together.
279 const cents = this.confirmedLines.reduce(Declares a JavaScript value used by this component or method.
280 (sum, line) => sum + Math.round(Number(line.amount || 0) * 100), 0Maps the value on the left to the value on the right.
281 );Opens or closes the expression begun on the surrounding lines.
282 return cents / 100;Returns this value to the caller and ends the method.
283 }Closes the current block or declaration.
284 Spacing separates related steps.
285 categoryLabel(category) {Opens a block; the indented lines below execute or belong together.
286 return this.categoryOptions.find((option) => option.value === category)?.label || category;Returns this value to the caller and ends the method.
287 }Closes the current block or declaration.
288 Spacing separates related steps.
289 get isConfirmDisabled() {Opens a block; the indented lines below execute or belong together.
290 return this.isSavingReview || !this.proposalCurrency ||Returns this value to the caller and ends the method.
291 this.reviewLines.length === 0 || this.reviewLines.some((line) => {Updates component state; the template may show the new value on rerender.
292 const amount = Number(line.amount);Declares a JavaScript value used by this component or method.
293 return !line.category || !line.label?.trim() || !Number.isFinite(amount) ||Returns this value to the caller and ends the method.
294 amount <= 0 || Math.abs(amount * 100 - Math.round(amount * 100)) > 0.00001;Assigns or configures the value on the left using the expression on the right.
295 });Completes the statement begun on this line or the preceding lines.
296 }Closes the current block or declaration.
297 Spacing separates related steps.
298 handleQuoteTypeChange(event) {Opens a block; the indented lines below execute or belong together.
299 this.quoteType = event.detail.value;Updates component state; the template may show the new value on rerender.
300 this.effectiveDate = this.isAmendment ? this.primaryAmendmentStartDate : undefined;Updates component state; the template may show the new value on rerender.
301 }Closes the current block or declaration.
302 Spacing separates related steps.
303 handleEffectiveDateChange(event) {Opens a block; the indented lines below execute or belong together.
304 this.effectiveDate = event.detail.value;Updates component state; the template may show the new value on rerender.
305 }Closes the current block or declaration.
306 Spacing separates related steps.
307 handleQuoteStartDateChange(event) {Opens a block; the indented lines below execute or belong together.
308 this.quoteStartDate = event.detail.value;Updates component state; the template may show the new value on rerender.
309 }Closes the current block or declaration.
310 Spacing separates related steps.
311 handleUploadFinished(event) {Opens a block; the indented lines below execute or belong together.
312 const file = event.detail.files[0];Declares a JavaScript value used by this component or method.
313 if (file) {Guard or branch: the following block runs only when this condition is true.
314 if (!file.name?.toLowerCase().endsWith('.pdf')) {Guard or branch: the following block runs only when this condition is true.
315 this.uploadedFileName = undefined;Updates component state; the template may show the new value on rerender.
316 this.contentDocumentId = undefined;Updates component state; the template may show the new value on rerender.
317 this.dispatchEvent(new ShowToastEvent({Opens a block; the indented lines below execute or belong together.
318 title: 'PDF required',Continues the argument list or condition on the next line.
319 message: 'Upload a signed PDF file to start analysis.',Continues the argument list or condition on the next line.
320 variant: 'error'Part of the surrounding declaration or expression; read it with the adjacent lines.
321 }));Completes the statement begun on this line or the preceding lines.
322 return;Ends the method here without returning a value.
323 }Closes the current block or declaration.
324 this.uploadedFileName = file.name;Updates component state; the template may show the new value on rerender.
325 this.contentDocumentId = file.documentId;Updates component state; the template may show the new value on rerender.
326 this.hasCurrentUploadQueued = false;Updates component state; the template may show the new value on rerender.
327 }Closes the current block or declaration.
328 }Closes the current block or declaration.
329 Spacing separates related steps.
330 async refreshAnalysis() {Method declaration: Fetch latest status and turn JSON into display rows. The parentheses define its inputs; the type before the name defines its return value.
331 if (!this.recordId || this.isLoadingAnalysis) {Guard or branch: the following block runs only when this condition is true.
332 return;Ends the method here without returning a value.
333 }Closes the current block or declaration.
334 this.isLoadingAnalysis = true;Updates component state; the template may show the new value on rerender.
335 try {Starts an operation whose exception can be handled below.
336 const analysis = await getLatestAnalysis({ opportunityId: this.recordId });Declares a JavaScript value used by this component or method.
337 if (!analysis) {Guard or branch: the following block runs only when this condition is true.
338 this.analysisId = undefined;Updates component state; the template may show the new value on rerender.
339 this.analysisStatus = undefined;Updates component state; the template may show the new value on rerender.
340 this.reviewLines = [];Updates component state; the template may show the new value on rerender.
341 this.confirmedLines = [];Updates component state; the template may show the new value on rerender.
342 this.proposalCurrency = undefined;Updates component state; the template may show the new value on rerender.
343 this.proposalTotal = undefined;Updates component state; the template may show the new value on rerender.
344 this.proposalReviewReason = undefined;Updates component state; the template may show the new value on rerender.
345 this.confirmedQuoteType = undefined;Updates component state; the template may show the new value on rerender.
346 this.createdQuoteId = undefined;Updates component state; the template may show the new value on rerender.
347 this.quoteCreationStatus = undefined;Updates component state; the template may show the new value on rerender.
348 this.quoteCreationError = undefined;Updates component state; the template may show the new value on rerender.
349 return;Ends the method here without returning a value.
350 }Closes the current block or declaration.
351 Spacing separates related steps.
352 this.analysisId = analysis.Id;Updates component state; the template may show the new value on rerender.
353 this.analysisStatus = analysis.Status__c;Updates component state; the template may show the new value on rerender.
354 this.confirmedQuoteType = analysis.Quote_Type__c;Updates component state; the template may show the new value on rerender.
355 this.quoteType = analysis.Quote_Type__c === 'Change Order' ? 'amendment' : 'new';Updates component state; the template may show the new value on rerender.
356 if (this.quoteType === 'amendment') {Guard or branch: the following block runs only when this condition is true.
357 this.effectiveDate = analysis.Effective_Date__c;Updates component state; the template may show the new value on rerender.
358 }Closes the current block or declaration.
359 this.createdQuoteId = analysis.Created_Quote__c;Updates component state; the template may show the new value on rerender.
360 this.quoteCreationStatus = analysis.Quote_Creation_Status__c;Updates component state; the template may show the new value on rerender.
361 this.quoteCreationError = analysis.Quote_Creation_Error__c;Updates component state; the template may show the new value on rerender.
362 this.reviewLines = [];Updates component state; the template may show the new value on rerender.
363 this.confirmedLines = [];Updates component state; the template may show the new value on rerender.
364 this.proposalReviewReason = undefined;Updates component state; the template may show the new value on rerender.
365 if (analysis.Status__c === 'Needs Review' && analysis.AI_Proposal_JSON__c) {Guard or branch: the following block runs only when this condition is true.
366 const proposal = JSON.parse(analysis.AI_Proposal_JSON__c);Declares a JavaScript value used by this component or method.
367 this.proposalCurrency = proposal.currency_code || analysis.CurrencyIsoCode;Updates component state; the template may show the new value on rerender.
368 this.proposalTotal = Number(proposal.quote_total || 0);Updates component state; the template may show the new value on rerender.
369 this.proposalReviewReason = proposal.review_reason;Updates component state; the template may show the new value on rerender.
370 this.reviewLines = (Array.isArray(proposal.lines) ? proposal.lines : []).map((line) => ({Updates component state; the template may show the new value on rerender.
371 key: `line-${++this.nextRowKey}`,Continues the argument list or condition on the next line.
372 category: line.category,Continues the argument list or condition on the next line.
373 label: line.label,Continues the argument list or condition on the next line.
374 amount: line.amountPart of the surrounding declaration or expression; read it with the adjacent lines.
375 }));Completes the statement begun on this line or the preceding lines.
376 } else if (analysis.Status__c === 'Confirmed' && analysis.Reviewed_Proposal_JSON__c) {Opens a block; the indented lines below execute or belong together.
377 const confirmed = JSON.parse(analysis.Reviewed_Proposal_JSON__c);Declares a JavaScript value used by this component or method.
378 this.proposalCurrency = confirmed.currency_code || analysis.CurrencyIsoCode;Updates component state; the template may show the new value on rerender.
379 this.confirmedLines = (Array.isArray(confirmed.lines) ? confirmed.lines : []).map((line, index) => ({Updates component state; the template may show the new value on rerender.
380 key: `confirmed-${index}`,Continues the argument list or condition on the next line.
381 categoryLabel: this.categoryLabel(line.category),Continues the argument list or condition on the next line.
382 label: line.label,Continues the argument list or condition on the next line.
383 amount: line.amountPart of the surrounding declaration or expression; read it with the adjacent lines.
384 }));Completes the statement begun on this line or the preceding lines.
385 }Closes the current block or declaration.
386 this.loadError = undefined;Updates component state; the template may show the new value on rerender.
387 } catch (error) {Opens a block; the indented lines below execute or belong together.
388 this.loadError = error?.body?.message || error?.message ||Updates component state; the template may show the new value on rerender.
389 'Could not load the latest analysis.';Completes the statement begun on this line or the preceding lines.
390 } finally {Opens a block; the indented lines below execute or belong together.
391 this.isLoadingAnalysis = false;Updates component state; the template may show the new value on rerender.
392 this.syncPolling();Calls syncPolling(): Refresh every five seconds while work is in progress.
393 }Closes the current block or declaration.
394 }Closes the current block or declaration.
395 Spacing separates related steps.
396 handleLineChange(event) {Opens a block; the indented lines below execute or belong together.
397 const key = event.target.dataset.key;Declares a JavaScript value used by this component or method.
398 const field = event.target.dataset.field;Declares a JavaScript value used by this component or method.
399 const value = event.detail.value;Declares a JavaScript value used by this component or method.
400 this.reviewLines = this.reviewLines.map((line) =>Updates component state; the template may show the new value on rerender.
401 line.key === key ? { ...line, [field]: value } : lineAssigns or configures the value on the left using the expression on the right.
402 );Opens or closes the expression begun on the surrounding lines.
403 }Closes the current block or declaration.
404 Spacing separates related steps.
405 handleAddLine() {Opens a block; the indented lines below execute or belong together.
406 this.reviewLines = [Updates component state; the template may show the new value on rerender.
407 ...this.reviewLines,Continues the argument list or condition on the next line.
408 { key: `line-${++this.nextRowKey}`, category: 'TIME_MATERIAL', label: '', amount: null }Closes the current block after this expression.
409 ];Completes the statement begun on this line or the preceding lines.
410 }Closes the current block or declaration.
411 Spacing separates related steps.
412 handleRemoveLine(event) {Opens a block; the indented lines below execute or belong together.
413 const key = event.target.dataset.key;Declares a JavaScript value used by this component or method.
414 this.reviewLines = this.reviewLines.filter((line) => line.key !== key);Updates component state; the template may show the new value on rerender.
415 }Closes the current block or declaration.
416 Spacing separates related steps.
417 async handleConfirmBreakdown() {Method declaration: Send reviewed lines to Apex and update the screen. The parentheses define its inputs; the type before the name defines its return value.
418 if (this.isConfirmDisabled) {Guard or branch: the following block runs only when this condition is true.
419 return;Ends the method here without returning a value.
420 }Closes the current block or declaration.
421 this.isSavingReview = true;Updates component state; the template may show the new value on rerender.
422 try {Starts an operation whose exception can be handled below.
423 const lines = this.reviewLines.map((line) => ({Declares a JavaScript value used by this component or method.
424 category: line.category,Continues the argument list or condition on the next line.
425 label: line.label.trim(),Continues the argument list or condition on the next line.
426 amount: Number(line.amount)Part of the surrounding declaration or expression; read it with the adjacent lines.
427 }));Completes the statement begun on this line or the preceding lines.
428 const reviewedJson = JSON.stringify({Declares a JavaScript value used by this component or method.
429 currency_code: this.proposalCurrency,Continues the argument list or condition on the next line.
430 quote_total: this.reviewedTotal,Continues the argument list or condition on the next line.
431 lines,Continues the argument list or condition on the next line.
432 needs_review: false,Continues the argument list or condition on the next line.
433 review_reason: ''Part of the surrounding declaration or expression; read it with the adjacent lines.
434 });Completes the statement begun on this line or the preceding lines.
435 await confirmBreakdown({ analysisId: this.analysisId, reviewedJson });Waits for this asynchronous JavaScript operation to complete.
436 this.confirmedLines = lines.map((line, index) => ({Updates component state; the template may show the new value on rerender.
437 key: `confirmed-${index}`,Continues the argument list or condition on the next line.
438 categoryLabel: this.categoryLabel(line.category),Continues the argument list or condition on the next line.
439 label: line.label,Continues the argument list or condition on the next line.
440 amount: line.amountPart of the surrounding declaration or expression; read it with the adjacent lines.
441 }));Completes the statement begun on this line or the preceding lines.
442 this.analysisStatus = 'Confirmed';Updates component state; the template may show the new value on rerender.
443 this.syncPolling();Calls syncPolling(): Refresh every five seconds while work is in progress.
444 this.dispatchEvent(new ShowToastEvent({Opens a block; the indented lines below execute or belong together.
445 title: 'Breakdown confirmed',Continues the argument list or condition on the next line.
446 message: this.isConfirmedAmendmentPart of the surrounding declaration or expression; read it with the adjacent lines.
447 ? 'The reviewed lines are ready to add to the CPQ amendment quote below.'Part of the surrounding declaration or expression; read it with the adjacent lines.
448 : 'The reviewed lines are saved for quote creation.',Continues the argument list or condition on the next line.
449 variant: 'success'Part of the surrounding declaration or expression; read it with the adjacent lines.
450 }));Completes the statement begun on this line or the preceding lines.
451 } catch (error) {Opens a block; the indented lines below execute or belong together.
452 this.dispatchEvent(new ShowToastEvent({Opens a block; the indented lines below execute or belong together.
453 title: 'Could not confirm breakdown',Continues the argument list or condition on the next line.
454 message: error?.body?.message || 'Check the line values and try again.',Continues the argument list or condition on the next line.
455 variant: 'error'Part of the surrounding declaration or expression; read it with the adjacent lines.
456 }));Completes the statement begun on this line or the preceding lines.
457 } finally {Opens a block; the indented lines below execute or belong together.
458 this.isSavingReview = false;Updates component state; the template may show the new value on rerender.
459 }Closes the current block or declaration.
460 }Closes the current block or declaration.
461 Spacing separates related steps.
462 async handleCreateQuote() {Method declaration: Start a New Services CPQ Quote. The parentheses define its inputs; the type before the name defines its return value.
463 if (!this.canCreateQuote || this.isCreateQuoteDisabled) return;Guard or branch: the following block runs only when this condition is true.
464 this.isCreatingQuote = true;Updates component state; the template may show the new value on rerender.
465 try {Starts an operation whose exception can be handled below.
466 await createQuote({Waits for this asynchronous JavaScript operation to complete.
467 analysisId: this.analysisId,Continues the argument list or condition on the next line.
468 quoteStartDate: this.isConfirmedNewServices ? this.quoteStartDate : nullPart of the surrounding declaration or expression; read it with the adjacent lines.
469 });Completes the statement begun on this line or the preceding lines.
470 this.quoteCreationStatus = 'Queued';Updates component state; the template may show the new value on rerender.
471 this.quoteCreationError = undefined;Updates component state; the template may show the new value on rerender.
472 this.syncPolling();Calls syncPolling(): Refresh every five seconds while work is in progress.
473 this.dispatchEvent(new ShowToastEvent({Opens a block; the indented lines below execute or belong together.
474 title: 'CPQ quote queued',Continues the argument list or condition on the next line.
475 message: 'Salesforce is creating the quote from the confirmed lines.',Continues the argument list or condition on the next line.
476 variant: 'success'Part of the surrounding declaration or expression; read it with the adjacent lines.
477 }));Completes the statement begun on this line or the preceding lines.
478 } catch (error) {Opens a block; the indented lines below execute or belong together.
479 this.dispatchEvent(new ShowToastEvent({Opens a block; the indented lines below execute or belong together.
480 title: 'Could not create CPQ quote',Continues the argument list or condition on the next line.
481 message: error?.body?.message || error?.message || 'Check the analysis and try again.',Continues the argument list or condition on the next line.
482 variant: 'error'Part of the surrounding declaration or expression; read it with the adjacent lines.
483 }));Completes the statement begun on this line or the preceding lines.
484 } finally {Opens a block; the indented lines below execute or belong together.
485 this.isCreatingQuote = false;Updates component state; the template may show the new value on rerender.
486 }Closes the current block or declaration.
487 }Closes the current block or declaration.
488 Spacing separates related steps.
489 async handleUseNativeAmendment() {Method declaration: Add approved lines to a native amendment Quote. The parentheses define its inputs; the type before the name defines its return value.
490 if (this.isUseNativeAmendmentDisabled || !this.isConfirmedAmendment) return;Guard or branch: the following block runs only when this condition is true.
491 this.isCreatingQuote = true;Updates component state; the template may show the new value on rerender.
492 try {Starts an operation whose exception can be handled below.
493 await useNativeAmendmentQuote({Waits for this asynchronous JavaScript operation to complete.
494 analysisId: this.analysisIdPart of the surrounding declaration or expression; read it with the adjacent lines.
495 });Completes the statement begun on this line or the preceding lines.
496 this.createdQuoteId = this.primaryAmendmentQuoteId;Updates component state; the template may show the new value on rerender.
497 this.quoteCreationStatus = 'Adding Lines';Updates component state; the template may show the new value on rerender.
498 this.quoteCreationError = undefined;Updates component state; the template may show the new value on rerender.
499 this.syncPolling();Calls syncPolling(): Refresh every five seconds while work is in progress.
500 this.dispatchEvent(new ShowToastEvent({Opens a block; the indented lines below execute or belong together.
501 title: 'Amendment update started',Continues the argument list or condition on the next line.
502 message: 'Salesforce is adding the confirmed products to the CPQ amendment quote.',Continues the argument list or condition on the next line.
503 variant: 'success'Part of the surrounding declaration or expression; read it with the adjacent lines.
504 }));Completes the statement begun on this line or the preceding lines.
505 } catch (error) {Opens a block; the indented lines below execute or belong together.
506 this.dispatchEvent(new ShowToastEvent({Opens a block; the indented lines below execute or belong together.
507 title: 'Could not use amendment quote',Continues the argument list or condition on the next line.
508 message: error?.body?.message || error?.message || 'Check the quote and try again.',Continues the argument list or condition on the next line.
509 variant: 'error'Part of the surrounding declaration or expression; read it with the adjacent lines.
510 }));Completes the statement begun on this line or the preceding lines.
511 } finally {Opens a block; the indented lines below execute or belong together.
512 this.isCreatingQuote = false;Updates component state; the template may show the new value on rerender.
513 }Closes the current block or declaration.
514 }Closes the current block or declaration.
515 Spacing separates related steps.
516 async handleStartAnalysis() {Method declaration: Call Apex to queue Workato analysis. The parentheses define its inputs; the type before the name defines its return value.
517 if (this.isStartDisabled) {Guard or branch: the following block runs only when this condition is true.
518 return;Ends the method here without returning a value.
519 }Closes the current block or declaration.
520 Spacing separates related steps.
521 this.isSubmitting = true;Updates component state; the template may show the new value on rerender.
522 try {Starts an operation whose exception can be handled below.
523 this.analysisId = await startAnalysis({Updates component state; the template may show the new value on rerender.
524 opportunityId: this.recordId,Continues the argument list or condition on the next line.
525 contentDocumentId: this.contentDocumentId,Continues the argument list or condition on the next line.
526 quoteType: this.quoteType,Continues the argument list or condition on the next line.
527 effectiveDate: this.isAmendment ? this.effectiveDate : nullPart of the surrounding declaration or expression; read it with the adjacent lines.
528 });Completes the statement begun on this line or the preceding lines.
529 this.analysisStatus = 'Queued';Updates component state; the template may show the new value on rerender.
530 this.reviewLines = [];Updates component state; the template may show the new value on rerender.
531 this.hasCurrentUploadQueued = true;Updates component state; the template may show the new value on rerender.
532 this.syncPolling();Calls syncPolling(): Refresh every five seconds while work is in progress.
533 this.dispatchEvent(new ShowToastEvent({Opens a block; the indented lines below execute or belong together.
534 title: 'Analysis queued',Continues the argument list or condition on the next line.
535 message: 'The signed document is ready for Workato.',Continues the argument list or condition on the next line.
536 variant: 'success'Part of the surrounding declaration or expression; read it with the adjacent lines.
537 }));Completes the statement begun on this line or the preceding lines.
538 } catch (error) {Opens a block; the indented lines below execute or belong together.
539 const message = error?.body?.message || 'Could not start the analysis.';Declares a JavaScript value used by this component or method.
540 this.dispatchEvent(new ShowToastEvent({Opens a block; the indented lines below execute or belong together.
541 title: 'Analysis not started',Continues the argument list or condition on the next line.
542 message,Continues the argument list or condition on the next line.
543 variant: 'error'Part of the surrounding declaration or expression; read it with the adjacent lines.
544 }));Completes the statement begun on this line or the preceding lines.
545 } finally {Opens a block; the indented lines below execute or belong together.
546 this.isSubmitting = false;Updates component state; the template may show the new value on rerender.
547 }Closes the current block or declaration.
548 }Closes the current block or declaration.
549}Closes the current block or declaration.
View complete source code
1import { LightningElement, api, wire } from 'lwc';
2import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
3import { ShowToastEvent } from 'lightning/platformShowToastEvent';
4import OPPORTUNITY_ACCOUNT_ID from '@salesforce/schema/Opportunity.AccountId';
5import startAnalysis from '@salesforce/apex/PsQuoteAnalyzerController.startAnalysis';
6import getLatestAnalysis from '@salesforce/apex/PsQuoteAnalysisReviewController.getLatestAnalysis';
7import confirmBreakdown from '@salesforce/apex/PsQuoteAnalysisReviewController.confirmBreakdown';
8import createQuote from '@salesforce/apex/PsQuoteCpqController.createQuote';
9import useNativeAmendmentQuote from '@salesforce/apex/PsQuoteCpqController.useNativeAmendmentQuote';
10import getPrimaryAmendmentQuote from '@salesforce/apex/PsQuoteCpqController.getPrimaryAmendmentQuote';
11
12const OPPORTUNITY_FIELDS = [OPPORTUNITY_ACCOUNT_ID];
13
14export default class PsQuoteAnalyzerTools extends LightningElement {
15 @api recordId;
16
17 quoteType = 'new';
18 accountId;
19 effectiveDate;
20 uploadedFileName;
21 contentDocumentId;
22 loadError;
23 analysisId;
24 analysisStatus;
25 proposalCurrency;
26 proposalTotal;
27 proposalReviewReason;
28 reviewLines = [];
29 confirmedLines = [];
30 confirmedQuoteType;
31 quoteStartDate;
32 createdQuoteId;
33 quoteCreationStatus;
34 quoteCreationError;
35 primaryAmendmentQuoteId;
36 primaryAmendmentQuoteName;
37 primaryAmendmentContractId;
38 primaryAmendmentContractName;
39 primaryAmendmentStartDate;
40 isCreatingQuote = false;
41 nextRowKey = 0;
42 hasCurrentUploadQueued = false;
43 isLoadingAnalysis = false;
44 isSavingReview = false;
45 isSubmitting = false;
46 isComponentActive = false;
47 pollTimer;
48 handleWindowFocus = () => {
49 if (this.isComponentActive && (this.isWorking || this.isQuoteWorking)) {
50 this.refreshAnalysis();
51 }
52 };
53
54 acceptedFormats = ['.pdf'];
55 quoteTypeOptions = [
56 { label: 'New services', value: 'new' },
57 { label: 'Change order / amend contract', value: 'amendment' }
58 ];
59 categoryOptions = [
60 { label: 'Time & Material', value: 'TIME_MATERIAL' },
61 { label: 'Time & Material — Prepaid', value: 'PREPAID_TIME_MATERIAL' },
62 { label: 'Milestone', value: 'MILESTONE' },
63 { label: 'Milestone — Time & Material', value: 'MILESTONE_TIME_MATERIAL' }
64 ];
65 @wire(getRecord, { recordId: '$recordId', fields: OPPORTUNITY_FIELDS })
66 async loadOpportunity({ data, error }) {
67 if (data) {
68 this.accountId = getFieldValue(data, OPPORTUNITY_ACCOUNT_ID);
69 this.loadError = undefined;
70 await this.refreshAnalysis();
71 await this.loadPrimaryAmendmentQuote();
72 } else if (error) {
73 this.accountId = undefined;
74 this.loadError = 'Unable to read the Opportunity account.';
75 }
76 }
77
78 connectedCallback() {
79 this.isComponentActive = true;
80 window.addEventListener('focus', this.handleWindowFocus);
81 this.syncPolling();
82 }
83
84 disconnectedCallback() {
85 this.isComponentActive = false;
86 window.removeEventListener('focus', this.handleWindowFocus);
87 this.stopPolling();
88 }
89
90 get isAmendment() {
91 return this.quoteType === 'amendment';
92 }
93
94 get uploadLabel() {
95 return this.isAmendment ? 'Upload signed change order (PDF)' : 'Upload signed SOW (PDF)';
96 }
97
98 get isStartDisabled() {
99 return !this.recordId || !this.contentDocumentId || this.isSubmitting ||
100 this.hasCurrentUploadQueued ||
101 (this.isAmendment && (!this.primaryAmendmentQuoteId || !this.effectiveDate));
102 }
103
104 get canReview() {
105 return this.analysisStatus === 'Needs Review' && Boolean(this.analysisId);
106 }
107
108 get isConfirmed() {
109 return this.analysisStatus === 'Confirmed' && this.confirmedLines.length > 0;
110 }
111
112 get isConfirmedNewServices() {
113 return this.isConfirmed && this.confirmedQuoteType === 'New Services';
114 }
115
116 get isConfirmedAmendment() {
117 return this.isConfirmed && this.confirmedQuoteType === 'Change Order';
118 }
119
120 get canCreateQuote() {
121 return this.isConfirmedNewServices && !this.createdQuoteId &&
122 (!this.quoteCreationStatus || this.quoteCreationStatus === 'Failed');
123 }
124
125 get isUseNativeAmendmentDisabled() {
126 return !this.primaryAmendmentQuoteId || this.createdQuoteId || this.isCreatingQuote ||
127 ['Queued', 'Adding Lines'].includes(this.quoteCreationStatus);
128 }
129
130 get hasPrimaryAmendmentQuote() {
131 return Boolean(this.primaryAmendmentQuoteId);
132 }
133
134 get primaryAmendmentQuoteUrl() {
135 return this.primaryAmendmentQuoteId
136 ? `/lightning/r/SBQQ__Quote__c/${this.primaryAmendmentQuoteId}/view`
137 : undefined;
138 }
139
140 get primaryAmendmentContractUrl() {
141 return this.primaryAmendmentContractId
142 ? `/lightning/r/Contract/${this.primaryAmendmentContractId}/view`
143 : undefined;
144 }
145
146 async loadPrimaryAmendmentQuote() {
147 if (!this.recordId) return;
148 try {
149 const primary = await getPrimaryAmendmentQuote({ opportunityId: this.recordId });
150 this.primaryAmendmentQuoteId = primary?.quoteId;
151 this.primaryAmendmentQuoteName = primary?.quoteName;
152 this.primaryAmendmentContractId = primary?.contractId;
153 this.primaryAmendmentContractName = primary?.contractName;
154 this.primaryAmendmentStartDate = primary?.startDate;
155 if (primary && !this.analysisId && !this.contentDocumentId) {
156 this.quoteType = 'amendment';
157 }
158 if (primary && !this.effectiveDate) this.effectiveDate = primary.startDate;
159 } catch (error) {
160 this.loadError = error?.body?.message || error?.message ||
161 'Could not find the primary amendment quote.';
162 }
163 }
164
165 get isCreateQuoteDisabled() {
166 return this.isCreatingQuote || (this.isConfirmedNewServices && !this.quoteStartDate);
167 }
168
169 get isQuoteWorking() {
170 return ['Queued', 'Adding Lines', 'Calculating'].includes(this.quoteCreationStatus);
171 }
172
173 get quoteUrl() {
174 return this.createdQuoteId
175 ? `/lightning/r/SBQQ__Quote__c/${this.createdQuoteId}/view`
176 : undefined;
177 }
178
179 get quoteStatusTitle() {
180 if (this.quoteCreationStatus === 'Queued') return 'Quote request queued';
181 if (this.quoteCreationStatus === 'Adding Lines') return 'Adding approved lines';
182 if (this.quoteCreationStatus === 'Calculating') return 'Calculating quote';
183 if (this.quoteCreationStatus === 'Ready') return 'CPQ quote ready';
184 if (this.quoteCreationStatus === 'Failed') return 'Quote creation needs attention';
185 return this.isConfirmedAmendment ? 'Add approved lines to the amendment quote' :
186 'Ready to create a CPQ quote';
187 }
188
189 get isWorking() {
190 return Boolean(this.analysisId) &&
191 !['needs review', 'confirmed', 'failed', 'error'].includes(
192 (this.analysisStatus || '').toLowerCase()
193 );
194 }
195
196 get statusTitle() {
197 const status = (this.analysisStatus || '').toLowerCase();
198 if (!this.analysisId) return 'Ready to start';
199 if (status === 'queued') return 'Waiting in queue';
200 if (status === 'needs review') return 'Ready for your review';
201 if (status === 'confirmed') return 'Breakdown confirmed';
202 if (status === 'failed' || status === 'error') return 'Analysis needs attention';
203 return 'Analyzing the document';
204 }
205
206 get statusDescription() {
207 const status = (this.analysisStatus || '').toLowerCase();
208 if (!this.analysisId) return 'Upload a signed PDF and start an analysis.';
209 if (status === 'queued') return 'The request was sent to Workato. Analysis will begin shortly.';
210 if (status === 'needs review') return 'The proposed lines are ready. Check each amount before confirming.';
211 if (status === 'confirmed') {
212 if (this.quoteCreationStatus === 'Ready') return 'Your CPQ quote is ready to open below.';
213 if (this.isQuoteWorking) return 'Your reviewed lines are saved. Salesforce is creating the quote.';
214 if (this.quoteCreationStatus === 'Failed') return 'Your reviewed lines are saved. Check the quote creation message below.';
215 return 'Your reviewed lines are saved and ready for quote creation.';
216 }
217 if (status === 'failed' || status === 'error') return 'Check the Workato job or try again with a new document.';
218 return 'Workato is reading the SOW and preparing the proposed lines.';
219 }
220
221 get statusIcon() {
222 const status = (this.analysisStatus || '').toLowerCase();
223 if (!this.analysisId) return 'utility:upload';
224 if (status === 'needs review') return 'utility:edit';
225 if (status === 'confirmed') return 'utility:success';
226 if (status === 'failed' || status === 'error') return 'utility:error';
227 return 'utility:sync';
228 }
229
230 get statusPanelClass() {
231 const status = (this.analysisStatus || '').toLowerCase();
232 if (status === 'needs review') return 'status-panel status-panel--review';
233 if (status === 'confirmed') return 'status-panel status-panel--confirmed';
234 if (status === 'failed' || status === 'error') return 'status-panel status-panel--error';
235 return 'status-panel status-panel--waiting';
236 }
237
238 get progressStep() {
239 const status = (this.analysisStatus || '').toLowerCase();
240 if (!this.analysisId) return 0;
241 if (status === 'confirmed') return 4;
242 if (status === 'needs review') return 3;
243 if (status === 'queued') return 1;
244 return 2;
245 }
246
247 stageClass(step) {
248 return step <= this.progressStep ? 'progress-step progress-step--active' : 'progress-step';
249 }
250
251 get requestStageClass() { return this.stageClass(1); }
252 get analysisStageClass() { return this.stageClass(2); }
253 get reviewStageClass() { return this.stageClass(3); }
254 get confirmedStageClass() { return this.stageClass(4); }
255
256 syncPolling() {
257 if ((this.isWorking || this.isQuoteWorking) && this.isComponentActive && !this.pollTimer) {
258 this.pollTimer = window.setInterval(() => this.refreshAnalysis(), 5000);
259 } else if (!this.isComponentActive || (!this.isWorking && !this.isQuoteWorking)) {
260 this.stopPolling();
261 }
262 }
263
264 stopPolling() {
265 if (this.pollTimer) {
266 window.clearInterval(this.pollTimer);
267 this.pollTimer = undefined;
268 }
269 }
270
271 get reviewedTotal() {
272 const cents = this.reviewLines.reduce(
273 (sum, line) => sum + Math.round(Number(line.amount || 0) * 100), 0
274 );
275 return cents / 100;
276 }
277
278 get confirmedTotal() {
279 const cents = this.confirmedLines.reduce(
280 (sum, line) => sum + Math.round(Number(line.amount || 0) * 100), 0
281 );
282 return cents / 100;
283 }
284
285 categoryLabel(category) {
286 return this.categoryOptions.find((option) => option.value === category)?.label || category;
287 }
288
289 get isConfirmDisabled() {
290 return this.isSavingReview || !this.proposalCurrency ||
291 this.reviewLines.length === 0 || this.reviewLines.some((line) => {
292 const amount = Number(line.amount);
293 return !line.category || !line.label?.trim() || !Number.isFinite(amount) ||
294 amount <= 0 || Math.abs(amount * 100 - Math.round(amount * 100)) > 0.00001;
295 });
296 }
297
298 handleQuoteTypeChange(event) {
299 this.quoteType = event.detail.value;
300 this.effectiveDate = this.isAmendment ? this.primaryAmendmentStartDate : undefined;
301 }
302
303 handleEffectiveDateChange(event) {
304 this.effectiveDate = event.detail.value;
305 }
306
307 handleQuoteStartDateChange(event) {
308 this.quoteStartDate = event.detail.value;
309 }
310
311 handleUploadFinished(event) {
312 const file = event.detail.files[0];
313 if (file) {
314 if (!file.name?.toLowerCase().endsWith('.pdf')) {
315 this.uploadedFileName = undefined;
316 this.contentDocumentId = undefined;
317 this.dispatchEvent(new ShowToastEvent({
318 title: 'PDF required',
319 message: 'Upload a signed PDF file to start analysis.',
320 variant: 'error'
321 }));
322 return;
323 }
324 this.uploadedFileName = file.name;
325 this.contentDocumentId = file.documentId;
326 this.hasCurrentUploadQueued = false;
327 }
328 }
329
330 async refreshAnalysis() {
331 if (!this.recordId || this.isLoadingAnalysis) {
332 return;
333 }
334 this.isLoadingAnalysis = true;
335 try {
336 const analysis = await getLatestAnalysis({ opportunityId: this.recordId });
337 if (!analysis) {
338 this.analysisId = undefined;
339 this.analysisStatus = undefined;
340 this.reviewLines = [];
341 this.confirmedLines = [];
342 this.proposalCurrency = undefined;
343 this.proposalTotal = undefined;
344 this.proposalReviewReason = undefined;
345 this.confirmedQuoteType = undefined;
346 this.createdQuoteId = undefined;
347 this.quoteCreationStatus = undefined;
348 this.quoteCreationError = undefined;
349 return;
350 }
351
352 this.analysisId = analysis.Id;
353 this.analysisStatus = analysis.Status__c;
354 this.confirmedQuoteType = analysis.Quote_Type__c;
355 this.quoteType = analysis.Quote_Type__c === 'Change Order' ? 'amendment' : 'new';
356 if (this.quoteType === 'amendment') {
357 this.effectiveDate = analysis.Effective_Date__c;
358 }
359 this.createdQuoteId = analysis.Created_Quote__c;
360 this.quoteCreationStatus = analysis.Quote_Creation_Status__c;
361 this.quoteCreationError = analysis.Quote_Creation_Error__c;
362 this.reviewLines = [];
363 this.confirmedLines = [];
364 this.proposalReviewReason = undefined;
365 if (analysis.Status__c === 'Needs Review' && analysis.AI_Proposal_JSON__c) {
366 const proposal = JSON.parse(analysis.AI_Proposal_JSON__c);
367 this.proposalCurrency = proposal.currency_code || analysis.CurrencyIsoCode;
368 this.proposalTotal = Number(proposal.quote_total || 0);
369 this.proposalReviewReason = proposal.review_reason;
370 this.reviewLines = (Array.isArray(proposal.lines) ? proposal.lines : []).map((line) => ({
371 key: `line-${++this.nextRowKey}`,
372 category: line.category,
373 label: line.label,
374 amount: line.amount
375 }));
376 } else if (analysis.Status__c === 'Confirmed' && analysis.Reviewed_Proposal_JSON__c) {
377 const confirmed = JSON.parse(analysis.Reviewed_Proposal_JSON__c);
378 this.proposalCurrency = confirmed.currency_code || analysis.CurrencyIsoCode;
379 this.confirmedLines = (Array.isArray(confirmed.lines) ? confirmed.lines : []).map((line, index) => ({
380 key: `confirmed-${index}`,
381 categoryLabel: this.categoryLabel(line.category),
382 label: line.label,
383 amount: line.amount
384 }));
385 }
386 this.loadError = undefined;
387 } catch (error) {
388 this.loadError = error?.body?.message || error?.message ||
389 'Could not load the latest analysis.';
390 } finally {
391 this.isLoadingAnalysis = false;
392 this.syncPolling();
393 }
394 }
395
396 handleLineChange(event) {
397 const key = event.target.dataset.key;
398 const field = event.target.dataset.field;
399 const value = event.detail.value;
400 this.reviewLines = this.reviewLines.map((line) =>
401 line.key === key ? { ...line, [field]: value } : line
402 );
403 }
404
405 handleAddLine() {
406 this.reviewLines = [
407 ...this.reviewLines,
408 { key: `line-${++this.nextRowKey}`, category: 'TIME_MATERIAL', label: '', amount: null }
409 ];
410 }
411
412 handleRemoveLine(event) {
413 const key = event.target.dataset.key;
414 this.reviewLines = this.reviewLines.filter((line) => line.key !== key);
415 }
416
417 async handleConfirmBreakdown() {
418 if (this.isConfirmDisabled) {
419 return;
420 }
421 this.isSavingReview = true;
422 try {
423 const lines = this.reviewLines.map((line) => ({
424 category: line.category,
425 label: line.label.trim(),
426 amount: Number(line.amount)
427 }));
428 const reviewedJson = JSON.stringify({
429 currency_code: this.proposalCurrency,
430 quote_total: this.reviewedTotal,
431 lines,
432 needs_review: false,
433 review_reason: ''
434 });
435 await confirmBreakdown({ analysisId: this.analysisId, reviewedJson });
436 this.confirmedLines = lines.map((line, index) => ({
437 key: `confirmed-${index}`,
438 categoryLabel: this.categoryLabel(line.category),
439 label: line.label,
440 amount: line.amount
441 }));
442 this.analysisStatus = 'Confirmed';
443 this.syncPolling();
444 this.dispatchEvent(new ShowToastEvent({
445 title: 'Breakdown confirmed',
446 message: this.isConfirmedAmendment
447 ? 'The reviewed lines are ready to add to the CPQ amendment quote below.'
448 : 'The reviewed lines are saved for quote creation.',
449 variant: 'success'
450 }));
451 } catch (error) {
452 this.dispatchEvent(new ShowToastEvent({
453 title: 'Could not confirm breakdown',
454 message: error?.body?.message || 'Check the line values and try again.',
455 variant: 'error'
456 }));
457 } finally {
458 this.isSavingReview = false;
459 }
460 }
461
462 async handleCreateQuote() {
463 if (!this.canCreateQuote || this.isCreateQuoteDisabled) return;
464 this.isCreatingQuote = true;
465 try {
466 await createQuote({
467 analysisId: this.analysisId,
468 quoteStartDate: this.isConfirmedNewServices ? this.quoteStartDate : null
469 });
470 this.quoteCreationStatus = 'Queued';
471 this.quoteCreationError = undefined;
472 this.syncPolling();
473 this.dispatchEvent(new ShowToastEvent({
474 title: 'CPQ quote queued',
475 message: 'Salesforce is creating the quote from the confirmed lines.',
476 variant: 'success'
477 }));
478 } catch (error) {
479 this.dispatchEvent(new ShowToastEvent({
480 title: 'Could not create CPQ quote',
481 message: error?.body?.message || error?.message || 'Check the analysis and try again.',
482 variant: 'error'
483 }));
484 } finally {
485 this.isCreatingQuote = false;
486 }
487 }
488
489 async handleUseNativeAmendment() {
490 if (this.isUseNativeAmendmentDisabled || !this.isConfirmedAmendment) return;
491 this.isCreatingQuote = true;
492 try {
493 await useNativeAmendmentQuote({
494 analysisId: this.analysisId
495 });
496 this.createdQuoteId = this.primaryAmendmentQuoteId;
497 this.quoteCreationStatus = 'Adding Lines';
498 this.quoteCreationError = undefined;
499 this.syncPolling();
500 this.dispatchEvent(new ShowToastEvent({
501 title: 'Amendment update started',
502 message: 'Salesforce is adding the confirmed products to the CPQ amendment quote.',
503 variant: 'success'
504 }));
505 } catch (error) {
506 this.dispatchEvent(new ShowToastEvent({
507 title: 'Could not use amendment quote',
508 message: error?.body?.message || error?.message || 'Check the quote and try again.',
509 variant: 'error'
510 }));
511 } finally {
512 this.isCreatingQuote = false;
513 }
514 }
515
516 async handleStartAnalysis() {
517 if (this.isStartDisabled) {
518 return;
519 }
520
521 this.isSubmitting = true;
522 try {
523 this.analysisId = await startAnalysis({
524 opportunityId: this.recordId,
525 contentDocumentId: this.contentDocumentId,
526 quoteType: this.quoteType,
527 effectiveDate: this.isAmendment ? this.effectiveDate : null
528 });
529 this.analysisStatus = 'Queued';
530 this.reviewLines = [];
531 this.hasCurrentUploadQueued = true;
532 this.syncPolling();
533 this.dispatchEvent(new ShowToastEvent({
534 title: 'Analysis queued',
535 message: 'The signed document is ready for Workato.',
536 variant: 'success'
537 }));
538 } catch (error) {
539 const message = error?.body?.message || 'Could not start the analysis.';
540 this.dispatchEvent(new ShowToastEvent({
541 title: 'Analysis not started',
542 message,
543 variant: 'error'
544 }));
545 } finally {
546 this.isSubmitting = false;
547 }
548 }
549}
lightning · 323 lines

psQuoteAnalyzerTools.html

The UI template: fields, buttons, rows, status panels, and event bindings to JavaScript.

Review and understand complete source code

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<template>Starts a template container that groups visible UI elements.
2 <lightning-card title="PS Quote Analyzer Tools" icon-name="standard:quotes">Adds a Salesforce Lightning UI control or display component.
3 <div class="quote-tool">Starts a template container that groups visible UI elements.
4 <div class="intro">Starts a template container that groups visible UI elements.
5 <p class="eyebrow">PROFESSIONAL SERVICES</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
6 <h2>Turn a signed SOW into a reviewed budget breakdown for Teamwork</h2>Declares a UI element or template instruction; its attributes control content, conditions, and events.
7 <p>Upload the final PDF, review the proposed product lines, and confirm the amounts before creating or updating the CPQ quote.</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
8 </div>Closes the corresponding HTML element or template block.
9 Spacing separates related steps.
10 <div class="section-heading">Starts a template container that groups visible UI elements.
11 <span class="step-number">1</span>Declares a UI element or template instruction; its attributes control content, conditions, and events.
12 <div>Starts a template container that groups visible UI elements.
13 <h3>Choose the request</h3>Declares a UI element or template instruction; its attributes control content, conditions, and events.
14 <p>Select new services or a change order.</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
15 </div>Closes the corresponding HTML element or template block.
16 </div>Closes the corresponding HTML element or template block.
17 <lightning-radio-groupAdds a Salesforce Lightning UI control or display component.
18 name="quoteType"Assigns or configures the value on the left using the expression on the right.
19 label="What are you quoting?"Assigns or configures the value on the left using the expression on the right.
20 options={quoteTypeOptions}Closes the current block after this expression.
21 value={quoteType}Closes the current block after this expression.
22 type="radio"Assigns or configures the value on the left using the expression on the right.
23 onchange={handleQuoteTypeChange}>Assigns or configures the value on the left using the expression on the right.
24 </lightning-radio-group>Closes the corresponding HTML element or template block.
25 Spacing separates related steps.
26 <template if:true={isAmendment}>Starts a template container that groups visible UI elements.
27 <div class="slds-m-top_medium">Starts a template container that groups visible UI elements.
28 <template if:true={hasPrimaryAmendmentQuote}>Starts a template container that groups visible UI elements.
29 <p><strong>Primary amendment quote:</strong>Declares a UI element or template instruction; its attributes control content, conditions, and events.
30 <lightning-formatted-url value={primaryAmendmentQuoteUrl}Adds a Salesforce Lightning UI control or display component.
31 label={primaryAmendmentQuoteName} target="_blank">Assigns or configures the value on the left using the expression on the right.
32 </lightning-formatted-url>Closes the corresponding HTML element or template block.
33 </p>Closes the corresponding HTML element or template block.
34 <p><strong>Contract being amended:</strong>Declares a UI element or template instruction; its attributes control content, conditions, and events.
35 <lightning-formatted-url value={primaryAmendmentContractUrl}Adds a Salesforce Lightning UI control or display component.
36 label={primaryAmendmentContractName} target="_blank">Assigns or configures the value on the left using the expression on the right.
37 </lightning-formatted-url>Closes the corresponding HTML element or template block.
38 </p>Closes the corresponding HTML element or template block.
39 </template>Closes the current block or declaration.
40 <template if:false={hasPrimaryAmendmentQuote}>Starts a template container that groups visible UI elements.
41 <p class="slds-text-color_error">This Opportunity has no primary CPQ amendment quote. Create the services change order from the Contact before starting analysis.</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
42 </template>Closes the current block or declaration.
43 </div>Closes the corresponding HTML element or template block.
44 Spacing separates related steps.
45 <div class="slds-m-top_medium">Starts a template container that groups visible UI elements.
46 <lightning-inputAdds a Salesforce Lightning UI control or display component.
47 type="date"Assigns or configures the value on the left using the expression on the right.
48 label="Change effective date"Assigns or configures the value on the left using the expression on the right.
49 value={effectiveDate}Closes the current block after this expression.
50 onchange={handleEffectiveDateChange}Closes the current block after this expression.
51 required>Part of the surrounding declaration or expression; read it with the adjacent lines.
52 </lightning-input>Closes the corresponding HTML element or template block.
53 <template if:true={hasPrimaryAmendmentQuote}>Starts a template container that groups visible UI elements.
54 <p class="confirm-note">Prefilled from the primary amendment quote. Check it against the signed change order; CPQ's existing contract lines were created using the quote's start date.</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
55 </template>Closes the current block or declaration.
56 </div>Closes the corresponding HTML element or template block.
57 </template>Closes the current block or declaration.
58 Spacing separates related steps.
59 <div class="section-heading slds-m-top_x-large">Starts a template container that groups visible UI elements.
60 <span class="step-number">2</span>Declares a UI element or template instruction; its attributes control content, conditions, and events.
61 <div>Starts a template container that groups visible UI elements.
62 <h3>Upload the signed document</h3>Declares a UI element or template instruction; its attributes control content, conditions, and events.
63 <p>PDF only. The original stays attached to the Opportunity.</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
64 </div>Closes the corresponding HTML element or template block.
65 </div>Closes the corresponding HTML element or template block.
66 <div class="upload-area">Starts a template container that groups visible UI elements.
67 <lightning-file-uploadAdds a Salesforce Lightning UI control or display component.
68 label={uploadLabel}Closes the current block after this expression.
69 name="signedDocument"Assigns or configures the value on the left using the expression on the right.
70 record-id={recordId}Closes the current block after this expression.
71 accept={acceptedFormats}Closes the current block after this expression.
72 onuploadfinished={handleUploadFinished}>Assigns or configures the value on the left using the expression on the right.
73 </lightning-file-upload>Closes the corresponding HTML element or template block.
74 </div>Closes the corresponding HTML element or template block.
75 Spacing separates related steps.
76 <template if:true={uploadedFileName}>Starts a template container that groups visible UI elements.
77 <div class="slds-box slds-theme_success slds-m-top_medium">Starts a template container that groups visible UI elements.
78 Uploaded: {uploadedFileName}Closes the current block after this expression.
79 </div>Closes the corresponding HTML element or template block.
80 </template>Closes the current block or declaration.
81 Spacing separates related steps.
82 <div class="slds-m-top_large">Starts a template container that groups visible UI elements.
83 <lightning-buttonAdds a Salesforce Lightning UI control or display component.
84 label="Start analysis"Assigns or configures the value on the left using the expression on the right.
85 variant="brand"Assigns or configures the value on the left using the expression on the right.
86 disabled={isStartDisabled}Closes the current block after this expression.
87 onclick={handleStartAnalysis}>Assigns or configures the value on the left using the expression on the right.
88 </lightning-button>Closes the corresponding HTML element or template block.
89 <template if:true={isSubmitting}>Starts a template container that groups visible UI elements.
90 <lightning-spinnerAdds a Salesforce Lightning UI control or display component.
91 alternative-text="Starting analysis"Assigns or configures the value on the left using the expression on the right.
92 size="small">Assigns or configures the value on the left using the expression on the right.
93 </lightning-spinner>Closes the corresponding HTML element or template block.
94 </template>Closes the current block or declaration.
95 </div>Closes the corresponding HTML element or template block.
96 Spacing separates related steps.
97 <section class={statusPanelClass} aria-live="polite">Starts a template container that groups visible UI elements.
98 <div class="status-top">Starts a template container that groups visible UI elements.
99 <lightning-icon icon-name={statusIcon} size="small" alternative-text={statusTitle}></lightning-icon>Adds a Salesforce Lightning UI control or display component.
100 <div class="status-copy">Starts a template container that groups visible UI elements.
101 <p class="eyebrow">ANALYSIS STATUS</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
102 <h3>{statusTitle}</h3>Declares a UI element or template instruction; its attributes control content, conditions, and events.
103 <p>{statusDescription}</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
104 </div>Closes the corresponding HTML element or template block.
105 <template if:true={analysisId}>Starts a template container that groups visible UI elements.
106 <lightning-buttonAdds a Salesforce Lightning UI control or display component.
107 label="Check for update"Assigns or configures the value on the left using the expression on the right.
108 disabled={isLoadingAnalysis}Closes the current block after this expression.
109 onclick={refreshAnalysis}>Assigns or configures the value on the left using the expression on the right.
110 </lightning-button>Closes the corresponding HTML element or template block.
111 </template>Closes the current block or declaration.
112 </div>Closes the corresponding HTML element or template block.
113 <div class="progress-track" aria-label="Analysis progress">Starts a template container that groups visible UI elements.
114 <span class={requestStageClass}>Request received</span>Declares a UI element or template instruction; its attributes control content, conditions, and events.
115 <span class={analysisStageClass}>AI analysis</span>Declares a UI element or template instruction; its attributes control content, conditions, and events.
116 <span class={reviewStageClass}>Review breakdown</span>Declares a UI element or template instruction; its attributes control content, conditions, and events.
117 <span class={confirmedStageClass}>Confirmed</span>Declares a UI element or template instruction; its attributes control content, conditions, and events.
118 </div>Closes the corresponding HTML element or template block.
119 <template if:true={isWorking}>Starts a template container that groups visible UI elements.
120 <p class="status-footnote">Checking automatically every 5 seconds while analysis runs.</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
121 </template>Closes the current block or declaration.
122 </section>Closes the corresponding HTML element or template block.
123 Spacing separates related steps.
124 <template if:true={canReview}>Starts a template container that groups visible UI elements.
125 <section class="review-panel">Starts a template container that groups visible UI elements.
126 <div class="section-heading">Starts a template container that groups visible UI elements.
127 <span class="step-number">3</span>Declares a UI element or template instruction; its attributes control content, conditions, and events.
128 <div>Starts a template container that groups visible UI elements.
129 <h3>Review proposed quote lines</h3>Declares a UI element or template instruction; its attributes control content, conditions, and events.
130 <p>Adjust categories, labels, and amounts. Add or remove lines as needed.</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
131 </div>Closes the corresponding HTML element or template block.
132 </div>Closes the corresponding HTML element or template block.
133 <p class="proposed-total">Declares a UI element or template instruction; its attributes control content, conditions, and events.
134 AI proposed totalPart of the surrounding declaration or expression; read it with the adjacent lines.
135 <lightning-formatted-numberAdds a Salesforce Lightning UI control or display component.
136 value={proposalTotal}Closes the current block after this expression.
137 format-style="currency"Assigns or configures the value on the left using the expression on the right.
138 currency-code={proposalCurrency}>Assigns or configures the value on the left using the expression on the right.
139 </lightning-formatted-number>Closes the corresponding HTML element or template block.
140 </p>Closes the corresponding HTML element or template block.
141 <template if:true={proposalReviewReason}>Starts a template container that groups visible UI elements.
142 <p class="slds-m-top_small">Review note: {proposalReviewReason}</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
143 </template>Closes the current block or declaration.
144 Spacing separates related steps.
145 <template for:each={reviewLines} for:item="line">Starts a template container that groups visible UI elements.
146 <div key={line.key} class="line-row">Starts a template container that groups visible UI elements.
147 <div>Starts a template container that groups visible UI elements.
148 <lightning-comboboxAdds a Salesforce Lightning UI control or display component.
149 label="Product category"Assigns or configures the value on the left using the expression on the right.
150 value={line.category}Closes the current block after this expression.
151 options={categoryOptions}Closes the current block after this expression.
152 data-key={line.key}Closes the current block after this expression.
153 data-field="category"Assigns or configures the value on the left using the expression on the right.
154 onchange={handleLineChange}Closes the current block after this expression.
155 required>Part of the surrounding declaration or expression; read it with the adjacent lines.
156 </lightning-combobox>Closes the corresponding HTML element or template block.
157 </div>Closes the corresponding HTML element or template block.
158 <div>Starts a template container that groups visible UI elements.
159 <lightning-inputAdds a Salesforce Lightning UI control or display component.
160 type="text"Assigns or configures the value on the left using the expression on the right.
161 label="Line label"Assigns or configures the value on the left using the expression on the right.
162 value={line.label}Closes the current block after this expression.
163 data-key={line.key}Closes the current block after this expression.
164 data-field="label"Assigns or configures the value on the left using the expression on the right.
165 onchange={handleLineChange}Closes the current block after this expression.
166 required>Part of the surrounding declaration or expression; read it with the adjacent lines.
167 </lightning-input>Closes the corresponding HTML element or template block.
168 </div>Closes the corresponding HTML element or template block.
169 <div>Starts a template container that groups visible UI elements.
170 <lightning-inputAdds a Salesforce Lightning UI control or display component.
171 type="number"Assigns or configures the value on the left using the expression on the right.
172 label="Amount"Assigns or configures the value on the left using the expression on the right.
173 value={line.amount}Closes the current block after this expression.
174 min="0.01"Assigns or configures the value on the left using the expression on the right.
175 step="0.01"Assigns or configures the value on the left using the expression on the right.
176 data-key={line.key}Closes the current block after this expression.
177 data-field="amount"Assigns or configures the value on the left using the expression on the right.
178 onchange={handleLineChange}Closes the current block after this expression.
179 required>Part of the surrounding declaration or expression; read it with the adjacent lines.
180 </lightning-input>Closes the corresponding HTML element or template block.
181 </div>Closes the corresponding HTML element or template block.
182 <div class="remove-line">Starts a template container that groups visible UI elements.
183 <lightning-button-iconAdds a Salesforce Lightning UI control or display component.
184 icon-name="utility:delete"Assigns or configures the value on the left using the expression on the right.
185 alternative-text="Remove line"Assigns or configures the value on the left using the expression on the right.
186 title="Remove line"Assigns or configures the value on the left using the expression on the right.
187 data-key={line.key}Closes the current block after this expression.
188 onclick={handleRemoveLine}>Assigns or configures the value on the left using the expression on the right.
189 </lightning-button-icon>Closes the corresponding HTML element or template block.
190 </div>Closes the corresponding HTML element or template block.
191 </div>Closes the corresponding HTML element or template block.
192 </template>Closes the current block or declaration.
193 Spacing separates related steps.
194 <div class="slds-m-top_medium">Starts a template container that groups visible UI elements.
195 <lightning-buttonAdds a Salesforce Lightning UI control or display component.
196 label="Add line"Assigns or configures the value on the left using the expression on the right.
197 onclick={handleAddLine}>Assigns or configures the value on the left using the expression on the right.
198 </lightning-button>Closes the corresponding HTML element or template block.
199 </div>Closes the corresponding HTML element or template block.
200 <p class="reviewed-total">Declares a UI element or template instruction; its attributes control content, conditions, and events.
201 Reviewed totalPart of the surrounding declaration or expression; read it with the adjacent lines.
202 <lightning-formatted-numberAdds a Salesforce Lightning UI control or display component.
203 value={reviewedTotal}Closes the current block after this expression.
204 format-style="currency"Assigns or configures the value on the left using the expression on the right.
205 currency-code={proposalCurrency}>Assigns or configures the value on the left using the expression on the right.
206 </lightning-formatted-number>Closes the corresponding HTML element or template block.
207 </p>Closes the corresponding HTML element or template block.
208 <lightning-buttonAdds a Salesforce Lightning UI control or display component.
209 label="Confirm breakdown"Assigns or configures the value on the left using the expression on the right.
210 variant="brand"Assigns or configures the value on the left using the expression on the right.
211 class="slds-m-top_medium"Assigns or configures the value on the left using the expression on the right.
212 disabled={isConfirmDisabled}Closes the current block after this expression.
213 onclick={handleConfirmBreakdown}>Assigns or configures the value on the left using the expression on the right.
214 </lightning-button>Closes the corresponding HTML element or template block.
215 <p class="confirm-note">Confirmation saves the reviewed breakdown. For change orders, use the CPQ amendment quote already created for this Opportunity.</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
216 </section>Closes the corresponding HTML element or template block.
217 </template>Closes the current block or declaration.
218 Spacing separates related steps.
219 <template if:true={isConfirmed}>Starts a template container that groups visible UI elements.
220 <section class="review-panel confirmed-panel">Starts a template container that groups visible UI elements.
221 <div class="section-heading">Starts a template container that groups visible UI elements.
222 <span class="step-number">✓</span>Declares a UI element or template instruction; its attributes control content, conditions, and events.
223 <div>Starts a template container that groups visible UI elements.
224 <h3>Confirmed budget breakdown</h3>Declares a UI element or template instruction; its attributes control content, conditions, and events.
225 <p>These are the lines saved after review.</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
226 </div>Closes the corresponding HTML element or template block.
227 </div>Closes the corresponding HTML element or template block.
228 <template for:each={confirmedLines} for:item="line">Starts a template container that groups visible UI elements.
229 <div key={line.key} class="confirmed-row">Starts a template container that groups visible UI elements.
230 <span class="confirmed-category">{line.categoryLabel}</span>Declares a UI element or template instruction; its attributes control content, conditions, and events.
231 <span class="confirmed-label">{line.label}</span>Declares a UI element or template instruction; its attributes control content, conditions, and events.
232 <lightning-formatted-numberAdds a Salesforce Lightning UI control or display component.
233 value={line.amount}Closes the current block after this expression.
234 format-style="currency"Assigns or configures the value on the left using the expression on the right.
235 currency-code={proposalCurrency}>Assigns or configures the value on the left using the expression on the right.
236 </lightning-formatted-number>Closes the corresponding HTML element or template block.
237 </div>Closes the corresponding HTML element or template block.
238 </template>Closes the current block or declaration.
239 <p class="reviewed-total">Declares a UI element or template instruction; its attributes control content, conditions, and events.
240 Confirmed totalPart of the surrounding declaration or expression; read it with the adjacent lines.
241 <lightning-formatted-numberAdds a Salesforce Lightning UI control or display component.
242 value={confirmedTotal}Closes the current block after this expression.
243 format-style="currency"Assigns or configures the value on the left using the expression on the right.
244 currency-code={proposalCurrency}>Assigns or configures the value on the left using the expression on the right.
245 </lightning-formatted-number>Closes the corresponding HTML element or template block.
246 </p>Closes the corresponding HTML element or template block.
247 <section class="quote-creation-panel" aria-live="polite">Starts a template container that groups visible UI elements.
248 <div class="section-heading">Starts a template container that groups visible UI elements.
249 <span class="step-number">4</span>Declares a UI element or template instruction; its attributes control content, conditions, and events.
250 <div>Starts a template container that groups visible UI elements.
251 <h3>Complete the CPQ quote</h3>Declares a UI element or template instruction; its attributes control content, conditions, and events.
252 <p>{quoteStatusTitle}</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
253 </div>Closes the corresponding HTML element or template block.
254 </div>Closes the corresponding HTML element or template block.
255 <template if:true={canCreateQuote}>Starts a template container that groups visible UI elements.
256 <template if:true={isConfirmedNewServices}>Starts a template container that groups visible UI elements.
257 <lightning-inputAdds a Salesforce Lightning UI control or display component.
258 type="date"Assigns or configures the value on the left using the expression on the right.
259 label="Quote start date"Assigns or configures the value on the left using the expression on the right.
260 value={quoteStartDate}Closes the current block after this expression.
261 onchange={handleQuoteStartDateChange}Closes the current block after this expression.
262 required>Part of the surrounding declaration or expression; read it with the adjacent lines.
263 </lightning-input>Closes the corresponding HTML element or template block.
264 </template>Closes the current block or declaration.
265 <lightning-buttonAdds a Salesforce Lightning UI control or display component.
266 label="Create CPQ quote"Assigns or configures the value on the left using the expression on the right.
267 variant="brand"Assigns or configures the value on the left using the expression on the right.
268 class="slds-m-top_medium"Assigns or configures the value on the left using the expression on the right.
269 disabled={isCreateQuoteDisabled}Closes the current block after this expression.
270 onclick={handleCreateQuote}>Assigns or configures the value on the left using the expression on the right.
271 </lightning-button>Closes the corresponding HTML element or template block.
272 </template>Closes the current block or declaration.
273 <template if:true={isConfirmedAmendment}>Starts a template container that groups visible UI elements.
274 <template if:true={hasPrimaryAmendmentQuote}>Starts a template container that groups visible UI elements.
275 <p class="confirm-note">Confirmed products will be added to the primary CPQ amendment quote on this Opportunity.</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
276 <p><strong>Quote:</strong> {primaryAmendmentQuoteName}</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
277 <p><strong>Contract being amended:</strong>Declares a UI element or template instruction; its attributes control content, conditions, and events.
278 <lightning-formatted-url value={primaryAmendmentContractUrl}Adds a Salesforce Lightning UI control or display component.
279 label={primaryAmendmentContractName} target="_blank">Assigns or configures the value on the left using the expression on the right.
280 </lightning-formatted-url>Closes the corresponding HTML element or template block.
281 </p>Closes the corresponding HTML element or template block.
282 <lightning-formatted-urlAdds a Salesforce Lightning UI control or display component.
283 value={primaryAmendmentQuoteUrl}Closes the current block after this expression.
284 label="Open primary amendment quote"Assigns or configures the value on the left using the expression on the right.
285 target="_blank">Assigns or configures the value on the left using the expression on the right.
286 </lightning-formatted-url>Closes the corresponding HTML element or template block.
287 </template>Closes the current block or declaration.
288 <template if:false={hasPrimaryAmendmentQuote}>Starts a template container that groups visible UI elements.
289 <p class="slds-text-color_error">This Opportunity has no primary CPQ amendment quote.</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
290 </template>Closes the current block or declaration.
291 <lightning-buttonAdds a Salesforce Lightning UI control or display component.
292 label="Add confirmed products to amendment"Assigns or configures the value on the left using the expression on the right.
293 variant="brand"Assigns or configures the value on the left using the expression on the right.
294 class="slds-m-top_medium"Assigns or configures the value on the left using the expression on the right.
295 disabled={isUseNativeAmendmentDisabled}Closes the current block after this expression.
296 onclick={handleUseNativeAmendment}>Assigns or configures the value on the left using the expression on the right.
297 </lightning-button>Closes the corresponding HTML element or template block.
298 </template>Closes the current block or declaration.
299 <template if:true={isQuoteWorking}>Starts a template container that groups visible UI elements.
300 <p class="confirm-note">Salesforce is preparing the quote. This page checks for updates every 5 seconds.</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
301 </template>Closes the current block or declaration.
302 <template if:true={createdQuoteId}>Starts a template container that groups visible UI elements.
303 <p class="slds-m-top_medium">Declares a UI element or template instruction; its attributes control content, conditions, and events.
304 <lightning-formatted-urlAdds a Salesforce Lightning UI control or display component.
305 value={quoteUrl}Closes the current block after this expression.
306 label="Open CPQ quote"Assigns or configures the value on the left using the expression on the right.
307 target="_blank">Assigns or configures the value on the left using the expression on the right.
308 </lightning-formatted-url>Closes the corresponding HTML element or template block.
309 </p>Closes the corresponding HTML element or template block.
310 </template>Closes the current block or declaration.
311 <template if:true={quoteCreationError}>Starts a template container that groups visible UI elements.
312 <p class="slds-text-color_error slds-m-top_medium">{quoteCreationError}</p>Declares a UI element or template instruction; its attributes control content, conditions, and events.
313 </template>Closes the current block or declaration.
314 </section>Closes the corresponding HTML element or template block.
315 </section>Closes the corresponding HTML element or template block.
316 </template>Closes the current block or declaration.
317 Spacing separates related steps.
318 <template if:true={loadError}>Starts a template container that groups visible UI elements.
319 <div class="slds-text-color_error slds-m-top_medium">{loadError}</div>Starts a template container that groups visible UI elements.
320 </template>Closes the current block or declaration.
321 </div>Closes the corresponding HTML element or template block.
322 </lightning-card>Closes the corresponding HTML element or template block.
323</template>Closes the current block or declaration.
View complete source code
1<template>
2 <lightning-card title="PS Quote Analyzer Tools" icon-name="standard:quotes">
3 <div class="quote-tool">
4 <div class="intro">
5 <p class="eyebrow">PROFESSIONAL SERVICES</p>
6 <h2>Turn a signed SOW into a reviewed budget breakdown for Teamwork</h2>
7 <p>Upload the final PDF, review the proposed product lines, and confirm the amounts before creating or updating the CPQ quote.</p>
8 </div>
9
10 <div class="section-heading">
11 <span class="step-number">1</span>
12 <div>
13 <h3>Choose the request</h3>
14 <p>Select new services or a change order.</p>
15 </div>
16 </div>
17 <lightning-radio-group
18 name="quoteType"
19 label="What are you quoting?"
20 options={quoteTypeOptions}
21 value={quoteType}
22 type="radio"
23 onchange={handleQuoteTypeChange}>
24 </lightning-radio-group>
25
26 <template if:true={isAmendment}>
27 <div class="slds-m-top_medium">
28 <template if:true={hasPrimaryAmendmentQuote}>
29 <p><strong>Primary amendment quote:</strong>
30 <lightning-formatted-url value={primaryAmendmentQuoteUrl}
31 label={primaryAmendmentQuoteName} target="_blank">
32 </lightning-formatted-url>
33 </p>
34 <p><strong>Contract being amended:</strong>
35 <lightning-formatted-url value={primaryAmendmentContractUrl}
36 label={primaryAmendmentContractName} target="_blank">
37 </lightning-formatted-url>
38 </p>
39 </template>
40 <template if:false={hasPrimaryAmendmentQuote}>
41 <p class="slds-text-color_error">This Opportunity has no primary CPQ amendment quote. Create the services change order from the Contact before starting analysis.</p>
42 </template>
43 </div>
44
45 <div class="slds-m-top_medium">
46 <lightning-input
47 type="date"
48 label="Change effective date"
49 value={effectiveDate}
50 onchange={handleEffectiveDateChange}
51 required>
52 </lightning-input>
53 <template if:true={hasPrimaryAmendmentQuote}>
54 <p class="confirm-note">Prefilled from the primary amendment quote. Check it against the signed change order; CPQ's existing contract lines were created using the quote's start date.</p>
55 </template>
56 </div>
57 </template>
58
59 <div class="section-heading slds-m-top_x-large">
60 <span class="step-number">2</span>
61 <div>
62 <h3>Upload the signed document</h3>
63 <p>PDF only. The original stays attached to the Opportunity.</p>
64 </div>
65 </div>
66 <div class="upload-area">
67 <lightning-file-upload
68 label={uploadLabel}
69 name="signedDocument"
70 record-id={recordId}
71 accept={acceptedFormats}
72 onuploadfinished={handleUploadFinished}>
73 </lightning-file-upload>
74 </div>
75
76 <template if:true={uploadedFileName}>
77 <div class="slds-box slds-theme_success slds-m-top_medium">
78 Uploaded: {uploadedFileName}
79 </div>
80 </template>
81
82 <div class="slds-m-top_large">
83 <lightning-button
84 label="Start analysis"
85 variant="brand"
86 disabled={isStartDisabled}
87 onclick={handleStartAnalysis}>
88 </lightning-button>
89 <template if:true={isSubmitting}>
90 <lightning-spinner
91 alternative-text="Starting analysis"
92 size="small">
93 </lightning-spinner>
94 </template>
95 </div>
96
97 <section class={statusPanelClass} aria-live="polite">
98 <div class="status-top">
99 <lightning-icon icon-name={statusIcon} size="small" alternative-text={statusTitle}></lightning-icon>
100 <div class="status-copy">
101 <p class="eyebrow">ANALYSIS STATUS</p>
102 <h3>{statusTitle}</h3>
103 <p>{statusDescription}</p>
104 </div>
105 <template if:true={analysisId}>
106 <lightning-button
107 label="Check for update"
108 disabled={isLoadingAnalysis}
109 onclick={refreshAnalysis}>
110 </lightning-button>
111 </template>
112 </div>
113 <div class="progress-track" aria-label="Analysis progress">
114 <span class={requestStageClass}>Request received</span>
115 <span class={analysisStageClass}>AI analysis</span>
116 <span class={reviewStageClass}>Review breakdown</span>
117 <span class={confirmedStageClass}>Confirmed</span>
118 </div>
119 <template if:true={isWorking}>
120 <p class="status-footnote">Checking automatically every 5 seconds while analysis runs.</p>
121 </template>
122 </section>
123
124 <template if:true={canReview}>
125 <section class="review-panel">
126 <div class="section-heading">
127 <span class="step-number">3</span>
128 <div>
129 <h3>Review proposed quote lines</h3>
130 <p>Adjust categories, labels, and amounts. Add or remove lines as needed.</p>
131 </div>
132 </div>
133 <p class="proposed-total">
134 AI proposed total
135 <lightning-formatted-number
136 value={proposalTotal}
137 format-style="currency"
138 currency-code={proposalCurrency}>
139 </lightning-formatted-number>
140 </p>
141 <template if:true={proposalReviewReason}>
142 <p class="slds-m-top_small">Review note: {proposalReviewReason}</p>
143 </template>
144
145 <template for:each={reviewLines} for:item="line">
146 <div key={line.key} class="line-row">
147 <div>
148 <lightning-combobox
149 label="Product category"
150 value={line.category}
151 options={categoryOptions}
152 data-key={line.key}
153 data-field="category"
154 onchange={handleLineChange}
155 required>
156 </lightning-combobox>
157 </div>
158 <div>
159 <lightning-input
160 type="text"
161 label="Line label"
162 value={line.label}
163 data-key={line.key}
164 data-field="label"
165 onchange={handleLineChange}
166 required>
167 </lightning-input>
168 </div>
169 <div>
170 <lightning-input
171 type="number"
172 label="Amount"
173 value={line.amount}
174 min="0.01"
175 step="0.01"
176 data-key={line.key}
177 data-field="amount"
178 onchange={handleLineChange}
179 required>
180 </lightning-input>
181 </div>
182 <div class="remove-line">
183 <lightning-button-icon
184 icon-name="utility:delete"
185 alternative-text="Remove line"
186 title="Remove line"
187 data-key={line.key}
188 onclick={handleRemoveLine}>
189 </lightning-button-icon>
190 </div>
191 </div>
192 </template>
193
194 <div class="slds-m-top_medium">
195 <lightning-button
196 label="Add line"
197 onclick={handleAddLine}>
198 </lightning-button>
199 </div>
200 <p class="reviewed-total">
201 Reviewed total
202 <lightning-formatted-number
203 value={reviewedTotal}
204 format-style="currency"
205 currency-code={proposalCurrency}>
206 </lightning-formatted-number>
207 </p>
208 <lightning-button
209 label="Confirm breakdown"
210 variant="brand"
211 class="slds-m-top_medium"
212 disabled={isConfirmDisabled}
213 onclick={handleConfirmBreakdown}>
214 </lightning-button>
215 <p class="confirm-note">Confirmation saves the reviewed breakdown. For change orders, use the CPQ amendment quote already created for this Opportunity.</p>
216 </section>
217 </template>
218
219 <template if:true={isConfirmed}>
220 <section class="review-panel confirmed-panel">
221 <div class="section-heading">
222 <span class="step-number">✓</span>
223 <div>
224 <h3>Confirmed budget breakdown</h3>
225 <p>These are the lines saved after review.</p>
226 </div>
227 </div>
228 <template for:each={confirmedLines} for:item="line">
229 <div key={line.key} class="confirmed-row">
230 <span class="confirmed-category">{line.categoryLabel}</span>
231 <span class="confirmed-label">{line.label}</span>
232 <lightning-formatted-number
233 value={line.amount}
234 format-style="currency"
235 currency-code={proposalCurrency}>
236 </lightning-formatted-number>
237 </div>
238 </template>
239 <p class="reviewed-total">
240 Confirmed total
241 <lightning-formatted-number
242 value={confirmedTotal}
243 format-style="currency"
244 currency-code={proposalCurrency}>
245 </lightning-formatted-number>
246 </p>
247 <section class="quote-creation-panel" aria-live="polite">
248 <div class="section-heading">
249 <span class="step-number">4</span>
250 <div>
251 <h3>Complete the CPQ quote</h3>
252 <p>{quoteStatusTitle}</p>
253 </div>
254 </div>
255 <template if:true={canCreateQuote}>
256 <template if:true={isConfirmedNewServices}>
257 <lightning-input
258 type="date"
259 label="Quote start date"
260 value={quoteStartDate}
261 onchange={handleQuoteStartDateChange}
262 required>
263 </lightning-input>
264 </template>
265 <lightning-button
266 label="Create CPQ quote"
267 variant="brand"
268 class="slds-m-top_medium"
269 disabled={isCreateQuoteDisabled}
270 onclick={handleCreateQuote}>
271 </lightning-button>
272 </template>
273 <template if:true={isConfirmedAmendment}>
274 <template if:true={hasPrimaryAmendmentQuote}>
275 <p class="confirm-note">Confirmed products will be added to the primary CPQ amendment quote on this Opportunity.</p>
276 <p><strong>Quote:</strong> {primaryAmendmentQuoteName}</p>
277 <p><strong>Contract being amended:</strong>
278 <lightning-formatted-url value={primaryAmendmentContractUrl}
279 label={primaryAmendmentContractName} target="_blank">
280 </lightning-formatted-url>
281 </p>
282 <lightning-formatted-url
283 value={primaryAmendmentQuoteUrl}
284 label="Open primary amendment quote"
285 target="_blank">
286 </lightning-formatted-url>
287 </template>
288 <template if:false={hasPrimaryAmendmentQuote}>
289 <p class="slds-text-color_error">This Opportunity has no primary CPQ amendment quote.</p>
290 </template>
291 <lightning-button
292 label="Add confirmed products to amendment"
293 variant="brand"
294 class="slds-m-top_medium"
295 disabled={isUseNativeAmendmentDisabled}
296 onclick={handleUseNativeAmendment}>
297 </lightning-button>
298 </template>
299 <template if:true={isQuoteWorking}>
300 <p class="confirm-note">Salesforce is preparing the quote. This page checks for updates every 5 seconds.</p>
301 </template>
302 <template if:true={createdQuoteId}>
303 <p class="slds-m-top_medium">
304 <lightning-formatted-url
305 value={quoteUrl}
306 label="Open CPQ quote"
307 target="_blank">
308 </lightning-formatted-url>
309 </p>
310 </template>
311 <template if:true={quoteCreationError}>
312 <p class="slds-text-color_error slds-m-top_medium">{quoteCreationError}</p>
313 </template>
314 </section>
315 </section>
316 </template>
317
318 <template if:true={loadError}>
319 <div class="slds-text-color_error slds-m-top_medium">{loadError}</div>
320 </template>
321 </div>
322 </lightning-card>
323</template>
lightning · 247 lines

psQuoteAnalyzerTools.css

The presentation: spacing, progress steps, status colors, quote rows, and narrow-screen layout.

Review and understand complete source code

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.quote-tool {CSS selector: the following declarations style matching elements.
2 padding: 1.5rem;CSS declaration: sets this visual property to the value after the colon.
3 color: #181818;CSS declaration: sets this visual property to the value after the colon.
4}Closes the current block or declaration.
5 Spacing separates related steps.
6.intro {CSS selector: the following declarations style matching elements.
7 padding: 1.5rem;CSS declaration: sets this visual property to the value after the colon.
8 margin-bottom: 1.75rem;CSS declaration: sets this visual property to the value after the colon.
9 border-radius: 0.75rem;CSS declaration: sets this visual property to the value after the colon.
10 background: linear-gradient(120deg, #eef5ff, #f8fbff);CSS declaration: sets this visual property to the value after the colon.
11 border: 1px solid #d6e5f8;CSS declaration: sets this visual property to the value after the colon.
12}Closes the current block or declaration.
13 Spacing separates related steps.
14.eyebrow {CSS selector: the following declarations style matching elements.
15 color: #536b86;CSS declaration: sets this visual property to the value after the colon.
16 font-size: 0.7rem;CSS declaration: sets this visual property to the value after the colon.
17 font-weight: 700;CSS declaration: sets this visual property to the value after the colon.
18 letter-spacing: 0.1em;CSS declaration: sets this visual property to the value after the colon.
19}Closes the current block or declaration.
20 Spacing separates related steps.
21.intro h2 {CSS selector: the following declarations style matching elements.
22 margin: 0.35rem 0;CSS declaration: sets this visual property to the value after the colon.
23 font-size: 1.35rem;CSS declaration: sets this visual property to the value after the colon.
24 font-weight: 700;CSS declaration: sets this visual property to the value after the colon.
25 line-height: 1.3;CSS declaration: sets this visual property to the value after the colon.
26}Closes the current block or declaration.
27 Spacing separates related steps.
28.intro p:last-child,Continues the argument list or condition on the next line.
29.section-heading p,Continues the argument list or condition on the next line.
30.status-copy p:last-child,Continues the argument list or condition on the next line.
31.confirm-note {CSS selector: the following declarations style matching elements.
32 color: #5d6571;CSS declaration: sets this visual property to the value after the colon.
33}Closes the current block or declaration.
34 Spacing separates related steps.
35.section-heading {CSS selector: the following declarations style matching elements.
36 display: flex;CSS declaration: sets this visual property to the value after the colon.
37 align-items: flex-start;CSS declaration: sets this visual property to the value after the colon.
38 gap: 0.75rem;CSS declaration: sets this visual property to the value after the colon.
39 margin-bottom: 1rem;CSS declaration: sets this visual property to the value after the colon.
40}Closes the current block or declaration.
41 Spacing separates related steps.
42.section-heading h3 {CSS selector: the following declarations style matching elements.
43 font-size: 1.1rem;CSS declaration: sets this visual property to the value after the colon.
44 font-weight: 700;CSS declaration: sets this visual property to the value after the colon.
45}Closes the current block or declaration.
46 Spacing separates related steps.
47.step-number {CSS selector: the following declarations style matching elements.
48 display: inline-flex;CSS declaration: sets this visual property to the value after the colon.
49 align-items: center;CSS declaration: sets this visual property to the value after the colon.
50 justify-content: center;CSS declaration: sets this visual property to the value after the colon.
51 flex: 0 0 1.8rem;CSS declaration: sets this visual property to the value after the colon.
52 height: 1.8rem;CSS declaration: sets this visual property to the value after the colon.
53 border-radius: 50%;CSS declaration: sets this visual property to the value after the colon.
54 background: #e8f1fc;CSS declaration: sets this visual property to the value after the colon.
55 color: #0758a8;CSS declaration: sets this visual property to the value after the colon.
56 font-weight: 700;CSS declaration: sets this visual property to the value after the colon.
57}Closes the current block or declaration.
58 Spacing separates related steps.
59.upload-area {CSS selector: the following declarations style matching elements.
60 padding: 1rem;CSS declaration: sets this visual property to the value after the colon.
61 border: 1px dashed #9eb7d3;CSS declaration: sets this visual property to the value after the colon.
62 border-radius: 0.5rem;CSS declaration: sets this visual property to the value after the colon.
63 background: #fafcff;CSS declaration: sets this visual property to the value after the colon.
64}Closes the current block or declaration.
65 Spacing separates related steps.
66.status-panel {CSS selector: the following declarations style matching elements.
67 margin-top: 2rem;CSS declaration: sets this visual property to the value after the colon.
68 padding: 1.25rem;CSS declaration: sets this visual property to the value after the colon.
69 border: 1px solid #d7e4f2;CSS declaration: sets this visual property to the value after the colon.
70 border-left: 4px solid #3b82c4;CSS declaration: sets this visual property to the value after the colon.
71 border-radius: 0.5rem;CSS declaration: sets this visual property to the value after the colon.
72 background: #f8fbff;CSS declaration: sets this visual property to the value after the colon.
73}Closes the current block or declaration.
74 Spacing separates related steps.
75.status-panel--review {CSS selector: the following declarations style matching elements.
76 border-left-color: #b87800;CSS declaration: sets this visual property to the value after the colon.
77 background: #fffaf0;CSS declaration: sets this visual property to the value after the colon.
78}Closes the current block or declaration.
79 Spacing separates related steps.
80.status-panel--confirmed {CSS selector: the following declarations style matching elements.
81 border-left-color: #25845a;CSS declaration: sets this visual property to the value after the colon.
82 background: #f4fcf7;CSS declaration: sets this visual property to the value after the colon.
83}Closes the current block or declaration.
84 Spacing separates related steps.
85.status-panel--error {CSS selector: the following declarations style matching elements.
86 border-left-color: #ba3b3b;CSS declaration: sets this visual property to the value after the colon.
87 background: #fff7f7;CSS declaration: sets this visual property to the value after the colon.
88}Closes the current block or declaration.
89 Spacing separates related steps.
90.status-top {CSS selector: the following declarations style matching elements.
91 display: flex;CSS declaration: sets this visual property to the value after the colon.
92 align-items: flex-start;CSS declaration: sets this visual property to the value after the colon.
93 gap: 0.85rem;CSS declaration: sets this visual property to the value after the colon.
94}Closes the current block or declaration.
95 Spacing separates related steps.
96.status-copy {CSS selector: the following declarations style matching elements.
97 flex: 1;CSS declaration: sets this visual property to the value after the colon.
98}Closes the current block or declaration.
99 Spacing separates related steps.
100.status-copy h3 {CSS selector: the following declarations style matching elements.
101 margin: 0.15rem 0;CSS declaration: sets this visual property to the value after the colon.
102 font-size: 1.15rem;CSS declaration: sets this visual property to the value after the colon.
103 font-weight: 700;CSS declaration: sets this visual property to the value after the colon.
104}Closes the current block or declaration.
105 Spacing separates related steps.
106.progress-track {CSS selector: the following declarations style matching elements.
107 display: grid;CSS declaration: sets this visual property to the value after the colon.
108 grid-template-columns: repeat(4, minmax(0, 1fr));CSS declaration: sets this visual property to the value after the colon.
109 gap: 0.5rem;CSS declaration: sets this visual property to the value after the colon.
110 margin-top: 1.25rem;CSS declaration: sets this visual property to the value after the colon.
111}Closes the current block or declaration.
112 Spacing separates related steps.
113.progress-step {CSS selector: the following declarations style matching elements.
114 padding: 0.6rem 0.7rem;CSS declaration: sets this visual property to the value after the colon.
115 border-radius: 0.35rem;CSS declaration: sets this visual property to the value after the colon.
116 background: #e9edf2;CSS declaration: sets this visual property to the value after the colon.
117 color: #697582;CSS declaration: sets this visual property to the value after the colon.
118 font-size: 0.78rem;CSS declaration: sets this visual property to the value after the colon.
119 font-weight: 600;CSS declaration: sets this visual property to the value after the colon.
120 text-align: center;CSS declaration: sets this visual property to the value after the colon.
121}Closes the current block or declaration.
122 Spacing separates related steps.
123.progress-step--active {CSS selector: the following declarations style matching elements.
124 background: #dcecff;CSS declaration: sets this visual property to the value after the colon.
125 color: #064f96;CSS declaration: sets this visual property to the value after the colon.
126}Closes the current block or declaration.
127 Spacing separates related steps.
128.status-panel--confirmed .progress-step--active {CSS selector: the following declarations style matching elements.
129 background: #dcf2e6;CSS declaration: sets this visual property to the value after the colon.
130 color: #1d6b49;CSS declaration: sets this visual property to the value after the colon.
131}Closes the current block or declaration.
132 Spacing separates related steps.
133.status-footnote {CSS selector: the following declarations style matching elements.
134 margin-top: 0.8rem;CSS declaration: sets this visual property to the value after the colon.
135 color: #536b86;CSS declaration: sets this visual property to the value after the colon.
136 font-size: 0.76rem;CSS declaration: sets this visual property to the value after the colon.
137}Closes the current block or declaration.
138 Spacing separates related steps.
139.review-panel {CSS selector: the following declarations style matching elements.
140 margin-top: 1.5rem;CSS declaration: sets this visual property to the value after the colon.
141 padding: 1.5rem;CSS declaration: sets this visual property to the value after the colon.
142 border: 1px solid #dce2e9;CSS declaration: sets this visual property to the value after the colon.
143 border-radius: 0.6rem;CSS declaration: sets this visual property to the value after the colon.
144}Closes the current block or declaration.
145 Spacing separates related steps.
146.proposed-total,Continues the argument list or condition on the next line.
147.reviewed-total {CSS selector: the following declarations style matching elements.
148 display: flex;CSS declaration: sets this visual property to the value after the colon.
149 justify-content: space-between;CSS declaration: sets this visual property to the value after the colon.
150 gap: 1rem;CSS declaration: sets this visual property to the value after the colon.
151 padding: 0.8rem 1rem;CSS declaration: sets this visual property to the value after the colon.
152 border-radius: 0.4rem;CSS declaration: sets this visual property to the value after the colon.
153 background: #f4f7fa;CSS declaration: sets this visual property to the value after the colon.
154 font-weight: 700;CSS declaration: sets this visual property to the value after the colon.
155}Closes the current block or declaration.
156 Spacing separates related steps.
157.reviewed-total {CSS selector: the following declarations style matching elements.
158 margin: 1.25rem 0 0.5rem;CSS declaration: sets this visual property to the value after the colon.
159 background: #eaf4ff;CSS declaration: sets this visual property to the value after the colon.
160}Closes the current block or declaration.
161 Spacing separates related steps.
162.line-row {CSS selector: the following declarations style matching elements.
163 display: grid;CSS declaration: sets this visual property to the value after the colon.
164 grid-template-columns: minmax(11rem, 1.1fr) minmax(14rem, 2fr) minmax(10rem, 1fr) auto;CSS declaration: sets this visual property to the value after the colon.
165 gap: 0.8rem;CSS declaration: sets this visual property to the value after the colon.
166 align-items: end;CSS declaration: sets this visual property to the value after the colon.
167 padding: 0.9rem 0;CSS declaration: sets this visual property to the value after the colon.
168 border-bottom: 1px solid #e5e8ed;CSS declaration: sets this visual property to the value after the colon.
169}Closes the current block or declaration.
170 Spacing separates related steps.
171.remove-line {CSS selector: the following declarations style matching elements.
172 padding-bottom: 0.2rem;CSS declaration: sets this visual property to the value after the colon.
173}Closes the current block or declaration.
174 Spacing separates related steps.
175.confirm-note {CSS selector: the following declarations style matching elements.
176 margin-top: 0.65rem;CSS declaration: sets this visual property to the value after the colon.
177 font-size: 0.78rem;CSS declaration: sets this visual property to the value after the colon.
178}Closes the current block or declaration.
179 Spacing separates related steps.
180.confirmed-panel {CSS selector: the following declarations style matching elements.
181 border-color: #b8dec8;CSS declaration: sets this visual property to the value after the colon.
182 background: #fbfefc;CSS declaration: sets this visual property to the value after the colon.
183}Closes the current block or declaration.
184 Spacing separates related steps.
185.confirmed-panel .step-number {CSS selector: the following declarations style matching elements.
186 background: #dcf2e6;CSS declaration: sets this visual property to the value after the colon.
187 color: #1d6b49;CSS declaration: sets this visual property to the value after the colon.
188}Closes the current block or declaration.
189 Spacing separates related steps.
190.confirmed-row {CSS selector: the following declarations style matching elements.
191 display: grid;CSS declaration: sets this visual property to the value after the colon.
192 grid-template-columns: minmax(11rem, 1.1fr) minmax(14rem, 2fr) minmax(10rem, 1fr);CSS declaration: sets this visual property to the value after the colon.
193 gap: 0.8rem;CSS declaration: sets this visual property to the value after the colon.
194 align-items: center;CSS declaration: sets this visual property to the value after the colon.
195 padding: 0.9rem 0.2rem;CSS declaration: sets this visual property to the value after the colon.
196 border-bottom: 1px solid #e1ece5;CSS declaration: sets this visual property to the value after the colon.
197}Closes the current block or declaration.
198 Spacing separates related steps.
199.confirmed-category {CSS selector: the following declarations style matching elements.
200 color: #1d6b49;CSS declaration: sets this visual property to the value after the colon.
201 font-weight: 700;CSS declaration: sets this visual property to the value after the colon.
202}Closes the current block or declaration.
203 Spacing separates related steps.
204.confirmed-label {CSS selector: the following declarations style matching elements.
205 font-weight: 600;CSS declaration: sets this visual property to the value after the colon.
206}Closes the current block or declaration.
207 Spacing separates related steps.
208.quote-creation-panel {CSS selector: the following declarations style matching elements.
209 margin-top: 1.5rem;CSS declaration: sets this visual property to the value after the colon.
210 padding: 1.25rem;CSS declaration: sets this visual property to the value after the colon.
211 border: 1px solid #c8d9ee;CSS declaration: sets this visual property to the value after the colon.
212 border-radius: 0.5rem;CSS declaration: sets this visual property to the value after the colon.
213 background: #f8fbff;CSS declaration: sets this visual property to the value after the colon.
214}Closes the current block or declaration.
215 Spacing separates related steps.
216@media (max-width: 760px) {Starts layout rules that apply only at the specified screen size.
217 .quote-tool,Continues the argument list or condition on the next line.
218 .review-panel {CSS selector: the following declarations style matching elements.
219 padding: 1rem;CSS declaration: sets this visual property to the value after the colon.
220 }Closes the current block or declaration.
221 Spacing separates related steps.
222 .status-top {CSS selector: the following declarations style matching elements.
223 flex-wrap: wrap;CSS declaration: sets this visual property to the value after the colon.
224 }Closes the current block or declaration.
225 Spacing separates related steps.
226 .status-top lightning-button {CSS selector: the following declarations style matching elements.
227 margin-left: 2.2rem;CSS declaration: sets this visual property to the value after the colon.
228 }Closes the current block or declaration.
229 Spacing separates related steps.
230 .progress-track {CSS selector: the following declarations style matching elements.
231 grid-template-columns: repeat(2, minmax(0, 1fr));CSS declaration: sets this visual property to the value after the colon.
232 }Closes the current block or declaration.
233 Spacing separates related steps.
234 .line-row {CSS selector: the following declarations style matching elements.
235 grid-template-columns: 1fr;CSS declaration: sets this visual property to the value after the colon.
236 gap: 0.35rem;CSS declaration: sets this visual property to the value after the colon.
237 }Closes the current block or declaration.
238 Spacing separates related steps.
239 .confirmed-row {CSS selector: the following declarations style matching elements.
240 grid-template-columns: 1fr;CSS declaration: sets this visual property to the value after the colon.
241 gap: 0.25rem;CSS declaration: sets this visual property to the value after the colon.
242 }Closes the current block or declaration.
243 Spacing separates related steps.
244 .remove-line {CSS selector: the following declarations style matching elements.
245 justify-self: end;CSS declaration: sets this visual property to the value after the colon.
246 }Closes the current block or declaration.
247}Closes the current block or declaration.
View complete source code
1.quote-tool {
2 padding: 1.5rem;
3 color: #181818;
4}
5
6.intro {
7 padding: 1.5rem;
8 margin-bottom: 1.75rem;
9 border-radius: 0.75rem;
10 background: linear-gradient(120deg, #eef5ff, #f8fbff);
11 border: 1px solid #d6e5f8;
12}
13
14.eyebrow {
15 color: #536b86;
16 font-size: 0.7rem;
17 font-weight: 700;
18 letter-spacing: 0.1em;
19}
20
21.intro h2 {
22 margin: 0.35rem 0;
23 font-size: 1.35rem;
24 font-weight: 700;
25 line-height: 1.3;
26}
27
28.intro p:last-child,
29.section-heading p,
30.status-copy p:last-child,
31.confirm-note {
32 color: #5d6571;
33}
34
35.section-heading {
36 display: flex;
37 align-items: flex-start;
38 gap: 0.75rem;
39 margin-bottom: 1rem;
40}
41
42.section-heading h3 {
43 font-size: 1.1rem;
44 font-weight: 700;
45}
46
47.step-number {
48 display: inline-flex;
49 align-items: center;
50 justify-content: center;
51 flex: 0 0 1.8rem;
52 height: 1.8rem;
53 border-radius: 50%;
54 background: #e8f1fc;
55 color: #0758a8;
56 font-weight: 700;
57}
58
59.upload-area {
60 padding: 1rem;
61 border: 1px dashed #9eb7d3;
62 border-radius: 0.5rem;
63 background: #fafcff;
64}
65
66.status-panel {
67 margin-top: 2rem;
68 padding: 1.25rem;
69 border: 1px solid #d7e4f2;
70 border-left: 4px solid #3b82c4;
71 border-radius: 0.5rem;
72 background: #f8fbff;
73}
74
75.status-panel--review {
76 border-left-color: #b87800;
77 background: #fffaf0;
78}
79
80.status-panel--confirmed {
81 border-left-color: #25845a;
82 background: #f4fcf7;
83}
84
85.status-panel--error {
86 border-left-color: #ba3b3b;
87 background: #fff7f7;
88}
89
90.status-top {
91 display: flex;
92 align-items: flex-start;
93 gap: 0.85rem;
94}
95
96.status-copy {
97 flex: 1;
98}
99
100.status-copy h3 {
101 margin: 0.15rem 0;
102 font-size: 1.15rem;
103 font-weight: 700;
104}
105
106.progress-track {
107 display: grid;
108 grid-template-columns: repeat(4, minmax(0, 1fr));
109 gap: 0.5rem;
110 margin-top: 1.25rem;
111}
112
113.progress-step {
114 padding: 0.6rem 0.7rem;
115 border-radius: 0.35rem;
116 background: #e9edf2;
117 color: #697582;
118 font-size: 0.78rem;
119 font-weight: 600;
120 text-align: center;
121}
122
123.progress-step--active {
124 background: #dcecff;
125 color: #064f96;
126}
127
128.status-panel--confirmed .progress-step--active {
129 background: #dcf2e6;
130 color: #1d6b49;
131}
132
133.status-footnote {
134 margin-top: 0.8rem;
135 color: #536b86;
136 font-size: 0.76rem;
137}
138
139.review-panel {
140 margin-top: 1.5rem;
141 padding: 1.5rem;
142 border: 1px solid #dce2e9;
143 border-radius: 0.6rem;
144}
145
146.proposed-total,
147.reviewed-total {
148 display: flex;
149 justify-content: space-between;
150 gap: 1rem;
151 padding: 0.8rem 1rem;
152 border-radius: 0.4rem;
153 background: #f4f7fa;
154 font-weight: 700;
155}
156
157.reviewed-total {
158 margin: 1.25rem 0 0.5rem;
159 background: #eaf4ff;
160}
161
162.line-row {
163 display: grid;
164 grid-template-columns: minmax(11rem, 1.1fr) minmax(14rem, 2fr) minmax(10rem, 1fr) auto;
165 gap: 0.8rem;
166 align-items: end;
167 padding: 0.9rem 0;
168 border-bottom: 1px solid #e5e8ed;
169}
170
171.remove-line {
172 padding-bottom: 0.2rem;
173}
174
175.confirm-note {
176 margin-top: 0.65rem;
177 font-size: 0.78rem;
178}
179
180.confirmed-panel {
181 border-color: #b8dec8;
182 background: #fbfefc;
183}
184
185.confirmed-panel .step-number {
186 background: #dcf2e6;
187 color: #1d6b49;
188}
189
190.confirmed-row {
191 display: grid;
192 grid-template-columns: minmax(11rem, 1.1fr) minmax(14rem, 2fr) minmax(10rem, 1fr);
193 gap: 0.8rem;
194 align-items: center;
195 padding: 0.9rem 0.2rem;
196 border-bottom: 1px solid #e1ece5;
197}
198
199.confirmed-category {
200 color: #1d6b49;
201 font-weight: 700;
202}
203
204.confirmed-label {
205 font-weight: 600;
206}
207
208.quote-creation-panel {
209 margin-top: 1.5rem;
210 padding: 1.25rem;
211 border: 1px solid #c8d9ee;
212 border-radius: 0.5rem;
213 background: #f8fbff;
214}
215
216@media (max-width: 760px) {
217 .quote-tool,
218 .review-panel {
219 padding: 1rem;
220 }
221
222 .status-top {
223 flex-wrap: wrap;
224 }
225
226 .status-top lightning-button {
227 margin-left: 2.2rem;
228 }
229
230 .progress-track {
231 grid-template-columns: repeat(2, minmax(0, 1fr));
232 }
233
234 .line-row {
235 grid-template-columns: 1fr;
236 gap: 0.35rem;
237 }
238
239 .confirmed-row {
240 grid-template-columns: 1fr;
241 gap: 0.25rem;
242 }
243
244 .remove-line {
245 justify-self: end;
246 }
247}
lightning · 21 lines

psNavigateToOpportunity.js

A small Flow action component that opens the new Opportunity record.

  • invoke() line 7Validate Flow’s Opportunity ID and navigate to its record page.
Review and understand complete source code

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.

1import { LightningElement, api } from 'lwc';Imports a framework feature or an Apex method used by this JavaScript file.
2import { NavigationMixin } from 'lightning/navigation';Imports a framework feature or an Apex method used by this JavaScript file.
3 Spacing separates related steps.
4export default class PsNavigateToOpportunity extends NavigationMixin(LightningElement) {Declares the Lightning component class and the behavior it contains.
5 @api opportunityId;Exposes this JavaScript property or method to the component’s parent.
6 Spacing separates related steps.
7 @api invoke() {Exposes this JavaScript property or method to the component’s parent.
8 if (!this.opportunityId) {Guard or branch: the following block runs only when this condition is true.
9 throw new Error('The change order did not return an Opportunity ID.');Stops this path and reports an error to the caller.
10 }Closes the current block or declaration.
11 Spacing separates related steps.
12 this[NavigationMixin.Navigate]({Opens a block; the indented lines below execute or belong together.
13 type: 'standard__recordPage',Continues the argument list or condition on the next line.
14 attributes: {Opens a block; the indented lines below execute or belong together.
15 recordId: this.opportunityId,Continues the argument list or condition on the next line.
16 objectApiName: 'Opportunity',Continues the argument list or condition on the next line.
17 actionName: 'view'Part of the surrounding declaration or expression; read it with the adjacent lines.
18 }Closes the current block or declaration.
19 });Completes the statement begun on this line or the preceding lines.
20 }Closes the current block or declaration.
21}Closes the current block or declaration.
View complete source code
1import { LightningElement, api } from 'lwc';
2import { NavigationMixin } from 'lightning/navigation';
3
4export default class PsNavigateToOpportunity extends NavigationMixin(LightningElement) {
5 @api opportunityId;
6
7 @api invoke() {
8 if (!this.opportunityId) {
9 throw new Error('The change order did not return an Opportunity ID.');
10 }
11
12 this[NavigationMixin.Navigate]({
13 type: 'standard__recordPage',
14 attributes: {
15 recordId: this.opportunityId,
16 objectApiName: 'Opportunity',
17 actionName: 'view'
18 }
19 });
20 }
21}

A five-minute study loop

  1. Pick a button or error message in the component.
  2. Find its JavaScript handler and the imported Apex method it calls.
  3. Mark the method’s inputs, checks, SOQL reads, DML writes, and return value.
  4. If it queues work, follow HEADER → LINES → CALCULATE through BuildJob.execute.
  5. Find the test for that branch and label its arrange, act, and assert portions. Check combined class coverage after a fresh run.