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.

21.5 KB
Raw Blame

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-30 (Phase 5 superseded — substrate is strictly post-placement; applier pricing rulings added) Tracking: Linear V-3616 · GitHub spree/spree#14611

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.
  • A change set belongs to one Order, never to an OrderGroup (RESOLVED 2026-08-10). Under multi-vendor a cart fans out into N child orders under one group, and 6.0-multi-vendor-marketplace.md (Decision 8) is explicit that line items, fulfillments and totals live on the children — the group holds only customer, payment and addresses. A change set mutates exactly those child-owned rows, so it binds to the child order. Editing two sellers' items is two change sets, which is also the correct commercial answer: each seller's balance settles against its own order. This keeps the partial unique index on (order_id) as designed, with no group-level variant. The cost is that a single admin edit spanning sellers is not one atomic operation — accepted, because a cross-seller atomic edit would need a distributed settle across N gateway captures, which the group cannot offer either.
  • A pending change set does not hold stock (RESOLVED 2026-08-10). 6.0-stock-reservations.md scopes reservations to checkout — held against a cart, extended on checkout activity, expired by a background job. A requested change set is an admin editing a placed order, which is neither a cart nor time-boxed by customer activity, so reusing that machinery would mean reservations with no natural expiry trigger. add_item therefore takes stock at confirm, and confirm is where an out-of-stock action fails. Accepted trade-off: a change set requested against the last unit can fail at confirm if someone else buys it first. That is the same race the current immediate-write path has, and the failure is visible and recoverable rather than silent.

Design Details

OrderChange

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

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

Two rulings from the negotiated-pricing work (2026-08-30, 6.0-draft-order-negotiation-mechanics.md):

  • Appliers never derive unit prices. An update_item quantity applier applies the quantity; the line's price is data — in particular a price_source: 'manual' (negotiated) line must come through an amendment untouched.
  • A post-placement price change is its own action kind — update_item_price (stamping price_source: 'manual'), registered when the first consumer needs it. It is the sanctioned "we agreed a new unit price after placement" gesture; discounts stay itemized concessions, never price-change vehicles.

Preview

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

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:

# 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.

What it replaces (shipped in 6.0, 2026-08-10; reshaped 2026-08-11): a dedicated admin order edit screen at /orders/$orderId/edit that manages line items — add, remove, change quantity — against a placed order.

The screen stages edits and applies them on Save. Quantities are inputs, a row's × marks it removed (struck through, reversible until save), and Save applies the batch while Discard drops it. There is no persisted draft. Since 2026-08-30 the screen does preview staged edits — struck-through before/after on the price, line total and subtotal — but only where the arithmetic is exact; the grand total falls back to the server's figure whenever shipping, tax, a discount or a fee is non-zero (see the narrowed constraint below). Phase 3's server-computed preview replaces that arithmetic and removes the fallback.

This reverses the original constraint that the screen must write immediately, one interaction per request (see decisions.md 2026-08-11). That rule was written to forbid a persisted per-domain draft — a shadow order in the database that Phase 3 would have to migrate — and wrongly extended to transient form state. A React form holding "quantity 2 → 3, line 4 removed" until submit persists nothing, so there is nothing for Phase 3 to unpick; it is the same dirty-tracked form pattern used across the dashboard. Immediate writes were also worse on their own terms: every quantity keystroke fired a request and re-summed the order, and removing a line was irreversible behind a confirm dialog.

Staged edits are the better fit for the substrate, not a worse one. OrderChange is begin → request → confirm → cancel — accumulate actions, then confirm — so a screen that already batches behind Save maps onto it directly. The immediate-write shape is the one that would have needed reshaping, having no confirm moment at all.

Its money math goes through a value-object-returning service specifically so Phase 3 can re-point it at OrderChanges::Preview without touching callers, per the constraint below.

Known 6.0 limitation: the batch is not atomic. There is no bulk line-item endpoint, so Save issues N calls against the existing per-item create/update/ delete routes; a failure partway leaves earlier writes applied. The screen reports what succeeded and keeps the rest staged. Phase 3 fixes this for free — OrderChanges::Confirm applies every action in one transaction, which is a reason to prefer the substrate over adding a bulk endpoint now.

Phase 3 keeps the screen, its route and its staged-edit shape, and changes what sits behind it: begin on entry, an action per staged edit, Preview driving a live totals delta, and confirm/cancel behind the Save/Discard the screen already has. Expect the UI diff to be additive — the delta display is the main thing 6.0 cannot offer.

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.

Superseded (2026-08-30, quote-work review): the substrate is strictly post-placement. A draft order (status: 'draft', cart_id: nil) is directly mutable, carries no payments and therefore no balance to settle — the confirm spine (settle at the gateway, re-derive statuses) is meaningless for it, and forcing drafts through preview-then-apply is pure ceremony. This is also what keeps B2B quotations thin (ee/docs/plans/b2b-quotes.md): pre-acceptance negotiation edits the mutable draft directly and needs no change-set; only post-conversion amendments ride OrderChange. The admin edit screen may share components across drafts and placed orders, but only placed orders create OrderChange rows.

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.

  • Do not persist a draft; transient form state is fine (revised 2026-08-11, reversing "the 6.0 edit screen writes immediately"). The prohibition is on a persisted shadow order — a draft model, a pending-changes table, anything Phase 3 would have to migrate. Staging edits in component state until the merchant hits Save persists nothing and is the shape the substrate wants, so the order edit screen batches its writes. What remains forbidden: any schema that stores pending edits, and approximating a projected total client-side — a hand-rolled guess at what the server would compute would disagree with it.

    Narrowed 2026-08-30 (the original text banned client-side projection outright). The 6.0 edit screen now previews staged edits as a struck-through before/after diff, because an editable unit price made the old behaviour actively misleading: staging a revert redisplayed the price being abandoned, with totals frozen. The line is EXACTNESS, not arithmetic. The subtotal is projected because price × quantity is exact. The grand total is projected ONLY when every other total line is zero, where the total simply IS the subtotal; the moment shipping, tax, a discount or a fee is non-zero it falls back to the server's figure, because a quantity change can cross a shipping band or promotion threshold and no client-side arithmetic can know that. A row whose price cannot be projected nulls the whole projection rather than contributing a partial sum. When Phase 3's begin/preview lands, the server-computed preview replaces this arithmetic and the fallbacks disappear — nothing here presumes to answer what only the server can.

  • Post-placement line-item mutation belongs to the edit screen, not the fulfillment card. The card manages fulfillments (what ships, from where, under which method); the edit screen manages what the order contains. Keeping the two apart is what lets Phase 3 wrap the edit surface in a change set without touching fulfillment UI.

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. Deferred: costs nothing to decide at Phase 2 when the schema lands, and the retention story is easier to size once we know how often change sets are abandoned in practice.
  • 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. Deferred: needs a real Preview to measure. The 6.0 screen does not call it at all (no preview), so nothing is blocked.

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-6.1-split-adjustments.md — typed money rows the preview projects
  • decisions.md 2026-07-27 — typed kind + concrete FKs over polymorphism