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.

12.5 KB
Raw Blame

Normalize state → status

Status: Implemented — every state machine removed (2026-08-19) Target: Spree 6.0 Depends on: Cart/Order split (6.0-cart-order-split.md), Split Adjustments (6.0-6.1-split-adjustments.md) Author: Damian + Claude Last updated: 2026-08-19

Summary

Rename the state column to status on the five remaining models that still use it. Newer models already use status. Order and Adjustment state columns are removed entirely by other 6.0 plans. This finishes the normalization so every state machine in Spree uses status.

Problem

Spree has two conventions for the state machine column name:

  • Legacy models use state: Payment, Shipment, InventoryUnit, ReturnAuthorization, GiftCard
  • Newer models use status: Product, PriceList, PaymentSession, PaymentSetupSession, Import, ImportRow, Invitation

This inconsistency means developers must remember which column each model uses. API responses mix state and status fields. Ransack filters differ per model. The CLAUDE.md rule says "default column should be status, legacy models use state" — 6.0 is the window to eliminate the exception.

Current State

Model Current column 6.0 action
Order state Removed (cart-order-split — no state machine on Order)
Adjustment state Removed (split-adjustments — no state machine)
Payment state Done (2026-08-18) — renamed AND machine removed (HasStatus + workflows; see amendment below)
Shipment state Done — became Fulfillment (HasStatus, no machine)
InventoryUnit state Done (2026-08-19) — became FulfillmentItem; column already status, machine removed
ReturnAuthorization state Gone — model deleted by the returns rework
GiftCard state Done (2026-08-19) — renamed AND machine removed
Product status Done (2026-08-19) — machine removed
PriceList status Done (2026-08-19) — machine removed
PaymentSession status Done (2026-08-18) — machine removed (PaymentSessionTransitions)
PaymentSetupSession status Done (2026-08-18) — machine removed (PaymentSessionTransitions)
Import status Done (2026-08-19) — machine removed
ImportRow status Done (2026-08-19) — machine removed
Invitation status Done (2026-08-19) — machine removed
ReturnItem reception_status, acceptance_status Already correct
Reimbursement reimbursement_status Already correct

Key Decisions (do not deviate without discussion)

  • status is the standard. All status columns use that name.
  • Single migration renames all five columns at once. Superseded 2026-08-18: each model renames in its own migration, in the same change that removes its machine (see the amendment below). Payment shipped as 20260818000001_rename_spree_payments_state_to_status; InventoryUnit and GiftCard get their own when their turn comes.
  • Deprecation aliases (alias_attribute :state, :status) for one release to avoid breaking custom code that reads .state.
  • API responses use status everywhere. No more state field in serializers.
  • Order payment_state and shipment_state stay as-is. These are derived summary fields on Order, not state machine columns. Renaming them to payment_status/shipment_status is optional and lower priority.

Amendment (2026-08-18): renames ride with machine removal

The Phase 2 sketch above (state_machine :status, ...) is superseded for the payment family. When a model's column renames, its machine goes at the same time — following Order and Fulfillment:

  • Payment — spree_payments.state renamed to status; the machine is removed in favor of Spree::HasStatus. Transitions live where the money moves: the Spree::Payments workflows and Spree::Payment::Processing, as explicit named writes (complete!, pend!, void!, failure!, invalidate!, started_processing!). payment.completed / payment.voided publish from the write itself, not a transition callback. The machine's guards survive as can_complete? / can_pend? / can_void? with the same from-state lists. The invalid status defines no predicate or scope — invalid? stays ActiveModel's; use has_invalid_status?.
  • PaymentSession / PaymentSetupSession — identical machines replaced by the shared Spree::PaymentSessionTransitions concern: non-raising guarded transitions (process/complete/fail/cancel/expire) matching the old non-bang events, because the webhook and synchronous completion paths race by design and the loser must be a no-op.
  • has_status applies its default: as an ActiveModel attribute default at instantiation (never a database default), replacing the per-model after_initialize callbacks. It also skips defining any predicate or scope whose name Rails already owns.
  • Deprecated bridges until 6.1: Payment#state/state=, has_invalid_state?, with_state, INVALID_STATES, and a state ransack alias.

InventoryUnit and GiftCard followed the same doctrine when they moved (2026-08-19), and with them the last machines in Spree went — see the amendment below.

Amendment (2026-08-19): the last machines are gone, and so is the gem

The remaining seven machines were removed in one change, finishing what the payment family started. state_machines-activerecord is no longer a dependency of spree_core — Spree ships no state machines at all.

  • GiftCard — spree_gift_cards.state renamed to status; redemption and cancellation are Spree::GiftCards::Redeem / ::Cancel. Full versus partial redemption is decided by the remaining balance rather than by which event the caller picked, and redeemed_at is stamped only on full redemption. Apply and Remove were promoted from services to workflows at the same time, since they are where a store's rules about spending a card belong. Bridges until 6.1: state/state=, display_state, a state ransack alias, and the verbs redeem!/partial_redeem!/cancel!.
  • Product — machine removed; Spree::Products::Activate / ::Archive / ::Draft. The empty after_activate / after_archive / after_draft stubs were deleted rather than carried over: they had been dead extension points for years, and hooks replace them. STATUS_TO_WEBHOOK_EVENT (unused, and naming a product.drafted event that never existed) and scope :paused (a status not in STATUSES) went with them.
  • PriceList — Spree::PriceLists::Activate / ::Deactivate. The controller's schedule-versus-activate branch moved into the workflow, so a caller no longer picks the event.
  • FulfillmentItem — machine removed. ship! and fill_backorder! are plain guarded writes; the return event was dead and did not come back. Filling a backorder no longer recalculates the whole order from a transition callback once per item — Spree::StockLevel collects the filled units and recalculates each affected order once. ship! also takes force:, fixing a bug the machine had: the guarded ship event raised on a backordered item, so a forced dispatch — which exists precisely to hand goods over regardless of the shelf — aborted partway instead of shipping.
  • Invitation — Spree::Invitations::Accept. The machine's state-scoped validations (expiry window, invitee present) became workflow guards, so an expired invitation is refused rather than turned into a record that will not save, and the three separate writes acceptance used to make are now one.
  • Import / ImportRow — the pipeline's steps are Spree::Imports::StartMapping, ::CompleteMapping, ::StartProcessing, ::Complete and ::RetryFailedRows. Dispatching row work no longer needs ActiveRecord.after_all_transactions_commit: that existed only because the machine ran its callbacks inside a transaction. ImportRow's whole lifecycle already lived in process!, so its statuses are written there directly.

Spree::HasStatus gained a with_status(*values) scope, replacing the multi-value class scope state_machines-activerecord generated.

Callbacks that were flows moved with the machines. Removing the machines made a related pattern visible: writers that stashed their input in an ivar for an after_save to apply. That is a multi-step flow disguised as an attribute assignment, and the order the callbacks happened to run in was load-bearing.

  • PriceList — product_ids= and prices= no longer stash. The new Spree::PriceLists::Create and ::Update apply both payloads as named steps, in the order the data requires (membership settles before prices, so a newly covered product has a row to overwrite). prices_attributes= went with them: it fed only the callback and had no callers. The model keeps apply_pending_rules, since flush_pending_typed_association is a convention shared with DeliveryMethod, CommissionRate and Promotion.
  • Product — the after_create/after_save replays of deferred variants and media become a step of Products::Create and ::Update. The stashing itself stays on the model, because it exists for a real reason (ActiveStorage cannot attach to an unsaved record), but replaying it is the workflow's job now. :validate still runs before the insert, so a rejected create still writes no variant or image — that property is pinned by a spec.

Every verb the machines generated survives as a deprecated shell until 6.1, following the Payment precedent — these were public API that extensions and host apps call, so they warn and delegate rather than disappearing: Product#activate!/archive!/draft!, GiftCard#redeem!/partial_redeem!/cancel!, PriceList#activate/deactivate/schedule, Invitation#accept/accept!, Import#start_mapping!/complete_mapping!/start_processing!/complete!/fail!/retry_failed_rows, ImportRow#start_processing!/complete!/fail! and FulfillmentItem#return!. Each keeps its original semantics: a bang verb raises when the workflow refuses, a non-bang one returns false, matching what the machine's guarded events did. Covered by spec/models/spree/deprecated_transition_verbs_spec.rb.

Every transition carries validate and after_* hooks, documented in docs/developer/customization/workflows.mdx.

Migration Path

Phase 1: Column renames

One migration per model, shipped with that model's machine removal — never a combined migration (superseded 2026-08-18). Shipped so far:

class RenameSpreePaymentsStateToStatus < ActiveRecord::Migration[8.1]
  def change
    rename_column :spree_payments, :state, :status
  end
end

Remaining: spree_inventory_units, spree_gift_cards. Shipment's column retired with the Fulfillment rework; ReturnAuthorization's model was deleted by the returns rework.

Phase 2: Model updates

For each of the five models:

  1. Update state_machine declaration:
# Before
state_machine initial: :pending do

# After
state_machine :status, initial: :pending do
  1. Add deprecation alias:
# Temporary — remove in 6.1
alias_attribute :state, :status
  1. Update any scopes or methods that reference the state column directly (e.g., where(state: 'shipped') → where(status: 'shipped')).

Phase 3: Serializer + API updates

  • All serializers return status instead of state
  • Ransack filters updated: filter[status_eq]=shipped instead of filter[state_eq]=shipped

Phase 4: StateChange model update

Spree::StateChange records state transitions with name field (e.g., "payment", "shipment"). The previous_state and next_state columns stay as-is — they store values like "pending", "shipped", not column names.

Phase 5: Cleanup (6.1)

  • Remove alias_attribute :state, :status from all five models
  • Remove any remaining state references in specs and factories

Constraints on Current Work

  • Use status in all new code. Don't add new state references.
  • New state machines must use status column. This is already the rule in CLAUDE.md.
  • Ransack filters on new endpoints should use status. Existing v3 endpoints will be updated in this plan.

Open Questions

None.

References

  • CLAUDE.md rule: "State machines: default column status (legacy uses state)"
  • Related plan: 6.0-cart-order-split.md (removes Order.state entirely)
  • Related plan: 6.0-6.1-split-adjustments.md (removes Adjustment.state entirely)
  • Decision log: docs/plans/decisions.md (2026-03-16 entry)