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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Settle return eligibility as a hook rather than a policy engine
Damian Legawiec365e1aba29ac
diff --git a/CLAUDE.md b/CLAUDE.mdindex 15f3e431e9..b3f38f408d 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. **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-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). **Return eligibility is a hook, not a policy engine (2026-08-03):** no window/restocking-fee/final-sale flag in core — a `validate` handler decides, enforcing for customers while letting staff override (it reads `created_by`), and region-varying policy reads `order.market`. Medusa/Saleor/Vendure ship no policy at all; Shopify's engine has no API. A `ReturnPolicy` model can arrive later behind the same hook.- `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)diff --git a/docs/plans/6.0-returns-exchanges-claims.md b/docs/plans/6.0-returns-exchanges-claims.mdindex 2ab4b1c160..a3334252b9 100644--- a/docs/plans/6.0-returns-exchanges-claims.md+++ b/docs/plans/6.0-returns-exchanges-claims.md@@ -68,6 +68,13 @@ Total: ~825 lines across 6+ models for return handling.- **No business logic in model callbacks.** Restocking, refunding and creatingreplacement fulfillments are named workflow steps. Nothing happens as a sideeffect of a save.+- **Core ships the eligibility seam, not a policy engine (2026-08-03).** No+ return window, restocking fee or final-sale flag in 6.0 — a `validate` hook+ on the create workflows is where a store's rules go. No open-source platform+ ships policy at all, and a `ReturnPolicy` model can arrive later behind the+ same hook. Eligibility is decided **in the workflow**, so a handler can+ enforce for customers and let staff override; policy that varies by region+ reads from `order.market`, not the store.- **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.@@ -559,13 +566,97 @@ payments differently from gateway payments. `Claims::Resolve` and| `Claims::Deny` | `after_deny` | || `Claims::Cancel` | `after_cancel` | |-### Why `validate` hooks matter here+### Return eligibility policy: the hook, not a policy engineReturn eligibility is the single most-customized rule in commerce — 30-daywindows, 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`.+consumer rights. **Core ships the seam and no policy.** A `validate` hook on+`Returns::Create`, `Exchanges::Create` and `Claims::Create` is where a store+puts its rules.++A market survey (2026-08-03) put this in perspective. Medusa, Saleor and+Vendure ship **no return-eligibility policy at all** — no window, no restocking+fee, no final-sale flag. Only Shopify has a real policy engine (window with a+delivery-date anchor, percentage restocking fee, final-sale product/collection+lists, per-market rule sets), and it exposes **no API for any of it** —+configuration is admin-UI only.++More telling is the seam itself. Medusa built a hook system, exposed+`setPricingContext` on returns, and deliberately did not expose a validation+hook — so a policy has to live in route middleware or a replaced workflow.+Saleor built the filter-veto webhook shape for shipping and never generalized+it to returns; an external app decides eligibility itself and then calls the+staff mutation, which never asks permission. Vendure's+`onTransitionStart` returning `false | string` is the only comparable veto, and+it hangs off a state machine rather than a return flow; its RMA issue is open+at priority P4.++So `validate` + `reject!(message)` is already the strongest extension point in+the field. Building a `ReturnPolicy` model with STI rules on top of it would be+the most capable thing on the market by a wide margin, and entirely+speculative — no competitor has demonstrated the demand, and the hook can carry+one later without changing its contract. **Not in 6.0.**++#### Enforce for customers, advise for staff++The one design lesson worth copying from Shopify: **eligibility is enforced on+the customer surface and advisory on the staff surface.** A Shopify staff+member can create a return on a final-sale item outside the window; the+customer account API refuses. Their `returnableFulfillments` deliberately+ignores return rules because it "mirrors the functionality of the store's+admin, where any authorized staff can create returns."++A handler that rejects unconditionally would be stricter than Shopify, which is+wrong for merchants — a supervisor overriding policy for a good customer is+ordinary retail, and the flow must not need code changes to allow it.++**This belongs in the workflow, not the model.** Eligibility is a decision made+during a flow with the caller's context in hand — who is asking, and whether+they may override — not a property of a return record. `Returns::Create`+therefore takes `created_by`, which is nil for customer self-service and set+for staff, and a handler decides what to do with that:++```ruby+module MyStore+ class ReturnWindow+ WINDOW = 30.days++ def call(workflow)+ return if workflow.order.completed_at > WINDOW.ago+ # Staff opened this — record the exception rather than blocking it.+ return if workflow.created_by.present?++ workflow.reject!(Spree.t('returns.errors.outside_window'))+ end+ end+end++Spree.hooks.register('returns.create.validate', 'MyStore::ReturnWindow')+```++Core provides no override audit trail in 6.0 — a store wanting one writes the+exception to the return's `metadata` from the same handler.++#### Per-market, not per-store++Return rules are a legal matter before they are a merchandising one: the EU+right of withdrawal is 14 days minimum, US practice is whatever the merchant+chooses. A store selling into both needs different answers, and Market is+already the per-region seam — `Order belongs_to :market`, and+`5.4-6.0-eu-legal-compliance.md` puts `withdrawal_period_days` and the other+legal settings there.++A handler therefore reads its window from `workflow.order.market`, not from the+store:++```ruby+days = workflow.order.market&.preferred_return_window_days || 30+```++Shopify reached the same conclusion — its per-market rule sets exist+specifically so EU orders can carry a longer window and a+cancel-until-fulfilled rule. Core does not ship the preference; the plan+records where it belongs when a store or `spree_enterprise` adds one.## Migration Path@@ -783,6 +874,10 @@ GET /api/v3/store/orders/:order_id/claims- **Don't persist a financial preview.** Showing an admin what a partial returnwill refund is computed in memory and discarded; the persisted previewsubstrate arrives in `6.1-order-change-substrate.md`.+- **Don't add return-policy columns or preferences to core.** No window,+ restocking fee or final-sale flag on Store, Market, Product or the return+ models. The `validate` hook carries policy in 6.0; adding half a policy+ engine now would fix its shape before anyone has asked for it.## Resolved Questionsdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex c856646e72..b5cb811aba 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,60 @@+## 2026-08-03: Return eligibility ships as a hook, not a policy engine — enforced in the workflow, scoped per market++A survey of Shopify, Medusa, Saleor and Vendure settled how far 6.0 goes on+return policy. **Core ships the seam and no policy**: a `validate` hook on+`Returns::Create`, `Exchanges::Create` and `Claims::Create`, with no return+window, restocking fee or final-sale flag anywhere in core.++**What the survey found.** Medusa, Saleor and Vendure ship *no* return+eligibility policy at all — not a different approach, genuinely nothing. Only+Shopify has an engine (window with a delivery-date anchor, percentage+restocking fee, final-sale product/collection lists, per-market rule sets), and+it exposes **no API for any of it**; configuration is admin-UI only.++The seam comparison mattered more than the feature list. Medusa built a hook+system, exposed `setPricingContext` on returns, and deliberately did not expose+a validation hook — policy has to live in route middleware or a replaced+workflow. Saleor built the filter-veto webhook shape for shipping and never+generalized it to returns; an external app decides eligibility itself and calls+the staff mutation, which never asks permission. Vendure's `onTransitionStart`+returning `false | string` is the only comparable veto and hangs off a state+machine rather than a return flow; its RMA issue is open at priority P4.++So `validate` + `reject!(message)` is already the strongest extension point in+the field. A `ReturnPolicy` model with STI rules would be the most capable+thing on the market by a wide margin and entirely speculative — no competitor+has demonstrated the demand, and the hook carries one later without changing+its contract. Deferred, not rejected.++**Enforce for customers, advise for staff.** The one lesson worth copying from+Shopify: eligibility is enforced on the customer surface and advisory on the+staff surface. A Shopify staff member can create a return on a final-sale item+outside the window; the customer API refuses. Their `returnableFulfillments`+deliberately ignores return rules because it mirrors the admin, "where any+authorized staff can create returns." A handler that rejects unconditionally+would be stricter than Shopify — a supervisor overriding policy for a good+customer is ordinary retail.++**This lives in the workflow, not the model.** Eligibility is a decision made+during a flow with the caller's context in hand — who is asking, and whether+they may override — not a property of a return record. `Returns::Create` takes+`created_by` (nil for customer self-service, set for staff) and the handler+decides what that means.++**Per market, not per store.** Return rules are legal before they are+merchandising: the EU right of withdrawal is 14 days minimum, US practice is+the merchant's choice. `Order belongs_to :market`, and+`5.4-6.0-eu-legal-compliance.md` already puts `withdrawal_period_days` and the+other legal settings on Market, so a handler reads its window from+`order.market`. Shopify reached the same conclusion — its per-market rule sets+exist specifically for EU compliance.++Also noted from Shopify but **not adopted in 6.0**: rules are snapshotted onto+the order at placement, so changing a window never retroactively invalidates a+pending return, and non-returnable reasons are tracked per *quantity* rather+than per line item. Both are right, and both belong with a policy engine rather+than ahead of one.+## 2026-08-02: Workflows replace state machines for new models; hooks ship on the 6.0 boundary; OrderChange substrate targets 6.1A review of our workflow and extension surface against the wider ecosystem