# Orders & Provisioning

How customer orders are created, where they live, and how fulfillment reaches WHMCS.

## Order Creation (Customer Checkout)

- Orders are created in Salesforce using the portal pricebook. The record includes:
  - AccountId (from the user’s mapping)
  - Order type (Internet, SIM, VPN)
  - Activation preferences (type, scheduled date, SIM/MNP details when provided)
  - Address snapshot copied from the customer profile/checkout form
  - Status starts at “Pending Review”
- Before creation we verify a WHMCS payment method exists and (for Internet) that WHMCS does not already have an active Internet service.
- Order items are built from the Salesforce pricebook entries for the selected SKUs.

## Fulfillment to WHMCS (Triggered by Salesforce)

- Salesforce Change Data Capture (CDC) watches for order status changes (e.g., Approved/Reactivate). When triggered, we enqueue a provisioning job.
- Fulfillment steps:
  1. Set Salesforce order activation status to “Activating.”
  2. Map Salesforce order items to WHMCS products and call WHMCS AddOrder to create the billing order (so invoices/subscriptions exist in WHMCS).
  3. For SIM orders, call Freebit to activate SIMs when required.
  4. Update Salesforce with WHMCS Order ID, activation status/results, and any error codes/messages.
  5. Publish live events so the UI can update order status in real time (SSE).
- If Salesforce shows the last error code “PAYMENT_METHOD_MISSING,” provisioning is paused until the customer adds a payment method in WHMCS.

## Where Data Lives

- Salesforce: master order record, status, address snapshot, product lines.
- WHMCS: billing copy created during fulfillment (used for invoices/subscriptions).
- Freebit: only for SIM provisioning tasks.

## Freshness & Caching

- Orders and order items use CDC-driven caching (no TTL). Salesforce order/order-item change events invalidate caches immediately.
- Cache is also invalidated when we create or provision an order.
- Customers can subscribe to order event streams; UI updates without manual refresh.

## What happens on errors

- Payment method missing: fulfillment is paused; Salesforce `Activation_Error_Code__c` is set to `PAYMENT_METHOD_MISSING` and the UI shows a prompt to add a payment method.
- Validation/mapping issues (e.g., bad SKU, missing mapping): we stop and return a clear error; Salesforce gets an error code/message for traceability.
- WHMCS errors while creating the billing order: we mark fulfillment as failed, write the error back to Salesforce, and keep the Salesforce order intact (no partial WHMCS order is kept if creation fails).
- Freebit/SIM errors: logged and surfaced in the activation status; order remains in Salesforce for retry.
- Connectivity issues (Salesforce/WHMCS): we return “try again later,” do not commit partial work, and leave caches unchanged.
