Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Plan the workflow extension surface and drop state machines from new models

Damian Legawiecb2f1c1df3e6a
diff --git a/CLAUDE.md b/CLAUDE.md
index 4b7477f828..14a83bafcd 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -22,7 +22,7 @@ Active plans (6.0 target, work pending):
- `6.0-typed-stock-movements.md` — Replace generic StockMovement with typed kinds + concrete FKs
- `6.0-normalize-state-to-status.md` — Rename state → status on Payment, Shipment, InventoryUnit, ReturnAuthorization, GiftCard
- `6.0-fulfillment-and-delivery.md` — Shipment→Fulfillment, ShippingMethod→DeliveryMethod, drop ShippingCategory, FulfillmentProvider strategy, pickup (merchant StockLocation) + pickup_point (third-party PickupPointProvider). **Shipped to 6-0-dev (Waves 2+4+6):** renames + deprecated twins, providers (Manual/Digital/Pickup/PickupPoint), dual-emit events, store pickup discovery endpoints, admin delivery_methods/delivery_zones CRUD + dashboard settings pages, FulfillmentMailer; Wave 7 shipping→delivery data migration remains
-- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain
+- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain. **No state machines (2026-08-02):** plain `status` string + inclusion validation; all fifteen transitions are workflows (`Returns::Receive`, `Exchanges::Fulfill`, `Claims::Resolve`, …) with `validate` hooks for return-eligibility policy and refunds as `external_step`. Nothing happens in a model or transition callback. Statuses live in a `class_attribute` via the core `Spree::HasStatus` concern (`has_status` + additive `add_status(value, after:)`, generating predicates and scopes) — extensible by design, additive only, and no transition graph (that would be a state machine again).
- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename (RefreshToken shipped in 5.4)
- `6.0-tax-provider.md` — Per-Market TaxProvider, replaces TaxRate.adjust + Calculator; TaxRate gets direct country/state FKs (tax decoupled from Zone; Zone model dropped in 6.0 via `6.0-delivery-zones.md`); reference provider: Avalara (decisions.md 2026-07-30)
- `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider wrapping Stock::Estimator (calculators stay — 2026-07-27 reversal), `store_id` on ShippingMethod, enriched DeliveryRate (carrier/service/date/metadata); monorepo ships one reference multi-carrier provider (Shippo/EasyPost, pick pending — decisions.md 2026-07-29); method rows stay regional (no cross-market method entity)
@@ -31,7 +31,7 @@ Active plans (6.0 target, work pending):
- `6.0-inventory-operations.md` — StockTransfer lifecycle (draft → ready_to_ship → in_transit → received with partial receive), new `Spree::PurchaseOrder` + `Spree::Supplier` (renamed from Vendor — `Spree::Vendor` is the marketplace seller, see decisions.md 2026-07-14) replacing today's "external receive" hack, variant + stock-location stock history panels. Consumes the typed-movement primitives from `6.0-typed-stock-movements.md`.
- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). **Shipped to 6-0-dev (PR #14302):** the Category surface (5.5–5.6) plus the 6.0 core — `spree_taxons`→`spree_categories` table rename + inheritance flip (`Spree::Category < Spree.base_class`, `Spree::Taxon` alias kept), the full `Collection` stack (model + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data migration, and de-ruling Category. Pending (all 6.1): channel-aware `CollectionRules::AvailableOn` (ships interim now, rides with channels) + dropping `spree_taxon_rules`/`Taxonomy`. No brand feature in 6.0 — brands are modeled as a Category/Collection; `brand_taxon`/`brand_name` removed with `Taxonomy`.
- `6.0-delivery-method-rules.md` — `Spree::DeliveryMethodRule` STI on DeliveryMethod (design finalized 2026-07-29): ItemTotal/Weight rules first (Channel/Market/CustomerGroup later in lockstep with payment-method-rules), enforced solely in `Stock::Estimator`'s method filter so calculator- AND provider-priced methods obey eligibility; replaces the FlatRate-only bound preferences (one-release bridge + data task). Phase 1 rides the 6.0 core-rewrite finishing work.
-- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` — named steps inside a plain `def perform(order:, ...)` (the ActiveJob::Continuable shape; bare `super` turns parameters into readers). Vocabulary: `step`/`external_step` (+ `with:`, `on_flow_failure:`), `run_hooks` + class-level `hooks`, `failure`/`halt!`; plain `ApplicationRecord.transaction`/`with_lock`/`rescue`/`publish_event`; every step instrumented as `step.spree_workflow`. Money lives in `Carts::RecalculateTotals` (single totals seam; the completed-order branch is the post-placement resum — rows re-summed, never regenerated), statuses in `Orders::UpdateStatuses` (refreshes each fulfillment's state, then rolls up); Order/CartUpdater are 6.1-removed warning shells. Shared Cart/Order surface lives in `Spree::Purchase::*` concerns; completion side effects (newsletter, account creation, risk) run in the sync `OrderPlacedSubscriber` on order.placed. Reserved for flows needing hooks, compensation/external I/O, or replay — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `Carts::Complete` battery must pass unmodified. **Durability = plain Rails:** long-running background work uses `ActiveJob::Continuable` directly (reference: `Spree::Imports::ProcessJob` — CSV spine with a row-number cursor; `CreateRowsJob`/`ProcessRowsJob` deprecated shells); workflows are synchronous request-cycle flows and are NOT jobs — Workflow-level durable execution ships only if the payout run proves the need.
+- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` — named steps inside a plain `def perform(order:, ...)` (the ActiveJob::Continuable shape; bare `super` turns parameters into readers). Vocabulary: `step`/`external_step` (+ `with:`, `on_flow_failure:`), `run_hooks` + class-level `hooks`, `failure`/`halt!`; plain `ApplicationRecord.transaction`/`with_lock`/`rescue`/`publish_event`; every step instrumented as `step.spree_workflow`. Money lives in `Carts::RecalculateTotals` (single totals seam; the completed-order branch is the post-placement resum — rows re-summed, never regenerated), statuses in `Orders::UpdateStatuses` (refreshes each fulfillment's state, then rolls up); Order/CartUpdater are 6.1-removed warning shells. Shared Cart/Order surface lives in `Spree::Purchase::*` concerns; completion side effects (newsletter, account creation, risk) run in the sync `OrderPlacedSubscriber` on order.placed. Reserved for flows needing hooks, compensation/external I/O, or replay — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively — but hooks on flows already in the tier ship deliberately on the 6.0 boundary (2026-08-02), since hook keys are public API and moving one later is breaking. **New models get no state machine** — plain `status` string + inclusion validation, transitions through workflows; gateway I/O never in a save callback. Three hook families, contracts settled 2026-08-02: **lifecycle** (past tense, read-only), **validate** (handler calls `workflow.reject!(message)` to veto), **context** (`set_*_context`/`get_provider_data` — handler returns a hash, `run_hooks` deep-merges all handlers and returns it; last writer wins on collision). Phase 3 waves: **Wave A** = two runtime additions (`run_hooks` returns merged hash, `reject!`) + hooks on existing workflows (AddItem, Complete, Recalculate, RecalculateTotals, Cancel, Resume); **Wave B** graduates `Fulfillments::Create`, `Payments::Capture`/`Refund`, `Payments::HandleWebhook`, `Carts::Merge`. No workflows for plain CRUD. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `Carts::Complete` battery must pass unmodified. **Durability = plain Rails:** long-running background work uses `ActiveJob::Continuable` directly (reference: `Spree::Imports::ProcessJob` — CSV spine with a row-number cursor; `CreateRowsJob`/`ProcessRowsJob` deprecated shells); workflows are synchronous request-cycle flows and are NOT jobs — Workflow-level durable execution ships only if the payout run proves the need.
- `6.0-store-scoped-custom-field-definitions.md` — Add `store_id` + persisted `filter_key` to `Spree::MetafieldDefinition` (today global and computed), making uniqueness `(store_id, resource_type, filter_key)` with a DB index. Deferred from the 5.6 custom-field search/sort/filter work (schema change, not patch-safe). **Until then:** `filter_key` is a computed method — no Ransack predicates or `where`/`order` against it; definitions are global; uniqueness rests on a `CONCAT` validation with no index behind it.
Multi-version plans (some phases shipped, some pending):
@@ -48,6 +48,7 @@ Multi-version plans (some phases shipped, some pending):
- `5.6-dashboard-typed-plugin-routes.md` — Plugin file routes compiled into the host's TanStack route tree: `spree.dashboard.routes` marker + virtual-route-config composition in `@spree/dashboard/vite`, `createDashboardRouter` + `<Dashboard router>` ownership inversion, typed cast-free links, cross-package collision pre-flight with package-named errors. Runtime route registry stays for dynamic/in-app cases (catch-all is lowest priority). Implemented; published-tarball spike passed.
Pending design work (drafts, no implementation yet):
+- `6.1-order-change-substrate.md` — `Spree::OrderChange` + `Spree::OrderChangeAction`: one preview-then-apply substrate behind every post-placement mutation (admin order edits, returns, exchanges, claims, draft-order amendments), replacing four per-domain draft models with one `begin → request → confirm → cancel` lifecycle. Actions are typed `kind` + concrete FKs (never polymorphic); **preview is computed in memory and never persisted**; confirm is a workflow with the balance settlement as an `external_step`. Deliberately 6.1 — new schema + new extension API, and 6.0 already carries the Cart/Order split, typed adjustments and the returns rework. 6.0 constraint: don't build a per-domain persisted preview/draft model, and expose post-placement money math through a service returning a value object so it can be re-pointed later.
- `5.7-payment-method-rules.md` — `Spree::PaymentMethodRule` STI on PaymentMethod (Channel / Market / OrderTotal / CustomerGroup rules), mirroring the PromotionRule/PriceRule/OrderRoutingRule pattern. Enforced solely through `Order#collect_frontend_payment_methods` (listing + `Payments::Create` + payment sessions all flow through it); admin/backoffice bypasses; no rules = available everywhere. Dashboard-only management (nested Admin API CRUD + `/payment_method_rules/types` discovery). Supersedes the "no distribution concept" rationale in `5.6-6.0-single-store-promotions-payment-methods.md`; per-channel provider credentials (multiple Stripe accounts, multi-entity setups) explicitly deferred for grooming — see decisions.md 2026-07-23.
- `5.7-channel-markets.md` — Optional Channel→Markets allowlist (`spree_channel_markets` join, empty = all markets). Enforced in market resolution (`set_market_from_country` + channel-aware `Spree::Current.market` fallback), channel-filtered Store API `/store/markets`, and order-level `market must be served by channel` validation. Composes with `MarketRule` from the payment-method-rules plan.
- `5.6-admin-spa-csv-import.md` — Universal dashboard CSV import over the existing `Spree::Import` pipeline (implemented). Admin API v3 surface (create via direct-upload signed blob, `complete_mapping`, `retry_failed_rows`, nested failed-rows index, write-scope gating), `client.imports` SDK resource, dashboard-core `ImportButton` (per-context `<Can>` gating, upload Sheet) + full-window wizard dialog driven by an `?import=` search param, with history under `/settings/imports` (new `audit` settings-nav group). Status via API polling — explicitly no ActionCable/Turbo Streams in the SPA; legacy per-row live feed replaced by polled counters + paginated failed-rows table.
@@ -188,7 +189,8 @@ end
- Target version: existing migrations keep their `ActiveRecord::Migration[7.2]` marker; new 6.0 migrations may target `[8.1]` — the 6.0 line requires Rails 8.1 (decisions.md 2026-07-29)
- No foreign key constraints
-- No default values
+- No default values on string/status columns (statuses are set by the creating workflow); integer, decimal and boolean columns DO carry defaults (`quantity` 1, amounts 0) so raw inserts can't produce nulls
+- New tables get a single `metadata` JSON column — no `public_metadata`/`private_metadata` split (legacy tables keep theirs)
- Always add `null: false` on required columns
- One migration per feature when possible
- Data transformations go in rake tasks, never in migrations
diff --git a/docs/plans/6.0-returns-exchanges-claims.md b/docs/plans/6.0-returns-exchanges-claims.md
index f3f55a1ee2..2ab4b1c160 100644
--- a/docs/plans/6.0-returns-exchanges-claims.md
+++ b/docs/plans/6.0-returns-exchanges-claims.md
@@ -2,9 +2,10 @@
**Status:** Draft
**Target:** Spree 6.0
-**Depends on:** Fulfillment & Delivery rework (6.0-fulfillment-and-delivery.md), Split Adjustments (6.0-split-adjustments.md), Normalize state→status (6.0-normalize-state-to-status.md)
+**Depends on:** Fulfillment & Delivery rework (6.0-fulfillment-and-delivery.md), Split Adjustments (6.0-split-adjustments.md), Normalize state→status (6.0-normalize-state-to-status.md), Service Workflows (6.0-service-workflows.md)
+**Successor:** 6.1-order-change-substrate.md — the mutation half of these flows moves onto the shared OrderChange substrate in 6.1 (additive; the models and statuses below do not change)
**Author:** Damian + Claude
-**Last updated:** 2026-03-22
+**Last updated:** 2026-08-02
## Summary
@@ -55,11 +56,142 @@ Total: ~825 lines across 6+ models for return handling.
- **Three first-class models:** `Return`, `Exchange`, `Claim`. Each belongs directly to Order.
- **Each has its own line items:** `ReturnItem`, `ExchangeItem`, `ClaimItem`. No shared polymorphic item model — each type has different fields.
-- **Simple status flow on each.** One state machine per entity, not layered state machines across multiple models.
+- **No state machines. Workflows own every transition.** Each entity carries a
+ plain `status` string column with an inclusion validation. Moving a return to
+ `received` is `Spree::Returns::Receive.call(...)`, not `return.receive!`. See
+ "Why workflows, not state machines" below — this is the load-bearing decision
+ in this plan and it is not negotiable.
+- **Statuses are configuration, not constants.** `Spree::HasStatus` holds them
+ in a `class_attribute` with an additive `add_status`, so a merchant can slot
+ in an `inspecting` step without reopening core. Additive only — core
+ workflows guard on core statuses, so removal is not offered.
+- **No business logic in model callbacks.** Restocking, refunding and creating
+ replacement fulfillments are named workflow steps. Nothing happens as a side
+ effect of a save.
- **Refund stays.** `Spree::Refund` is the payment-level reversal — it stays as-is. Returns and Claims link to Refunds when money needs to go back.
- **Drop:** `CustomerReturn`, `Reimbursement`, `ReimbursementType` (all four subtypes), `ReturnAuthorization`. Their functionality is absorbed into the three new models.
- **ReturnItem is reused** (renamed from the current model, simplified). ExchangeItem and ClaimItem are new.
+## Why workflows, not state machines
+
+An earlier draft of this plan gave each entity a `state_machine :status` block
+with the real work hanging off transition callbacks —
+`after_transition to: :received, do: :restock_items`,
+`after_transition to: :refunded, do: :process_refund`. That is the pattern
+6.0 is systematically removing, and it is worth stating plainly why, because
+these three models are the last place it would have been reintroduced.
+
+**It hides money movement inside a save.** `process_refund` called from
+`after_transition` runs inside the transaction that saves the status column. A
+refund is a gateway call. Gateway I/O inside a database transaction is the
+exact failure the `Carts::Complete` three-phase design exists to prevent: the
+connection is held open across a network round trip, and a timeout leaves the
+database and the payment processor disagreeing about reality.
+
+**Transitions cannot take arguments.** `return.receive!` has nowhere to put
+"who received it", "which items actually arrived", "two of the three are not
+resellable". Every real return is partial. Callback-driven transitions push
+that state into instance variables set before the bang method, which is how
+the current ReturnAuthorization → CustomerReturn → Reimbursement chain became
+unreadable.
+
+**There is no compensation story.** If restocking succeeds and the refund
+fails, a state machine has already committed the status change. `Spree::Workflow`
+arms `on_flow_failure:` undo steps when the surrounding transaction commits and
+unwinds them in reverse.
+
+**Guards are invisible at the call site.** `allow_cancel?` living inside a
+transition guard means a caller discovers the rejection as a raised
+`StateMachines::InvalidTransition` rather than a `Result` it can inspect.
+
+**The layered-state-machine problem is what we set out to kill.** The stated
+purpose of this plan is escaping six interlocking state machines. Replacing six
+with three is an improvement in degree, not in kind. Replacing them with
+explicit workflows is the actual fix.
+
+The order-level precedent already shipped: `Spree::Orders::Cancel` and
+`Spree::Orders::Resume` absorbed what `Order#after_cancel` and `#after_resume`
+buried, and the order state machine itself is gone in 6.0
+(`6.0-cart-order-split.md`). Returns, exchanges and claims follow the same rule.
+`state_machines-activerecord` stays a dependency for legacy models during the
+6.0 window; **new models do not get state machines.**
+
+### Status as a plain column
+
+`Spree::HasStatus` ships in core (`app/models/concerns/spree/has_status.rb`)
+as the house replacement for state machines. Values live in a
+`class_attribute`, not a frozen constant, so extensions can add statuses
+without reopening core:
+
+```ruby
+module Spree::HasStatus
+ extend ActiveSupport::Concern
+
+ class_methods do
+ # Declares the valid values and generates predicates + scopes only — no
+ # events, no transitions, no callbacks. Transitions belong to workflows.
+ def has_status(*values, default:)
+ class_attribute :statuses, default: values.map(&:to_s)
+ class_attribute :default_status, default: default.to_s
+
+ validates :status, inclusion: { in: -> (record) { record.class.statuses } }
+
+ values.each { |value| define_status_methods(value) }
+ end
+
+ # Additive only — core statuses can't be removed (see below).
+ def add_status(value, after: nil)
+ return if statuses.include?(value.to_s)
+
+ index = after ? statuses.index(after.to_s)&.+(1) : statuses.size
+ self.statuses = statuses.dup.insert(index || statuses.size, value.to_s)
+ define_status_methods(value)
+ end
+
+ private
+
+ def define_status_methods(value)
+ define_method("#{value}?") { status == value.to_s }
+ scope value, -> { where(status: value.to_s) }
+ end
+ end
+end
+```
+
+The default is applied by the creating workflow, never as a database default
+(CLAUDE.md: no default values in migrations).
+
+**Why additive only.** `Returns::Refund` guards on `return.received?`. If an
+extension could replace the status list and drop `received`, that guard would
+silently never pass — returns would stop working with no error at the point of
+removal. Adding a status is safe; removing a core one is not, so the API only
+offers the safe half.
+
+A custom status needs a custom workflow to move records into it — `add_status`
+deliberately takes no `from:`/`to:` graph, since validating transitions
+centrally would be a state machine by another name.
+
+```ruby
+# Extension: an inspection step between receipt and refund
+Spree::Return.add_status(:inspecting, after: :received)
+
+module MyStore
+ class Returns::Inspect < Spree::Workflow
+ hooks :after_inspect
+
+ def perform(return_record:, inspector:)
+ super
+ step :ensure_inspectable
+ ApplicationRecord.transaction do
+ step :mark_inspecting
+ run_hooks :after_inspect
+ end
+ success(return_record.reload)
+ end
+ end
+end
+```
+
## Design Details
### Return
@@ -80,64 +212,34 @@ class Spree::Return < Spree.base_class
belongs_to :order, class_name: 'Spree::Order', inverse_of: :returns
belongs_to :stock_location, class_name: 'Spree::StockLocation'
belongs_to :reason, class_name: 'Spree::ReturnReason', optional: true
+ # Staff only. Customer-initiated (Store API) records leave this nil —
+ # the requester is always order.customer, so no second FK is needed.
belongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: true
has_many :return_items, class_name: 'Spree::ReturnItem', dependent: :destroy, inverse_of: :return
has_many :refunds, class_name: 'Spree::Refund', as: :originator
+ include Spree::HasStatus
+ has_status :requested, :approved, :received, :refunded, :canceled, default: :requested
+
validates :order, :stock_location, presence: true
validates :return_items, presence: true
accepts_nested_attributes_for :return_items, allow_destroy: true
- state_machine :status, initial: :requested do
- event :approve do
- transition from: :requested, to: :approved
- end
- event :receive do
- transition from: :approved, to: :received
- end
- event :refund do
- transition from: :received, to: :refunded
- end
- event :cancel do
- transition from: [:requested, :approved], to: :canceled
- end
-
- after_transition to: :received, do: :restock_items
- after_transition to: :refunded, do: :process_refund
- end
+ # Predicates (#received?) and scopes (.received) are generated by has_status.
- # Total refund amount
+ # Total refund amount. A pure read — safe on the model.
def refund_total
return_items.sum(:pre_tax_amount)
end
-
- private
-
- def restock_items
- return_items.each do |item|
- next unless item.resellable?
-
- stock_location.restock(item.variant, item.quantity)
- end
- end
-
- def process_refund
- # Create Refund against the order's payment
- payment = order.payments.completed.last
- return unless payment
-
- Spree::Refund.create!(
- payment: payment,
- amount: refund_total,
- reason: Spree::RefundReason.return_processing,
- originator: self
- )
- end
end
```
+The model holds associations, validations, scopes and pure reads. Restocking
+and refunding live in `Spree::Returns::Receive` and `Spree::Returns::Refund`
+(below).
+
### ReturnItem (simplified)
```ruby
@@ -194,64 +296,28 @@ class Spree::Exchange < Spree.base_class
# If there's a price difference, link to a refund or additional payment
has_many :refunds, class_name: 'Spree::Refund', as: :originator
+ include Spree::HasStatus
+ has_status :requested, :approved, :received, :fulfilled, :canceled, default: :requested
+
validates :order, :stock_location, presence: true
validates :exchange_items, presence: true
accepts_nested_attributes_for :exchange_items, allow_destroy: true
- state_machine :status, initial: :requested do
- event :approve do
- transition from: :requested, to: :approved
- end
- event :receive do
- transition from: :approved, to: :received
- end
- event :fulfill do
- transition from: :received, to: :fulfilled
- end
- event :cancel do
- transition from: [:requested, :approved], to: :canceled
- end
-
- after_transition to: :received, do: :restock_returned_items
- after_transition to: :fulfilled, do: :create_exchange_fulfillment
- end
-
# Price difference: positive = customer owes more, negative = refund due
def price_difference
exchange_items.sum { |ei| ei.new_variant_price - ei.original_price }
end
-
- private
-
- def restock_returned_items
- exchange_items.each do |item|
- next unless item.resellable?
-
- stock_location.restock(item.original_variant, item.quantity)
- end
- end
-
- def create_exchange_fulfillment
- # Create a new fulfillment with the exchange variants
- fulfillment = order.fulfillments.create!(
- stock_location: stock_location,
- fulfillment_type: 'shipping',
- address: order.ship_address
- )
-
- exchange_items.each do |item|
- fulfillment.fulfillment_items.create!(
- variant: item.new_variant,
- quantity: item.quantity,
- order: order,
- line_item: item.line_item
- )
- end
- end
end
```
+Restocking and replacement-fulfillment creation live in
+`Spree::Exchanges::Receive` and `Spree::Exchanges::Fulfill`. The price
+difference is settled through the internal-vs-gateway branch (see "Refunding:
+internal vs gateway" below) — a gateway capture or refund runs as an
+`external_step` outside the transaction that writes the status; store-credit
+settlement stays inside it.
+
### ExchangeItem
```ruby
@@ -295,7 +361,12 @@ class Spree::Claim < Spree.base_class
publishes_lifecycle_events
- CLAIM_TYPES = %w[damaged missing wrong_item other].freeze
+ # Configuration, not a frozen constant (same ruling as statuses) — a
+ # merchant adds a claim type without reopening core:
+ # Spree::Claim.claim_types += ['late_delivery']
+ # Types are pure labels with no per-type behaviour, so extending the
+ # list needs no accompanying workflow.
+ class_attribute :claim_types, default: %w[damaged missing wrong_item other]
belongs_to :order, class_name: 'Spree::Order', inverse_of: :claims
belongs_to :reason, class_name: 'Spree::ClaimReason', optional: true
@@ -305,75 +376,28 @@ class Spree::Claim < Spree.base_class
has_many :refunds, class_name: 'Spree::Refund', as: :originator
has_one :replacement_fulfillment, class_name: 'Spree::Fulfillment', as: :originator
+ include Spree::HasStatus
+ has_status :open, :approved, :resolved, :denied, :canceled, default: :open
+
+ RESOLUTIONS = %w[refund replacement refund_and_replacement].freeze
+
validates :order, :claim_type, presence: true
validates :claim_items, presence: true
- validates :claim_type, inclusion: { in: CLAIM_TYPES }
+ validates :claim_type, inclusion: { in: -> (record) { record.class.claim_types } }
+ validates :resolution, inclusion: { in: RESOLUTIONS }, allow_nil: true
accepts_nested_attributes_for :claim_items, allow_destroy: true
- state_machine :status, initial: :open do
- event :approve do
- transition from: :open, to: :approved
- end
- event :resolve do
- transition from: :approved, to: :resolved
- end
- event :deny do
- transition from: :open, to: :denied
- end
- event :cancel do
- transition from: [:open, :approved], to: :canceled
- end
-
- after_transition to: :resolved, do: :execute_resolution
- end
-
- # Resolution type: how the claim is being resolved
- # 'refund', 'replacement', 'refund_and_replacement'
- attribute :resolution, :string
-
- private
-
- def execute_resolution
- process_refund if resolution&.include?('refund')
- create_replacement if resolution&.include?('replacement')
- end
-
- def process_refund
- payment = order.payments.completed.last
- return unless payment
-
- amount = claim_items.sum(:refund_amount)
- return if amount.zero?
-
- Spree::Refund.create!(
- payment: payment,
- amount: amount,
- reason: Spree::RefundReason.claim_processing,
- originator: self
- )
- end
-
- def create_replacement
- stock_location = Spree::StockLocation.default
- fulfillment = order.fulfillments.create!(
- stock_location: stock_location,
- fulfillment_type: 'shipping',
- address: order.ship_address
- )
-
- claim_items.where(send_replacement: true).each do |item|
- fulfillment.fulfillment_items.create!(
- variant: item.replacement_variant || item.variant,
- quantity: item.quantity,
- order: order,
- line_item: item.line_item
- )
- end
+ def refund_total
+ claim_items.sum(:refund_amount)
end
end
```
+`Spree::Claims::Resolve` takes the resolution as an argument rather than
+reading it off the record, so the caller's intent is explicit; refunds settle
+through the internal-vs-gateway branch (see "Refunding: internal vs gateway").
+
### ClaimItem
```ruby
@@ -425,12 +449,139 @@ end
Note: this is the one intentional polymorphic association — Refund needs to know what triggered it, and the originator set is small and closed (3 types + nil). The performance concern from Adjustments doesn't apply here because refunds are infrequent and never bulk-queried in hot paths.
+## Workflows
+
+Every transition is a workflow in `app/workflows/spree/`. These qualify for the
+workflow tier under `6.0-service-workflows.md` on all three counts: they carry
+extension hooks, they perform gateway I/O that must sit outside a transaction,
+and they need compensation.
+
+### Returns
+
+| Workflow | Arguments | Hooks | Notes |
+|---|---|---|---|
+| `Returns::Create` | `order:`, `items:`, `reason:`, `stock_location:`, `created_by:` | `validate`, `after_create` | `validate` is where a store rejects out-of-window returns |
+| `Returns::Approve` | `return:`, `approver:`, `note:` | `after_approve` | Optionally generates the return label (`external_step` — carrier API) |
+| `Returns::Receive` | `return:`, `items:`, `received_by:` | `before_restock`, `after_receive` | Partial receipt is the normal case: `items:` carries actual quantities and per-item resellable flags |
+| `Returns::Refund` | `return:`, `amount:`, `refund_method:` | `before_refund`, `after_refund` | Branches on refund method (below); `on_flow_failure:` reverses the status |
+| `Returns::Cancel` | `return:`, `reason:` | `after_cancel` | Restocks nothing; only valid from requested/approved |
+
+```ruby
+module Spree
+ module Returns
+ # Receives physically-returned items. Quantities and resellable flags come
+ # from the warehouse, not from what the customer said they would send —
+ # partial and damaged receipt is the normal case, not an edge case.
+ class Receive < Spree::Workflow
+ hooks :before_restock, :after_receive
+
+ # @param return_record [Spree::Return]
+ # @param items [Array<Hash>] `[{ return_item:, quantity:, resellable: }]`
+ # @param received_by [Object, nil]
+ def perform(return_record:, items:, received_by: nil)
+ super
+
+ step :ensure_receivable
+ step :validate_quantities
+
+ ApplicationRecord.transaction do
+ step :record_receipt
+ run_hooks :before_restock
+ step :restock_resellable_items
+ step :mark_received
+ end
+
+ run_hooks :after_receive
+ return_record.publish_event('return.received')
+ success(return_record.reload)
+ end
+
+ private
+
+ def ensure_receivable
+ failure(return_record, :not_approved) unless return_record.approved?
+ end
+
+ def restock_resellable_items
+ items.each do |item|
+ next unless item[:resellable]
+
+ return_record.stock_location.restock(
+ item[:return_item].variant, item[:quantity], return_record
+ )
+ end
+ end
+ end
+ end
+end
+```
+
+### Refunding: internal vs gateway
+
+Not every refund is a network call. Store credit and gift cards are internal
+ledger writes, so forcing them through `external_step` would push a pure
+database write outside the transaction that marks the return refunded — a crash
+between the two would leave a refunded return with no credit issued.
+`Returns::Refund` branches:
+
+```ruby
+ApplicationRecord.transaction do
+ run_hooks :before_refund # veto point — before any money moves
+ step :mark_refunded
+ step :issue_internal_credit if internal_refund?
+end
+
+external_step :refund_at_gateway, on_flow_failure: :revert_refunded unless internal_refund?
+```
+
+`internal_refund?` covers store credit and gift cards. The precedent is
+`Orders::Cancel#settle_payments`, which already treats gift-card-covered
+payments differently from gateway payments. `Claims::Resolve` and
+`Exchanges::Fulfill` use the same branch when settling money.
+
+### Exchanges
+
+| Workflow | Hooks | Notes |
+|---|---|---|
+| `Exchanges::Create` | `validate`, `after_create` | Validates replacement variants are purchasable |
+| `Exchanges::Approve` | `after_approve` | |
+| `Exchanges::Receive` | `before_restock`, `after_receive` | Same partial-receipt shape as returns |
+| `Exchanges::Fulfill` | `before_settle`, `after_fulfill` | Creates the replacement fulfillment, then settles `price_difference` as an `external_step` |
+| `Exchanges::Cancel` | `after_cancel` | |
+
+### Claims
+
+| Workflow | Hooks | Notes |
+|---|---|---|
+| `Claims::Create` | `validate`, `after_create` | Store API entry point; `validate` gates self-service claims |
+| `Claims::Approve` | `after_approve` | |
+| `Claims::Resolve` | `before_settle`, `after_resolve` | Takes `resolution:` explicitly; refund settles via the internal-vs-gateway branch, replacement fulfillment is in-transaction |
+| `Claims::Deny` | `after_deny` | |
+| `Claims::Cancel` | `after_cancel` | |
+
+### Why `validate` hooks matter here
+
+Return eligibility is the single most-customized rule in commerce — 30-day
+windows, final-sale categories, per-customer-group policies, region-specific
+consumer rights. A `validate` hook on `Returns::Create` and `Claims::Create` is
+the seam that keeps those out of core. It pairs with the EU consumer-rights
+withdrawal period in `5.4-6.0-eu-legal-compliance.md`.
+
## Migration Path
### Phase 1: Create new tables
+Per CLAUDE.md migration rules: no foreign key constraints, `null: false` on
+required columns, JSON columns guarded with `respond_to?(:jsonb)`. Defaults
+(refined 2026-08-02): **status/string columns get no database default** — the
+creating workflow sets the status; **integer and decimal columns do carry
+defaults** (`quantity` 1, amounts 0), so a raw insert can never produce a null
+quantity or amount. Metadata is a **single `metadata` column** — the new 6.0
+tables drop the legacy public/private split (`metadata` is already the primary
+API param on carts).
+
```ruby
-class CreateReturnsExchangesClaims < ActiveRecord::Migration[7.2]
+class CreateReturnsExchangesClaims < ActiveRecord::Migration[8.1]
def change
create_table :spree_returns do |t|
t.string :number, null: false
@@ -438,13 +589,17 @@ class CreateReturnsExchangesClaims < ActiveRecord::Migration[7.2]
t.references :stock_location, null: false
t.references :reason
t.references :created_by
- t.string :status, null: false, default: 'requested'
+ t.string :status, null: false
t.text :memo
- t.jsonb :public_metadata
- t.jsonb :private_metadata
+ if t.respond_to?(:jsonb)
+ t.jsonb :metadata
+ else
+ t.json :metadata
+ end
t.timestamps
end
add_index :spree_returns, :number, unique: true
+ add_index :spree_returns, :status
create_table :spree_exchanges do |t|
t.string :number, null: false
@@ -452,28 +607,36 @@ class CreateReturnsExchangesClaims < ActiveRecord::Migration[7.2]
t.references :stock_location, null: false
t.references :reason
t.references :created_by
- t.string :status, null: false, default: 'requested'
+ t.string :status, null: false
t.text :memo
- t.jsonb :public_metadata
- t.jsonb :private_metadata
+ if t.respond_to?(:jsonb)
+ t.jsonb :metadata
+ else
+ t.json :metadata
+ end
t.timestamps
end
add_index :spree_exchanges, :number, unique: true
+ add_index :spree_exchanges, :status
create_table :spree_claims do |t|
t.string :number, null: false
t.references :order, null: false
t.references :reason
t.references :created_by
- t.string :status, null: false, default: 'open'
+ t.string :status, null: false
t.string :claim_type, null: false
t.string :resolution
t.text :memo
- t.jsonb :public_metadata
- t.jsonb :private_metadata
+ if t.respond_to?(:jsonb)
+ t.jsonb :metadata
+ else
+ t.json :metadata
+ end
t.timestamps
end
add_index :spree_claims, :number, unique: true
+ add_index :spree_claims, :status
# Rename old return_items to legacy, create new simplified table
rename_table :spree_return_items, :spree_return_items_legacy
@@ -543,13 +706,26 @@ end
### Phase 3: Model migration
-- Create Return, Exchange, Claim models + line items
+- Create Return, Exchange, Claim models + line items — associations,
+ validations, scopes and pure reads only
+- Add the `Spree::HasStatus` concern
- Update Order associations
- Update Refund with originator
- Create ReturnReason, ClaimReason models (or reuse existing reason tables)
- Update FulfillmentItem (was InventoryUnit) to remove return-specific methods
- Wire into events system (lifecycle events for each entity)
+### Phase 3b: Workflows
+
+The fifteen workflows above, in `app/workflows/spree/{returns,exchanges,claims}/`.
+No transition is reachable except through one of them — there is no
+`return.receive!`. Admin and Store API controllers call the workflow and render
+its `Result`.
+
+Ordering note: Phase 3b lands with Phase 3, not after it. A model shipped with
+a status column and no way to move it is not usable, and shipping a temporary
+state machine "just to unblock" would defeat the purpose.
+
### Phase 4: Drop legacy models
- Drop: ReturnAuthorization, CustomerReturn, Reimbursement, ReimbursementType (all subtypes)
@@ -568,6 +744,7 @@ DELETE /api/v3/admin/returns/:id
POST /api/v3/admin/returns/:id/approve
POST /api/v3/admin/returns/:id/receive
POST /api/v3/admin/returns/:id/refund
+POST /api/v3/admin/returns/:id/cancel
# Exchanges
POST /api/v3/admin/orders/:order_id/exchanges
@@ -576,6 +753,7 @@ PATCH /api/v3/admin/exchanges/:id
POST /api/v3/admin/exchanges/:id/approve
POST /api/v3/admin/exchanges/:id/receive
POST /api/v3/admin/exchanges/:id/fulfill
+POST /api/v3/admin/exchanges/:id/cancel
# Claims
POST /api/v3/admin/orders/:order_id/claims
@@ -583,6 +761,8 @@ GET /api/v3/admin/orders/:order_id/claims
PATCH /api/v3/admin/claims/:id
POST /api/v3/admin/claims/:id/approve
POST /api/v3/admin/claims/:id/resolve
+POST /api/v3/admin/claims/:id/deny
+POST /api/v3/admin/claims/:id/cancel
# Store API: customers can initiate returns/claims
POST /api/v3/store/orders/:order_id/returns
@@ -597,6 +777,12 @@ GET /api/v3/store/orders/:order_id/claims
- **Don't add new ReimbursementType subtypes.** The STI hierarchy is being dropped.
- **New return/exchange logic should be designed for the three-model pattern.** Think "Return with ReturnItems" not "ReturnAuthorization with ReturnItems through CustomerReturn."
- **Refund stays as-is.** It's the payment-level primitive. Returns, Exchanges, and Claims create Refunds when money needs to go back.
+- **No state machine on any new model in this area.** Plain `status` string,
+ inclusion validation, transitions through workflows. This generalizes beyond
+ returns — see `6.0-service-workflows.md` → "State machines".
+- **Don't persist a financial preview.** Showing an admin what a partial return
+ will refund is computed in memory and discarded; the persisted preview
+ substrate arrives in `6.1-order-change-substrate.md`.
## Resolved Questions
@@ -614,6 +800,11 @@ None at this time.
- Current return models: `spree/core/app/models/spree/return_authorization.rb`, `return_item.rb`, `customer_return.rb`, `reimbursement.rb`
- Current ReimbursementType hierarchy: `spree/core/app/models/spree/reimbursement_type/`
+- Related plan: `6.0-service-workflows.md` (the workflow tier; no-state-machines rule)
- Related plan: `6.0-fulfillment-and-delivery.md` (FulfillmentItem replaces InventoryUnit, Fulfillment replaces Shipment)
- Related plan: `6.0-split-adjustments.md` (return credits removed from adjustment system)
- Related plan: `6.0-typed-stock-movements.md` (restock on return creates `received` movement)
+- Successor plan: `6.1-order-change-substrate.md` (the mutation half moves onto
+ the shared preview-then-apply substrate; additive)
+- Precedent: `Spree::Orders::Cancel` / `Spree::Orders::Resume` — the same
+ callback-to-workflow conversion, already shipped
diff --git a/docs/plans/6.0-service-workflows.md b/docs/plans/6.0-service-workflows.md
index 16f3ad8134..802751c519 100644
--- a/docs/plans/6.0-service-workflows.md
+++ b/docs/plans/6.0-service-workflows.md
@@ -4,7 +4,7 @@
**Target:** Spree 6.0
**Depends on:** `6.0-cart-order-split.md` (Carts::Complete is the reference implementation and stress test). Coordinates with: `6.0-multi-vendor-marketplace.md` (payout runs are the first durable-flow consumer), the Rails 8.1 floor decision (decisions.md 2026-07-29 — ActiveJob Continuations are the durability primitive).
**Author:** Damian Legawiec + Claude (design session 2026-07-30)
-**Last updated:** 2026-07-31
+**Last updated:** 2026-08-02
## Summary
@@ -141,6 +141,163 @@ green and its observable semantics byte-identical.
flow, `step :reserve_stock, with: -> { Spree.stock_reserve_service }`
keeps step implementations swappable without subclassing the whole flow.
+11. **Workflows replace state machines for new models (2026-08-02).** A new
+ model gets a plain `status` string column with an inclusion validation and
+ generated predicates — never a `state_machine :status` block. Transitions
+ are workflows: `Spree::Returns::Receive.call(...)`, not `return.receive!`.
+ See "State machines" below for the full rule and the narrow exceptions.
+
+12. **Hook keys are public API and ship on the 6.0 boundary (2026-08-02 —
+ amends decision 6 and the "never speculatively" clause in decision 1).**
+ The original rule — a service graduates the moment it earns a hook, and
+ hooks are added by demand — was written to prevent speculative
+ abstraction, and it still governs *workflows*. It does not govern *hooks*
+ on flows already in the workflow tier. A hook is a published extension
+ point: adding one later is cheap, but *moving* one means restructuring a
+ flow extension authors have already registered against, which is a
+ breaking change. 6.0 is the breaking-change window. A documented,
+ coherent extension surface is itself the demand — so hooks are placed
+ deliberately across the existing workflows now, at the points a
+ third-party integration would need them, rather than one at a time as
+ individual merchants ask. The bar remains real: a hook must name a point
+ where an extension would plausibly inject behaviour, and every hook ships
+ documented. Speculative *workflows* are still forbidden.
+
+## Hooks
+
+Three families, because they solve different problems:
+
+**Lifecycle hooks** — past tense, fired after something happened, for
+extensions that react: `after_item_added`, `after_cancel`, `after_confirm`.
+Handlers read the workflow instance and cannot change the outcome. This is
+what we ship today.
+
+**Validation hooks** — `validate`, fired before the work, for extensions that
+*reject*. A handler calls `reject!(message)` on the workflow to abort the flow
+(contract below). This is the seam merchants ask for most (return windows, B2B
+purchase limits, per-group eligibility) and today they have to replace the
+whole workflow class to get it.
+
+**Context hooks** — imperative (`set_pricing_context`, `set_tax_line_context`,
+`set_promotion_context`, `get_provider_data`), fired before a calculation so
+extensions can feed data *into* it.
+
+### Hook contracts (resolved 2026-08-02)
+
+**Context hooks collect and deep-merge handler return values.** A handler
+returns a hash; `run_hooks` merges every handler's hash in registration order
+and returns the result. No shared mutable state — handlers stay pure and
+independently testable, and a handler that returns `nil` contributes nothing
+rather than corrupting the context.
+
+```ruby
+# Handler
+class MyApp::PricingContext
+ def call(workflow)
+ { customer_tier: workflow.cart.customer&.tier }
+ end
+end
+
+# Workflow
+context = run_hooks(:set_pricing_context) # => { customer_tier: 'gold' }
+Spree.price_selector.call(cart, **context)
+```
+
+`run_hooks` returning a value is additive — lifecycle hooks ignore the return
+and are unaffected. On a key collision the last registered handler wins, and
+the collision is logged via `Rails.error.report` in development so two
+extensions fighting over the same key is visible rather than mysterious.
+
+**`validate` handlers reject with `reject!(message)`.** A purpose-named method
+on the workflow that wraps the existing failure path — it raises
+`FailureSignal`, so the undo stack unwinds and an open transaction rolls back
+exactly as a failed step would. The distinct name keeps "an extension vetoed
+this" legible against "this step failed" at the call site.
+
+```ruby
+class MyApp::LimitReturnWindow
+ def call(workflow)
+ return if workflow.order.completed_at > 30.days.ago
+
+ workflow.reject!(Spree.t('returns.errors.outside_window'))
+ end
+end
+```
+
+### What is public API (resolved 2026-08-02)
+
+The 6.0 extension surface is deliberately narrow, because everything in it is
+frozen for the release:
+
+**Public** — hook keys and their contracts, `reject!`, `Spree::Dependencies`
+class swapping, `has_status`/`add_status`, workflow `#perform` keyword
+signatures.
+
+**Internal** — `with:` step targets, step names, step boundaries and ordering.
+`step :reserve_stock, with: -> { Spree.stock_reserve_service }` stays a core
+seam: documenting it would freeze every step name and its collaborator kwarg
+contract as public API, locking internal structure we still expect to refactor
+during the 6.0 finishing work. Extensions get hooks (finer-grained than class
+swapping, and safe) and Dependencies (coarser, already public). Revisit in 6.1
+once real hook usage shows what is genuinely missing.
+
+### Configurable statuses
+
+`Spree::HasStatus` (see "State machines" below) holds its values in a
+`class_attribute`, not a frozen constant, so extensions can add statuses
+without reopening core. The API is deliberately **additive only**:
+
+```ruby
+# Core
+class Spree::Return < Spree.base_class
+ has_status :requested, :approved, :received, :refunded, :canceled,
+ default: :requested
+end
+
+# Extension decorator
+Spree::Return.add_status(:inspecting, after: :received)
+Spree::Return.statuses
+# => %w[requested approved received inspecting refunded canceled]
+```
+
+Adding is safe; wholesale replacement is not offered. Core workflows guard on
+core statuses (`Returns::Refund` requires `received?`), so allowing an
+extension to remove one would silently break core flows with no error at the
+point of removal — the guard would simply never pass.
+
+A custom status needs a custom workflow to move records into it. That is the
+intended shape, not a gap: `add_status` deliberately takes no `from:`/`to:`
+transition graph, because validating transitions centrally is a state machine
+by another name — the exact thing decision 11 removes. Extensions write a
+workflow the same way core does.
+
+### State machines
+
+`state_machines-activerecord` stays a dependency through 6.0 for the models
+that still carry machines (Payment, Fulfillment, InventoryUnit,
+ReturnAuthorization, GiftCard — see `6.0-normalize-state-to-status.md`).
+**New models do not get state machines.** The reasoning, argued at length in
+`6.0-returns-exchanges-claims.md` → "Why workflows, not state machines":
+
+- Transition callbacks run inside the save transaction, which puts gateway I/O
+ in a database transaction — the exact failure `Carts::Complete`'s three-phase
+ design exists to prevent.
+- Transitions take no arguments, so partial and contextual operations
+ (receive two of three items, one not resellable) have nowhere to put their
+ inputs.
+- There is no compensation story; `on_flow_failure:` is.
+- Guards raise `StateMachines::InvalidTransition` instead of returning an
+ inspectable `Result`.
+
+The precedent is already shipped: the Order state machine is gone in 6.0
+(`6.0-cart-order-split.md`), and `Orders::Cancel`/`Orders::Resume` absorbed
+`Order#after_cancel`/`#after_resume`.
+
+The narrow exception: a model whose status genuinely has no side effects at
+all — a pure label with no restocking, no money, no fulfillment — may keep a
+machine if the transition graph is doing real validation work. In practice
+this has not come up.
+
## Design Details
- **The whole workflow vocabulary is five words**: `step :name` (runs the
@@ -198,9 +355,11 @@ plan.
`RecalculateTotals`, single status writer, `use_shipping` fix).
Acceptance held throughout: batteries green unmodified.
3. **Phase 1c — hooks — shipped:** `after_item_added` (AddItem),
- `before_finalize` (Complete) and `after_cancel` (Orders::Cancel,
- in-transaction) registered-hook seams. These three only; more hooks
- are added by demand, not speculation. Extension-facing docs pending.
+ `before_finalize` (Complete), `after_cancel` (Orders::Cancel,
+ in-transaction) and `after_resume` (Orders::Resume) registered-hook
+ seams. The original "more hooks are added by demand, not speculation"
+ stance is amended by decision 12 — Phase 3 below places the remaining
+ hooks deliberately on the 6.0 boundary. Extension-facing docs pending.
4. **Rolling adoption:** services migrate when meaningfully touched — never a
big-bang sweep. `ServiceModule::Base` is not deprecated in 6.0.
5. **Phase 2 — resolved:** plain `ActiveJob::Continuable` jobs are the
@@ -209,6 +368,61 @@ plan.
execution is deliberately not shipped — revisit with the payout run
per the note above.
+### Phase 3 — extension surface (2026-08-02, targets 6.0)
+
+Two waves that finish the extension surface on the 6.0 boundary, per decision
+12. Wave A adds no classes; Wave B graduates four services that have already
+earned the tier. Neither is a sweep — the list is closed.
+
+**Wave A — runtime contracts + hooks on existing workflows.** Two runtime
+additions first (both additive, neither changes existing behaviour):
+
+1. `run_hooks` collects handler return values and deep-merges them into a hash
+ it returns. Lifecycle hooks ignore it; context hooks consume it.
+2. `reject!(message)` on `Spree::Workflow`, wrapping the existing failure path.
+
+Then the hooks themselves — each a `hooks :name` declaration plus a `run_hooks`
+call at an existing seam, with no restructuring:
+
+| Workflow | Hook | Why |
+|---|---|---|
+| `Carts::AddItem` | `validate` | Reject an add before the line item is built — purchase limits, B2B eligibility, per-group rules |
+| `Carts::Complete` | `validate` | Guard completion (fraud, credit hold, required custom fields) |
+| `Carts::Complete` | `after_finalize` | We ship `before_finalize` only; there is no in-flow point after placement succeeds |
+| `Carts::Recalculate` | `after_recalculate` | React to a repriced cart before the caller sees it |
+| `Orders::Cancel` | `before_cancel` | Veto a cancellation (already-shipped guard, vendor policy) |
+| `Orders::Resume` | `before_resume` | Symmetry with cancel |
+
+Context hooks are **no longer blocked** (contracts resolved 2026-08-02), so
+`Carts::Recalculate` also gains `set_promotion_context` and
+`Carts::RecalculateTotals` gains `set_tax_line_context` — both consuming the
+merged hash `run_hooks` now returns.
+
+**Wave B — graduate four services.** Each carries external I/O or real
+orchestration and is currently hand-rolling what `Spree::Workflow` provides:
+
+| Service today | Becomes | Hooks | Why it qualifies |
+|---|---|---|---|
+| `Fulfillments::Create` (274 lines) | `app/workflows/spree/fulfillments/create.rb` | `validate`, `after_create`, `get_provider_data` | Hand-rolled `order.lock!`, `return failure` inside a transaction, unit movement + stock transfer + repricing + totals. The clearest case in the codebase |
+| `Payment#capture!` / `#credit!` (model methods) | `Payments::Capture`, `Payments::Refund` | `before_capture`, `after_capture`, `before_refund`, `after_refund` | Gateway I/O currently runs wherever the caller happens to be, including inside transactions. `external_step` is exactly this |
+| `Payments::HandleWebhook` | `app/workflows/spree/payments/handle_webhook.rb` | `after_handle` | Branchy dispatch over gateway callbacks with no compensation and no replay guard |
+| `Carts::Merge` | `app/workflows/spree/carts/merge.rb` | `validate`, `after_merge` | Spans a transaction plus a totals recalculation; `validate` is where a store customizes merge policy |
+
+`get_provider_data` on fulfillment creation is a context hook, using the same
+collect-and-merge contract: handlers return provider-specific payload
+(carrier account, service level, customs data) that the fulfillment provider
+call consumes.
+
+**Explicitly out of scope.** No workflows for CRUD. Creating, updating and
+deleting a region, tax rate, API key or product is a controller plus a model
+save; wrapping those in workflow classes would add hundreds of pass-through
+classes with no hook, no compensation and no external I/O to justify them.
+Workflows are earned by orchestration, not by being a write.
+
+**Sequencing.** Wave A first — it is additive and low-risk, and it settles the
+`validate` contract that Wave B depends on. `6.1-order-change-substrate.md`
+depends on both and must not start before they land.
+
## Constraints on Current Work
- New services are plain sequential `ServiceModule` bodies (like
@@ -218,12 +432,16 @@ plan.
needs it belongs in `app/workflows/` on `Spree::Workflow`.
- Adding an extension hook to a plain service means graduating it to the
workflow tier first — hooks exist only as `run_hooks` declarations.
+- **No `state_machine` on a new model.** Plain `status` string, inclusion
+ validation, transitions through workflows (decision 11).
+- **No new business logic in model callbacks or transition callbacks** —
+ especially not gateway I/O. If a save has a side effect that touches money,
+ stock or an external system, it belongs in a workflow step.
+- **New `set_*_context` hooks follow the collect-and-merge contract** ("Hook
+ contracts" above) — handlers return a hash, never mutate shared state.
## Open Questions
-- Should `with:` step swapping be exposed to extensions or reserved for core
- seams initially?
-- Context object mutability rules for hooks (read-write vs read-plus-merge).
- Whether the sweeper that resumes stuck completions generalizes into flow
infrastructure in Phase 2 or stays completion-specific.
diff --git a/docs/plans/6.1-order-change-substrate.md b/docs/plans/6.1-order-change-substrate.md
new file mode 100644
index 0000000000..16b5cd1c2c
--- /dev/null
+++ b/docs/plans/6.1-order-change-substrate.md
@@ -0,0 +1,312 @@
+# OrderChange — a preview-then-apply substrate for post-placement order mutation
+
+**Status:** Draft
+**Target:** Spree 6.1
+**Depends on:** 6.0-service-workflows.md (workflow tier), 6.0-returns-exchanges-claims.md (first consumer), 6.0-cart-order-split.md (Order is immutable-by-default after placement)
+**Author:** Damian + Claude
+**Last updated:** 2026-08-02
+
+## Summary
+
+Every post-placement change to an order — a return, an exchange, a claim, an
+admin editing line items, a draft order being amended — is the same shape:
+someone proposes a set of changes, somebody reviews the financial consequence,
+and then the changes are applied atomically or thrown away. Today each of those
+flows would invent its own draft model. This plan introduces one shared
+substrate, `Spree::OrderChange` plus `Spree::OrderChangeAction`, that all of
+them build on: a pending change set that can be previewed (what would the order
+look like, what would the customer owe or be owed) and then confirmed in a
+single transaction.
+
+This is deliberately **6.1, not 6.0**. It is a new schema surface and a new
+extension API, and 6.0 already carries the Cart/Order split, typed adjustments,
+the fulfillment rename and the returns rework. Shipping it late in 6.0 would
+mean designing it under time pressure against three consumers that are
+themselves still landing. The 6.0 returns/exchanges/claims work ships on its
+own status flows (see that plan) and adopts this substrate in 6.1 without a
+breaking API change.
+
+## Why this exists
+
+Order edits, returns, exchanges, claims and draft-order amendments all reduce
+to the same three moves: accumulate actions, preview, confirm. The uniformity
+is the point — one preview path, one confirm path, one compensation story, and
+a consistent `begin → request → confirm → cancel` lifecycle across five
+different business operations.
+
+Without it, each of those flows needs its own draft representation, its own
+"what will this cost" calculation and its own atomic-apply logic. We would
+write the same thing five times and they would drift.
+
+The concrete pain it solves for us:
+
+- **Previewing money is currently impossible.** An admin adding a line item to
+ a placed order cannot see the new total, tax and balance-due before
+ committing. Our totals only exist after rows are written.
+- **Partial application.** A return that restocks two of three items, or an
+ exchange where one replacement is out of stock, has no natural
+ representation.
+- **Audit.** "Who changed this order, when, and what did it cost" is currently
+ reconstructed from typed money rows and metadata. An OrderChange is the
+ record.
+
+## Key Decisions (do not deviate without discussion)
+
+- **Two models only:** `Spree::OrderChange` (the change set) and
+ `Spree::OrderChangeAction` (one proposed mutation). No per-domain draft
+ models.
+- **Actions are typed rows, not polymorphic.** Following the 6.0 design
+ language (`decisions.md` 2026-07-27, split-adjustments,
+ typed-stock-movements): an action carries a `kind` string plus concrete
+ nullable FKs (`line_item_id`, `variant_id`, `fulfillment_id`,
+ `delivery_method_id`), never `subject_type`/`subject_id`.
+- **Preview is computed, never persisted.** Previewing builds the projected
+ order in memory and runs the existing totals workflow against it. No
+ shadow order rows, no "draft" duplicates of line items. This is the single
+ most important constraint — persisted previews are how the legacy
+ adjustments system became unmaintainable.
+- **Confirm is a workflow, not a state-machine callback.** Applying a change
+ set is `Spree::OrderChanges::Confirm` on `Spree::Workflow`: gateway I/O
+ (capturing the difference, refunding the difference) is an `external_step`,
+ everything else is in one transaction with compensation armed.
+- **`OrderChange` owns no money columns.** Amounts are derived by previewing.
+ The only persisted money is on the order's own typed rows after confirm.
+- **One open change set per order at a time**, enforced by a partial unique
+ index on `(order_id)` where `status IN ('pending', 'requested')` — a
+ requested set is still open. Concurrent edits are a conflict, not a merge.
+- **The four consumers keep their own top-level models.** `Return`,
+ `Exchange`, `Claim` and admin order edits are still first-class entities
+ with their own statuses and their own API resources. They *reference* an
+ OrderChange for the mutation mechanics; they are not replaced by it. The
+ substrate is deliberately a mechanism, not a replacement domain model:
+ reducing a return to "a view over a change set" would cost merchants the
+ first-class return entity `6.0-returns-exchanges-claims.md` exists to give
+ them.
+
+## Design Details
+
+### OrderChange
+
+```ruby
+class Spree::OrderChange < Spree.base_class
+ has_prefix_id :ordchg
+
+ include Spree::Metadata
+
+ publishes_lifecycle_events
+
+ belongs_to :order, class_name: 'Spree::Order', inverse_of: :order_changes
+ # Staff only — customer-initiated changes (6.1 Phase 4 self-service
+ # returns) leave this nil; the requester is always order.customer.
+ belongs_to :requested_by, class_name: Spree.admin_user_class.to_s, optional: true
+
+ # What business operation opened this change set. Concrete FKs, exactly-one
+ # (or none, for a plain admin order edit).
+ belongs_to :return, class_name: 'Spree::Return', optional: true
+ belongs_to :exchange, class_name: 'Spree::Exchange', optional: true
+ belongs_to :claim, class_name: 'Spree::Claim', optional: true
+
+ has_many :actions, class_name: 'Spree::OrderChangeAction', dependent: :destroy,
+ inverse_of: :order_change
+
+ include Spree::HasStatus
+ # pending → requested → confirmed | canceled | declined
+ has_status :pending, :requested, :confirmed, :canceled, :declined,
+ default: :pending
+end
+```
+
+`status` uses the `Spree::HasStatus` concern from
+`6.0-returns-exchanges-claims.md` — plain string column, inclusion validation,
+generated predicates and scopes, extensible via `add_status`, no state
+machine. Transitions are driven by the workflows below.
+
+### OrderChangeAction
+
+```ruby
+class Spree::OrderChangeAction < Spree.base_class
+ has_prefix_id :ordchga
+
+ # Configuration, not a frozen constant (same ruling as statuses) —
+ # register_action_kind appends here alongside registering the applier.
+ class_attribute :kinds, default: %w[
+ add_item update_item remove_item
+ add_fulfillment update_fulfillment remove_fulfillment
+ add_delivery update_delivery remove_delivery
+ add_discount remove_discount
+ return_item receive_item
+ ]
+
+ belongs_to :order_change, class_name: 'Spree::OrderChange', inverse_of: :actions
+
+ belongs_to :line_item, class_name: 'Spree::LineItem', optional: true
+ belongs_to :variant, class_name: 'Spree::Variant', optional: true
+ belongs_to :fulfillment, class_name: 'Spree::Fulfillment', optional: true
+ belongs_to :delivery_method, class_name: 'Spree::DeliveryMethod', optional: true
+
+ validates :kind, inclusion: { in: -> (record) { record.class.kinds } }
+ validates :quantity, numericality: { greater_than: 0 }, allow_nil: true
+end
+```
+
+Each `kind` has a known applier — a plain method on the confirm workflow, not
+a class hierarchy. Extensions add kinds through the `register_action_kind`
+seam (see Extension surface).
+
+### Preview
+
+```ruby
+Spree::OrderChanges::Preview.call(order_change: change)
+# => Result(value: Spree::OrderChangePreview)
+```
+
+The preview builds the projected order **in memory** — applying each action to
+unsaved copies of the affected rows — then runs the existing
+`Spree::Orders::RecalculateTotals` against that projection inside a rolled-back
+transaction. The result is an `ActiveModel::Model` value object (per CLAUDE.md
+— never `Struct`) carrying projected item total, tax total, discount total,
+order total, and the **balance delta**: positive means the customer owes more,
+negative means a refund is due.
+
+This is the single seam every consumer shares. The returns admin UI, the
+exchange price-difference display and the order-edit screen all call it.
+
+### Confirm
+
+`Spree::OrderChanges::Confirm` is a `Spree::Workflow`:
+
+```
+ step :ensure_confirmable # status == 'requested', order still mutable
+ step :recompute_preview # re-derive the delta; guard against drift
+ ApplicationRecord.transaction do
+ step :apply_actions # each action's applier, in order
+ step :resum_totals, with: -> { Spree.order_recalculate_totals_workflow }
+ run_hooks :before_settle
+ end
+ external_step :settle_balance # capture or refund the delta — gateway I/O
+ step :update_statuses, with: -> { Spree.order_update_statuses_service }
+ run_hooks :after_confirm
+```
+
+The transaction boundary mirrors `Carts::Complete`: money movement at a
+gateway never shares a database transaction, and everything after the charge
+is small and idempotent.
+
+### Order association
+
+```ruby
+class Spree::Order < Spree.base_class
+ has_many :order_changes, class_name: 'Spree::OrderChange', dependent: :destroy
+
+ def pending_order_change
+ order_changes.find_by(status: %w[pending requested])
+ end
+end
+```
+
+## Workflows
+
+Per `6.0-service-workflows.md`, these live in `app/workflows/spree/order_changes/`
+because they carry hooks, compensation and external I/O:
+
+| Workflow | Hooks | Notes |
+|---|---|---|
+| `OrderChanges::Begin` | `after_begin` | Opens the change set; fails if one is already open |
+| `OrderChanges::AddAction` | `validate` | Appends an action; `validate` lets extensions reject |
+| `OrderChanges::Request` | `after_request` | pending → requested; freezes the action list |
+| `OrderChanges::Confirm` | `before_settle`, `after_confirm` | The heavy one; external settle step |
+| `OrderChanges::Cancel` | `after_cancel` | Discards a pending/requested set |
+
+`Preview` stays a plain Tier 1 service — it is a pure read with no hooks and no
+side effects.
+
+## Extension surface
+
+Two seams, both consistent with the existing hook registry:
+
+```ruby
+# Register a custom action kind and its applier
+Spree::OrderChange.register_action_kind('gift_wrap', Spree::MyExtension::ApplyGiftWrap)
+
+# Reject actions from a hook
+Spree.hooks.register('order_changes.add_action.validate', MyApp::LimitEditWindow)
+```
+
+## Migration Path
+
+### Phase 1 — schema
+
+`spree_order_changes` and `spree_order_change_actions` per the models above.
+Partial unique index on `spree_order_changes (order_id) WHERE status IN
+('pending','requested')`. Follows the house migration rules (see the
+returns-plan migration for the reference shape): no FK constraints,
+`null: false` on required columns, no defaults on string/status columns,
+defaults on integer/decimal columns, a single `metadata` JSON column guarded
+with `respond_to?(:jsonb)`.
+
+### Phase 2 — substrate
+
+Models, `Preview`, the five workflows, the action appliers, specs. Nothing
+consumes it yet; it ships dormant and is exercised only by its own specs.
+
+### Phase 3 — admin order edit as the first consumer
+
+Admin order editing is the right first consumer: it has no existing model to
+migrate, it is the simplest financially (add/remove/update items, re-settle the
+difference), and it immediately replaces the current post-placement edit path
+that writes rows directly and re-sums.
+
+### Phase 4 — returns, exchanges, claims adopt it
+
+Each gains a nullable `order_change_id`. Their existing status flows stay
+exactly as designed in `6.0-returns-exchanges-claims.md` — what changes is that
+the *mutation* half (restock, replacement fulfillment, refund) moves from
+status-transition side effects into an OrderChange confirm. Additive: 6.0-era
+returns keep working with `order_change_id` null.
+
+### Phase 5 — draft orders
+
+Amending a draft order becomes an OrderChange, so draft-order editing and
+placed-order editing share one implementation.
+
+## Constraints on Current Work
+
+These apply during 6.0, before any of this is implemented:
+
+- **Do not build a per-domain draft/preview model.** If a 6.0 flow needs to
+ preview a financial change, compute it in memory and throw it away — do not
+ persist a shadow order. A persisted per-domain draft would have to be
+ migrated onto this substrate later.
+- **Keep post-placement mutation inside a workflow**, not in a model callback
+ or a state-machine transition. The 6.0 returns plan is being amended for
+ exactly this reason.
+- **Do not add a polymorphic `subject` to any new post-placement row.** Typed
+ `kind` + concrete FKs, per decisions.md 2026-07-27.
+- **New post-placement flows expose their money math through a service that
+ returns a value object**, so it can be re-pointed at `OrderChanges::Preview`
+ in 6.1 without changing callers.
+
+## Open Questions
+
+- **Does an OrderChange need to survive rejection?** Keeping declined change
+ sets is good audit but grows a hot table. Leaning toward keeping them with a
+ retention rake task.
+- **Multi-vendor interaction.** When an order splits across vendors
+ (`6.0-multi-vendor-marketplace.md`), does a change set span vendors or is
+ there one per `OrderGroup` member? Needs resolving with that plan before
+ Phase 3.
+- **Does `Preview` need caching?** The order-edit UI will call it on every
+ keystroke-ish interaction. Probably debounced client-side rather than cached
+ server-side, but worth measuring.
+- **Stock reservation during a pending change.** An `add_item` action that sits
+ in `requested` for an hour does not hold stock. Whether it should reuse
+ `6.0-stock-reservations.md` is unresolved.
+
+## References
+
+- `docs/plans/6.0-service-workflows.md` — the workflow tier this is built on
+- `docs/plans/6.0-returns-exchanges-claims.md` — first business consumer
+- `docs/plans/6.0-cart-order-split.md` — post-placement edit path and the
+ `resum_typed_totals!` semantics Confirm reuses
+- `docs/plans/6.0-split-adjustments.md` — typed money rows the preview projects
+- `decisions.md` 2026-07-27 — typed `kind` + concrete FKs over polymorphism
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index e9cc987a7e..c856646e72 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1,3 +1,134 @@
+## 2026-08-02: Workflows replace state machines for new models; hooks ship on the 6.0 boundary; OrderChange substrate targets 6.1
+
+A review of our workflow and extension surface against the wider ecosystem
+settled three things.
+
+**1. New models get no state machine.** The returns/exchanges/claims draft gave
+each of `Return`, `Exchange` and `Claim` a `state_machine :status` block with
+the real work on transition callbacks (`after_transition to: :received,
+do: :restock_items`, `do: :process_refund`). That is now removed: plain `status`
+string column, inclusion validation, generated predicates, and every transition
+is a workflow.
+
+Why: a transition callback runs inside the transaction that saves the status
+column, so `process_refund` would put a gateway call inside a database
+transaction — the exact failure `Carts::Complete`'s three-phase design exists to
+prevent. Transitions also take no arguments, and every real return is partial
+("two of three arrived, one not resellable") with nowhere to put that input;
+there is no compensation story where `on_flow_failure:` is; and guards raise
+`StateMachines::InvalidTransition` instead of returning an inspectable `Result`.
+The stated purpose of that plan was escaping six interlocking state machines —
+replacing six with three is a difference of degree, not of kind.
+
+The precedent had already shipped: the Order state machine is gone in 6.0, and
+`Orders::Cancel`/`Orders::Resume` absorbed `Order#after_cancel`/`#after_resume`,
+moving gateway settlement out of the transaction in the process.
+`state_machines-activerecord` stays a dependency for the legacy models through
+6.0; it is simply not used on anything new.
+
+**2. Hook keys are public API, so they ship on the breaking-change boundary.**
+The doctrine's "a service graduates the moment it earns a hook — never
+speculatively" was written to stop speculative abstraction, and it still governs
+*workflows*. It does not govern *hooks on flows already in the workflow tier*.
+Adding a hook later is cheap; *moving* one means restructuring a flow extensions
+have registered against, which breaks them. 6.0 is the window. A documented,
+coherent extension surface is itself the demand, so hooks are placed
+deliberately across the existing workflows now rather than one merchant request
+at a time. Two closed waves (see `6.0-service-workflows.md` Phase 3): Wave A
+adds `validate` and lifecycle hooks to the existing workflows; Wave B graduates
+four services that already qualify on external I/O or orchestration
+(`Fulfillments::Create`, `Payments::Capture`/`Refund`,
+`Payments::HandleWebhook`, `Carts::Merge`).
+
+Three hook families are now named: **lifecycle** (past tense, react, cannot
+change the outcome — what we ship today), **validation** (`validate`, reject
+before the work — the most-requested seam, currently only reachable by replacing
+a whole service class), and **context** (`set_pricing_context`,
+`get_provider_data` — feed data *into* a calculation). Context hooks are
+**blocked**: they need handlers to write back, and `run_hooks` currently
+dispatches the workflow instance for reading only. Do not ship a `set_*_context`
+hook until that contract is settled.
+
+Explicitly rejected: workflows for plain CRUD. Wrapping every region, tax-rate
+and API-key write in a workflow class would add hundreds of pass-through
+classes with no hook, no compensation and no external I/O. Workflows are earned
+by orchestration, not by being a write.
+
+**3. The OrderChange substrate targets 6.1, not 6.0**
+(`6.1-order-change-substrate.md`). One `OrderChange` + `OrderChangeAction` pair
+behind every post-placement mutation — admin order edits, returns, exchanges,
+claims, draft-order amendments — with a `begin → request → confirm → cancel`
+lifecycle, so those flows stop inventing four separate draft models and four
+separate "what will this cost" calculations. It is deferred because it is new
+schema plus a new extension API, and 6.0 already carries the Cart/Order split,
+typed adjustments, the fulfillment rename and the returns rework; designing it
+under time pressure against three consumers that are themselves still landing
+is how it would go wrong. The 6.0 returns work ships on its own status flows and
+adopts the substrate additively in 6.1 via a nullable `order_change_id`.
+
+Two constraints apply to 6.0 work in the meantime: **do not persist a financial
+preview** (compute in memory and discard — a persisted per-domain draft would
+have to be migrated onto the substrate later), and expose post-placement money
+math through a service returning a value object so callers can be re-pointed
+without changing.
+
+**4. Hook contracts and configurable statuses (settled interactively the same
+day), which unblock Wave A:**
+
+*Context hooks collect and deep-merge handler return values.* A handler returns
+a hash; `run_hooks` merges every handler's hash in registration order and
+returns it. Chosen over a mutable context object because handlers stay pure and
+independently testable, with no order-dependent shared state. `run_hooks`
+returning a value is additive — lifecycle hooks ignore it. Last writer wins on
+a key collision, reported via `Rails.error.report` in development so two
+extensions fighting over one key is visible. **This unblocks the context-hook
+family** — `set_promotion_context`, `set_tax_line_context` and
+`get_provider_data` now ship in Waves A and B rather than being deferred.
+
+*`validate` handlers reject with `reject!(message)`* — a purpose-named method
+wrapping the existing failure path (raises `FailureSignal`, unwinds the undo
+stack, rolls back an open transaction). Preferred over reusing `failure(...)`
+so "an extension vetoed this" stays legible against "this step failed", and
+over a falsy return value, where a stray `nil` would abort a flow by accident.
+
+*Statuses are configuration, not frozen constants.* `Spree::HasStatus` holds
+values in a `class_attribute` with an additive `add_status(value, after:)`, so
+a merchant can add an `inspecting` step between `received` and `refunded`
+without reopening core. This follows the established `class_attribute` pattern
+for genuinely configurable collections (`DeliveryZoneMember.range_capable_country_isos`,
+`RichTextSanitizer.allowed_tags`) rather than the frozen-constant pattern used
+for closed value lists.
+
+**Additive only — wholesale replacement is not offered.** Core workflows guard
+on core statuses (`Returns::Refund` requires `received?`); letting an extension
+drop one would silently break core flows with no error at the point of removal,
+because the guard would simply never pass. Adding is safe, removing is not, so
+the API exposes only the safe half.
+
+`add_status` deliberately takes **no `from:`/`to:` transition graph**. A custom
+status needs a custom workflow to move records into it, which is the intended
+shape, not a gap: validating transitions centrally is a state machine by
+another name — precisely what ruling 1 removes.
+
+**5. Two smaller rulings from the same session.**
+
+*Refunds branch on method, not blanket `external_step`.* Store credit and gift
+cards are internal ledger writes, so routing them through `external_step` would
+push a pure database write outside the transaction that marks the return
+refunded — a crash between the two leaves a refunded return with no credit
+issued. `Returns::Refund` (and `Claims::Resolve`, `Exchanges::Fulfill`) keeps
+internal credit inside the transaction and sends only gateway refunds outside
+it. Precedent: `Orders::Cancel#settle_payments` already distinguishes
+gift-card-covered payments from gateway payments.
+
+*`with:` step swapping stays a core-only seam in 6.0.* The public extension
+surface is hook keys and their contracts, `reject!`, `Spree::Dependencies`
+class swapping, `has_status`/`add_status`, and workflow `#perform` signatures.
+Step names, step boundaries and `with:` targets are explicitly internal —
+documenting them would freeze internal structure we still expect to refactor
+during the 6.0 finishing work, in exchange for granularity that hooks largely
+already provide. Revisit in 6.1 once real hook usage shows what is missing.
+
## 2026-07-27: One owner pattern for cart/order-scoped rows — dual concrete FKs, not polymorphic
The cart-order-split stub's "polymorphic `LineItem#owner`" is superseded. Every