A state machine protects one aggregate transition. A workflow coordinates several aggregates and external systems. Adocommerce Kit uses both because checkout needs both kinds of safety.
State machines use conditional writes
A transition is defined by allowed source states, one destination, and optional guards. Persistence uses a conditional update:
UPDATE commerce_orders
SET state = 'confirmed'
WHERE id = ? AND state = 'placed'Zero updated rows means the state was stale or invalid, so the service throws E_STATE_TRANSITION. It does not read a state, decide in memory, and write later.
Orders, payment intents, payments, refunds, shipments, and reservations expose explicit state vocabularies. Controllers call services; they do not assign state columns.
The persisted vocabularies are:
| Aggregate | States |
|---|---|
| Order | cart, placed, pending_payment, pending_cod, review_required, confirmed, partially_fulfilled, fulfilled, completed, canceled |
| Payment intent | created, requires_action, pending, authorized, captured, partially_refunded, refunded, expired, review_required, voided, failed |
| Payment | authorized, captured, partially_refunded, refunded, voided, failed |
| Capture / refund | pending, succeeded, failed |
| External payment operation | started, completed, failed, uncertain |
| Shipment | pending, preparing, ready, shipped, delivered, delivery_failed, returned, canceled |
| Reservation | active, consumed, released |
| Return | requested, authorized, received, inspecting, approved, rejected, canceled, refunded, exchanged, closed |
These lists are not permission to jump between arbitrary states. In particular, paid is
not an order state: payment settlement and the order lifecycle are separate. A deferred
intent remains pending while its order awaits payment or COD; expiry and conflicting
provider state use explicit expiry/review paths.
A provider’s pending refund is not a successful refund. It reserves refundable capacity,
keeps its external operation uncertain, and emits neither RefundSucceeded nor
RefundFailed until a terminal result arrives. Webhooks or
commerce.reconcile_payment_operations settle that work; an authorized operator can record
provider evidence when automatic reconciliation is unavailable.
Checkout is a compensating workflow
The default place-order workflow performs these responsibilities in order:
- Validate and reprice the cart.
- Lock the active cart and move it to
checking_out. - Reserve inventory with guarded SQL updates.
- Create the order ledger and persist its checkout-idempotency linkage.
- Create and confirm the payment intent outside the ledger transaction (unless the total is zero).
- Finalize the order, payment, reservation, and cart state.
- Emit transactional events.
Steps that acquire resources define compensation. A later failure refunds each successful
capture with its own idempotency key and voids remaining authorization, releases reservations,
and cancels the order while retaining its order/payment/capture/refund ledgers for reconciliation.
Compensation runs in reverse order and its report is attached to E_WORKFLOW_FAILED.
A throwing external step is itself eligible for compensation: throwing does not prove it
created no external side effect. If compensation fails, the order becomes review_required
and its cart stays locked in checking_out; an operator must reconcile provider and ledger
state before allowing another checkout. Do not delete the ledgers or simply unlock that cart.
Zero-total checkout
A zero-total order is paid without a payment intent or provider call. It still validates and
locks the cart, reserves/consumes inventory, creates the order ledger, runs checkout-completed
hooks, completes idempotency, and emits normal order events. Configured orders.autoConfirm
still confirms it. Supplying an existing intent for a zero-total order is rejected with
E_PAYMENT_INTENT_MISMATCH, rather than charging an unrelated authorization.
Idempotency closes the retry gap
Checkout claims an idempotency row before workflow execution. The claim stores a canonical request hash.
- Same key, same completed request: return the stored order.
- Same key, different request:
E_IDEMPOTENCY_CONFLICT. - Same key while another request is running: a retry-later conflict.
- No key: derive one from cart identity and update timestamp.
This protocol prevents a browser retry from creating a second order or second payment.
Recovery handles process death
Compensation cannot run if the process dies. ReconcileStuckCheckouts finds carts left in checking_out beyond the configured grace period.
- Recoverable pending, authorized, or captured intent plus an existing order: resume finalization. In automatic capture mode, recovery captures authorized payments before finalization.
- Zero-total order with no intent: finalize without a payment provider.
- Otherwise: void what can be voided, cancel the abandoned phantom order, release stock, and reactivate the cart.
review_requiredorders: leave them and their carts untouched for operator reconciliation.
Order metadata persists checkoutIdempotencyId, so recovery completes the original checkout
claim rather than losing its retry linkage. Recovery is idempotent and shares the same services
and guarded transitions as the synchronous path.
Customize in the workflow, not around it
PlaceOrderWorkflow supports insertBefore, insertAfter, replace, and remove. Register changes in a provider after resolving the singleton. A custom step receives the workflow context, including the cart, input, transaction, order, intent, and payment.
Steps implement run(context) and declare boundary: 'trx' | 'external'; execute is
not a step method. Consecutive transactional steps share a transaction. The default names
are validate_cart, lock_cart, reserve_inventory, create_order, create_payment,
finalize, and emit; only create_payment has the external boundary.
context.trx is undefined outside a transactional segment.
Every step that creates a durable side effect should have a compensation strategy or a clear reason it is safe to repeat. See Add a workflow step.
PlaceOrderWorkflow.registerCaptureAmountResolver(resolver: (context: PlaceOrderContext) => Promise<Money | undefined>): this sets the capture amount
used by both initial automatic capture and recovery. Returning undefined uses the payment
service’s default amount. The preorder provider uses this hook to capture deposits and
non-preorder amounts at placement while retaining the authorized balance for release.
Backorders are outstanding quantities
Allowing a backorder does not create negative physical stock. Consuming a reservation
decrements on-hand only for units actually present and records the shortfall in
backorderedQuantity. Receipts satisfy consumed outstanding reservations in
createdAt, then ID, order and write sale movements. Cancellation/compensation and return
restocking account for already returned and still-backordered quantities so unreceived
units cannot be restocked as if they existed. Migration 018_inventory_backorders supplies
the quantity column and FIFO index.
Returns and exchanges
An RMA follows request, authorization, receipt, inspection, and approval/rejection before
refund or exchange and closure. Approval requires inspection recorded on every line and
at least one positive accepted quantity; an entirely rejected inspection must be rejected,
not approved. Uninspected RMAs reserve requested quantities; once inspection is recorded,
only accepted quantities remain reserved against delivered, unrefunded order quantities.
Concurrent RMAs therefore cannot over-return stock. Approval restocks only accepted quantities
with disposition restock, writing return movements with per-return/line references through
InventoryService.restockFromReturn; approval and restock share a transaction.
Refund computes accepted-line value including allocated eligible non-included adjustments.
Pending provider refunds leave the RMA approved and preserve its refund linkage for retry.
A failed refund can start a new idempotent attempt; replay of pending/successful work does
not re-refund or increment refunded quantity twice. Completion waits for successful provider
refund (or a non-payment-only refund), then commits quantities, state, and events atomically.
Gift-only refunds have a nullable payment refund ID; mixed tender splits total value into
provider paymentAmount and gift/store-credit nonPaymentAmount.
Exchange creates a replacement order and applies accepted-return credit:
- Equal value: zero due, confirmed replacement order.
- Higher value: replacement order retains the positive difference for payment; it is not automatically paid or confirmed.
- Lower value: unused credit is refunded through the return flow before the exchange completes.
For admin/service integrations, list({ state?, orderId?, channelIds?, cursor?, limit? })
returns a cursor page and restricts visibility by the supplied channel IDs.
find(id) returns the loaded return with order/lines or null; it is not channel-scoped,
so authorize the returned order’s channel before exposing it.
Use refund/exchange options.onCommitted(result, trx) for audit writes in the final ledger
transaction. Do not wrap refund or exchange in an outer transaction: their provider calls
must run outside database locks; a callback is the atomic auditing seam, not a provider wrapper.
Fulfillment cancellation and tracking
FulfillmentService.cancel(shipment, { reason? }, options?) allows only pending,
preparing, or ready shipments (before handoff); repeating cancellation is idempotent.
It records cancellation reason rather than pretending a shipped parcel was canceled.
Provider canceled status only cancels in those legal states; on_hold is informational
and does not advance state. Stale occurredAt, duplicate, and backward/illegal tracking
updates do not roll shipment state backward; canceled/returned shipments ignore further tracking.
markReturnedToSender(shipment, { reference }, options?) transitions through the return
status path. Returned shipment inventory is restocked once, guarded by inventoryRestockedAt;
replayed references/events cannot repeatedly increase stock. Return-to-sender restocking
is distinct from RMA inspection/disposition and does not reopen fulfilled preorder allocations.