SAP Commerce Cart & Checkout Architecture — Part 8
From Add to Cart to Order Placement: Building Customer-Aware B2B Business Rules
Version 1 · Technical editorial draft · SAP Commerce 2211 reference baseline
A cart request that is not just an add-to-cart operation
A buyer at an industrial spare-parts distributor needs two used hydraulic assemblies. The catalog lists part HYD-410 in three sellable conditions: new, refurbished, and used. The buyer sees the used offer at a lower price and clicks Add to cart.
In a simple demonstration, adding an item means finding a product and updating a quantity. In a real B2B storefront, that click can involve customer entitlement, contract pricing, stock by condition and warehouse, quantity limits, and delivery restrictions. Our implementation must enforce those rules without turning the OCC controller into a second business-service layer.
Running requirement
Account NORTH-INDUSTRIAL may purchase used HYD-410 only when its agreement allows used parts, an applicable price can be resolved, and sufficient used stock exists in an eligible warehouse. The buyer must select an authorized Ship-To. All material conditions are checked again before order placement.
We will follow the same cart from request to order, introducing an extension point only when the next business requirement needs it.
First choose what a “used product” means in the catalog
Before adding validators, settle product identity. A used assembly is not necessarily interchangeable with a new assembly for pricing, warranty, serial number, inventory, or fulfillment. One design is to represent each sellable condition as a separate SKU or variant, linked to a shared part family. Another is to model condition-specific offers under a canonical product. Both can work; what matters is that a cart entry identifies the exact sellable item and the corresponding stock and price context.
Part family: HYD-410 ├── HYD-410-NEW → New, regular supply ├── HYD-410-REF → Refurbished, limited supply └── HYD-410-USED → Used, serial/condition-sensitive stock
For this article, we choose separate sellable SKUs. This keeps the sample straightforward: the cart entry references HYD-410-USED, not a generic product whose condition could change later.
Design Insight
Product condition is a domain identity decision, not merely a checkbox on the storefront. Decide it before designing stock lookup, price selection, and order entry mapping.
Modeling the sellable condition
For our chosen separate-SKU approach, the condition is a characteristic of the sellable product, while its commercial terms and stock remain tied to the specific SKU. The following illustrates a custom attribute definition, not a claim that these attributes ship OOTB:
<enumtype code="PartCondition" autocreate="true" generate="true"> <value code="NEW"/> <value code="REFURBISHED"/> <value code="USED"/></enumtype><itemtype code="Product" autocreate="false" generate="false"> <attributes> <attribute qualifier="partCondition" type="PartCondition"> <modifiers optional="true"/> <persistence type="property"/> </attribute> </attributes></itemtype>
For a production model, define the enum in the appropriate extension, assess catalog synchronization and data migration, and decide whether each serialized used unit needs a separate inventory/offer entity. The SKU-based example assumes used inventory is fungible within its defined grade; that assumption must be revisited for individually serialized item

Cart modification lifecycle — conceptual responsibility flow
Following the OOTB add-to-cart boundary
The request enters through the storefront or OCC endpoint. The controller validates the shape of the request and delegates to a facade. The facade resolves the cart and product context and uses the commerce cart service to perform the modification. The core concepts to inspect in SAP Commerce 2211 are CommerceCartService, CommerceCartParameter, and CommerceCartModification; exact facade/controller names and signatures depend on the installed extensions.
OCC / storefront ↓Cart facade ↓Custom eligibility orchestration (before mutation) ↓CommerceCartService.addToCart(...) ↓Cart modification result + calculation ↓Facade maps response to OCC / UI
We should reuse the OOTB cart modification pathway for entry merging, modification status, and calculation integration rather than directly inserting AbstractOrderEntryModel records in a controller.
Common Mistake
Directly changing cart entries withmodelService.save()from OCC to avoid the cart service. This bypasses expected commerce cart behaviors and creates inconsistencies around recalculation and modification status.
Using the OOTB cart mutation contract
Rather than adding entries directly to CartModel, construct a CommerceCartParameter and delegate to CommerceCartService. The following is a representative 2211-style service-layer pattern; project-specific exceptions, cart resolution and exact signatures require verification in the installed patch.
public CommerceCartModification addValidatedItem( final CartModel cart, final ProductModel product, final long quantity) throws CommerceCartModificationException { final long existing = cart.getEntries().stream() .filter(e -> product.equals(e.getProduct())) .mapToLong(e -> e.getQuantity() == null ? 0L : e.getQuantity()) .sum(); eligibilityService.assertEligible( cart, product, Math.addExact(existing, quantity), EligibilityPhase.CART_MODIFICATION); final CommerceCartParameter parameter = new CommerceCartParameter(); parameter.setCart(cart); parameter.setProduct(product); parameter.setQuantity(quantity); parameter.setEnableHooks(true); return commerceCartService.addToCart(parameter);}
Important: The resulting-quantity calculation above is illustrative. For updates, replacements, entry-number semantics, configurable products, and multiple entries of the same SKU, derive the final quantity using the actual cart operation and OOTB modification behavior. Treat a successful precheck as advisory until mutation and final checks complete.
Design Insight
Facades should orchestrate user-facing flows; reusable policies should live in services/strategies. Do not bypass OOTB cart modification and calculation by directly saving order entries.

Customer-aware business rules — conceptual responsibility flow
Introducing a reusable eligibility policy
We now need to reject purchases that violate the account agreement, but we do not want the same logic copied into add-to-cart, quantity update, and checkout. A custom eligibility service coordinates focused rules and returns structured failures.
// Project-specific contract: not an OOTB SAP Commerce interfacepublic interface CartEligibilityService { EligibilityResult evaluate( CartModel cart, ProductModel sellableProduct, long resultingQuantity, EligibilityPhase phase);}public enum EligibilityPhase { CART_MODIFICATION, PRE_ORDER}
The resultingQuantity matters: if the cart already contains two units and the buyer adds two more, the rule must evaluate four, not just the increment of two.
// Illustrative orchestration; adapt to your project's service contractspublic EligibilityResult evaluate( final CartModel cart, final ProductModel product, final long resultingQuantity, final EligibilityPhase phase) { final EligibilityResult result = new EligibilityResult(); customerProductPolicy.check(cart.getUser(), product, result); quantityPolicy.check(product, resultingQuantity, result); pricePolicy.check(cart, product, result); inventoryPolicy.check(cart, product, resultingQuantity, result); if (phase == EligibilityPhase.PRE_ORDER) { shipToPolicy.check(cart, result); } return result;}
These policy interfaces and EligibilityResult are custom design examples, not classes delivered by SAP Commerce. A production implementation should use stable error codes, localization, and appropriate exception-to-OCC mappings.
Returning structured, actionable rule failures
// Custom project contract — not an SAP Commerce OOTB APIpublic record EligibilityViolation( String code, String productCode, String message) {}public record EligibilityResult( boolean allowed, List<EligibilityViolation> violations) {}public interface CartRule { List<EligibilityViolation> evaluate( CartModel cart, ProductModel product, long resultingQuantity, EligibilityPhase phase);}public class DefaultCartEligibilityService implements CartEligibilityService { private List<CartRule> rules; @Override public EligibilityResult evaluate(CartModel cart, ProductModel product, long resultingQuantity, EligibilityPhase phase) { final List<EligibilityViolation> violations = rules.stream() .flatMap(rule -> rule.evaluate( cart, product, resultingQuantity, phase).stream()) .toList(); return new EligibilityResult(violations.isEmpty(), violations); } public void setRules(List<CartRule> rules) { this.rules = rules; }}
The rule list is intentionally project-owned: entitlement, commercial pricing, quantity policy, and eligible stock can be tested independently. For pre-order checks, evaluate every relevant cart entry, not only the product most recently modified.
Wiring the policy through Spring
<bean id="cartEligibilityService" class="com.example.core.cart.impl.DefaultCartEligibilityService"> <property name="rules"> <list> <ref bean="accountProductRule"/> <ref bean="contractPriceRule"/> <ref bean="conditionQuantityRule"/> <ref bean="eligibleStockRule"/> </list> </property></bean>
The bean identifiers and classes above are custom examples. Integration should use a deliberate facade/service orchestration or a verified cart extension point, rather than assuming all cart operations automatically invoke this bean.
Rule 1: Product eligibility belongs to the trusted B2B account
The buyer may see a used part in search, but the account agreement determines whether it can be purchased. The eligibility policy resolves the authenticated customer and active B2B context on the server. It must not trust an arbitrary account ID submitted by the browser.
Authenticated user → active B2B unit/account ↓ Entitlement / agreement lookup ↓ Is HYD-410-USED purchasable here?
When a rule fails, return a business error such as PRODUCT_NOT_ELIGIBLE_FOR_ACCOUNT and avoid mutating the cart. The same rule must protect quantity changes and final order placement; hiding an Add to Cart button is only a UX aid, not authorization.
Design Decision
Keep the policy behind a dedicated service so entitlement data can later come from SAP Commerce models, an ERP contract service, or a cached integration without changing the OCC contract.
Rule 2: A visible product is not always a priced product
The account can purchase used parts, but can we calculate a valid price for this particular buyer, currency, unit, and quantity? SAP Commerce has OOTB price calculation mechanisms, including price rows, but some enterprises resolve prices from external contract systems. We should not assume the price displayed in a search index is the price the buyer will pay.
Our price policy distinguishes three outcomes: a valid purchasable price, no applicable price, or a temporary pricing-service failure. These are not equivalent. An absent contract price may require a quote workflow; a service timeout may warrant a retryable error. Neither should silently fall back to an unrelated list price unless the business explicitly permits that behavior.
Customer + B2B account + currency + product + quantity ↓ Pricing resolution ↓ Valid price | No price | Service failure
Once the cart changes, the standard calculation pathway must still calculate line totals, discounts, tax, and order totals. A custom eligibility check should not replace the calculation engine.
Rule 3: Used-part stock is limited and condition-specific
There are only three used units in an eligible warehouse. The buyer wants two, and another buyer may be shopping for the same stock. A pre-add inventory check improves feedback but does not guarantee fulfillment. Inventory can change after the check.
The stock policy therefore asks for availability of the exact used SKU in warehouses eligible for the current delivery context. It must account for existing cart quantity and units that are genuinely available to sell—not simply an unrestricted global stock number.
HYD-410-USED Warehouse A: 3 eligible units Warehouse B: 5 units, not eligible for this Ship-ToRequested resulting cart quantity: 4Eligible available quantity: 3Outcome: reject / adjust under approved business rule
We will explicitly distinguish availability check, reservation, and allocation. If the business requires a hard guarantee, checkout needs an atomic reservation or other concurrency-safe stock commitment supported by the fulfillment architecture.
Common Mistake
Checking available quantity once at add-to-cart and assuming the order cannot oversell. A second check alone can also race; the final stock commitment needs a concurrency strategy.
Rule 4: Quantity rules use the resulting cart state
Different conditions may have different purchase limits. A new part might require multiples of five; a used part might allow only one to three units because each unit is scarce. The policy checks minimum quantity, increment, maximum quantity, and any account-specific limit.
// Illustrative project-specific quantity rulepublic void checkQuantity( final long resultingQuantity, final long minimum, final long increment, final long maximum) { if (resultingQuantity < minimum || resultingQuantity > maximum) { throw new QuantityPolicyException("QUANTITY_OUT_OF_RANGE"); } if ((resultingQuantity - minimum) % increment != 0) { throw new QuantityPolicyException("INVALID_QUANTITY_INCREMENT"); }}
For a quantity update, calculate the final quantity before applying the rule. For an add-to-cart request, first determine whether the service would merge with an existing entry; avoid assuming each request creates a new entry.
Cart calculation is a separate responsibility
After a permitted cart modification, the totals must reflect the updated entries. Pricing, taxes, discounts, delivery cost, and totals have distinct responsibilities. Cart calculation may be triggered by standard cart operations or explicitly when needed by the checkout flow; do not scatter manual recalculation calls throughout controllers.
Cart modification ↓Pricing / discounts / tax inputs ↓Cart calculation ↓Calculated cart totals ↓Product / cart response mapping
When a custom pricing integration participates, pay special attention to timeouts, stale data, currency consistency, and recalculation loops. Keep diagnostic logs around pricing decisions without exposing confidential customer prices or credentials.
Pricing and calculation must use the same business context
The presence of a PriceRow does not itself prove the correct B2B contract price was selected. Determine the active user, currency, quantity, date and pricing agreement before confirming a purchasable price. When a remote pricing service participates, separate no valid agreement from temporarily unavailable so the storefront can offer the right next action.
After cart mutation, allow the configured OOTB cart calculation path to recalculate totals. Before order placement, verify that totals are current and the buyer can accept any changed amount. Avoid treating a stale search-result price as an authoritative checkout amount.
Rule 5: Ship-To authorization belongs at checkout
The buyer selects a Ship-To address that exists in the system but belongs to a different B2B organization. The UI might hide it, but the server must reject it. Address selection should validate the relationship between the trusted account and the selected delivery destination.
Checkout preparation uses the project’s configured commerce checkout services for delivery address, delivery mode, and payment details. A custom Ship-To policy belongs in a reusable service invoked at address selection and again before placing the order.
Authenticated B2B account +Selected Ship-To identifier ↓Trusted account-to-address relationship check ↓Permitted? → continue delivery mode / fulfillment validation
Because warehouse eligibility may depend on Ship-To, changing the address can invalidate previously displayed availability and delivery options. The UI should communicate those changes instead of assuming earlier validation remains valid.
Checkout preparation is more than address validation
In the actual checkout journey, the buyer selects an authorized delivery address, an available delivery mode, and an appropriate payment option. The facade should delegate to the installed checkout services for setting delivery information and payment details. A project-specific Ship-To service should validate the selected address against the trusted B2B unit, and the final pre-order gate must check it again.
Typical OOTB concepts to inspect: CommerceCheckoutService, CommerceCheckoutParameter, CommerceCheckoutPaymentInfoStrategy (where present in the installed extension set), and the configured checkout facade. Exact service calls and payment integration vary by storefront and extensions; do not assume a universal payment workflow.
Cart validated → delivery address accepted for active B2B unit → delivery mode available for this cart and destination → payment details / payment authorization as applicable → cart recalculated with delivery and tax context → final pre-order validation → order placement

Checkout to order — conceptual responsibility flow
Rule 6: Revalidate before the cart becomes an order
The cart was valid at 9:00 AM. At 10:30 AM, a contract price changed and one used unit was sold. Order placement must not rely solely on the earlier cart checks.
Use the checkout service’s supported validation and order-placement extension points. In SAP Commerce projects, CommerceCheckoutService and CommercePlaceOrderMethodHook are relevant concepts to inspect, but hooks should be used only for their intended lifecycle and with careful attention to transaction behavior. Do not perform slow, irreversible external operations inside a database transaction without a recovery design.
Place Order request ↓Authenticated cart + account context ↓Final product / quantity / Ship-To checks ↓Price refresh and cart recalculation ↓Concurrency-safe stock commitment (if required) ↓OOTB checkout / place-order pathway ↓Persisted order + downstream processing
Design Insight
“Validated at add-to-cart” and “safe to place order” are different statements. Rules that depend on changing external state must be reconsidered at the last responsible moment.
Placing the order through the checkout boundary
At the order boundary, build the checkout parameter with the current cart and call the configured CommerceCheckoutService placement operation. SAP Commerce exposes CommercePlaceOrderMethodHook for supported lifecycle customization, but the exact hook sequence and transaction semantics must be verified in the project’s 2211 patch.
// Representative flow, not a drop-in checkout implementationpublic OrderModel submit(final CartModel cart, final String requestKey) throws InvalidCartException { idempotencyService.claim(requestKey, cart); // durable, unique claim preOrderPolicy.assertAllEntriesEligible(cart); shipToPolicy.assertAuthorized(cart); checkoutCalculationService.ensureCurrentTotals(cart); final CommerceCheckoutParameter parameter = new CommerceCheckoutParameter(); parameter.setCart(cart); parameter.setEnableHooks(true); final CommerceOrderResult result = commerceCheckoutService.placeOrder(parameter); idempotencyService.recordOrder(requestKey, result.getOrder()); return result.getOrder();}
Production caveat: The example communicates orchestration responsibilities only. The durable claim, placement and outcome recording must be made atomic or recoverable through a rigorously designed state machine and uniqueness constraints; simply invoking these methods in sequence is not concurrency-safe. Payment authorization, stock reservation and cart-validation contracts require project-specific integration.
After persistence: Order processing should start via the configured order business process. ERP submission should use an asynchronous, retryable integration with an idempotent message identity or outbox-equivalent design; avoid making irreversible ERP calls inside the order database transaction.

Failure and recovery boundaries — conceptual responsibility flow
What if the buyer clicks Place Order twice?
Suppose the order request times out after the order was created. The buyer retries. A disabled UI button reduces accidental clicks but cannot prevent network retries, mobile reconnections, or API clients from resubmitting.
A project-level idempotency design can bind a client request key to the authenticated buyer, cart, and operation. The server stores a durable record of processing state and the resulting order. Repeating the same operation returns the existing outcome rather than creating a second order. This must be implemented with database uniqueness and concurrency control; a simple in-memory map is insufficient across CCv2 nodes.
Request key + trusted user/cart context ↓Atomic idempotency claim ├─ new → process and persist result ├─ complete → return prior result └─ in progress → safe retry / status response
For downstream ERP submission, use an outbox/event or equivalent reliable integration pattern with retry and deduplication. A persisted SAP Commerce order and a successfully acknowledged ERP order are separate milestones.
Returning useful failures to OCC and the storefront
The user should not receive a generic “Cart could not be updated” for every rule. The facade can translate domain errors into stable codes and field-relevant messages, while the OCC layer maps them to appropriate HTTP responses. The frontend can then display a specific resolution.
{ "code": "INSUFFICIENT_USED_STOCK", "message": "Only 3 eligible used units are available.", "productCode": "HYD-410-USED"}
This JSON is a proposed custom error format, not the standard OCC error contract. If extending an existing OCC endpoint, preserve its established error structure and compatibility expectations.
Examples of user-facing outcomes include “This account is not eligible to purchase used parts,” “A valid contract price is unavailable,” and “Please select an authorized delivery address.”
OCC and UI error mapping
Map domain violations to stable codes in the facade/API boundary, with appropriate HTTP status and localization. Do not leak pricing agreements, internal stock locations or another account’s entitlements. The composable storefront and Accelerator should display actionable errors and prevent a misleading “success” state, but the server remains the enforcement boundary.
{ "errors": [ { "type": "CartEligibilityError", "reason": "USED_PART_NOT_ELIGIBLE", "message": "This part is not available for your account." } ]}
This payload is a proposed custom contract, not an OOTB OCC error schema. Match the deployed OCC API version and existing error conventions.
Testing the entire cart-to-order journey
Unit tests validate each policy independently. Service tests confirm that cart mutation is not performed after a rejected precondition. Integration tests exercise the configured OOTB cart and checkout pathway. Concurrency tests matter for the two highest-risk paths: limited used stock and duplicate place-order requests.
- Existing cart quantity 2 + add 2 evaluates resulting quantity 4.
- Customer changes active B2B unit and loses used-part entitlement.
- Price service returns no agreement price versus temporary failure.
- Warehouse A has stock but cannot serve selected Ship-To.
- Stock changes between add-to-cart and place order.
- Two identical order requests arrive concurrently with one idempotency key.
- Order is persisted but downstream ERP acknowledgement is delayed.
Capture separate timings for entitlement, pricing, inventory, calculation, and order persistence. Otherwise, a “slow checkout” alert is too broad to diagnose.
Tests that protect the customization
Test the OOTB cart path with the real configured Spring context where possible. Assert that a failed precheck leaves cart entries unchanged; successful modifications preserve OOTB modification status and totals; account switches invalidate eligibility; price service outages are not mistaken for “no price”; and checkout refuses stale stock or unauthorized Ship-To. Add concurrency tests for simultaneous used-stock purchases and duplicate idempotency keys across application nodes.
Use contract tests for OCC error codes and UI behavior, and integration tests for the order business process and ERP retry semantics. A unit test of a custom validator alone cannot prove that every order-entry path enforces it.
The architecture we end up with
OCC / Storefront ↓Cart / Checkout Facade ↓Custom Cart Eligibility Service ├── Account-product entitlement ├── Contract price availability ├── Condition-specific quantity policy ├── Eligible warehouse / stock policy └── Ship-To authorization (checkout) ↓OOTB CommerceCartService + Calculation ↓Checkout service + final validation ↓Concurrency-safe stock / idempotency boundary ↓Order persistence ↓Reliable downstream ERP / fulfillment integration
This is a responsibility diagram, not a promise that each operation executes sequentially in one database transaction. The specific extension points, hook ordering, and failure semantics must be verified in the installed SAP Commerce 2211 patch and project configuration.
Final thoughts
The interesting part of enterprise cart development is rarely the first Add to cart request. It is deciding which business rules belong to product eligibility, which depend on the customer’s commercial agreement, which must use current inventory, and which require final confirmation at order placement.
By keeping those rules behind focused services and using the OOTB cart and checkout lifecycle, we can evolve the business without duplicating logic across OCC, storefront, and background processes.
Design Insight
A reliable checkout is not simply one that creates an order. It is one that creates the right order, for the right customer, with defensible pricing, fulfillment eligibility, and safe recovery when requests fail or repeat.
SAP Commerce Architect Series — Practical SAP Commerce learning focused not only on how the platform works, but on how to think through enterprise design decisions.Technical examples are conceptual/project-specific where labeled. Validate exact OOTB signatures, hooks, and transactional behavior in your SAP Commerce environment before implementation.

Leave a Reply