Pricing procedures cover most of what a price needs: list prices, adjustment schedules, attribute and bundle rows, formulas. Some rules still don't fit, and an Apex pricing hook is how we add them. A hook is an Apex class that the procedure plan runs as its own section, before pricing (a prehook) or after it (a posthook). It reads the same pricing context the procedure reads, and writes values back into it.1
This page builds one: a QuantumBit prehook that discounts training lines when the same quote carries the Complete Solution.
What it's for
Reach for a hook only when the procedure can't express the rule on its own. The usual reasons:
| The rule needs | Why a pricing element struggles | Hook |
|---|---|---|
| To look across lines ("training is cheaper when the quote also has the Complete Solution") | Elements price one line at a time against lookup tables | Prehook |
| A value from another system, such as a rate or an entitlement | Procedures don't make callouts | Prehook, with limits below |
| To adjust group or header results after every line is priced | Group totals only exist once pricing has run | Posthook |
| A field or attribute the standard elements don't read | Elements read mapped tags, nothing else | Prehook that sets a tag the procedure does read |
If a decision table, an adjustment schedule or a formula element can do it, use that instead. A hook is code: it needs tests, it adds to the transaction's CPU time, and every pricing change runs it.
How it works
Where a hook runs
In short: a hook is an Apex section in a procedure plan, placed above or below the Pricing section, and it runs only when Procedure Plan Orchestration for Pricing is on.
Procedure plans decide which procedures run for a quote or order and in what order. When the Procedure Plan Orchestration for Pricing setting is on in Revenue Settings, the procedure plan, not the single procedure named in Revenue Settings, drives pricing, and it can hold Apex sections.1 The RevSignaling namespace, which every hook implements, requires the same setting.3
A hook is a section on the procedure plan definition with Section Type Apex, Phase Pricing and Resolution Type Default, pointing at an Apex class. Sections above the Pricing section are prehooks; sections below it are posthooks. Manage Sections sets the order.1 When the plan uses the Revenue Cloud process type, an Apex section must be the first or last element of the plan's execution sequence.1
In the data, that's three objects. The definition is ProcedurePlanDefinition (the launchpad's quote plan is RLM_Quote_Pricing_Procedure_Plan, Primary Object Quote). Its sections are ProcedurePlanSection rows with SectionType, Phase and Sequence. Each section's options are ProcedurePlanOption rows, and an Apex option carries ApexClassName. We read those fields from our lab org on 2026-11-08.
ProcedurePlanDefinition for the Quote has ProcedurePlanSection rows (SectionType Apex, Phase Pricing, a Sequence); each section has ProcedurePlanOption rows, and the option's ApexClassName names your class, which implements RevSignaling.SignalingApexProcessor.The interface
In short: implement RevSignaling.SignalingApexProcessor, take a TransactionRequest, return a TransactionResponse with a status.
The interface has one method:4
public RevSignaling.TransactionResponse execute(RevSignaling.TransactionRequest request)
| Class | What you use |
|---|---|
TransactionRequest |
ctxInstanceId, the ID of the pricing context instance, and procedurePlanInstance, the plan run that called you5 |
ProcedurePlan |
prevStepOutput, a Map<String, Object> holding the previous step's output6 |
TransactionResponse |
status (a TransactionStatus: SUCCESS or FAILED) and message7 |
Salesforce's own samples are global classes. We follow them, so the class can be picked in the plan's Apex selection box.
Reading and writing the context
In short: read with Context.IndustriesContext.leanerQueryTags, asking only for the tags you need; write with updateContextAttributes.
The hook never touches records. It works on the pricing context, the in-memory copy of the quote that the procedure prices, through the Context.IndustriesContext class.1
TransactionRequest names the context instance. The hook reads tag values with leanerQueryTags, decides in plain Apex with no context so unit tests can reach it, writes a Discount back with updateContextAttributes, and returns a TransactionResponse with SUCCESS or FAILED. It never runs DML.There are two ways to read. queryTags returns full nodes, with six fields wrapped around every attribute of every item, and every attribute of the tag you ask for. leanerQueryTags returns flat tag values and a shared recordsInfo list of record IDs, and Salesforce recommends it wherever it works.2 Ask for specific tags, such as ItemProductCode or LineItemQuantity, not the broad SalesTransactionItem tag.2
A leaner result looks like this. Each tag value carries recordIdIndexesForPath: index 0 points at the transaction, index 1 at the line, and index 2 at a detail under the line.2
{
"isSuccess": true,
"leanerQueryTagResult": {
"ItemProductCode": [
{ "recordIdIndexesForPath": [0, 1], "tagValue": "QB-COMPLETE", "isNodeLevelTag": false }
]
},
"recordsInfo": [
{ "recordId": "0Q0...", "dmlStatusOrdinal": null },
{ "recordId": "0QL...", "dmlStatusOrdinal": null }
]
}
Lines being deleted in this same change still appear in the result. To skip them, ask for LineItem$DmlStatus as a separate tag and drop lines whose value is DELETED.2
ItemProductCode QB-COMPLETE carries recordIdIndexesForPath 0 and 1: index 0 picks the quote from the shared recordsInfo list and index 1 picks the line. The write uses the same IDs in order as its dataPath, so updateContextAttributes sets Discount on that one line.To write, pass updateContextAttributes a list of node paths and attributes. A line's path is the transaction ID, then the line ID. Salesforce's discount sample sets the attribute named Discount this way.1
The limits that shape the code
In short: one Apex transaction for the whole plan, no DML, and callouts only in some cases.
- One transaction. Every hook in the plan runs in the same Apex transaction, so CPU time adds up across all of them. Large quotes feel it first.2
- No DML. Inserts and updates inside a hook aren't supported: they can leave the pricing context stale.1
- Callouts, sometimes. A hook can call out only when the request came from the Salesforce UI or the Place Sales Transaction API, never from Apex or a Flow, and not when Double Persist mode is on. Salesforce also warns that callouts make response times unpredictable.1
- Heap. Values you hold in Apex variables count against heap, which is one more reason to query only the tags you need.1
Build it
The rule: when a quote carries the QuantumBit Complete Solution (QB-COMPLETE), every QuantumBit training line on it (codes starting QB-TRN-) gets a 10 percent discount before pricing. A pricing element prices one line and can't see that the Complete Solution sits on a different line. A hook can.
We split the class into three parts so the rule can be tested without a pricing context: read the context, decide with plain Apex, write the context.
global class QBTrainingDiscountHook implements RevSignaling.SignalingApexProcessor {
@TestVisible static final String ANCHOR_CODE = 'QB-COMPLETE';
@TestVisible static final String TRAINING_PREFIX = 'QB-TRN-';
@TestVisible static final Decimal TRAINING_DISCOUNT = 10;
@TestVisible static final List<String> TAGS = new List<String>{ 'LineItem', 'LineItem$DmlStatus', 'ItemProductCode' };
public RevSignaling.TransactionResponse execute(RevSignaling.TransactionRequest request) {
RevSignaling.TransactionResponse response = new RevSignaling.TransactionResponse();
try {
Context.IndustriesContext ctx = new Context.IndustriesContext();
// 1. Read: only the tags the rule needs, with the lightweight query.
Map<String, Object> output = ctx.leanerQueryTags(new Map<String, Object>{
'contextId' => request.ctxInstanceId, 'tags' => TAGS
});
// 2. Decide: plain Apex, no context, so a unit test can reach it.
Lines lines = linesFrom(output);
List<Map<String, Object>> updates = updatesFor(lines.quoteId, discountsFor(lines.codeByLine));
// 3. Write: back into the context, never with DML.
if (!updates.isEmpty()) {
ctx.updateContextAttributes(new Map<String, Object>{
'contextId' => request.ctxInstanceId, 'nodePathAndAttributes' => updates
});
}
response.status = RevSignaling.TransactionStatus.SUCCESS;
response.message = 'Training discount applied to ' + updates.size() + ' line(s).';
} catch (Exception e) {
response.status = RevSignaling.TransactionStatus.FAILED;
response.message = 'QBTrainingDiscountHook: ' + e.getMessage();
}
return response;
}
@TestVisible class Lines {
public String quoteId;
public Map<String, String> codeByLine = new Map<String, String>();
}
/** Turn a leanerQueryTags result into product codes by line, skipping deleted lines. */
@TestVisible static Lines linesFrom(Map<String, Object> output) {
Map<String, Object> result = (Map<String, Object>) output.get('leanerQueryTagResult');
List<Object> records = (List<Object>) output.get('recordsInfo');
Lines lines = new Lines();
Set<String> deleted = new Set<String>();
for (Object o : listOf(result, 'LineItem$DmlStatus')) {
Map<String, Object> tag = (Map<String, Object>) o;
if (String.valueOf(tag.get('tagValue')) == 'DELETED') deleted.add(idAt(records, tag, 1));
}
for (Object o : listOf(result, 'ItemProductCode')) {
Map<String, Object> tag = (Map<String, Object>) o;
String lineId = idAt(records, tag, 1); // index 0 is the quote, index 1 the line
lines.quoteId = idAt(records, tag, 0);
if (!deleted.contains(lineId)) lines.codeByLine.put(lineId, (String) tag.get('tagValue'));
}
return lines;
}
/** The rule itself. */
@TestVisible static Map<String, Decimal> discountsFor(Map<String, String> codeByLine) {
Map<String, Decimal> discounts = new Map<String, Decimal>();
if (!codeByLine.values().contains(ANCHOR_CODE)) return discounts;
for (String lineId : codeByLine.keySet()) {
String code = codeByLine.get(lineId);
if (code != null && code.startsWith(TRAINING_PREFIX)) discounts.put(lineId, TRAINING_DISCOUNT);
}
return discounts;
}
/** One updateContextAttributes entry per discounted line: the path is [quote, line]. */
@TestVisible static List<Map<String, Object>> updatesFor(String quoteId, Map<String, Decimal> discounts) {
List<Map<String, Object>> updates = new List<Map<String, Object>>();
for (String lineId : discounts.keySet()) {
updates.add(new Map<String, Object>{
'nodePath' => new Map<String, Object>{ 'dataPath' => new List<Object>{ quoteId, lineId } },
'attributes' => new List<Object>{
new Map<String, Object>{ 'attributeName' => 'Discount', 'attributeValue' => discounts.get(lineId) }
}
});
}
return updates;
}
static List<Object> listOf(Map<String, Object> result, String tag) {
Object values = result == null ? null : result.get(tag);
return values == null ? new List<Object>() : (List<Object>) values;
}
static String idAt(List<Object> records, Map<String, Object> tag, Integer level) {
List<Object> indexes = (List<Object>) tag.get('recordIdIndexesForPath');
return (String) ((Map<String, Object>) records[Integer.valueOf(indexes[level])]).get('recordId');
}
}
Then wire it in, as the lab does step by step:
- Check that Procedure Plan Orchestration for Pricing is on in Revenue Settings, and leave Exclude Default and Sales Transaction Type Pricing Procedures off.1
- Deploy the class and its test.
- On the quote's procedure plan definition, add a Standard section of type Apex, with Phase Pricing, Resolution Type Default and the class QBTrainingDiscountHook.1
- With Manage Sections, move it above the Pricing section, then save the plan.1
Test and debug
There is no pricing context inside an Apex unit test, so we don't try to call the context. We test the three plain parts with a fake leaner result built in the shape Salesforce documents. One more test checks that execute reports FAILED instead of throwing when the context call fails.
@IsTest
private class QBTrainingDiscountHookTest {
// The shape leanerQueryTags returns: flat tag values that point into a shared recordsInfo list.
static Map<String, Object> leanerOutput(Map<String, String> codeByLine, Set<String> deletedLines) {
List<Object> records = new List<Object>{ new Map<String, Object>{ 'recordId' => 'quote1' } };
List<Object> codes = new List<Object>(), statuses = new List<Object>();
for (String lineId : codeByLine.keySet()) {
records.add(new Map<String, Object>{ 'recordId' => lineId });
List<Object> path = new List<Object>{ 0, records.size() - 1 };
codes.add(new Map<String, Object>{ 'tagValue' => codeByLine.get(lineId), 'recordIdIndexesForPath' => path });
statuses.add(new Map<String, Object>{ 'tagValue' => deletedLines.contains(lineId) ? 'DELETED' : null, 'recordIdIndexesForPath' => path });
}
return new Map<String, Object>{
'leanerQueryTagResult' => new Map<String, Object>{ 'ItemProductCode' => codes, 'LineItem$DmlStatus' => statuses },
'recordsInfo' => records
};
}
@IsTest static void readsLinesAndSkipsDeletedOnes() {
QBTrainingDiscountHook.Lines lines = QBTrainingDiscountHook.linesFrom(leanerOutput(
new Map<String, String>{ 'line1' => 'QB-COMPLETE', 'line2' => 'QB-TRN-FUND' }, new Set<String>{ 'line2' }));
Assert.areEqual('quote1', lines.quoteId);
Assert.areEqual(new Map<String, String>{ 'line1' => 'QB-COMPLETE' }, lines.codeByLine);
}
@IsTest static void discountsTrainingWhenCompleteSolutionIsOnTheQuote() {
Map<String, Decimal> d = QBTrainingDiscountHook.discountsFor(new Map<String, String>{
'line1' => 'QB-COMPLETE', 'line2' => 'QB-TRN-ESSNTLS', 'line3' => 'QB-TRN-FUND', 'line4' => 'QB-DB'
});
Assert.areEqual(new Set<String>{ 'line2', 'line3' }, d.keySet());
Assert.areEqual(10, d.get('line2'));
}
@IsTest static void leavesTrainingAloneWithoutCompleteSolution() {
Assert.isTrue(QBTrainingDiscountHook.discountsFor(new Map<String, String>{ 'line1' => 'QB-TRN-ESSNTLS' }).isEmpty());
}
@IsTest static void buildsOneContextUpdatePerLine() {
List<Map<String, Object>> updates = QBTrainingDiscountHook.updatesFor('quote1', new Map<String, Decimal>{ 'line2' => 10 });
Assert.areEqual(1, updates.size());
Map<String, Object> nodePath = (Map<String, Object>) updates[0].get('nodePath');
Assert.areEqual(new List<Object>{ 'quote1', 'line2' }, nodePath.get('dataPath'));
}
@IsTest static void reportsFailureInsteadOfThrowing() {
// No pricing context exists in a unit test, so the context call fails; the hook must say so, not throw.
RevSignaling.TransactionResponse res = new QBTrainingDiscountHook().execute(new RevSignaling.TransactionRequest(null, 'not-a-context'));
Assert.areEqual(RevSignaling.TransactionStatus.FAILED, res.status);
Assert.isTrue(res.message.startsWith('QBTrainingDiscountHook: '));
}
}
On 2026-11-08 we deployed both classes to our lab org (API 68.0), running only this test class. All five tests passed, and the hook class had 48 of its 55 lines covered (87 percent). The uncovered lines are the successful path through the live context, which only a real pricing run reaches.
When the hook runs for real:
- Apex debug logs show your
System.debuglines. Salesforce's samples log the request and the update payload withJSON.serializePrettybefore writing it.1 - The price waterfall on the quote line shows whether pricing picked up the discount the hook set.
- The response message is yours to fill. Keep it short and specific, so a failed run says which hook failed and why.
Watch out
A hook only sets values; it doesn't undo them. Ours sets a 10 percent discount when the Complete Solution is there, but if a rep removes the Complete Solution later, the training lines keep the discount. Clearing it would also clear a discount the rep typed by hand. Decide which you want, and write it down.
Querying the broad SalesTransactionItem tag returns every attribute of every line. Hooks written from Salesforce's first samples do this. Move them to specific tags and leanerQueryTags before quotes get large.
Lines deleted in the current change are still in the context. Without the LineItem$DmlStatus tag, your rule counts them.
All hooks in a plan share one transaction's CPU limit. Two well-behaved hooks can still add up to a timeout on a 500-line quote.
No DML inside a hook, not even to write a log record. Use debug logs, or publish what you need to record from somewhere outside pricing.
Callouts from a hook fail when pricing is started from Apex or a Flow. A hook that calls out works from the UI and the Place Sales Transaction API, then breaks in an integration that calls the action from a Flow.
Sources
Every numbered note links to the Salesforce page it comes from. We read each one on 2026-11-08, when the Help article was last published 2026-11-06.
- Salesforce Help: Customize Your Procedure Plans With Apex Hooks, and Best Practices for Apex Pricing Hooks, Winter '27 (264), read 2026-11-08
- Revenue Management Developer Guide: Salesforce Pricing Apex Reference, the
RevSignalingnamespace, read 2026-11-08 - Our lab org (built with Salesforce's rlm-base-dev launchpad): procedure plan objects and fields, product codes and the test run above, read 2026-11-08