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.

57.2 KB
Raw Blame

Returns, Exchanges & Claims as First-Class Entities

Status: Implemented — legacy chain removed Target: Spree 6.0 Depends on: Fulfillment & Delivery rework (6.0-fulfillment-and-delivery.md), Split Adjustments (6.0-6.1-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-10-01

Summary

Replace the deeply nested return/reimbursement chain (ReturnAuthorization → ReturnItem → CustomerReturn → Reimbursement → ReimbursementType → Refund/Exchange) with three first-class entities that directly model the business operations:

  • Return — customer sends items back, gets a refund
  • Exchange — customer sends items back, gets different items
  • Claim — customer reports a problem (damaged, missing, wrong item), may keep the original

Each is a top-level model on Order with its own line items, status, and resolution. No more 6-model-deep nesting. No more exchanges-as-a-reimbursement-type hack.

Implementation Status (2026-08-05)

Complete. The new system is live end to end and the legacy chain is gone. Core, API and emails suites are green (7478 / 2639 / 95 examples, 0 failures), as are the dashboard's typecheck, lint and 44 unit tests.

Shipped earlier (now on main):

  • Models: Spree::Return, Spree::Exchange, Spree::Claim with Spree::ReturnLineItem, Spree::ExchangeLineItem, Spree::ClaimLineItem (naming note below), plus the Spree::HasStatus concern.
  • All fifteen workflows in spree/core/app/workflows/spree/{returns,exchanges,claims}/, each with a leading validate hook (shipped on every workflow, not just the Create ones), lifecycle events (return.requested … claim.resolved), and the internal-vs-gateway refund branch.
  • Spree::Refund#originator (polymorphic), per-transition timestamp columns (approved_at, received_at, …), received_quantity on line items (partial receipt), SingleStoreResource + store_id on all three entities.
  • Admin API v3 (nested under orders: index/show/create/update + PATCH member transitions), Store API v3 (returns + claims: index/show/create), admin + store serializers, dashboard pages (returns.tsx, exchanges.tsx, claims.tsx, order returns card), model/workflow/controller specs, and the developer doc (docs/v6/developer/core-concepts/returns-exchanges-claims.mdx).

Landed on feature/cleanup-old-returns-system:

  1. Legacy drop. ReturnAuthorization, CustomerReturn, Reimbursement, ReimbursementType (+ all subtypes, ReimbursementPerformer, ReimbursementTaxCalculator, the type engine/validator), the legacy ReturnItem with its eligibility validators, ReturnsCalculator and Calculator::Returns::DefaultRefundAmount, the v3 legacy serializers and their dependency registrations, the reimbursement mailer, and every reference across Order, Store, FulfillmentItem, permission sets, seeds, permitted attributes, factories and locales. Legacy tables stay as a safety net (dropped in 6.1).
  2. Data migration spree:upgrade:migrate_returns (Spree::ReturnsMigrator, defined in the rake file alongside its sibling upgrade tasks) — reads the legacy tables by name through throwaway AR classes, converting authorizations into Returns or Exchanges and re-pointing reimbursement-era refunds via originator. Resumable by construction: the legacy number is copied onto the new record and uniquely indexed there, so the task scopes itself to authorizations whose number isn't present yet — an interrupted run picks up where it stopped and a re-run is a no-op, with no cursor or job state to manage. Registered in the 5.6→6.0 upgrade manifest after the adjustments step that freezes returns-bearing orders.
  3. Reason models. ReturnAuthorizationReason → ReturnReason (table renamed, constant alias kept for one release) plus a new ClaimReason; the three reason associations repointed.
  4. Spree::Metafields on Return, Exchange and Claim (with the three added to the engine's metafields.enabled_resources).

Replacements built where the drop would otherwise have removed capability:

  • Spree::ReturnMailer#refunded_email + ReturnEmailSubscriber on return.refunded, replacing the reimbursement email (the legacy expedited- exchange section had no equivalent in the new model and was dropped).
  • Order#outstanding_balance lost its reimbursement_paid_total term, on the reasoning that refunds are already netted out of payment_total. That reasoning was wrong (2026-10-02): netting the refund out of payments without lowering the order's total turned every refunded return into a balance due. The term came back as returned_items_refund_total — refunds whose originator is a return, claim or exchange. Refund#return_items became #return_line_items reading through originator.
  • Return#refunded_total now sums refunds and store credits — store credit is its own ledger and never creates a Spree::Refund row, so the old sum reported zero for a store-credit refund. Extended 2026-09-22 to the order: a refund paid as credit names the order it settles (spree_store_credits.refunded_order_id), all three workflows issue it through Refunds::OrderPayments#issue_refund_store_credit, and Orders::UpdateStatuses counts both ledgers — without which an order refunded this way went on reading paid.
  • StoreCreditCategory.default_reimbursement_category → .default_refund_category (deprecated alias kept). Superseded 2026-08-18: store credits no longer carry a category at all — the workflows set only originator + memo, and both class methods are deprecated shells.
  • OrderStatusSubscriber now listens to return.received/refunded/canceled instead of the return_item.* events.
  • Sample data creates a real Return through Returns::Create; user docs rewritten for 6.0 under docs/v6/user/ and the v6 nav repointed.

Reason management (closed 2026-08-05). The legacy Rails admin was the only place reasons could be edited, so its removal left ReturnReason, ClaimReason and RefundReason seed-only and every record created reasonless. Now shipped: admin-only CRUD at /api/v3/admin/{return,claim,refund}_reasons (plain ResourceController subclasses, settings scope), a combined Settings → Reasons page holding all three lists, and a reason picker on all three create dialogs. mutable is not writable through the API — a client must not be able to unlock a record core depends on — and the guard moved onto Spree::NamedType itself (can_be_deleted?, a rename validation and a destroy guard), because the previous cannot [:edit, :update], …, mutable: false ability rule is never consulted on the secret-key path, which authorizes by scope. Reason serializers are admin-only and excluded from the Store SDK.

Problem

1. Six models for a simple return

Today's flow: ReturnAuthorization → ReturnItem → CustomerReturn → Reimbursement → ReimbursementType → Refund. A merchant processing a return touches 6 interconnected models. Each has its own state machine. The mental model is impossible for new developers.

2. Exchanges are not a first-class concept

An exchange is modeled as a ReturnItem with an exchange_variant_id, processed through ReimbursementType::Exchange. There's no Exchange model — you can't query "all exchanges this month" or "exchanges pending fulfillment" without digging through ReturnItems that happen to have an exchange_variant set.

3. Claims don't exist

If a customer receives a damaged item, there's no way to model "we're sending a replacement without requiring the original back." Today merchants either create a manual order or hack it through the return flow (create a return authorization, immediately mark as received, create an exchange). There's no Claim entity.

4. CustomerReturn is confusing

CustomerReturn represents "physical receipt of returned items at the warehouse." It's the bridge between ReturnAuthorization (permission) and Reimbursement (money). But it duplicates validation logic from ReturnItem, has no state machine, and its order method derives the order from return_items → inventory_units — not a direct association.

5. ReimbursementType STI is over-engineered

Four STI subtypes (Credit, Exchange, OriginalPayment, StoreCredit) that each implement self.reimburse. The Exchange subtype delegates to Spree::Exchange. The OriginalPayment subtype delegates to Refund. The indirection adds complexity without flexibility — the actual reimbursement logic lives in Refund and Exchange, not in the type classes.

Current State

Model Purpose State machine? Lines
ReturnAuthorization Permission to return Yes (authorized → canceled) ~110
ReturnItem Individual item in a return Yes (reception_status + acceptance_status) ~290
CustomerReturn Physical receipt at warehouse No ~95
Reimbursement Money-back execution Yes (pending → reimbursed/errored) ~170
ReimbursementType STI: how to reimburse No (strategy class) ~20 + 4 subtypes
Refund Actual payment reversal No (after_create: perform!) ~140

Total: ~825 lines across 6+ models for return handling.

Key Decisions (do not deviate without discussion)

  • Three first-class models: Return, Exchange, Claim. Each belongs directly to Order (and to Store via SingleStoreResource).
  • Each has its own line items: ReturnLineItem, ExchangeLineItem, ClaimLineItem. No shared polymorphic item model — each type has different fields. Naming settled 2026-08-05: the *LineItem names — chosen during implementation because legacy Spree::ReturnItem was still in service — are permanent. They mirror Spree::LineItem, and renaming to the shorter *Item after the legacy drop would cost a table rename plus serializer/SDK/dashboard churn for nothing.
  • 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.
  • 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, and the legacy ReturnItem with its eligibility validators. Their functionality is absorbed into the three new models.
  • Reasons (2026-08-05): all three entities share one reason model. The legacy drop renames ReturnAuthorizationReason → ReturnReason (table included; deprecated Spree::ReturnAuthorizationReason alias for one release per the deprecation-bridge rule) and adds a separate ClaimReason — claim reasons ("arrived damaged", "never arrived") are a different vocabulary from return reasons ("wrong size", "changed mind"). RefundReason stays as-is.
  • A balance the customer owes is never auto-charged (as shipped). When an exchange's replacements cost more, Exchanges::Fulfill puts the difference on the order as an exchange fee (2026-10-01) — the order then shows it due — and leaves collection to the merchant, through the order's payments. Charging a stored card without a fresh authorization is not something core does silently. Only a credit due back branches into store-credit/gateway settlement.
  • Tax goes back with the money (2026-10-01, V-3725). Returns, claims and exchanges give back the tax the customer paid on what came back. The order's tax provider decides the figure (estimate_refund; the built-in answer is the recorded share of the sale's rows) and writes it as credit rows on the post-sale lines; post-sale code never calculates tax itself. An exchange's replacement is taxed as a new sale (estimate_replacement), at the discount the replaced item carried. Delivery and its tax are never refunded.

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:

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.

# 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 (as shipped)

A customer returns items and gets a refund (to original payment, store credit, or gift card).

class Spree::Return < Spree.base_class
  has_prefix_id :ret

  include Spree::Core::NumberGenerator.new(prefix: 'RET', length: 9)
  include Spree::NumberIdentifier
  include Spree::SingleStoreResource
  include Spree::HasStatus
  include Spree::Metafields   # ships with the legacy-drop branch
  include Spree::Metadata

  publishes_lifecycle_events

  has_status :requested, :approved, :received, :refunded, :canceled, default: :requested

  belongs_to :store, class_name: 'Spree::Store'
  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_line_items, class_name: 'Spree::ReturnLineItem',
                               dependent: :destroy, inverse_of: :return
  has_many :refunds, class_name: 'Spree::Refund', as: :originator, dependent: :nullify

  validates :order, :stock_location, presence: true
  validates :return_line_items, presence: true, on: :create

  accepts_nested_attributes_for :return_line_items, allow_destroy: true

  # Predicates (#received?) and scopes (.received) are generated by has_status.

  # What the customer is owed; #refunded_total sums actual refunds —
  # a return can be refunded in more than one step.
  def refund_total
    return_line_items.sum(&:refund_amount)
  end
end

The model holds associations, validations, scopes and pure reads. Restocking and refunding live in Spree::Returns::Receive and Spree::Returns::Refund (below). The record also carries per-transition timestamps (approved_at, received_at, refunded_at, canceled_at) written by the workflows, plus memo.

ReturnLineItem (as shipped)

class Spree::ReturnLineItem < Spree.base_class
  has_prefix_id :rli

  belongs_to :return, class_name: 'Spree::Return', inverse_of: :return_line_items
  belongs_to :fulfillment_item, class_name: 'Spree::FulfillmentItem'  # renamed from InventoryUnit
  belongs_to :line_item, class_name: 'Spree::LineItem'
  belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'

  validates :fulfillment_item, :line_item, :variant, presence: true
  validates :quantity, numericality: { greater_than: 0 }
  validates :received_quantity, numericality: { greater_than_or_equal_to: 0 }
  validates :pre_tax_amount, numericality: { greater_than_or_equal_to: 0 }

  # quantity (default 1), received_quantity (default 0, written by
  # Returns::Receive), pre_tax_amount and resellable carry DB defaults.
  # pre_tax_amount defaults to this item's share of what the customer
  # actually paid after discounts (LineItem#discounted_amount_for) —
  # refunding list price would give back more than was taken.
  before_validation :set_defaults_from_line_item, on: :create

  delegate :order, :currency, to: :return

  # What this line refunds, tax included. pre_tax_amount and the two tax
  # totals are what the announced units are worth and never move; once the
  # warehouse has counted, only the units that arrived are paid for. Rounded
  # to the currency, because a third of $29.99 taken three times is not
  # $29.99 until it is.
  def refund_amount
    counted_share(pre_tax_amount + included_tax_total + additional_tax_total)
  end
end

The line carries its tax the way an order line does (2026-10-01, V-3725): pre_tax_amount truly before tax, included_tax_total and additional_tax_total beside it, and credit Spree::TaxLine rows behind them (has_many :tax_lines, via Spree::PostSale::TaxedLine). Returns::Create asks the order's tax provider for the credit (estimate_refund) and copies the rows onto the columns, with the before-tax figure taken as what was paid after discounts less the tax inside it, so the three add up to the cent. Returns::Refund asks again before any money moves, rewriting the rows — not the columns — for the units that arrived and the amount actually refunded; the refund's tax_amount is what they hold. A line opened before this recorded no tax against a taxed sale line and refunds exactly what it was opened with. That is read from the columns, never from whether rows exist: a settle whose money step then failed may have deleted them.

Return#counted? is received? || refunded?, read from the status rather than received_at: the 5.x migration task writes the status and no timestamps, so keying off the timestamp would leave an upgraded store's received returns owed the quantities nobody counted.

The line owns this sum, not the return — Return#refund_total and #refunded_line_amounts both just add up what each line says, the same shape as Claim#refund_total over ClaimLineItem#refund_amount. Keeping it in one place is what stops the offered amount and the amount actually owed drifting apart (2026-09-18).

What the announced units are worth comes from LineItem#discounted_amount_for, which ClaimLineItem#paid_amount shares: the line's discounted_amount (price × quantity plus every discount row on the line, promotions and manual ones alike) spread over its units, multiplied before dividing and rounded to the currency. It is not the stored LineItem#pre_tax_amount: only a tax estimate writes that column, it defaults to zero, and it takes VAT out of a tax-inclusive price. The tax charged on top comes from the credit rows above, never from the price; the line's own fees are not refunded.

Exchange (as shipped)

A customer returns items and gets different items in return (different size, different product).

class Spree::Exchange < Spree.base_class
  has_prefix_id :exch

  include Spree::Core::NumberGenerator.new(prefix: 'EX', length: 9)
  include Spree::NumberIdentifier
  include Spree::SingleStoreResource
  include Spree::HasStatus
  include Spree::Metafields   # ships with the legacy-drop branch
  include Spree::Metadata

  publishes_lifecycle_events

  has_status :requested, :approved, :received, :fulfilled, :canceled, default: :requested

  belongs_to :store, class_name: 'Spree::Store'
  belongs_to :order, class_name: 'Spree::Order', inverse_of: :exchanges
  belongs_to :stock_location, class_name: 'Spree::StockLocation'
  belongs_to :reason, class_name: 'Spree::ReturnReason', optional: true
  belongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: true

  has_many :exchange_line_items, class_name: 'Spree::ExchangeLineItem',
                                 dependent: :destroy, inverse_of: :exchange
  has_many :refunds, class_name: 'Spree::Refund', as: :originator, dependent: :nullify

  validates :order, :stock_location, presence: true
  validates :exchange_line_items, presence: true, on: :create

  accepts_nested_attributes_for :exchange_line_items, allow_destroy: true

  # Positive = customer owes more, negative = refund due.
  def price_difference
    exchange_line_items.sum(&:price_difference)
  end
end

There is no has_one :exchange_fulfillment association (the plan's earlier sketch had one): Exchanges::Fulfill builds replacement fulfillment items on the order and routes them through Spree::Stock::Coordinator, which may legitimately produce several fulfillments; they attach to the order like any other. Only the money records (Refund, StoreCredit) carry the originator back-reference.

Replacement units are flagged spree_fulfillment_items.replacement (2026-09-25). They hang off the line they replace, and an edit of that line counts only the unflagged units, so the replacement is neither counted toward the quantity nor removed when it falls. Fulfillments::Create leaves flagged units alone too (2026-10-02): adding a fulfillment for a line takes only the units the customer bought, unless a source_fulfillment is named. Then it moves that parcel's units, replacements included — how a partial dispatch splits a replacement parcel and how a canceled replacement is sent again. Exchanges::Fulfill and Claims::Resolve both build replacements through Spree::Fulfillments::Replacements.

Restocking and replacement-fulfillment creation live in Spree::Exchanges::Receive and Spree::Exchanges::Fulfill. A credit due back is settled through the internal-vs-gateway branch (see "Refunding: internal vs gateway" below); a balance the customer owes is recorded but never auto-charged (Key Decisions).

ExchangeLineItem (as shipped)

class Spree::ExchangeLineItem < Spree.base_class
  has_prefix_id :eli

  belongs_to :exchange, class_name: 'Spree::Exchange', inverse_of: :exchange_line_items
  belongs_to :fulfillment_item, class_name: 'Spree::FulfillmentItem'  # the original item being returned
  belongs_to :line_item, class_name: 'Spree::LineItem'                # original line item
  belongs_to :original_variant, -> { with_deleted }, class_name: 'Spree::Variant'
  belongs_to :new_variant, -> { with_deleted }, class_name: 'Spree::Variant'

  validates :fulfillment_item, :line_item, :original_variant, :new_variant, presence: true
  validates :quantity, numericality: { greater_than: 0 }
  validates :received_quantity, numericality: { greater_than_or_equal_to: 0 }
  validate  :replacement_must_differ   # swapping a variant for itself is a return

  # Both halves carry tax (2026-10-01). original_price is what the customer
  # paid for the units coming back after discounts
  # (LineItem#discounted_amount_for) plus the tax charged on top, from the
  # credit rows. new_variant_price is the replacement at the same discount —
  # its base price × the old line's discounted_amount ÷ amount, so a
  # same-price swap costs nothing — plus its own tax, taxed as a new sale by
  # the provider's estimate_replacement. original_* / new_* columns hold the
  # two halves' tax for the announced quantity.
  def price_difference
    new_variant_price - original_price
  end
end

Claim

A customer reports a problem — damaged, missing, or wrong item. The merchant may send a replacement, issue a refund, or both — without requiring the original item back.

class Spree::Claim < Spree.base_class
  has_prefix_id :claim

  include Spree::Core::NumberGenerator.new(prefix: 'CLM', length: 9)
  include Spree::NumberIdentifier
  include Spree::SingleStoreResource
  include Spree::HasStatus
  include Spree::Metafields   # ships with the legacy-drop branch
  include Spree::Metadata

  publishes_lifecycle_events

  has_status :open, :approved, :resolved, :denied, :canceled, default: :open

  # Each resolution drives real behaviour in Spree::Claims::Resolve, so
  # this stays closed — an unrecognised value would silently do nothing.
  RESOLUTIONS = %w[refund replacement refund_and_replacement].freeze

  belongs_to :store, class_name: 'Spree::Store'
  belongs_to :order, class_name: 'Spree::Order', inverse_of: :claims
  belongs_to :reason, class_name: 'Spree::ClaimReason', optional: true
  belongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: true

  has_many :claim_line_items, class_name: 'Spree::ClaimLineItem',
                              dependent: :destroy, inverse_of: :claim
  has_many :refunds, class_name: 'Spree::Refund', as: :originator, dependent: :nullify

  validates :order, presence: true
  validates :claim_line_items, presence: true, on: :create
  validates :resolution, inclusion: { in: RESOLUTIONS }, allow_nil: true

  accepts_nested_attributes_for :claim_line_items, allow_destroy: true

  def refund_total
    claim_line_items.sum(&:refund_amount)
  end
end

As with Exchange, there is no has_one :replacement_fulfillment association — Claims::Resolve routes replacements through Spree::Stock::Coordinator onto the order.

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").

ClaimLineItem (as shipped)

class Spree::ClaimLineItem < Spree.base_class
  has_prefix_id :cli

  belongs_to :claim, class_name: 'Spree::Claim', inverse_of: :claim_line_items
  belongs_to :line_item, class_name: 'Spree::LineItem'
  belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'
  # Nil means "send the same thing again"; a different variant swaps it.
  belongs_to :replacement_variant, -> { with_deleted }, class_name: 'Spree::Variant', optional: true

  # Photographic evidence of damage, supplied by the customer.
  has_many_attached :images

  validates :line_item, :variant, presence: true
  validates :quantity, numericality: { greater_than: 0 }
  validates :refund_amount, numericality: { greater_than_or_equal_to: 0 }

  # quantity (1), send_replacement (false) and refund_amount (0) carry DB
  # defaults; description holds the customer's account of the problem.
  # #paid_amount (what was actually paid after discounts, from
  # LineItem#discounted_amount_for, plus the tax charged on top — 2026-10-01)
  # is the ceiling for a refund on this line, and refund_amount is entered tax
  # included; #variant_to_send is what ships on a replacement resolution.
  # Like a return line it carries included/additional tax totals and credit
  # TaxLine rows, settled to the money actually refunded at resolution.
end

Order associations

class Spree::Order < Spree.base_class
  # Shipped (ordered by created_at for the order page's post-sale view):
  has_many :returns, -> { order(:created_at) }, class_name: 'Spree::Return', inverse_of: :order
  has_many :exchanges, -> { order(:created_at) }, class_name: 'Spree::Exchange', inverse_of: :order
  has_many :claims, -> { order(:created_at) }, class_name: 'Spree::Claim', inverse_of: :order

  # Removed by the legacy drop:
  # has_many :return_authorizations
  # has_many :reimbursements
  # has_many :customer_returns, through: :return_authorizations
end

Refund gains polymorphic originator

class Spree::Refund < Spree.base_class
  # Existing: belongs_to :payment
  # Add: polymorphic originator — who triggered this refund?
  belongs_to :originator, polymorphic: true, optional: true
  # originator can be: Spree::Return, Spree::Exchange, Spree::Claim, or nil (manual refund)
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.

As shipped, every workflow carries a leading validate hook — not just the Create ones. An extension can veto any transition (block a refund, gate an approval), which is strictly more capable than the plan's original hook set and costs nothing.

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_record:, approver: validate, after_approve No label generation — see Resolved Question 2
Returns::Receive return_record:, items:, received_by: validate, before_restock, after_receive Partial receipt is the normal case: items: carries actual quantities and per-item resellable flags, written to received_quantity
Returns::Refund return_record:, amount:, refund_method: validate, before_refund, after_refund Branches on refund method (below); on_flow_failure: reverses the status. refundable_total is both the default amount and the ceiling, so a caller naming an amount cannot get more than one who names none
Returns::Cancel return_record:, reason: validate, after_cancel Restocks nothing; only valid from requested/approved
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 :validate, :before_restock, :after_receive

      # @param return_record [Spree::Return]
      # @param items [Array<Hash>, nil] `[{ return_line_item:, quantity:,
      #   resellable: }]`; nil receives everything as requested and resellable
      # @param received_by [Object, nil]
      def perform(return_record:, items: nil, received_by: nil)
        super

        step :ensure_receivable
        step :normalize_items
        run_hooks :validate

        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

      # ... restocks each resellable received quantity at the return's
      # stock location and writes received_quantity on each line item.
    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:

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.

All three settle tax first (2026-10-01): before any money moves, the provider rewrites the credit rows for what actually goes back, and a short refund — a restocking fee kept — gives tax back in the same proportion as the goods. The gateway refund rows carry that tax in Spree::Refund#tax_amount, which reporting nets from taxes rather than from net sales. Filing the credit with the provider (refund, and commit_replacement for an exchange) runs after, reported rather than raised on failure, because the money has moved.

A return owed nothing — a free gift sent back, or one where nothing that arrived was worth anything — closes through the same workflow at zero: it moves to refunded with no refund row, no store credit and no tax credit, and still publishes return.refunded. Zero is accepted only when zero is owed; on a return the customer is still owed money it is refused with refund_amount_required, so a mistyped amount cannot close a return unpaid. The emails engine sends no refund email when refunded_total is zero, and the dashboard names the action "Complete return" instead of "Refund" (2026-09-30).

Exchanges

Workflow Hooks Notes
Exchanges::Create validate, after_create Validates replacement variants are purchasable
Exchanges::Approve validate, after_approve
Exchanges::Receive validate, before_restock, after_receive Same partial-receipt shape as returns
Exchanges::Fulfill validate, before_settle, after_fulfill Builds replacement fulfillments via Stock::Coordinator (only for quantities actually received; fails on out-of-stock replacements), then settles a credit due back as an external_step; a balance owed goes on the order as an exchange fee and is never auto-charged
Exchanges::Cancel validate, after_cancel

Claims

Workflow Hooks Notes
Claims::Create validate, after_create Store API entry point; validate gates self-service claims
Claims::Approve validate, after_approve
Claims::Resolve validate, before_settle, after_resolve Takes resolution: explicitly; refund settles via the internal-vs-gateway branch, replacement fulfillment is in-transaction
Claims::Deny validate, after_deny
Claims::Cancel validate, after_cancel

Return eligibility policy: the hook, not a policy engine

Return eligibility is the single most-customized rule in commerce — 30-day windows, final-sale categories, per-customer-group policies, region-specific 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:

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:

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

Phase 1: Create new tables — SHIPPED

Landed as spree/core/db/migrate/20260802190001_create_spree_returns.rb and 20260802210001_create_spree_exchanges_and_claims.rb. Follows the CLAUDE.md migration rules (no FK constraints, null: false on required columns, respond_to?(:jsonb) guard, no defaults on status columns, defaults on integer/decimal columns, single metadata column). As-built differences from the original sketch:

  • Tables are spree_return_line_items, spree_exchange_line_items, spree_claim_line_items. The legacy spree_return_items table was never renamed — it keeps its name until dropped, and the _legacy rename is off the table.
  • Every entity table carries store_id (SingleStoreResource) and per-transition timestamps (approved_at, received_at, refunded_at / fulfilled_at / resolved_at, canceled_at, denied_at).
  • Return and exchange line items carry received_quantity (default 0) for partial receipt.
  • spree_refunds.originator_{type,id} + index shipped in the returns migration.

Phase 2: Data migration (rake task) — SHIPPED

Spree::ReturnsMigrator, invoked by rake spree:upgrade:migrate_returns and registered in the 5.6→6.0 upgrade manifest (after migrate_adjustments_to_typed_rows, which freezes returns-bearing orders for exactly this step). Historical rows are written with save(validate: false) — they can reference deleted variants and stock locations that today's validations reject, and refusing to copy history is worse than copying it imperfectly.

Resumption needs no cursor. The legacy number carries onto the new record and is uniquely indexed there, so "what is left to migrate" is a query (where.not(number: already_migrated)) rather than tracked state. That makes an interrupted run resume at exactly the right place, a re-run a no-op, and a partial failure retryable — without a job, a checkpoint table, or a cursor to get out of sync with reality.

# rake spree:upgrade:migrate_returns
#
# Reads the legacy tables via lightweight anonymous AR classes (pattern:
# migrate_users_to_customers.rake) — NOT the legacy models, which are being
# deleted in the same release. Decision 2026-08-05: the task and the drop
# ship together so the drop is never blocked waiting on Wave 7.
#
# For each ReturnAuthorization + its ReturnItems:
#   If any ReturnItem has exchange_variant_id:
#     → Create Exchange with ExchangeLineItems
#   Else:
#     → Create Return with ReturnLineItems
#   Status mapping: authorized → approved (or received/refunded when the
#   chain progressed), canceled → canceled
#
# For each Reimbursement:
#   Link its Refunds to the new Return/Exchange via originator
#
# Claims: no migration needed (didn't exist before)

Phase 3: Model migration — SHIPPED

Models + line items, Spree::HasStatus, Order associations, Refund originator and lifecycle events shipped first; the legacy-drop branch completed the phase with the ReturnAuthorizationReason → ReturnReason rename (+ ClaimReason), Spree::Metafields on all three entities, and the removal of the return-specific methods on FulfillmentItem (current_or_new_return_item, current_return_item, exchanged_unit?, and the original_return_item association — required_quantity survives for Stock::Adjuster with its exchange branch collapsed). The removal left replacement units indistinguishable from bought ones; the replacement flag (2026-09-25) restores that one distinction, and nothing else of the old exchanged-unit API.

Phase 3b: Workflows — SHIPPED

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. Covered by lifecycle specs (spree/core/spec/workflows/spree/{returns,exchanges,claims}/lifecycle_spec.rb).

Phase 4: Drop legacy models — SHIPPED

  • Drop models: ReturnAuthorization, CustomerReturn, Reimbursement, ReimbursementType (all subtypes), ReimbursementPerformer, ReimbursementTaxCalculator, Reimbursement::Credit, the reimbursement_type_engine/validator, legacy ReturnItem + its eligibility validators, ReturnsCalculator, and the Spree::Exchange service class (replaced by the model)
  • Tables are deliberately NOT dropped. Every legacy table (spree_return_authorizations, spree_return_items, spree_customer_returns, spree_reimbursements, spree_reimbursement_types, spree_reimbursement_credits) survives 6.0 as the data migration's source and rollback safety net; they are dropped in 6.1 once installs have run spree:upgrade:migrate_returns. Only the Ruby classes go.
  • Swept the referencing surface: v3 legacy serializers (return_authorization_serializer, customer_return_serializer, reimbursement_serializer + admin twins) and their Spree::Api::Dependencies registrations, permission sets, seeds (Seeds::ReturnsEnvironment), Order/Store/FulfillmentItem associations and methods, PermittedAttributes, factories, locale keys, sample data, the emails engine, and the SDK type barrels

Phase 5: API — SHIPPED

As built, transitions are PATCH member actions (matching the house style of orders/:id/approve etc.), records are updatable but not deletable — a mistaken return is canceled, never destroyed — and top-level read-only index/show endpoints exist alongside the order-nested ones:

# Admin — same shape for returns / exchanges / claims
GET    /api/v3/admin/orders/:order_id/returns
GET    /api/v3/admin/orders/:order_id/returns/:id
POST   /api/v3/admin/orders/:order_id/returns
PATCH  /api/v3/admin/orders/:order_id/returns/:id
PATCH  /api/v3/admin/orders/:order_id/returns/:id/approve
PATCH  /api/v3/admin/orders/:order_id/returns/:id/receive
PATCH  /api/v3/admin/orders/:order_id/returns/:id/refund     # fulfill on exchanges; resolve/deny on claims
PATCH  /api/v3/admin/orders/:order_id/returns/:id/cancel
GET    /api/v3/admin/returns          # + /exchanges, /claims — cross-order listing
GET    /api/v3/admin/returns/:id

# Store API — customers initiate returns and claims (exchanges are admin-only)
GET    /api/v3/store/orders/:order_id/returns
GET    /api/v3/store/orders/:order_id/returns/:id
POST   /api/v3/store/orders/:order_id/returns
GET    /api/v3/store/orders/:order_id/claims
GET    /api/v3/store/orders/:order_id/claims/:id
POST   /api/v3/store/orders/:order_id/claims

# Reasons — admin only (back-office vocabulary, no storefront surface)
GET    /api/v3/admin/return_reasons        # + /claim_reasons, /refund_reasons
POST   /api/v3/admin/return_reasons
PATCH  /api/v3/admin/return_reasons/:id
DELETE /api/v3/admin/return_reasons/:id

Constraints on Current Work

  • The legacy chain is frozen and being deleted this cycle. Don't add features to ReturnAuthorization, CustomerReturn, or Reimbursement, and don't build anything new on top of them — they won't exist after the feature/cleanup-old-returns-system branch lands.
  • Don't add new ReimbursementType subtypes. The STI hierarchy is being dropped.
  • New return/exchange logic uses the three-model pattern. Think "Return with ReturnLineItems" 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. Its one addition is tax_amount, the tax inside the amount (2026-10-01).
  • What a returned or claimed unit is worth is LineItem#discounted_amount_for. Don't recompute it from price × quantity, which ignores every discount on the line, and don't read LineItem#pre_tax_amount, which only a tax estimate writes. The tax on top comes from the line's credit rows.
  • Post-sale code never calculates tax. It asks the order's tax provider (estimate_refund, estimate_replacement) and reads the credit rows. Storing the tax when the record opens is not a persisted financial preview: the money figure is stored then too, and the rows are rewritten to what actually went back before money moves.
  • 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.
  • 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 Questions

  1. Store API return initiation. Both Store API (self-service) and Admin API. Customers can initiate returns and claims; self-service returns are the modern standard and backoffice-only is legacy.

    Exchanges are admin-only in 6.0 (settled 2026-08-07). The Store API ships returns and claims under an order but no exchanges: picking a replacement variant needs a catalog browsing flow that only a real customer portal can justify. The exchange serializers carry the same expandable reason association as the other two, so the Store API surface is a route and a controller away when it lands. Deferred to 6.1 alongside the self-service customer return portal.

  2. Return shipping labels — not in 6.0 (reversed 2026-08-06). An earlier draft of this plan shipped a return_label_url column plus a generate_label: seam on Returns::Approve. Both are removed: the seam read Spree.return_label_provider, which was never registered in Spree::Dependencies, so the guard was permanently false and the column unreachable — a feature that could not be turned on.

    A market check settled the direction rather than just the bug. No comparable platform stores a label URL on the return. Medusa returns label_url on a fulfillment (FulfillmentLabel) and its own docs admit the default return flow lacks the data to create a return shipment; Saleor's Fulfillment object carries only trackingNumber; Vendure has no return-label concept, generating labels as a side effect of a FulfillmentHandler calling a courier. Labels are carrier output, not return state.

    So it rides with the carrier provider in 6.0-delivery-rate-provider.md, where an EasyPost/Shippo provider actually exists to mint one and it can attach to a fulfillment like everyone else's. A store needing a label before then puts the URL in the return's metadata — no core surface to support or deprecate. Same reasoning as the return-policy decision above: core ships the seam when there is something real behind it, not a speculative column.

    Superseded 2026-09-03 by 6.0-shipping-labels-and-deliveries.md: the real thing now exists. A return label is a Spree::ShippingLabel whose polymorphic owner is the Return, bought through Returns::PurchaseLabel (EasyPost is_return shipment from the customer's address to the return's stock location), mounted at /admin/orders/:order_id/returns/:id/labels, and downloadable by the customer on the Store API. The inbound parcel is a Spree::Delivery on the return, whose delivered report never calls Returns::Receive — arrival is not inspection. The interim "URL in metadata" advice is withdrawn; nothing in core reads it.

  3. Partial returns/exchanges. No separate "case" or "ticket" model. All three entities belong to Order — order.returns, order.exchanges, order.claims gives the full picture. The admin UI shows a unified "Post-sale" tab on the order page listing all three chronologically. If correlation is needed (e.g., "this claim was filed because the exchange arrived damaged"), use the metadata JSON column.

  4. Line-item naming (2026-08-05). ReturnLineItem / ExchangeLineItem / ClaimLineItem are permanent, not a coexistence workaround. They mirror Spree::LineItem and a post-drop rename to *Item would cost table + serializer + SDK + dashboard churn for a shorter name.

  5. Reason models (2026-08-05). ReturnAuthorizationReason is renamed to ReturnReason (deprecated alias one release) and a separate ClaimReason is added — claim vocabulary ("arrived damaged") differs from return vocabulary ("wrong size"). All three entities' reason associations repoint on the legacy-drop branch.

  6. Data migration timing (2026-08-05). spree:migrate_returns ships on the legacy-drop branch, reading legacy tables through lightweight anonymous AR classes so it survives the model deletion. Riding Wave 7 would have blocked the drop.

  7. Balance owed on exchanges. Never auto-charged — put on the order as an exchange fee (2026-10-01) for the merchant to collect. Charging a stored card without a fresh authorization is not something core does silently.

Open Questions

None at this time.

References

  • New models: spree/core/app/models/spree/{return,exchange,claim}.rb + *_line_item.rb
  • Workflows: spree/core/app/workflows/spree/{returns,exchanges,claims}/
  • Status concern: spree/core/app/models/concerns/spree/has_status.rb
  • Developer doc: docs/v6/developer/core-concepts/returns-exchanges-claims.mdx
  • Legacy models being dropped: spree/core/app/models/spree/return_authorization.rb, return_item.rb, customer_return.rb, reimbursement.rb
  • Legacy 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-6.1-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