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.

Drop the state machine dependency

Damian Legawiec928118b3f36f
diff --git a/CLAUDE.md b/CLAUDE.md
index 6aac3145e7..83beb1a5ae 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -189,7 +189,7 @@ Per-request context available in models, controllers, jobs, and services:
- Include `Spree::Metadata` for JSON metadata support
- ALWAYS Use string columns instead of enums
- NEVER use `Struct` for domain value objects — use a plain Ruby class with `ActiveModel::Model` + `ActiveModel::Attributes` (typed attributes, validations) so it behaves like an ActiveRecord object (e.g. `Spree::PickupPointOption`)
-- State machines: legacy models use `state_machines-activerecord` gem, default column `status` (legacy uses `state`, see docs/plans/6.0-normalize-state-to-status.md), all new models should use `has_status` and Workflows instead
+- No state machines. Spree has none since 6.0 and `state_machines-activerecord` is not a dependency — declare statuses with `has_status` (column always `status`) and move records between them with Workflows (see docs/plans/6.0-normalize-state-to-status.md)
- NEVER cast IDs to integer — always treat as strings (UUID support)
- Uniqueness validations: ALWAYS use `scope: spree_base_uniqueness_scope`, should be also enforced by database index
- If needed use paranoia gem for soft delete support (via `acts_as_paranoid`)
diff --git a/docs/developer/core-concepts/imports-exports.mdx b/docs/developer/core-concepts/imports-exports.mdx
index 2c9d83454f..7bbc54dd0a 100644
--- a/docs/developer/core-concepts/imports-exports.mdx
+++ b/docs/developer/core-concepts/imports-exports.mdx
@@ -270,24 +270,12 @@ module Spree
has_many :mappings # Field mappings
has_many :rows # CSV rows to process
- # State machine
- state_machine initial: :pending do
- event :start_mapping do
- transition to: :mapping
- end
- event :complete_mapping do
- transition from: :mapping, to: :completed_mapping
- end
- event :start_processing do
- transition from: :completed_mapping, to: :processing
- end
- event :complete do
- transition from: :processing, to: :completed
- end
- event :fail do
- transition to: :failed
- end
- end
+ # Statuses. Each move between them is a workflow — Spree::Imports::
+ # StartMapping, CompleteMapping, StartProcessing, Complete and
+ # RetryFailedRows — so every step of the pipeline can be hooked.
+ include Spree::HasStatus
+ has_status :pending, :mapping, :completed_mapping, :processing, :completed, :failed,
+ default: :pending
# Key methods
def import_schema # Returns schema class instance
diff --git a/docs/developer/core-concepts/store-credits-gift-cards.mdx b/docs/developer/core-concepts/store-credits-gift-cards.mdx
index 8d2dd0b566..0cbe7e7405 100644
--- a/docs/developer/core-concepts/store-credits-gift-cards.mdx
+++ b/docs/developer/core-concepts/store-credits-gift-cards.mdx
@@ -179,7 +179,7 @@ erDiagram
GiftCard {
string code
- string state
+ string status
decimal amount
decimal amount_used
decimal amount_authorized
@@ -204,28 +204,26 @@ erDiagram
| `code` | Unique redemption code | `abc1234def` |
| `amount` | Total gift card value | `50.00` |
| `amount_used` | Amount already redeemed | `0.00` |
-| `state` | Current state | `active` |
+| `status` | Current status | `active` |
| `currency` | Currency code | `USD` |
| `expires_at` | Optional expiration date | `2025-12-31` |
-### Gift Card States
+### Gift Card Statuses
-```mermaid
-stateDiagram-v2
- [*] --> active: Created
- active --> partially_redeemed: Partial redemption
- active --> redeemed: Full redemption
- active --> canceled: Admin cancels
- partially_redeemed --> redeemed: Remaining redeemed
- partially_redeemed --> partially_redeemed: Another partial redemption
-```
+| Status | Description | How it gets there |
+|-------|-------------|-------------------|
+| `active` | Available for redemption | The status a card is created with |
+| `partially_redeemed` | Some value has been redeemed | `Spree::GiftCards::Redeem`, when a balance remains |
+| `redeemed` | Fully redeemed | `Spree::GiftCards::Redeem`, when nothing is left |
+| `canceled` | Voided, and no longer spendable | `Spree::GiftCards::Cancel` |
-| State | Description |
-|-------|-------------|
-| `active` | Available for redemption |
-| `partially_redeemed` | Some value has been redeemed |
-| `redeemed` | Fully redeemed |
-| `canceled` | Canceled by admin |
+Redemption does not need the caller to choose: `Spree::GiftCards::Redeem`
+looks at what is left on the card and marks it partially or fully redeemed
+accordingly. A card can be partially redeemed more than once, and each spend
+publishes its own event.
+
+Cancelling is refused once a card has been spent against, so cancellation can
+never take back value a customer has already used.
<Note>
Gift cards can also be `expired` if `expires_at` date has passed and the card hasn't been fully redeemed.
diff --git a/docs/developer/customization/workflows.mdx b/docs/developer/customization/workflows.mdx
index d3ceeac5f9..38c31906d7 100644
--- a/docs/developer/customization/workflows.mdx
+++ b/docs/developer/customization/workflows.mdx
@@ -285,6 +285,36 @@ is reported through `Rails.error` so it's visible rather than mysterious.
| `products.update` | `after_update` | lifecycle | After the product is saved (in transaction) |
| `products.destroy` | `validate` | validate | Before the product is soft-deleted — refuse a deletion your store shouldn't allow |
| `products.destroy` | `after_destroy` | lifecycle | After the soft-delete, for host cleanup (in transaction) |
+| `products.activate` | `validate` | validate | Before the product goes on sale — the place to require an image, a price or a category |
+| `products.activate` | `after_activate` | lifecycle | After the status is written (in transaction) |
+| `products.archive` | `validate` | validate | Before the product is taken off sale |
+| `products.archive` | `after_archive` | lifecycle | After the status is written (in transaction) |
+| `products.draft` | `validate` | validate | Before the product returns to draft |
+| `products.draft` | `after_draft` | lifecycle | After the status is written (in transaction) |
+| `gift_cards.apply` | `validate` | validate | Before a card is drawn against — who may spend a card, on what, up to how much |
+| `gift_cards.apply` | `after_apply` | lifecycle | After the store credit and payment exist (in transaction) |
+| `gift_cards.remove` | `validate` | validate | Before a card is taken back off an order |
+| `gift_cards.remove` | `after_remove` | lifecycle | After the balance is returned to the card (in transaction) |
+| `gift_cards.redeem` | `validate` | validate | Before the card is recorded as spent |
+| `gift_cards.redeem` | `after_redeem` | lifecycle | After the status is written (in transaction) |
+| `gift_cards.cancel` | `validate` | validate | Before a card is voided |
+| `gift_cards.cancel` | `after_cancel` | lifecycle | After the card is voided (in transaction) |
+| `price_lists.activate` | `validate` | validate | Before a price list takes effect |
+| `price_lists.activate` | `after_activate` | lifecycle | After the list goes live or is scheduled (in transaction) |
+| `price_lists.deactivate` | `validate` | validate | Before a price list stops applying |
+| `price_lists.deactivate` | `after_deactivate` | lifecycle | After the list is switched off (in transaction) |
+| `invitations.accept` | `validate` | validate | After the expiry and invitee checks pass, before any access is granted |
+| `invitations.accept` | `after_accept` | lifecycle | After the role is granted and the invitation marked accepted (in transaction) |
+| `imports.start_mapping` | `validate` | validate | Before the uploaded file is read |
+| `imports.start_mapping` | `after_start_mapping` | lifecycle | After the column mappings are built (in transaction) |
+| `imports.complete_mapping` | `validate` | validate | Before the mapping is accepted — refuse a mapping your store considers incomplete |
+| `imports.complete_mapping` | `after_complete_mapping` | lifecycle | After the mapping is accepted, before row creation is dispatched (in transaction) |
+| `imports.start_processing` | `validate` | validate | Before the import starts working through its rows |
+| `imports.start_processing` | `after_start_processing` | lifecycle | After the status is written (in transaction) |
+| `imports.complete` | `validate` | validate | Before the import is closed out |
+| `imports.complete` | `after_complete` | lifecycle | After the import is completed and the store touched (in transaction) |
+| `imports.retry_failed_rows` | `validate` | validate | Before failed rows are queued again |
+| `imports.retry_failed_rows` | `after_retry` | lifecycle | After the import returns to processing, before re-dispatch (in transaction) |
`before_cancel` and `before_resume` accept `reject!` like a `validate` hook.
@@ -404,11 +434,68 @@ Two rules worth internalising:
connection open across a network round trip, and a timeout leaves your database
and the payment processor disagreeing about what happened.
-**New models get a plain `status` string, not a state machine.** Transitions are
+**Models get a plain `status` string, not a state machine.** Transitions are
workflows: `MyStore::Subscriptions::Cancel.call(...)`, not `subscription.cancel!`.
Transition callbacks hide side effects inside a save, cannot take arguments, and
have no compensation story.
+As of 6.0 this is not just advice for new models — Spree has no state machines
+left. Every status a record can hold is declared with `Spree::HasStatus`, and
+every move between two of them is a workflow you can hook.
+
+## Statuses
+
+`Spree::HasStatus` declares the statuses a model can hold:
+
+```ruby
+class MyStore::Subscription < Spree.base_class
+ include Spree::HasStatus
+ has_status :trialing, :active, :paused, :canceled, default: :trialing
+end
+```
+
+That gives you an inclusion validation, a predicate per value
+(`subscription.paused?`), a scope per value (`Subscription.paused`) and
+`with_status(:active, :trialing)` for several at once. It deliberately does
+*not* give you a transition graph — deciding which moves are legal is the
+workflow's job, which is what lets a transition take arguments, call out to a
+gateway outside a transaction, and undo itself when a later step fails.
+
+Statuses are additive, so an extension can add its own without reopening the
+model:
+
+```ruby
+Spree::GiftCard.add_status(:on_hold, after: :active)
+```
+
+A custom status needs a custom workflow to move records into it. That is the
+design, not a gap: a central place validating transitions would be a state
+machine again.
+
+<Note>
+`has_status` never overwrites something the model already defines. Where a
+status name means more than the column value — `Spree::GiftCard#active?` also
+requires the card not to have expired, and `Spree::GiftCard.active` includes
+partially redeemed cards — the model's own definition wins and the generated
+one is skipped.
+</Note>
+
+### Moving a record between statuses
+
+Call the workflow, not the model:
+
+```ruby
+result = Spree.product_archive_workflow.call(product: product)
+result.success?
+```
+
+Spree ships one workflow per transition — `Spree::Products::Activate`,
+`Spree::GiftCards::Redeem`, `Spree::Imports::Complete`, and so on — each with
+its own `validate` and `after_*` hooks, all in
+[Available hooks](#available-hooks) above. Because the write and the event it
+publishes happen in the same place, registering against a hook is enough to
+see every transition, wherever it was triggered from.
+
## Observability
Every step emits an `ActiveSupport::Notifications` event, so your APM sees the
diff --git a/docs/plans/6.0-normalize-state-to-status.md b/docs/plans/6.0-normalize-state-to-status.md
index 457bffa64d..2d05424cd3 100644
--- a/docs/plans/6.0-normalize-state-to-status.md
+++ b/docs/plans/6.0-normalize-state-to-status.md
@@ -1,10 +1,10 @@
# Normalize state → status
-**Status:** Design finalized, implementation not started
+**Status:** Complete — 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-03-16
+**Last updated:** 2026-08-19
## Summary
@@ -27,16 +27,16 @@ This inconsistency means developers must remember which column each model uses.
| 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` | Rename → `status` |
+| **InventoryUnit** | `state` | **Done (2026-08-19)** — became FulfillmentItem; column already `status`, machine removed |
| **ReturnAuthorization** | `state` | Gone — model deleted by the returns rework |
-| **GiftCard** | `state` | Rename → `status` |
-| Product | `status` | Already correct |
-| PriceList | `status` | Already correct |
+| **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` | Already correct |
-| ImportRow | `status` | Already correct |
-| Invitation | `status` | Already correct |
+| 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 |
@@ -82,9 +82,71 @@ time — following Order and Fulfillment:
`has_invalid_state?`, `with_state`, `INVALID_STATES`, and a `state`
ransack alias.
-InventoryUnit and GiftCard still pend, and follow the same doctrine when
-they move: rename + machine removal together, never a `state_machine
-:status` halfway state.
+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.
+
+**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
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
index c405ca1317..522b2aae26 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/error_handler.rb
@@ -96,7 +96,6 @@ module Spree
rescue_from ActiveRecord::RecordInvalid, with: :handle_record_invalid
rescue_from ArgumentError, with: :handle_argument_error
rescue_from ActionDispatch::Http::Parameters::ParseError, with: :handle_parse_error
- rescue_from StateMachines::InvalidTransition, with: :handle_invalid_transition
end
protected
@@ -236,15 +235,6 @@ module Spree
)
end
- def handle_invalid_transition(exception)
- Rails.error.report(exception, context: error_context, source: 'spree.api.v3')
- render_error(
- code: ERROR_CODES[:cart_cannot_transition],
- message: exception.message,
- status: :unprocessable_content
- )
- end
-
private
diff --git a/spree/core/app/services/spree/orders/approve.rb b/spree/core/app/services/spree/orders/approve.rb
index 78c46a7bfb..06e6f3acf0 100644
--- a/spree/core/app/services/spree/orders/approve.rb
+++ b/spree/core/app/services/spree/orders/approve.rb
@@ -33,7 +33,7 @@ module Spree
order.publish_event('order.approved')
success(order.reload)
- rescue ActiveRecord::RecordInvalid, StateMachines::InvalidTransition
+ rescue ActiveRecord::RecordInvalid
failure(order)
end
end
diff --git a/spree/core/app/workflows/spree/orders/cancel.rb b/spree/core/app/workflows/spree/orders/cancel.rb
index 0d0210c098..f10d77180d 100644
--- a/spree/core/app/workflows/spree/orders/cancel.rb
+++ b/spree/core/app/workflows/spree/orders/cancel.rb
@@ -57,7 +57,7 @@ module Spree
step :update_statuses, with: -> { Spree.order_update_statuses_service }
order.publish_event('order.canceled', order.event_payload.merge(notify_customer: notify_customer))
success(order.reload)
- rescue ActiveRecord::RecordInvalid, StateMachines::InvalidTransition
+ rescue ActiveRecord::RecordInvalid
failure(order)
end
diff --git a/spree/core/app/workflows/spree/orders/resume.rb b/spree/core/app/workflows/spree/orders/resume.rb
index e30a079419..f0500e3830 100644
--- a/spree/core/app/workflows/spree/orders/resume.rb
+++ b/spree/core/app/workflows/spree/orders/resume.rb
@@ -25,7 +25,7 @@ module Spree
step :update_statuses, with: -> { Spree.order_update_statuses_service }
order.publish_event('order.resumed')
success(order.reload)
- rescue ActiveRecord::RecordInvalid, StateMachines::InvalidTransition
+ rescue ActiveRecord::RecordInvalid
failure(order)
end
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index fe73db5cd7..bf14991e0e 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -26,7 +26,6 @@ require 'rails-html-sanitizer'
require 'paranoia'
require 'request_store'
require 'ransack'
-require 'state_machines-activerecord'
require 'active_storage_validations'
require 'wannabe_bool'
require 'geocoder'
@@ -35,10 +34,6 @@ require 'safely_block'
require 'ar_lazy_preload'
require 'sqids'
-# This is required because ActiveModel::Validations#invalid? conflicts with the
-# invalid state of a Payment. In the future this should be removed.
-StateMachines::Machine.ignore_method_conflicts = true
-
module Spree
mattr_accessor :base_class, :customer_class, :admin_user_class,
:private_storage_service_name, :public_storage_service_name,
diff --git a/spree/core/spec/models/spree/credit_card_spec.rb b/spree/core/spec/models/spree/credit_card_spec.rb
index b9c5713bd5..9bce9d5b57 100644
--- a/spree/core/spec/models/spree/credit_card_spec.rb
+++ b/spree/core/spec/models/spree/credit_card_spec.rb
@@ -18,10 +18,6 @@ describe Spree::CreditCard, type: :model do
before { allow(payment).to receive_messages payment_method: payment_method }
- def self.payment_states
- Spree::Payment.state_machine.states.keys
- end
-
describe '#can_capture?' do
shared_examples 'can be captured' do
it 'can be captured' do
diff --git a/spree/core/spree_core.gemspec b/spree/core/spree_core.gemspec
index 6ab8901909..61f727c7d8 100644
--- a/spree/core/spree_core.gemspec
+++ b/spree/core/spree_core.gemspec
@@ -55,8 +55,6 @@ Gem::Specification.new do |s|
s.add_dependency 'request_store', '~> 1.5'
s.add_dependency 'rexml'
- s.add_dependency 'state_machines-activerecord', '~> 0.100'
- s.add_dependency 'state_machines-activemodel', '~> 0.100'
s.add_dependency 'stringex'
s.add_dependency 'tracking_number'
s.add_dependency 'validates_zipcode'