Class Name: CheckoutOrderExtension¶
Last Updated: 2025-10-22 Source Code: https://github.com/AANP-IT/I2C.Salesforce.Metadata/blob/STAGING/force-app/main/default/classes/CheckoutOrderExtension.cls
API Name: CheckoutOrderExtension Type: Commerce Cloud Cart Extension (Order Creation) Test Coverage: CheckoutOrderExtensionTest.cls Created: 06/26/2024 Author: Ecaterina Popa
Business Purpose¶
This class extends Salesforce Commerce Cloud's order creation process to automatically populate custom order fields and handle person account contact assignments during checkout. It ensures orders are properly classified with subscription metadata (Order_Source__c, Order_Level__c, Purchase_Type__c) and correctly linked to person account contacts for billing and shipping. This automation is critical for AANP's membership and subscription business model, enabling proper order categorization and downstream processing for recurring billing, membership fulfillment, and reporting.
Class Overview¶
Scope and Sharing¶
- Sharing Model: Inherited from CartExtension.CheckoutCreateOrder (system context)
- Access Modifier: public virtual
- Interfaces Implemented: None (extends CartExtension.CheckoutCreateOrder)
Key Responsibilities¶
- Override Commerce Cloud order creation to inject custom field values
- Populate order classification fields for subscription/membership tracking
- Extract and assign product information to order
- Handle person account contact assignments for billing and shipping
- Maintain compatibility with Commerce Cloud order creation flow
- Support testability through virtual methods
Public Methods¶
createOrder¶
public virtual override CartExtension.CreateOrderResponse createOrder(CartExtension.CreateOrderRequest request)
Purpose: CartExtension framework callback that executes during order creation from cart. Overrides base implementation to customize order fields before finalizing the order.
Parameters:
- request (CartExtension.CreateOrderRequest): Commerce Cloud request object containing cart and checkout context
Returns:
- CartExtension.CreateOrderResponse: Response object containing created OrderGraph with populated Order and OrderItems
Throws: - QueryException: If Product2 or Account queries fail (not explicitly handled) - NullPointerException: If product or account not found (not explicitly handled) - CartExtension exceptions: Various Commerce Cloud exceptions
Usage Example:
// Called automatically by Commerce Cloud during checkout
// Configured in Commerce Setup:
// Setup → Commerce → Checkout → Create Order
// Extension Point: Commerce_Domain_Checkout_CreateOrder
// Implementation: CheckoutOrderExtension
Business Logic:
-
Extract Cart from Request:
-
Call Default Order Creation:
- Invokes base class createOrder() via helper method
-
Gets OrderGraph with created Order and OrderItems
-
Get Order from OrderGraph:
-
Populate Order Classification Fields:
- Hardcoded values for web-based subscription orders
-
Supports membership/subscription business logic
-
Extract Product Information:
- Finds first OrderItem with Type = 'Order Product'
-
Ignores charge items, delivery charges, etc.
-
Query and Assign Product Name:
- Populates custom field with product name
-
No null check if productId is null
-
Handle Person Account Contacts:
- Queries person account by order's AccountId
- Sets both billing and shipping contacts to PersonContactId
-
Only processes person accounts (B2C model)
-
Return Response:
- Response contains modified Order within OrderGraph
- Commerce Cloud commits changes
callDefault (TestVisible helper)¶
@TestVisible
private virtual CartExtension.CreateOrderResponse callDefault(CartExtension.CreateOrderRequest request)
Purpose: Test-visible helper method that invokes base class createOrder(). Allows test classes to mock the default behavior without calling actual Commerce Cloud order creation.
Parameters:
- request (CartExtension.CreateOrderRequest): Original request object
Returns:
- CartExtension.CreateOrderResponse: Response from base class
Usage: - Called by createOrder() to get default order - Mocked in tests to avoid actual order creation - Virtual to allow test subclass override
Private/Helper Methods¶
None besides callDefault() helper.
Could benefit from extraction:
- populateOrderClassification(order)
- extractProductInfo(orderItems)
- assignPersonAccountContacts(order)
Dependencies¶
Apex Classes¶
- CartExtension.CheckoutCreateOrder (base class): Commerce Cloud framework
- No other Apex dependencies
Salesforce Objects¶
Order (Standard) - Fields modified: - Order_Source__c (custom) - Order_Level__c (custom) - Purchase_Type__c (custom) - Type (standard) - Line_Product_Name__c (custom) - BillToContactId (standard) - ShipToContactId (standard) - Fields read: AccountId
OrderItem (Standard) - Fields read: Type, Product2Id - Purpose: Identify order product for name extraction
Product2 (Standard) - Fields read: Id, Name, Family - Purpose: Get product name for Line_Product_Name__c
Account (Standard) - Fields read: Id, Name, PersonContactId, IsPersonAccount - Purpose: Get person account contact for billing/shipping
CartExtension Framework Objects - Cart: Contains checkout data - OrderGraph: Contains Order and OrderItems - CreateOrderRequest: Input to extension - CreateOrderResponse: Output from extension
Custom Settings/Metadata¶
- None identified - Consider adding:
- Order_Classification__mdt: Configurable field values
- Commerce_Settings__mdt: Enable/disable customizations
External Services¶
- None - Pure internal Commerce Cloud processing
Commerce Cloud Configuration¶
- Required Setup:
- Extension registered at: Commerce_Domain_Checkout_CreateOrder
- Custom fields on Order object must exist
- Person accounts configured in org
- Integration activated in Commerce setup
Design Patterns¶
- Extension Pattern: Extends CartExtension.CheckoutCreateOrder
- Template Method Pattern: Overrides createOrder() hook
- Decorator Pattern: Wraps default order creation with customizations
- Test Double Pattern: callDefault() enables test mocking
Why These Patterns: - Extension pattern required by Commerce Cloud framework - Template method provides hook into order creation lifecycle - Decorator adds functionality without changing base behavior - Test double pattern enables unit testing
Governor Limits Considerations¶
SOQL Queries: 2 (Product2 query, Account query - conditional) DML Operations: 0 (changes via OrderGraph, committed by framework) CPU Time: Low (simple field assignments) Heap Size: Low (small objects)
Bulkification: N/A (single order per checkout) Async Processing: No (synchronous)
Governor Limit Risks: - LOW: 2 SOQL queries well within limits - LOW: No DML operations directly - NONE: No loops over large datasets
Performance Considerations: - Called once per checkout - Should execute quickly (<200ms) - Queries could be optimized if performance becomes issue
Recommendations: - Current implementation efficient for single orders - If batch order creation needed, refactor queries
Error Handling¶
Strategy: No explicit error handling - relies on Commerce Cloud framework
Logging: - None - No custom logging - Commerce Cloud logs framework errors - No debug statements
User Notifications: - Errors surface as generic Commerce Cloud checkout errors - No custom user-friendly messages - Users see Salesforce error pages on failure
Validation: - None - No validation of: - productId before query - personAccount.PersonContactId before assignment - Order classification field values
Rollback Behavior: - Commerce Cloud manages transaction - All changes rolled back on error - Order creation fails entirely (no partial orders)
Recommended Improvements: - Add try-catch around queries - Validate productId not null before query - Validate PersonContactId populated - Log customization steps for troubleshooting - Add custom error messages for common failures
Security Considerations¶
Sharing Rules: SYSTEM CONTEXT - CartExtension runs as system - No sharing declaration - Runs with system privileges - Appropriate for order creation
Field-Level Security: NOT ENFORCED - CartExtension bypasses FLS - Appropriate for checkout automation - Can populate any order fields
CRUD Permissions: NOT ENFORCED - System context allows all operations - Appropriate for order creation
Input Validation: NONE - No validation of cart data - No validation of product or account existence - Trusts framework input
Security Risks: - LOW: System context appropriate for checkout - LOW: Cart belongs to authenticated user - LOW: No user input (framework-driven)
Commerce Security: - Commerce Cloud enforces user authentication - Cart validated before order creation - Extension operates on user's cart only
Mitigation Recommendations: 1. Add validation of queried data exists 2. Log order customizations for audit 3. Regular review of hardcoded field values
Test Class¶
Test Class: CheckoutOrderExtensionTest.cls Coverage: To be determined
Test Scenarios That Should Be Covered: - ✓ Order created with proper classification fields - ✓ Line_Product_Name__c populated from first Order Product - ✓ Person account contacts assigned to billing/shipping - ✓ Business account (non-person) doesn't break contact assignment - ✓ Multiple order items processed correctly - ✓ Order Product type identified correctly - ✓ callDefault() mocked in tests - ✓ Missing product doesn't break checkout - ✓ Missing person account handled gracefully - ✓ OrderGraph structure maintained - ✓ Response returned correctly
Testing Challenges: - CartExtension mocking is complex - OrderGraph construction difficult - Must mock callDefault() to avoid actual order creation - Commerce Cloud test data setup required
Test Data Requirements: - Product2 records - Account records (person and business) - WebCart with items - Order and OrderItem test records
Mock Pattern:
@TestVisible
private virtual CartExtension.CreateOrderResponse callDefault(
CartExtension.CreateOrderRequest request
) {
// In test subclass, return mock response
// In production, calls super.createOrder()
}
Changes & History¶
- Created: 06/26/2024
- Author: Ecaterina Popa
- Purpose: Order field customization for Commerce Cloud
- Last Modified: Check git log
Related Changes: - Part of Commerce Cloud checkout implementation - Works with CheckoutDeliveryIntegration - Supports membership/subscription model
⚠️ Pre-Go-Live Concerns¶
CRITICAL - Fix Before Go-Live¶
- No Error Handling on Queries: Lines 36 and 39-44 query without try-catch - checkout breaks with cryptic errors if queries fail.
- Null Product ID Risk: If no "Order Product" type item found, productId remains null and query fails. Add null check before query.
- No PersonContactId Validation: Assigns PersonContactId without checking if populated - could create orders with null contacts.
- Hardcoded Field Values: Order classification values hardcoded - if business rules change, requires code deployment.
HIGH - Address Soon After Go-Live¶
- No Logging: Zero logging makes troubleshooting checkout customization failures impossible.
- Single Product Logic: Only processes first Order Product - multi-product orders lose other product info.
- No Account Type Validation: Assumes IsPersonAccount filter sufficient - business accounts silently skip contact assignment.
- Missing Field Validation: No check that custom fields (Order_Source__c, etc.) exist on Order object.
MEDIUM - Future Enhancement¶
- Hardcoded Classification: 'Subscription', 'Individual', 'Regular' should be configurable per product type or cart context.
- Product Family Unused: Queries Product2.Family but never uses it - remove or implement logic.
- Limited Order Item Logic: Could handle charge items, delivery charges differently.
- No Configuration: All behavior hardcoded - no custom metadata control.
LOW - Monitor¶
- Code Organization: Could extract helper methods for better readability and testability.
- Virtual Methods: Class is virtual but no known subclasses - remove if unneeded.
- Test Coverage: Verify comprehensive test coverage for all scenarios.
Maintenance Notes¶
Complexity: Medium (Commerce Cloud framework + custom logic) Recommended Review Schedule: Quarterly, before Commerce Cloud upgrades
Key Maintainer Notes:
🛒 COMMERCE CLOUD CRITICALITY: - This class customizes EVERY order created through Commerce Cloud - Failures block all checkouts - Must be tested in full Commerce sandbox - Changes require Commerce Cloud expertise
📋 Usage Patterns:
- Called automatically during every checkout
- Runs once per order creation
- Must be registered in Commerce: Setup → Commerce → Checkout
- Extension point: Commerce_Domain_Checkout_CreateOrder
🧪 Testing Requirements: - Test with person accounts and business accounts - Test with multiple order items - Test with different product types - Test missing product scenario - Test end-to-end checkout flow - Verify field values populated correctly
🔧 Commerce Cloud Configuration: - Extension must be activated - Custom Order fields must exist: - Order_Source__c - Order_Level__c - Purchase_Type__c - Line_Product_Name__c - Person accounts must be enabled
⚠️ Gotchas and Warnings: - Only first "Order Product" type item processed - Business accounts don't get contact assignments - Hardcoded values apply to ALL orders - Queries can fail if data deleted mid-checkout - No rollback of partial customizations
📅 When to Review This Class: - Before Commerce Cloud upgrades - When adding new product types - If order classification rules change - When implementing B2B (business accounts) - During checkout failure investigations
🛑 Emergency Deactivation:
// Option 1: Deactivate in Commerce setup
// Setup → Commerce → Checkout → Create Order
// Deactivate CheckoutOrderExtension
// Option 2: Add metadata check:
public virtual override CartExtension.CreateOrderResponse createOrder(
CartExtension.CreateOrderRequest request
) {
Commerce_Settings__mdt settings = Commerce_Settings__mdt.getInstance('OrderCustomization');
if (settings != null && !settings.Enabled__c) {
return super.createOrder(request);
}
// ... rest of method
}
🔍 Debugging Tips: - Enable Commerce Cloud debug logs - Check Setup → Commerce → Checkout configuration - Query Order fields after checkout - Verify Product2 and Account records exist - Check OrderItem.Type values
📊 Monitoring Checklist: - Daily: Checkout success rate - Weekly: Order field population errors - Monthly: Validate classification values still accurate - Monitor: Commerce Cloud error logs
🔗 Related Components: - CheckoutDeliveryIntegration: Runs alongside for shipping - Product2: Source for Line_Product_Name__c - Account: Source for contact assignments - Order/OrderItem: Modified by this class - Commerce pricing/tax: Run in same checkout flow
Business Owner¶
Primary: E-Commerce / Sales Operations Secondary: IT Operations / Commerce Cloud Admin Stakeholders: Product Management, Member Services, Finance, Development Team