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.

Checkout consolidation and refactor

Damian Legawiecd226ae70808f
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
index 49a8f344d6..22376e24ac 100644
--- a/.claude/settings.local.json
+++ b/.claude/settings.local.json
@@ -24,7 +24,8 @@
"mcp__scout-apm__get_app_insights",
"mcp__scout-apm__get_app_error_groups",
"mcp__scout-apm__get_app_anomaly_events",
- "mcp__claude_ai_Spree_Commerce_Docs_MCP__query_docs_filesystem_spree_commerce_documentation"
+ "mcp__claude_ai_Spree_Commerce_Docs_MCP__query_docs_filesystem_spree_commerce_documentation",
+ "Bash(bundle exec *)"
],
"deny": [
"Bash(sudo *)",
diff --git a/CLAUDE.md b/CLAUDE.md
index 097b0fc717..4b7477f828 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -31,7 +31,7 @@ Active plans (6.0 target, work pending):
- `6.0-inventory-operations.md` — StockTransfer lifecycle (draft → ready_to_ship → in_transit → received with partial receive), new `Spree::PurchaseOrder` + `Spree::Supplier` (renamed from Vendor — `Spree::Vendor` is the marketplace seller, see decisions.md 2026-07-14) replacing today's "external receive" hack, variant + stock-location stock history panels. Consumes the typed-movement primitives from `6.0-typed-stock-movements.md`.
- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). **Shipped to 6-0-dev (PR #14302):** the Category surface (5.5–5.6) plus the 6.0 core — `spree_taxons`→`spree_categories` table rename + inheritance flip (`Spree::Category < Spree.base_class`, `Spree::Taxon` alias kept), the full `Collection` stack (model + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data migration, and de-ruling Category. Pending (all 6.1): channel-aware `CollectionRules::AvailableOn` (ships interim now, rides with channels) + dropping `spree_taxon_rules`/`Taxonomy`. No brand feature in 6.0 — brands are modeled as a Category/Collection; `brand_taxon`/`brand_name` removed with `Taxonomy`.
- `6.0-delivery-method-rules.md` — `Spree::DeliveryMethodRule` STI on DeliveryMethod (design finalized 2026-07-29): ItemTotal/Weight rules first (Channel/Market/CustomerGroup later in lockstep with payment-method-rules), enforced solely in `Stock::Estimator`'s method filter so calculator- AND provider-priced methods obey eligibility; replaces the FlatRate-only bound preferences (one-release bridge + data task). Phase 1 rides the 6.0 core-rewrite finishing work.
-- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` — named steps inside a plain `def perform(order:, ...)` (the ActiveJob::Continuable shape; bare `super` turns parameters into readers). Vocabulary: `step`/`external_step` (+ `with:`, `on_flow_failure:`), `run_hooks` + class-level `hooks`, `failure`/`halt!`; plain `ApplicationRecord.transaction`/`with_lock`/`rescue`/`publish_event`; every step instrumented as `step.spree_workflow`. Reserved for flows needing hooks, compensation/external I/O, or replay — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `Carts::Complete` battery must pass unmodified. **Durability = plain Rails:** long-running background work uses `ActiveJob::Continuable` directly (reference: `Spree::Imports::ProcessJob` — CSV spine with a row-number cursor; `CreateRowsJob`/`ProcessRowsJob` deprecated shells); workflows are synchronous request-cycle flows and are NOT jobs — Workflow-level durable execution ships only if the payout run proves the need.
+- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` — named steps inside a plain `def perform(order:, ...)` (the ActiveJob::Continuable shape; bare `super` turns parameters into readers). Vocabulary: `step`/`external_step` (+ `with:`, `on_flow_failure:`), `run_hooks` + class-level `hooks`, `failure`/`halt!`; plain `ApplicationRecord.transaction`/`with_lock`/`rescue`/`publish_event`; every step instrumented as `step.spree_workflow`. Money lives in `Carts::RecalculateTotals` (single totals seam; the completed-order branch is the post-placement resum — rows re-summed, never regenerated), statuses in `Orders::UpdateStatuses` (refreshes each fulfillment's state, then rolls up); Order/CartUpdater are 6.1-removed warning shells. Shared Cart/Order surface lives in `Spree::Purchase::*` concerns; completion side effects (newsletter, account creation, risk) run in the sync `OrderPlacedSubscriber` on order.placed. Reserved for flows needing hooks, compensation/external I/O, or replay — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `Carts::Complete` battery must pass unmodified. **Durability = plain Rails:** long-running background work uses `ActiveJob::Continuable` directly (reference: `Spree::Imports::ProcessJob` — CSV spine with a row-number cursor; `CreateRowsJob`/`ProcessRowsJob` deprecated shells); workflows are synchronous request-cycle flows and are NOT jobs — Workflow-level durable execution ships only if the payout run proves the need.
- `6.0-store-scoped-custom-field-definitions.md` — Add `store_id` + persisted `filter_key` to `Spree::MetafieldDefinition` (today global and computed), making uniqueness `(store_id, resource_type, filter_key)` with a DB index. Deferred from the 5.6 custom-field search/sort/filter work (schema change, not patch-safe). **Until then:** `filter_key` is a computed method — no Ransack predicates or `where`/`order` against it; definitions are global; uniqueness rests on a `CONCAT` validation with no index behind it.
Multi-version plans (some phases shipped, some pending):
@@ -117,6 +117,7 @@ Backend: http://localhost:3000, admin at `/admin`, hosted React Dashboard at `/d
- If n-commits are needed for a single logical change, use `git commit --fixup` for the follow-ups and `git rebase -i --autosquash` to combine into a single commit before merging
- Documentation also needs to follow the same principles — focus on the "what" and "why", not the "how". Don't include implementation details in docs. Docs should explain the feature, its purpose, and how to use it, but not how it's implemented internally.
- NEVER commit anything to main branch, always use feature/fix/chore branches for development
+- ALWAYS use plain english language when communicating with the human, NEVER use technical jargon, be precise and clear, avoid abbreviations and acronyms, and use proper grammar and punctuation. Avoid using slang or informal language. Use simple and concise sentences to convey your message effectively. Avoid using complex sentence structures or convoluted phrasing that may confuse the reader. Use active voice instead of passive voice whenever possible. Avoid using overly technical terms or industry-specific jargon that may not be familiar to the reader. Use examples or analogies to explain complex concepts in a way that is easy to understand. Avoid using vague or ambiguous language that may lead to misinterpretation. Use headings, bullet points, and numbered lists to organize information and make it easier to read. Avoid using long paragraphs or blocks of text that may overwhelm the reader. Use visuals such as diagrams, charts, or screenshots to supplement written explanations when appropriate. Avoid using visuals that are unclear or difficult to interpret.
## Backend (Ruby)
diff --git a/docs/developer/upgrades/5.6-to-6.0.mdx b/docs/developer/upgrades/5.6-to-6.0.mdx
new file mode 100644
index 0000000000..6ecb37ddca
--- /dev/null
+++ b/docs/developer/upgrades/5.6-to-6.0.mdx
@@ -0,0 +1,232 @@
+---
+title: Upgrading to Spree 6.0
+description: Guide to upgrading a Spree 5.6 application to Spree 6.0
+hidden: true
+---
+
+<Info>
+ Before proceeding to upgrade, please ensure you're at [Spree 5.6](/developer/upgrades/5.5-to-5.6). Spree 6.0 requires **Rails 8.1** and is the designated breaking-change window for the platform — read the behavioral changes section even if your upgrade runs clean.
+</Info>
+
+Spree 6.0 is a major release. The headline changes:
+
+- **Cart and Order are separate models.** `Spree::Cart` owns shopping and checkout; completing checkout copies the cart into an immutable `Spree::Order`. The order state machine is gone.
+- **Checkout has no server-side state machine.** Steps are advisory metadata for your frontend; the backend enforces exactly one hard gate — completion.
+- **Adjustments are typed rows.** The polymorphic `Spree::Adjustment` is replaced by `Spree::TaxLine`, `Spree::Discount` and `Spree::Fee`.
+- **Master Variant** is gone, replaced by a `default_variant_id` foreign key on `Spree::Product`. There's no hidden/dummy Variant created now, the default variant is a real Variant with its own SKU, price, stock, etc.
+- **Fulfillment vocabulary.** `Shipment` → `Fulfillment`, `ShippingMethod` → `DeliveryMethod`, `Zone` → `DeliveryZone`, with a pluggable `FulfillmentProvider` strategy.
+- **Two-tier services.** Plain services in `app/services`, plus `Spree::Workflow` classes in `app/workflows` for the curated multi-step flows (completion, cancellation, recalculation) — with named steps, instrumentation and extension hooks.
+
+The upgrade is completed in four steps:
+
+1. **Update the Ruby gems**
+2. **Run database migrations**
+3. **Run data backfills** — convert your existing records into the new schema
+4. **Review behavioral changes** — this release changes runtime behavior, not just schema
+
+## How to upgrade
+
+<CodeGroup>
+
+```bash Spree CLI (Docker)
+spree upgrade
+```
+
+```bash Without Spree CLI
+# cd backend if you're in the monorepo root
+bundle update
+bundle exec rake spree:install:migrations && bin/rails db:migrate
+bundle exec rake spree:upgrade
+```
+
+</CodeGroup>
+
+Skipping versions and re-running are both safe — `bundle exec rake spree:upgrade` figures out what still needs to happen and does nothing on data that's already migrated.
+
+## What the upgrade does
+
+Reference material — the data backfills `bundle exec rake spree:upgrade` executes. Every task is idempotent.
+
+### Convert incomplete orders into carts
+
+```bash
+bundle exec rake spree:migrate_incomplete_orders_to_carts
+```
+
+Every order that never completed and was never canceled becomes a `Spree::Cart` with the same token, so in-flight guest and customer checkouts survive the deploy. The cart re-owns the order's line items, fulfillments, payments, payment sessions, reservations and coupon codes; the hollow order row is deleted. Completed and canceled orders are untouched. Orders holding payment sessions convert last, so an interrupted run leaves the riskiest rows for the retry.
+
+### Convert legacy adjustments into typed rows
+
+```bash
+bundle exec rake spree:migrate_adjustments_to_typed_rows
+```
+
+Rebuilds `spree_adjustments` into `Spree::TaxLine`, `Spree::Discount` and `Spree::Fee` rows. Orders whose typed sums do not reconcile with the stored totals are left untouched and flagged (`private_metadata['typed_adjustments_frozen']`) for manual review instead of silently changing money.
+
+### Backfill fulfillment and delivery naming
+
+```bash
+bundle exec rake spree:migrate_shipping_to_delivery
+bundle exec rake spree:migrate_zones_to_delivery_zones
+bundle exec rake spree:migrate_calculator_bounds_to_delivery_method_rules
+```
+
+Moves stored strings, statuses and class names to the fulfillment/delivery vocabulary, converts delivery-referenced `Spree::Zone` records into `Spree::DeliveryZone` with typed members, and converts FlatRate calculator eligibility bounds into `Spree::DeliveryMethodRule` records.
+
+### Remove master variants
+
+```bash
+bundle exec rake spree:remove_master_variant
+```
+
+Products now carry a `default_variant_id` foreign key; `is_master` is gone from the models. (The physical column drop lands in 6.1.)
+
+### Categories and collections
+
+```bash
+bundle exec rake spree:migrate_taxons_to_categories_and_collections
+```
+
+Taxons become `Spree::Category` (hierarchy) and automatic taxons become `Spree::Collection` (flat, rule-based). `Spree::Taxon` remains as an alias for one release.
+
+### Markets on orders
+
+```bash
+bundle exec rake spree:backfill_order_markets
+```
+
+Orders missing a market get the store default — `market` is required on carts and orders in 6.0.
+
+## The Cart/Order split
+
+The single biggest change. What used to be one `Spree::Order` living through checkout and beyond is now two models:
+
+- **`Spree::Cart`** (`spree_carts`, prefixed IDs `cart_...`) owns the shopping and checkout phase: line items, addresses, payments-in-progress, delivery proposals, promotions, stock reservations. Carts have **no status column** — `completed_at` is the only lifecycle marker.
+- **`Spree::Order`** is created *by completion* — the cart is copied into it (line items, fulfillments, addresses, typed money rows — **copies, never shared rows**). Orders carry `status` (`draft` / `placed` / `canceled`) and are money-frozen once placed.
+
+Consequences to review:
+
+- **Completed carts are read-only.** The cart is retained after completion (abandonment analytics, idempotent replay) but rejects every write. Post-checkout life belongs to the order.
+- **Completion is idempotent.** `Spree::Carts::Complete` guards with a unique `spree_orders.cart_id` index and a `completing_at` lock: a double-clicked Place Order returns the same order, a crashed completion replays safely, and a pre-capture payment failure rolls the draft order back and re-points payments to the cart.
+- **The guest token carries over** from cart to order, so confirmation pages keep working with the credential the guest already holds.
+- **Dual concrete FKs, not polymorphism.** Records owned by either side (`LineItem`, `Fulfillment`, `TaxLine`, `Discount`, `Fee`, `Payment`, `StockReservation`) carry nullable `cart_id` + `order_id` with an exactly-one rule and an `#owner` method. Code that assumed `line_item.order` is always present must read `line_item.owner`.
+- **Shared model surface** lives in `Spree::Purchase::*` concerns (addresses, taxation, store credits, gift cards, digital items, payment processing, market/channel/currency/locale resolution) — included by both Cart and Order. Decorators targeting `Spree::Order` methods that moved should decorate the concern or the new owner.
+
+## Checkout without a state machine
+
+`Spree::Order` no longer has a `state` column, a state machine, or the `checkout_flow` DSL. If your app customized checkout with `checkout_flow`, `go_to_state`, `insert_checkout_step`, `remove_checkout_step` or `remove_transition` — those APIs are gone (not deprecated: the machine they configured no longer exists).
+
+The replacement model:
+
+- **Steps are advisory.** `cart.checkout_steps`, `current_checkout_step` and `completed_checkout_steps` are *derived* from cart data — there is no stored step and no server-side sequencing. Clients may write any checkout field in any order. "Steps" are a grouping label telling your frontend which page an unmet requirement belongs to.
+- **One hard gate.** `Spree::Carts::Complete` is the only place checkout is enforced. It validates the full requirement battery (line items, email, addresses, delivery selection, payment coverage, per-item stock, discontinued products, guest policy) and returns structured `{ step, field, code, message }` errors.
+- **`Spree::Checkout::Registry` is the extension surface.** One declaration serves both the advisory feed and the completion gate:
+
+```ruby
+# config/initializers/spree.rb
+Rails.application.config.to_prepare do
+ Spree::Checkout::Registry.add_requirement(
+ step: :payment,
+ field: :po_number,
+ message: 'PO number is required',
+ satisfied: ->(cart) { cart.metadata['po_number'].present? },
+ applicable: ->(cart) { cart.customer.present? }
+ )
+end
+```
+
+ The requirement appears in the Cart API's `requirements` array (so a storefront rendering the feed generically needs zero changes) *and* blocks completion. `register_step` adds whole steps (spliced into `checkout_steps` at `before:`/`after:` anchors); built-in steps are customized through `Registry.base_steps` — an ordered `{ name => applicability }` hash you can mutate directly (`base_steps.delete('confirm')`).
+- **The API `requirements` array now carries a stable `code`** on every entry (`email_required`, `out_of_stock`, `guest_checkout_not_allowed`, ...). Additive change — existing consumers keep working.
+- **"Logic between steps" has no backend home by design.** Side effects hang off data writes (workflow hooks such as `Carts::Complete`'s `before_finalize` and `Carts::AddItem`'s `after_item_added`) and events (`cart.updated`, `order.placed`) — not step transitions.
+
+## Statuses: derived, then persisted
+
+`payment_state` and `shipment_state` machine columns are replaced by `payment_status` and `fulfillment_status` — stored, indexed, and recomputed from payment/refund/fulfillment records by a single writer, `Spree::Orders::UpdateStatuses`. The legacy names remain as read aliases for one release.
+
+Behavior to review:
+
+- Nothing else writes these columns. If your code assigned `order.payment_state = 'paid'`, replace it with the underlying records (payments/refunds) and let the recompute derive.
+- The `payment_status` domain gains `overcharged` and `voided`; `fulfillment_status` includes `backorder`. Money comparisons are quantized to currency precision and refunds are netted before comparing.
+- A completed payment updates **only the payment side of the ledger** (`payment_total` + statuses). It never re-sums item or adjustment money.
+- Fulfillment is a fact: a fulfilled fulfillment is never downgraded by later payment-state changes.
+
+## Recalculation on write
+
+Transition-triggered recalculation is gone with the machine. Instead:
+
+- **`Spree::Carts::RecalculateTotals`** is the single totals seam: money inputs, typed-row regeneration (promotions via the winner-only adjuster, tax via `Spree.tax_provider`), folding and one persist. It runs on the writes that matter — item changes, address/market changes (which also re-price items and rebuild delivery proposals) — not on step transitions.
+- Promotion eligibility is evaluated against **current** totals in the same recalculation — a cart crossing a coupon threshold gets the discount on that recalculation, not the next one.
+- **Completed orders are money-frozen.** Typed rows are never regenerated post-placement; recalculation only re-sums them. Post-placement money edits go through the explicit admin services (`Orders::Discounts::*`, `Orders::Fees::*`), which write rows and re-sum.
+- `Spree::OrderUpdater` and `Spree::CartUpdater` remain as deprecated shells — every method warns and runs the full recalculation. Removed in 6.1.
+
+## Completion, in one workflow
+
+`Spree::Orders::Complete` is the one home for everything that happens when an order becomes placed — payment processing (when needed), fulfillment finalization, placement, coupon/gift-card redemption, digital auto-fulfillment, statuses, and the `order.placed` event. Checkout reaches it through `Carts::Complete`; admin/B2B draft completion calls it directly (`payment_pending: true` places without processing payments for invoice-later flows).
+
+- **`Order#finalize!` is deprecated** (removed in 6.1) and delegates to the workflow. Behavioral change: finalizing an **already-completed order is now a no-op** — the workflow halts idempotently instead of re-running side effects.
+- **Completion side effects moved out of the model.** Newsletter subscription, checkout account creation and risk assessment run in the synchronous `Spree::OrderPlacedSubscriber` on the `order.placed` event. Decorators that patched `finalize!` should become event subscribers or `before_finalize` hook handlers.
+- **`order.placed` is the completion event.** `order.completed` still fires as a deprecated alias for one release (webhook consumers should migrate; wildcard subscribers can dedupe on the `deprecated_alias_of` metadata marker).
+- `Order.register_update_hook` no longer runs during completion.
+
+## Addresses
+
+The full address surface is shared by Cart and Order through `Spree::Purchase::Addresses`, which means cart checkout regains behavior that 5.x orders had:
+
+- Address writes **deduplicate** against the customer's address book and **promote** checkout addresses to the customer's defaults (quick-checkout wallet addresses excluded).
+- `ship_address_id=` / `bill_address_id=` are **ownership-guarded**: an address not owned by the record's customer resolves to `nil`.
+- A signed-in customer entering checkout gets blank address slots **auto-filled from their saved defaults**.
+- **`use_billing` is deprecated** (removed in 6.1): the shipping address is canonical — use `use_shipping` to copy ship → bill.
+
+## Dependency injection changes
+
+6.0 introduces `*_workflow` keys for the flows that graduated to the workflow tier. The old `*_service` keys **stay settable and readable one release so applications don't crash at boot — but a legacy write is stashed, not applied**: a class written against the old service contract is not interchangeable with the workflow the new call sites consume. Reads return your stashed class (legacy code calling its own override keeps working), falling back to the workflow. Removed in 6.1.
+
+| Legacy key (stash-only) | 6.0 key | Resolves to |
+|---|---|---|
+| `cart_add_item_service` | `cart_add_item_workflow` | `Spree::Carts::AddItem` |
+| `cart_recalculate_service` | `cart_recalculate_workflow` | `Spree::Carts::Recalculate` |
+| `carts_complete_service` | `carts_complete_workflow` | `Spree::Carts::Complete` |
+| `order_cancel_service` | `order_cancel_workflow` | `Spree::Orders::Cancel` |
+| `order_complete_service` | `order_complete_workflow` | `Spree::Orders::Complete` |
+| `shipment_update_service` | `fulfillment_update_service` | `Spree::Fulfillments::Update` |
+
+New seams with no legacy counterpart:
+
+| Key | Resolves to | Purpose |
+|---|---|---|
+| `cart_recalculate_totals_workflow` | `Spree::Carts::RecalculateTotals` | the single totals seam |
+| `order_recalculate_totals_workflow` | `Spree::Orders::RecalculateTotals` | order twin (post-placement re-sum) |
+| `order_resume_workflow` | `Spree::Orders::Resume` | resume canceled orders |
+| `order_discount_create_service` | `Spree::Orders::Discounts::Create` | renamed from `order_add_manual_discount_service` (never released) |
+| `order_update_statuses_service` | `Spree::Orders::UpdateStatuses` | the sole status writer |
+
+Removed keys (their classes no longer exist): `carts_validate_service` (completion validation is `Spree::Checkout::Requirements` directly), plus the dead legacy `Spree::Cart::*` service namespace registrations.
+
+If you override a workflow seam, subclass the shipped workflow (or implement the same `perform` keyword contract) — workflow arguments are plain Ruby keywords, so a mismatch raises `ArgumentError` at call time, not silently.
+
+## Deprecated in 6.0, removed in 6.1
+
+Every rename keeps the legacy name working for one release with a deprecation warning. The notable ones:
+
+| Deprecated | Use instead |
+|---|---|
+| `Order#finalize!` | `Spree.order_complete_workflow` |
+| `Order#updater`, `Spree::OrderUpdater`, `Spree::CartUpdater` | `#recalculate_totals!` / `#update_statuses!` |
+| `Order#shipping_discount` | `#fulfillment_discount` |
+| `use_billing` / `clone_billing_address` | `use_shipping` (shipping address is canonical) |
+| `Fulfillment#ship`, `#ship!`, `#shipped?`, `#can_ship?`, `#shipping_method`, `#add_shipping_method` | `#fulfill`, `#fulfill!`, `#fulfilled?`, `#can_fulfill?`, `#delivery_method`, `#add_delivery_method` |
+| `LineItem#target_shipment` | `#target_fulfillment` |
+| `Order#remove_out_of_stock_items!` | cart-side only (`Spree::Carts::RemoveOutOfStockItems`) |
+| `Cart#number` (Store API field) | `id` — carts have no order-style number; the field mirrors the prefixed ID for one release |
+| `order.completed` event | `order.placed` |
+| Calling cart services with `order:` kwargs | `cart:` kwargs |
+
+## For extension authors
+
+- **Don't reach for model business methods from services** — 6.0 code style writes behavior inline in service/workflow steps; models keep data, validations, predicates and persistence primitives. Extensions patching removed model methods (`finalize!` internals, updater hooks) should move to workflow hooks (`Spree.hooks.register('carts.complete.before_finalize') { |flow| ... }` — handlers receive the workflow instance) or event subscribers.
+- **Store-scoped data is single-owner.** `Product`, `Promotion` and `PaymentMethod` `belongs_to :store`; the `stores: [...]` writers are gone. Multi-store sharing lives in the `spree_multi_store` extension.
+- The Store API v3 contract is stable across the split — cart endpoints keep their shapes; `requirements` gains `code`, and serializer `number` on carts is bridged as described above.
+
+<Warning>
+ This guide tracks the 6.0 development line and will grow until release. If a behavioral change you hit isn't documented here, treat it as a documentation bug and report it.
+</Warning>
diff --git a/docs/plans/6.0-cart-order-split.md b/docs/plans/6.0-cart-order-split.md
index ed79d5012a..0385d85390 100644
--- a/docs/plans/6.0-cart-order-split.md
+++ b/docs/plans/6.0-cart-order-split.md
@@ -4,7 +4,7 @@
**Target:** Spree 6.0
**Depends on:** API v3 conventions. **Gates (they depend on this plan):** `6.0-split-adjustments.md` (typed-line owner), `6.0-fulfillment-and-delivery.md` (fulfillment/rate owner), `6.0-multi-vendor-marketplace.md` Phase 3 (split fires inside `Carts::Complete`), `6.0-normalize-state-to-status.md` (Order.state removed here). This is the most upstream unstarted 6.0 refactor.
**Author:** Damian + Claude
-**Last updated:** 2026-07-28
+**Last updated:** 2026-08-01
## Summary
@@ -54,7 +54,13 @@ Every competitor treats this as load-bearing. `Spree::Carts::Complete`:
### 5. State machine removed — three replacements, not one
-**(a) Checkout progression → Requirements.** `current_step`/`completed_steps`/`requirements` are computed by `Checkout::Requirements` against cart data. `Checkout::Registry` becomes the extension surface (`register_step`, `add_requirement` with before/after anchors), replacing the `checkout_flow`/`insert_checkout_step` class-attribute API, and owns its own ordered step list. A `Spree::Carts::Validate` service runs the full battery at completion (lines present + in stock + not discontinued, email, addresses, delivery selected, payment coverage, guest policy) returning structured per-field errors with stable codes — also exposed read-only so storefronts can render checkout readiness without attempting completion (OSS platform B's model; OSS platform C's five `ArrangingPayment` guards expressed as data).
+**(a) Checkout progression → Requirements.** `current_step`/`completed_steps`/`requirements` are computed by `Checkout::Requirements` against cart data. `Checkout::Registry` becomes the extension surface (`register_step`, `add_requirement` with before/after anchors), replacing the `checkout_flow`/`insert_checkout_step` class-attribute API, and owns its own ordered step list. The full battery runs at completion via `Checkout::Requirements` (completion mode) (lines present + in stock + not discontinued, email, addresses, delivery selected, payment coverage, guest policy) returning structured per-field errors with stable codes — also exposed read-only so storefronts can render checkout readiness without attempting completion (OSS platform B's model; OSS platform C's five `ArrangingPayment` guards expressed as data).
+
+**Checkout doctrine (settled 2026-08-01).** The backend enforces exactly **one hard gate** — `Carts::Complete` — and everything else about checkout is advisory. There is no server-side step sequencing: clients may write any checkout field in any order; "steps" are only a grouping label on requirements (which frontend page surfaces the error) plus serializer sugar (`current_checkout_step` = first unmet requirement). Sequencing is a frontend concern by design — the 5.x pain of hopping between backend flow definitions and frontend pages came from the backend owning the sequence, and it no longer does. Consequences, each with one home:
+- **One completion truth:** every check is declared in `Checkout::DefaultRequirements` (completion-only checks — per-item stock, discontinued, guest policy — behind `completion: true` so the advisory feed on cart reads stays cheap) or registered via `Checkout::Registry.add_requirement`. `Requirements#call(completion: true)` *is* the completion answer — `Carts::Complete` calls it directly (the `Carts::Validate` shell was deleted once it became a one-liner), so the API `requirements` array (now carrying stable `code`s) and the completion gate can never disagree.
+- **One step vocabulary:** `Registry.base_steps` — an ordered `{name => applicability-proc}` hash — is the sole declaration of built-in steps; `Purchase::CheckoutSteps#checkout_steps` delegates to `Registry.step_names_for(record)`, which splices applicable registered custom steps at their `before:`/`after:` anchors. Installs customize by mutating `base_steps` (replace a predicate, delete `confirm`) or registering steps — no constants, no subclassing.
+- **Customization surface:** extra requirement → one `Registry.add_requirement` line (appears in the API feed *and* blocks completion, zero frontend changes for feed-rendering storefronts); "logic between steps" intentionally has no backend home — side effects hang off data writes (workflow hooks: `Carts::AddItem#after_item_added`, `Carts::Complete#before_finalize`) and events (`cart.updated`, `order.placed`). If step-entry side effects ever demand extensibility, `Carts::Update` graduates to the workflow tier per the services doctrine.
+- **One finalize home:** the order-side completion (payments when needed, fulfillment finalize, place, side effects, auto-fulfill, statuses, `order.placed`) is the `Spree::Orders::Complete` workflow — named steps, serving both checkout (`Carts::Complete` delegates its FINALIZE phase) and admin/B2B drafts (`order_complete_workflow`, legacy `order_complete_service` key bridged); `Order#finalize!` is a deprecated 6.1-removal shell. Doctrine rider: services/workflows never hide behavior behind model business methods — logic is written inline in named steps (models keep data, validations, predicates, persistence primitives).
**(b) Transition-triggered recalculation → recalculation-on-write.** Today tax/prices/shipment rebuilds fire *only* on state transitions (4 call sites) — an address changed in place at `payment` never re-runs tax. The Cart model recalculates explicitly on the writes that matter: address/market change → re-price, re-tax, rebuild delivery proposals (the destructive `create_proposed_shipments` behavior becomes an idempotent cart-side rebuild; the order's fulfillments are a frozen copy, never rebuilt); item changes → totals + reservations (the existing Release/Reserve/Extend dispatch in `Carts::Update` carries over). The stale memoized `tax_zone` hazard dies with the memoized order context.
diff --git a/docs/plans/6.0-core-rewrite-tasks.md b/docs/plans/6.0-core-rewrite-tasks.md
index 1d9557c967..78db0bb4be 100644
--- a/docs/plans/6.0-core-rewrite-tasks.md
+++ b/docs/plans/6.0-core-rewrite-tasks.md
@@ -257,7 +257,7 @@ The point of no return; biggest single wave. Everything before it exists so this
### Wave 6 outcome notes (2026-07-29 — COMPLETE)
-**Backend (T6.1/T6.2).** Admin nested `/orders/:id/{tax_lines,discounts,fees}` (tax read-only; discounts manual-CRUD with `422 discount_not_editable` on promotion rows; fees full CRUD, `kind` defaults `surcharge`) — all mutations run `OrderUpdater#resum_typed_totals!`, the sanctioned post-placement edit path (re-sums rows into totals WITHOUT re-running promotion competition/tax estimation; works on completed orders). `Spree::Orders::AddManualDiscount` (DI `order_add_manual_discount_service`) computes flat/percent line-item rows or distributes order-level via the extracted `Spree::Adjusters::LargestRemainder`. Net-new admin `delivery_methods` CRUD (+`/calculators` discovery with preference schemas; flat `calculator_type`/`calculator_preferences` params; prefixed `tax_category_id`/`delivery_zone_ids`) + `delivery_zones` CRUD (typed members by `country_iso`/`state_abbr`/postal prefix-or-range; `members` replaces the set atomically). Store `delivery_methods` discovery (`storefront_visible` scope, `fulfillment_type` filter) + `/:id/pickup_locations` (pickup-enabled stock locations, `cart_id` narrows to full-cart local coverage) + `/:id/pickup_points?latitude&longitude` via `DeliveryMethod#pickup_point_provider_instance`. Cart pickup selection: `preferred_stock_location_id` — **a preference (`preference :stock_location_id`), not a column (Damian 2026-07-29)** — prefixed-ID writer validating pickup_enabled, copied to the order column at completion; `pickup_point_external_id` on cart fulfillment update validated via provider and frozen into `pickup_point_data`. FulfillmentSerializer: `status` column-backed, `fulfillment_type` column-with-fallback, `pickup_point_data` + `selected_delivery_rate_id` exposed, real-name associations. Admin orders scope excludes transient completion drafts (`draft` + `cart_id` set). `AppliedPromotionSerializer` rename frees `DiscountSerializer` (+`TaxLine`/`Fee`/`DeliveryZone`/`DeliveryZoneMember` serializers, registry keys, payment-session serializer gets `cart_id` + owner-bridged `order_id`). `ConfigurationManagement` grants DeliveryMethod/DeliveryZone/Member.
+**Backend (T6.1/T6.2).** Admin nested `/orders/:id/{tax_lines,discounts,fees}` (tax read-only; discounts manual-CRUD with `422 discount_not_editable` on promotion rows; fees full CRUD, `kind` defaults `surcharge`) — all mutations run `OrderUpdater#resum_typed_totals!`, the sanctioned post-placement edit path (re-sums rows into totals WITHOUT re-running promotion competition/tax estimation; works on completed orders). `Spree::Orders::Discounts::Create` (DI `order_discount_create_service`; originally shipped as `Orders::AddManualDiscount`, renamed pre-release to match the `Fees::Create` naming) computes flat/percent line-item rows or distributes order-level via the extracted `Spree::Adjusters::LargestRemainder`. Net-new admin `delivery_methods` CRUD (+`/calculators` discovery with preference schemas; flat `calculator_type`/`calculator_preferences` params; prefixed `tax_category_id`/`delivery_zone_ids`) + `delivery_zones` CRUD (typed members by `country_iso`/`state_abbr`/postal prefix-or-range; `members` replaces the set atomically). Store `delivery_methods` discovery (`storefront_visible` scope, `fulfillment_type` filter) + `/:id/pickup_locations` (pickup-enabled stock locations, `cart_id` narrows to full-cart local coverage) + `/:id/pickup_points?latitude&longitude` via `DeliveryMethod#pickup_point_provider_instance`. Cart pickup selection: `preferred_stock_location_id` — **a preference (`preference :stock_location_id`), not a column (Damian 2026-07-29)** — prefixed-ID writer validating pickup_enabled, copied to the order column at completion; `pickup_point_external_id` on cart fulfillment update validated via provider and frozen into `pickup_point_data`. FulfillmentSerializer: `status` column-backed, `fulfillment_type` column-with-fallback, `pickup_point_data` + `selected_delivery_rate_id` exposed, real-name associations. Admin orders scope excludes transient completion drafts (`draft` + `cart_id` set). `AppliedPromotionSerializer` rename frees `DiscountSerializer` (+`TaxLine`/`Fee`/`DeliveryZone`/`DeliveryZoneMember` serializers, registry keys, payment-session serializer gets `cart_id` + owner-bridged `order_id`). `ConfigurationManagement` grants DeliveryMethod/DeliveryZone/Member.
**Directives landed mid-wave (Damian):** (1) `market` + `channel` **required** on Cart AND Order (`belongs_to` without optional). Supporting invariant: **every store owns a bootstrap default market** — `Stores::Markets#ensure_default_market` is unconditional (country fallback: creation param → legacy default_country column → US, created if the countries table is empty), inherits the store's column configuration (currency/locale/supported_locales), and is flagged `bootstrap_default` so the MarketCountry shipping-coverage validation skips it (plus a `DeliveryMethod.none?` bootstrap exemption). Store column edits to default_locale/default_currency **sync onto the default market** (diff-based, not dirty-tracking); `supported_currencies_list`/`supported_locales_list` are now the **union of markets + legacy columns**; `Market#ensure_single_default` resets the owning store's association caches; markets cascade-delete with their store via `destroyed_by_association`; `Current.market` always resolves. `defined_preferences` no longer picks up `preferred_*` association writers (Order#preferred_stock_location= phantom), preference readers/writers tolerate NULL preferences columns. (2) **Promotion STI namespace rename REVERTED** — classes stay `Spree::Promotion::Rules::*`/`Spree::Promotion::Actions::*` incl. `CreateItemAdjustments` (typed-Discount behavior under legacy names; wire type back to `create_item_adjustments`; single calculator registry key; T7.5 type-column task dropped; decisions.md 2026-03-16 marked reversed). (3) Cart totals columns get **DB-level defaults** (0/0.0) in migration 100001; dummy apps rebuilt. (4) `preferred_stock_location_id` on Cart is a **preference** (`preference :stock_location_id`), not a column — migration dropped. (5) `docs/developer` updates skipped (full Spree 6 docs rewrite comes separately).
diff --git a/packages/admin-sdk/src/types/generated/Cart.ts b/packages/admin-sdk/src/types/generated/Cart.ts
index 850553ba8f..5cecf3ff5d 100644
--- a/packages/admin-sdk/src/types/generated/Cart.ts
+++ b/packages/admin-sdk/src/types/generated/Cart.ts
@@ -1,4 +1,4 @@
-// Typelizer digest f4a041b4f1727c26dec5d12359219518
+// Typelizer digest 2557adc5a29a1a4d28e7906e5cc35332
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {LineItem, Address, Market, AppliedPromotion} from '@/types'
@@ -41,7 +41,7 @@ interface Cart {
covered_by_store_credit: boolean;
current_step: string;
completed_steps: Array<string>;
- requirements: Array<{step: string, field: string, message: string}>;
+ requirements: Array<{step: string, field: string, code: string, message: string}>;
shipping_eq_billing_address: boolean;
items: Array<LineItem>;
billing_address: Address | null;
diff --git a/packages/sdk/src/types/generated/Cart.ts b/packages/sdk/src/types/generated/Cart.ts
index cb64f9dfe5..b33257ebfc 100644
--- a/packages/sdk/src/types/generated/Cart.ts
+++ b/packages/sdk/src/types/generated/Cart.ts
@@ -1,4 +1,4 @@
-// Typelizer digest 33c04dc6c5d4bc56f52a6833f901a5fd
+// Typelizer digest 29e31fed91907dd0ccb46f7d0e051df2
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
import type {AppliedPromotion, LineItem, Fulfillment, Payment, Address, PaymentMethod, GiftCard, Market} from '@/types'
@@ -41,7 +41,7 @@ interface Cart {
covered_by_store_credit: boolean;
current_step: string;
completed_steps: Array<string>;
- requirements: Array<{step: string, field: string, message: string}>;
+ requirements: Array<{step: string, field: string, code: string, message: string}>;
shipping_eq_billing_address: boolean;
discounts: Array<AppliedPromotion>;
items: Array<LineItem>;
diff --git a/packages/sdk/src/zod/generated/Cart.ts b/packages/sdk/src/zod/generated/Cart.ts
index 747f8802da..e14f03cc80 100644
--- a/packages/sdk/src/zod/generated/Cart.ts
+++ b/packages/sdk/src/zod/generated/Cart.ts
@@ -47,7 +47,7 @@ export const CartSchema = z.object({
covered_by_store_credit: z.boolean(),
current_step: z.string(),
completed_steps: z.array(z.string()),
- requirements: z.array(z.object({ step: z.string(), field: z.string(), message: z.string() })),
+ requirements: z.array(z.object({ step: z.string(), field: z.string(), code: z.string(), message: z.string() })),
shipping_eq_billing_address: z.boolean(),
discounts: z.array(AppliedPromotionSchema),
items: z.array(LineItemSchema),
diff --git a/spree/api/app/serializers/spree/api/v3/cart_serializer.rb b/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
index 2d3cfb64bc..c50f07d89a 100644
--- a/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/cart_serializer.rb
@@ -8,7 +8,7 @@ module Spree
customer_note: [:string, nullable: true], market_id: [:string, nullable: true], channel_id: [:string, nullable: true],
currency: :string, locale: [:string, nullable: true], total_quantity: :number,
coupon_code: [:string, nullable: true],
- requirements: 'Array<{step: string, field: string, message: string}>',
+ requirements: 'Array<{step: string, field: string, code: string, message: string}>',
item_total: [:string, nullable: true], display_item_total: [:string, nullable: true],
delivery_total: [:string, nullable: true], display_delivery_total: [:string, nullable: true],
adjustment_total: [:string, nullable: true], display_adjustment_total: [:string, nullable: true],
diff --git a/spree/core/app/models/concerns/spree/purchase/checkout_steps.rb b/spree/core/app/models/concerns/spree/purchase/checkout_steps.rb
index acaa50e7f4..eede340520 100644
--- a/spree/core/app/models/concerns/spree/purchase/checkout_steps.rb
+++ b/spree/core/app/models/concerns/spree/purchase/checkout_steps.rb
@@ -7,14 +7,13 @@ module Spree
# (payment_required?/confirmation_required?) live in
# {Spree::Purchase::PaymentProcessing}.
module CheckoutSteps
+ # The Registry owns the step vocabulary and applicability — built-in
+ # and registered custom steps alike (see
+ # Spree::Checkout::Registry.base_steps / .register_step).
+ #
# @return [Array<String>]
def checkout_steps
- steps = ['address']
- steps << 'delivery' if delivery_required?
- steps << 'payment' if payment_required?
- steps << 'confirm' if confirmation_required?
- steps << 'complete'
- steps
+ Spree::Checkout::Registry.step_names_for(self)
end
# @param step [String, Symbol]
diff --git a/spree/core/app/models/spree/checkout/default_requirements.rb b/spree/core/app/models/spree/checkout/default_requirements.rb
index 7b3ccfb087..310577ad93 100644
--- a/spree/core/app/models/spree/checkout/default_requirements.rb
+++ b/spree/core/app/models/spree/checkout/default_requirements.rb
@@ -3,7 +3,10 @@ module Spree
# Built-in checkout requirements that map to the standard Spree checkout flow.
#
# Checks line items, email, shipping address, shipping method, and payment
- # against the cart — checkout is a cart-phase concern.
+ # against the cart — checkout is a cart-phase concern. The heavier
+ # completion-only checks (per-item stock, discontinued products, guest
+ # policy) run only when +completion: true+ is passed, so the advisory
+ # requirements feed on cart reads stays cheap.
#
# @see Requirements
class DefaultRequirements
@@ -12,9 +15,19 @@ module Spree
@cart = cart
end
- # @return [Array<Hash{Symbol => String}>] unmet default requirements as
- # +{ step:, field:, message: }+ hashes
- def call
+ # @param completion [Boolean] include the completion-only checks
+ # @return [Array<Hash{Symbol => String}>] unmet requirements as
+ # +{ step:, field:, code:, message: }+ hashes
+ def call(completion: false)
+ requirements = advisory_requirements
+ return requirements unless completion
+
+ requirements + completion_requirements
+ end
+
+ private
+
+ def advisory_requirements
[].tap do |r|
r << req('cart', 'line_items', Spree.t('checkout_requirements.line_items_required')) unless @cart.line_items.any?
r << req('address', 'email', Spree.t('checkout_requirements.email_required')) unless @cart.email.present?
@@ -24,7 +37,21 @@ module Spree
end
end
- private
+ def completion_requirements
+ errors = stock_errors
+ errors << req('address', 'email', Spree.t(:guest_checkout_not_allowed), code: 'guest_checkout_not_allowed') if @cart.guest_checkout_disallowed?
+ errors
+ end
+
+ def stock_errors
+ @cart.line_items.includes(variant: :product).filter_map do |line_item|
+ if line_item.variant.product.discontinued?
+ req('cart', 'line_items', Spree.t('cart_line_item.discontinued', li_name: line_item.name), code: 'discontinued')
+ elsif !line_item.sufficient_stock?
+ req('cart', 'line_items', Spree.t('cart_line_item.out_of_stock', li_name: line_item.name), code: 'out_of_stock')
+ end
+ end
+ end
def delivery_required?
@cart.delivery_required?
@@ -42,8 +69,8 @@ module Spree
@cart.payments.valid.any?
end
- def req(step, field, message)
- { step: step, field: field, message: message }
+ def req(step, field, message, code: nil)
+ { step: step, field: field, code: code || "#{field}_required", message: message }
end
end
end
diff --git a/spree/core/app/models/spree/checkout/registry.rb b/spree/core/app/models/spree/checkout/registry.rb
index 440462fcaf..e4f7aaead0 100644
--- a/spree/core/app/models/spree/checkout/registry.rb
+++ b/spree/core/app/models/spree/checkout/registry.rb
@@ -69,18 +69,59 @@ module Spree
requirements.reject! { |r| r.step == step.to_s && r.field == field.to_s }
end
- # Canonical ordered list of built-in checkout step names, used to
- # resolve +before:+/+after:+ anchors. The registry owns this list —
- # installs that reorder or remove built-in steps set it directly
- # (+base_step_names=+) instead of customizing the removed
- # +checkout_flow+ state machine API.
+ # Canonical ordered built-in steps with their applicability — the ONE
+ # place the step vocabulary is declared. Keys are step names, values
+ # are nil (always applicable) or a lambda receiving the cart/order.
+ # Installs customize it directly:
#
+ # Spree::Checkout::Registry.base_steps['payment'] = ->(cart) { cart.total > 0 }
+ # Spree::Checkout::Registry.base_steps.delete('confirm')
+ #
+ # @return [Hash{String => Proc, nil}]
+ def base_steps
+ @base_steps ||= {
+ 'address' => nil,
+ 'delivery' => ->(record) { record.delivery_required? },
+ 'payment' => ->(record) { record.payment_required? },
+ 'confirm' => ->(record) { record.confirmation_required? },
+ 'complete' => nil
+ }
+ end
+
# @return [Array<String>]
def base_step_names
- @base_step_names ||= %w[address delivery payment confirm complete]
+ base_steps.keys
end
- attr_writer :base_step_names
+ # Reorder/remove built-in steps by name; known steps keep their
+ # default applicability.
+ #
+ # @param names [Array<String>]
+ def base_step_names=(names)
+ defaults = base_steps
+ @base_steps = names.map(&:to_s).index_with { |name| defaults[name] }
+ end
+
+ # The full ordered step list for a record: applicable base steps with
+ # applicable registered custom steps spliced at their before/after
+ # anchors (unanchored customs land before 'complete').
+ #
+ # @param record [Spree::Cart, Spree::Order]
+ # @return [Array<String>]
+ def step_names_for(record)
+ names = base_steps.filter_map do |name, applicable|
+ name if applicable.nil? || applicable.call(record)
+ end
+
+ ordered_steps.each do |step|
+ next unless step.applicable?(record)
+
+ anchor_index = names.index(step.before) || (names.index(step.after)&.+ 1)
+ names.insert(anchor_index || names.index('complete') || names.length, step.name)
+ end
+
+ names.uniq
+ end
# Returns steps sorted by +before+/+after+ constraints relative to
# {base_step_names}. Steps with anchors are ordered by the anchor's
@@ -115,7 +156,7 @@ module Spree
def reset!
@steps = []
@requirements = []
- @base_step_names = nil
+ @base_steps = nil
end
end
end
diff --git a/spree/core/app/models/spree/checkout/requirements.rb b/spree/core/app/models/spree/checkout/requirements.rb
index 0b902256f4..f2b410022c 100644
--- a/spree/core/app/models/spree/checkout/requirements.rb
+++ b/spree/core/app/models/spree/checkout/requirements.rb
@@ -1,17 +1,20 @@
module Spree
module Checkout
- # Aggregates all checkout requirements for a cart.
- #
- # Combines built-in checks from {DefaultRequirements} with custom steps and
- # requirements registered in {Registry}. The resulting array of hashes is
- # exposed on the Cart API as the +requirements+ attribute.
+ # Aggregates all checkout requirements for a cart — the single source of
+ # truth for "what does this cart still need". Combines built-in checks
+ # from {DefaultRequirements} with custom steps and requirements
+ # registered in {Registry}. The resulting array of hashes is exposed on
+ # the Cart API as the +requirements+ attribute; with +completion: true+
+ # it includes the heavier completion-only checks (stock, discontinued,
+ # guest policy) and is exactly what Spree::Carts::Complete gates
+ # completion on.
#
# Each requirement hash has the shape:
- # { step: String, field: String, message: String }
+ # { step: String, field: String, code: String, message: String }
#
# @example
# reqs = Spree::Checkout::Requirements.new(cart)
- # reqs.call # => [{ step: "address", field: "email", message: "Email address is required" }]
+ # reqs.call # => [{ step: "address", field: "email", code: "email_required", message: "Email address is required" }]
# reqs.met? # => false
class Requirements
# @param cart [Spree::Cart]
@@ -19,9 +22,11 @@ module Spree
@cart = cart
end
+ # @param completion [Boolean] include the completion-only checks
# @return [Array<Hash{Symbol => String}>] all unmet requirements
- def call
- default + from_registered_steps + from_additional_requirements
+ def call(completion: false)
+ requirements = default(completion: completion) + from_registered_steps + from_additional_requirements
+ requirements.map { |requirement| { code: "#{requirement[:field]}_required" }.merge(requirement) }
end
# @return [Boolean] true when all requirements are satisfied
@@ -32,8 +37,8 @@ module Spree
private
# @return [Array<Hash>] built-in checkout requirements
- def default
- DefaultRequirements.new(@cart).call
+ def default(completion:)
+ DefaultRequirements.new(@cart).call(completion: completion)
end
# @return [Array<Hash>] requirements from unsatisfied registered steps
diff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rb
index e3b9f663ac..6f463d41b2 100644
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@ -644,34 +644,11 @@ module Spree
# Finalizes an in progress order after checkout is complete.
# Called after transition to complete state when payments will have been processed
+ # @deprecated Completion lives in {Spree::Orders::Complete} (checkout
+ # reaches it through +Spree.carts_complete_workflow+). Removed in 6.1.
def finalize!
- # Typed adjustment rows are frozen once completed — the totals
- # recalculation only re-sums them, never regenerates (see
- # Spree::Carts::RecalculateTotals) — so no per-row locking is needed.
-
- fulfillments.each do |shipment|
- shipment.update!(self)
- shipment.finalize!
- end
-
- self.status = 'placed'
- save!
- update_hooks.each { |hook| send(hook) }
-
- touch :completed_at
-
- # Completion side effects — each guards its own idempotency. The
- # customer-facing ones (newsletter, account creation, risk) live in
- # Spree::OrderPlacedSubscriber, triggered by the order.placed event
- # published below.
- use_all_coupon_codes
- redeem_gift_card
-
- Spree::Fulfillments::AutoFulfill.call(order: self)
-
- update_statuses!
-
- publish_order_placed_event
+ Spree::Deprecation.warn('Spree::Order#finalize! is deprecated and will be removed in Spree 6.1. Completion runs through Spree.order_complete_workflow (Spree::Orders::Complete).')
+ Spree.order_complete_workflow.call(order: self, payment_pending: true)
end
def fulfill!
@@ -1125,13 +1102,5 @@ module Spree
end
end
- def publish_order_placed_event
- payload = event_payload.merge(notify_customer: notify_customer)
- publish_event('order.placed', payload)
- # One-release alias for 5.x webhook consumers; removed in 6.1.
- # Wildcard subscribers dedupe on the metadata marker.
- publish_event('order.completed', payload, { deprecated_alias_of: 'order.placed' })
- end
-
end
end
diff --git a/spree/core/app/services/spree/carts/update.rb b/spree/core/app/services/spree/carts/update.rb
index d433da3754..0359f33a92 100644
--- a/spree/core/app/services/spree/carts/update.rb
+++ b/spree/core/app/services/spree/carts/update.rb
@@ -13,6 +13,7 @@ module Spree
clear_shipping_address_if_outside_market
assign_address(:shipping_address)
assign_address(:billing_address)
+ assign_default_addresses
cart.save!
@@ -83,6 +84,16 @@ module Spree
raise StandardError, result.error.to_s if result.failure?
end
+ # Legacy `before_transition to: :address` parity: once a signed-in
+ # customer is in checkout, blank address slots fill from their saved
+ # defaults (assign_default_addresses! guards each slot itself).
+ def assign_default_addresses
+ return unless cart.user
+ return unless cart.email.present? || cart.ship_address_id.present?
+
+ cart.assign_default_addresses!
+ end
+
def resolve_address_id(prefixed_id)
return unless cart.user
diff --git a/spree/core/app/services/spree/carts/validate.rb b/spree/core/app/services/spree/carts/validate.rb
deleted file mode 100644
index 69db35cc9b..0000000000
--- a/spree/core/app/services/spree/carts/validate.rb
+++ /dev/null
@@ -1,51 +0,0 @@
-module Spree
- module Carts
- # The full completion battery, returning structured per-field errors with
- # stable codes: { step:, field:, code:, message: }. Also exposed read-only
- # so storefronts can render checkout readiness without attempting
- # completion.
- class Validate
- prepend Spree::ServiceModule::Base
-
- def call(cart:)
- errors = errors_for(cart)
- errors.empty? ? success(cart) : failure(cart, errors)
- end
-
- # @return [Array<Hash>] structured errors; empty when the cart can complete
- def errors_for(cart)
- errors = Spree::Checkout::Requirements.new(cart).call.map do |requirement|
- requirement.merge(code: code_for(requirement))
- end
-
- errors.concat(stock_errors(cart))
- errors << guest_policy_error(cart) if cart.guest_checkout_disallowed?
- errors.compact
- end
-
- private
-
- def code_for(requirement)
- "#{requirement[:field]}_required"
- end
-
- def stock_errors(cart)
- cart.line_items.includes(variant: :product).filter_map do |line_item|
- if line_item.variant.product.discontinued?
- error('cart', 'line_items', 'discontinued', Spree.t('cart_line_item.discontinued', li_name: line_item.name))
- elsif !line_item.sufficient_stock?
- error('cart', 'line_items', 'out_of_stock', Spree.t('cart_line_item.out_of_stock', li_name: line_item.name))
- end
- end
- end
-
- def guest_policy_error(cart)
- error('address', 'email', 'guest_checkout_not_allowed', Spree.t(:guest_checkout_not_allowed))
- end
-
- def error(step, field, code, message)
- { step: step, field: field, code: code, message: message }
- end
- end
- end
-end
diff --git a/spree/core/app/services/spree/fulfillments/auto_fulfill.rb b/spree/core/app/services/spree/fulfillments/auto_fulfill.rb
deleted file mode 100644
index 6fc4270a05..0000000000
--- a/spree/core/app/services/spree/fulfillments/auto_fulfill.rb
+++ /dev/null
@@ -1,36 +0,0 @@
-module Spree
- module Fulfillments
- # Fires providers that auto-fulfill on completion (digital delivery):
- # forces each auto-fulfill fulfillment to ready and fulfills it through
- # the machine so all hooks (links, events, webhooks) run. Line items
- # with digital assets that ship through other providers (physical +
- # download combos) still get their links, idempotently and per
- # quantity. Runs during finalize, before the confirmation email
- # subscriber reads the links.
- class AutoFulfill
- prepend Spree::ServiceModule::Base
-
- def call(order:)
- handled_line_item_ids = []
-
- order.fulfillments.reload.each do |fulfillment|
- next unless fulfillment.provider.auto_fulfill?
- next if fulfillment.fulfilled? || fulfillment.canceled?
-
- fulfillment.update_columns(status: 'ready', updated_at: Time.current) unless fulfillment.ready?
- fulfillment.fulfill!
- handled_line_item_ids.concat(fulfillment.line_items.map(&:id))
- end
-
- return success(order) unless order.with_digital_assets?
-
- provider = Spree::FulfillmentProvider::Digital.new
- order.digital_line_items.where.not(id: handled_line_item_ids).includes(variant: :digitals).each do |line_item|
- provider.ensure_links_for(line_item)
- end
-
- success(order)
- end
- end
- end
-end
diff --git a/spree/core/app/services/spree/orders/complete.rb b/spree/core/app/services/spree/orders/complete.rb
deleted file mode 100644
index e0d988ee50..0000000000
--- a/spree/core/app/services/spree/orders/complete.rb
+++ /dev/null
@@ -1,27 +0,0 @@
-module Spree
- module Orders
- # Admin-side completion of a draft order, sharing finalize semantics with
- # cart checkout (idempotency, inventory finalization, reservation release).
- #
- # @param order [Spree::Order]
- # @param payment_pending [Boolean] if true, completes the order without
- # processing payments. Order is placed but `payment_status` may be
- # 'balance_due'. Useful for B2B / invoice-later flows.
- # @param notify_customer [Boolean] if true, the customer receives the
- # standard order confirmation email. Defaults to false — admin orders
- # complete silently unless explicitly opted in.
- # @return [Spree::ServiceModule::Result]
- class Complete
- prepend Spree::ServiceModule::Base
-
- def call(order:, payment_pending: false, notify_customer: false)
- order.notify_customer = notify_customer
-
- Spree::Dependencies.carts_complete_workflow.constantize.call(
- cart: order,
- payment_pending: payment_pending
- )
- end
- end
- end
-end
diff --git a/spree/core/app/workflows/spree/carts/complete.rb b/spree/core/app/workflows/spree/carts/complete.rb
index 360156889e..141366d9a9 100644
--- a/spree/core/app/workflows/spree/carts/complete.rb
+++ b/spree/core/app/workflows/spree/carts/complete.rb
@@ -62,37 +62,25 @@ module Spree
private
- # Admin/B2B draft orders bypass the cart but reuse the same finalize
- # semantics (idempotency + inventory + reservation release in one home).
+ # Admin/B2B draft orders bypass the cart — the order-side completion
+ # workflow (Spree::Orders::Complete) owns that path end to end.
def complete_draft_order
- order = cart
- halt!(order) if order.completed?
- failure(order, 'Order is canceled') if order.canceled?
-
- order.with_lock do
- skip_payments = payment_pending || !order.payment_required?
- order.process_payments! if !skip_payments && !payment_covered?(order)
-
- failure(order, order.errors.full_messages.to_sentence) if order.errors.any?
- failure(order, Spree.t(:payment_processing_failed)) if !skip_payments && !payment_covered?(order)
-
- order.finalize! unless order.completed?
- Spree::StockReservations::Release.call(owner: order)
- order.update_statuses!
- end
-
- halt!(order)
+ result = Spree.order_complete_workflow.call(order: cart, payment_pending: payment_pending)
+ failure(result.value, result.error) if result.failure?
+ halt!(result.value)
end
- # A draft here means a previous attempt died mid-pipeline — re-verify
- # payment coverage, then re-run FINALIZE (idempotent).
+ # An existing order here means a previous attempt died mid-pipeline —
+ # re-verify payment coverage on drafts, then re-run FINALIZE
+ # (idempotent, and the only healer for the crash window between the
+ # order commit and the cart stamp).
def replay_completed
order = completion_result(cart)
return if order.nil?
- halt!(order) if order.placed? || order.canceled?
+ halt!(order) if order.canceled?
- if order.payment_required? && !payment_covered?(order)
+ if !order.placed? && order.payment_required? && !payment_covered?(order)
failure(cart, code: 'payment_failed', message: Spree.t(:payment_processing_failed))
end
@@ -117,7 +105,7 @@ module Spree
end
def validate_cart
- validation = Spree::Carts::Validate.new.errors_for(cart)
+ validation = Spree::Checkout::Requirements.new(cart).call(completion: true)
failure(cart, code: 'validation_failed', errors: validation) if validation.any?
end
@@ -296,18 +284,22 @@ module Spree
order.payments.valid.where(state: %w[pending processing completed]).sum(:amount) >= order.total
end
+ # The FINALIZE phase: the order-side completion workflow owns the
+ # placement side effects; the two cart-side stamps follow.
def finalize!(cart, order)
- ApplicationRecord.transaction do
- order.finalize! unless order.placed?
- order.update_columns(status: 'placed') unless order.reload.placed?
- cart.update_columns(completed_at: Time.current, completing_at: nil)
- end
- Spree::StockReservations::Release.call(owner: order)
- order.update_statuses!
- mark_coupon_codes_used!(cart, order)
+ @order = order
+ step :complete_order, with: -> { Spree.order_complete_workflow }
+ step :complete_cart
+ step :mark_coupon_codes_used
+ end
+
+ def complete_cart
+ return if cart.completed?
+
+ cart.update_columns(completed_at: Time.current, completing_at: nil)
end
- def mark_coupon_codes_used!(_cart, order)
+ def mark_coupon_codes_used
Spree::CouponCode.where(order_id: order.id).unused.update_all(state: 1)
end
end
diff --git a/spree/core/app/workflows/spree/orders/complete.rb b/spree/core/app/workflows/spree/orders/complete.rb
new file mode 100644
index 0000000000..75b64bf835
--- /dev/null
+++ b/spree/core/app/workflows/spree/orders/complete.rb
@@ -0,0 +1,140 @@
+module Spree
+ module Orders
+ # The order-side completion workflow — the ONE home for everything that
+ # happens when an order becomes placed. Serves both entry points:
+ # checkout ({Spree::Carts::Complete} delegates its FINALIZE phase here
+ # with payments already captured) and admin/B2B draft completion (which
+ # may still need to process payments). Idempotent: an already-placed
+ # order halts successfully, so interrupted completions replay safely.
+ class Complete < Spree::Workflow
+ # @param order [Spree::Order]
+ # @param payment_pending [Boolean] when true the order places without
+ # processing payments (B2B / invoice-later) — payment_status stays
+ # 'balance_due'
+ # @param notify_customer [Boolean, nil] admin drafts pass false to
+ # complete silently; nil (checkout) leaves customer notification on
+ def perform(order:, payment_pending: false, notify_customer: nil)
+ super
+
+ order.notify_customer = notify_customer unless notify_customer.nil?
+
+ halt!(order) if order.completed?
+ step :ensure_not_canceled
+
+ order.with_lock do
+ unless order.reload.placed?
+ step :process_payments unless payment_pending || !order.payment_required?
+ step :finalize_fulfillments
+ step :place_order
+ step :use_coupon_codes
+ step :redeem_gift_card
+ step :fulfill_auto_fulfillments
+ step :ensure_digital_links
+ end
+ end
+
+ step :ensure_placed_status
+ step :release_stock_reservations
+ step :update_statuses
+ step :publish_order_placed
+
+ success(order)
+ end
+
+ private
+
+ def ensure_not_canceled
+ failure(order, 'Order is canceled') if order.canceled?
+ end
+
+ def process_payments
+ order.process_payments! unless payment_covered?
+
+ failure(order, order.errors.full_messages.to_sentence) if order.errors.any?
+ failure(order, Spree.t(:payment_processing_failed)) unless payment_covered?
+ end
+
+ # Typed adjustment rows are frozen once completed — the totals
+ # recalculation only re-sums them, never regenerates (see
+ # Spree::Carts::RecalculateTotals) — so no per-row locking is needed.
+ def finalize_fulfillments
+ order.fulfillments.each do |fulfillment|
+ fulfillment.update!(order)
+ fulfillment.finalize!
+ end
+ end
+
+ def place_order
+ order.update!(status: 'placed', completed_at: Time.current)
+ end
+
+ def use_coupon_codes
+ Spree::CouponCodes::CouponCodesHandler.new(order: order).use_all_codes
+ end
+
+ def redeem_gift_card
+ return if order.gift_card.nil?
+
+ Spree.gift_card_redeem_service.call(gift_card: order.gift_card)
+ end
+
+ # Providers that opt into auto_fulfill? (digital delivery today) get
+ # forced to ready and fulfilled through the machine so all hooks
+ # (links, events, webhooks) run.
+ def fulfill_auto_fulfillments
+ @auto_fulfilled_line_item_ids = []
+
+ order.fulfillments.reload.each do |fulfillment|
+ next unless fulfillment.provider.auto_fulfill?
+ next if fulfillment.fulfilled? || fulfillment.canceled?
+
+ fulfillment.update_columns(status: 'ready', updated_at: Time.current) unless fulfillment.ready?
+ fulfillment.fulfill!
+ @auto_fulfilled_line_item_ids.concat(fulfillment.line_items.map(&:id))
+ end
+ end
+
+ # Digital links for items delivered by non-digital providers (physical
+ # + download combos) — links are a digital-domain concern regardless of
+ # the carrier; idempotent per quantity. Runs before the confirmation
+ # email subscriber reads the links.
+ def ensure_digital_links
+ return unless order.with_digital_assets?
+
+ provider = Spree::FulfillmentProvider::Digital.new
+ order.digital_line_items.where.not(id: @auto_fulfilled_line_item_ids).includes(variant: :digitals).each do |line_item|
+ provider.ensure_links_for(line_item)
+ end
+ end
+
+ # Belt-and-braces for a completion interrupted between save and commit
+ # in an earlier attempt.
+ def ensure_placed_status
+ order.update_columns(status: 'placed') unless order.reload.placed?
+ end
+
+ def release_stock_reservations
+ Spree::StockReservations::Release.call(owner: order)
+ end
+
+ def update_statuses
+ Spree::Orders::UpdateStatuses.call(order: order)
+ end
+
+ # The customer-facing side effects (newsletter, account creation, risk)
+ # live in Spree::OrderPlacedSubscriber, triggered by this event.
+ # order.completed is a one-release alias for 5.x webhook consumers;
+ # wildcard subscribers dedupe on the metadata marker.
+ def publish_order_placed
+ payload = order.event_payload.merge(notify_customer: order.notify_customer)
+ order.publish_event('order.placed', payload)
+ order.publish_event('order.completed', payload, { deprecated_alias_of: 'order.placed' })
+ end
+
+ def payment_covered?
+ order.payments.reset
+ order.payments.valid.where(state: %w[pending processing completed]).sum(:amount) >= order.total
+ end
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/dependencies.rb b/spree/core/lib/spree/core/dependencies.rb
index 0e38d6d396..4b68b8f5a3 100644
--- a/spree/core/lib/spree/core/dependencies.rb
+++ b/spree/core/lib/spree/core/dependencies.rb
@@ -36,7 +36,6 @@ module Spree
carts_create_service: 'Spree::Carts::Create',
carts_update_service: 'Spree::Carts::Update',
carts_upsert_items_service: 'Spree::Carts::UpsertItems',
- carts_validate_service: 'Spree::Carts::Validate',
cart_merge_strategy: 'Spree::Carts::Merge',
# checkout
@@ -56,7 +55,7 @@ module Spree
order_approve_service: 'Spree::Orders::Approve',
order_cancel_workflow: 'Spree::Orders::Cancel',
order_resume_workflow: 'Spree::Orders::Resume',
- order_complete_service: 'Spree::Orders::Complete',
+ order_complete_workflow: 'Spree::Orders::Complete',
order_discount_create_service: 'Spree::Orders::Discounts::Create',
order_discount_update_service: 'Spree::Orders::Discounts::Update',
order_discount_destroy_service: 'Spree::Orders::Discounts::Destroy',
@@ -140,7 +139,8 @@ module Spree
cart_add_item_service: :cart_add_item_workflow,
cart_recalculate_service: :cart_recalculate_workflow,
carts_complete_service: :carts_complete_workflow,
- order_cancel_service: :order_cancel_workflow
+ order_cancel_service: :order_cancel_workflow,
+ order_complete_service: :order_complete_workflow
}.freeze
# Same stash-don't-apply treatment for the 6.0 Shipment→Fulfillment
diff --git a/spree/core/spec/models/spree/order/finalizing_spec.rb b/spree/core/spec/models/spree/order/finalizing_spec.rb
deleted file mode 100644
index 20a2fb3175..0000000000
--- a/spree/core/spec/models/spree/order/finalizing_spec.rb
+++ /dev/null
@@ -1,90 +0,0 @@
-require 'spec_helper'
-
-describe Spree::Order, type: :model do
- let(:store) { @default_store }
- let(:order) { create(:order, store: store) }
-
- context '#finalize!' do
- let(:order) { Spree::Order.create(email: '[email protected]') }
-
- before do
- order.update_columns(completed_at: Time.current, status: 'placed')
- end
-
- after { Spree::Config.set track_inventory_levels: true }
-
- it 'sets completed_at' do
- expect(order).to receive(:touch).with(:completed_at)
- order.finalize!
- end
-
- it 'sells inventory units' do
- order.shipments.each do |shipment| # rubocop:disable RSpec/IteratedExpectation
- expect(shipment).to receive(:update!)
- expect(shipment).to receive(:finalize!)
- end
- order.finalize!
- end
-
- it 'decreases the stock for each variant in the shipment' do
- order.shipments.each do |shipment|
- expect(shipment.stock_location).to receive(:decrease_stock_for_variant)
- end
- order.finalize!
- end
-
- it 'changes the shipment state to ready if order is paid' do
- Spree::Shipment.create(order: order, stock_location: create(:stock_location))
- order.shipments.reload
-
- allow(order).to receive_messages(paid?: true, complete?: true)
- order.finalize!
- order.reload # reload so we're sure the changes are persisted
- expect(order.shipment_state).to eq('ready')
- end
-
- it 'does not sell inventory units if track_inventory_levels is false' do
- Spree::Config.set track_inventory_levels: false
- expect(Spree::InventoryUnit).not_to receive(:sell_units)
- order.finalize!
- end
-
- it 'freezes adjustment recalculation (order-level freeze)' do
- order.finalize!
- expect(Spree::Adjusters::Promotion).not_to receive(:adjust)
- order.recalculate_totals!
- end
-
- context 'order is considered risky' do
- before do
- allow_any_instance_of(Spree::Order).to receive_messages(is_risky?: true)
- end
-
- it 'changes state to risky', :events do
- expect { order.finalize! }.to change { order.reload.considered_risky }.to(true)
- end
-
- context 'and order is approved' do
- before do
- allow(order).to receive_messages approved?: true
- end
-
- it 'leaves order in complete state' do
- order.finalize!
- expect(order.status).to eq 'placed'
- end
- end
- end
-
- context 'order is not considered risky' do
- before do
- allow(order).to receive_messages is_risky?: false
- end
-
- it 'sets completed_at' do
- order.finalize!
- expect(order.completed_at).to be_present
- end
- end
- end
-end
diff --git a/spree/core/spec/models/spree/order_spec.rb b/spree/core/spec/models/spree/order_spec.rb
index d64adad4ad..ea97a115e6 100644
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@ -317,102 +317,6 @@ describe Spree::Order, type: :model do
end
end
- describe '#finalize!' do
- let(:order) { Spree::Order.create(email: '[email protected]', store: store) }
-
- before do
- order.update_columns(completed_at: Time.current, status: 'placed')
- end
-
- after { Spree::Config.set track_inventory_levels: true }
-
- it 'sets completed_at' do
- expect(order).to receive(:touch).with(:completed_at)
- order.finalize!
- end
-
- it 'sells inventory units' do
- order.shipments.each do |shipment| # rubocop:disable RSpec/IteratedExpectation
- expect(shipment).to receive(:update!)
- expect(shipment).to receive(:finalize!)
- end
- order.finalize!
- end
-
- it 'decreases the stock for each variant in the shipment' do
- order.shipments.each do |shipment|
- expect(shipment.stock_location).to receive(:decrease_stock_for_variant)
- end
- order.finalize!
- end
-
- it 'changes the shipment state to ready if order is paid' do
- Spree::Shipment.create(order: order, stock_location: create(:stock_location))
- order.shipments.reload
-
- allow(order).to receive_messages(paid?: true, complete?: true)
- order.finalize!
- order.reload # reload so we're sure the changes are persisted
- expect(order.shipment_state).to eq('ready')
- end
-
- it 'does not sell inventory units if track_inventory_levels is false' do
- Spree::Config.set track_inventory_levels: false
- expect(Spree::InventoryUnit).not_to receive(:sell_units)
- order.finalize!
- end
-
- it 'freezes adjustment recalculation (order-level freeze)' do
- order.finalize!
- expect(Spree::Adjusters::Promotion).not_to receive(:adjust)
- order.recalculate_totals!
- end
-
- context 'order is considered risky' do
- before do
- allow_any_instance_of(Spree::Order).to receive_messages(is_risky?: true)
- end
-
- it 'changes state to risky', :events do
- expect { order.finalize! }.to change { order.reload.considered_risky }.to(true)
- end
-
- context 'and order is approved' do
- before do
- allow(order).to receive_messages approved?: true
- end
-
- it 'leaves the order placed' do
- order.finalize!
- expect(order.status).to eq 'placed'
- end
- end
- end
-
- context 'events', :events do
- let(:order) { create(:order_with_line_items, store: store) }
-
- before { order.update_columns(completed_at: Time.current, status: 'placed') }
-
- it 'publishes order.completed event' do
- expect(order).to receive(:publish_event).with('order.placed', hash_including(:notify_customer)).at_least(:once)
- expect(order).to receive(:publish_event).with('order.completed', hash_including(:notify_customer), { deprecated_alias_of: 'order.placed' }).at_least(:once)
- allow(order).to receive(:publish_event).with(anything)
- allow(order).to receive(:publish_event).with(anything, anything)
- order.finalize!
- end
-
- it 'enqueues RefreshMetricsJob for each product in the order' do
- product_count = order.line_items.map { |li| li.variant.product_id }.uniq.count
-
- expect do
- order.finalize!
- perform_enqueued_jobs(only: Spree::Events::SubscriberJob)
- end.to have_enqueued_job(Spree::Products::RefreshMetricsJob).exactly(product_count).times
- end
- end
- end
-
context 'insufficient_stock_lines' do
let(:line_item) { create(:line_item) }
@@ -585,24 +489,6 @@ describe Spree::Order, type: :model do
end
end
- context 'add_update_hook' do
- before do
- Spree::Order.class_eval do
- register_update_hook :add_awesome_sauce
- end
- end
-
- after do
- Spree::Order.update_hooks = Set.new
- end
-
- it 'calls hook during finalize' do
- order = create(:order)
- expect(order).to receive(:add_awesome_sauce)
- order.finalize!
- end
- end
-
describe '#tax_address' do
subject { order.tax_address }
diff --git a/spree/core/spec/services/spree/carts/update_spec.rb b/spree/core/spec/services/spree/carts/update_spec.rb
index ac153e861f..422586bde4 100644
--- a/spree/core/spec/services/spree/carts/update_spec.rb
+++ b/spree/core/spec/services/spree/carts/update_spec.rb
@@ -278,6 +278,44 @@ module Spree
end
end
+ describe 'default address filling on checkout entry' do
+ let(:default_bill) { create(:address, user: user) }
+ let(:default_ship) { create(:address, user: user) }
+ let(:cart) { create(:cart_with_line_items, customer: user, store: store) }
+
+ before { user.update!(bill_address: default_bill, ship_address: default_ship) }
+
+ it 'fills blank slots from the customer saved defaults once in checkout' do
+ described_class.call(cart: cart, params: { email: '[email protected]' })
+
+ expect(cart.reload.bill_address_id).to eq(default_bill.id)
+ expect(cart.ship_address_id).to eq(default_ship.id)
+ end
+
+ it 'never fills before checkout begins' do
+ described_class.call(cart: cart, params: { customer_note: 'gift please' })
+
+ expect(cart.reload.bill_address_id).to be_nil
+ expect(cart.ship_address_id).to be_nil
+ end
+
+ it 'does not overwrite an explicitly provided address' do
+ explicit = create(:address, user: user)
+ described_class.call(cart: cart, params: { email: '[email protected]', shipping_address_id: explicit.prefixed_id })
+
+ expect(cart.reload.ship_address_id).to eq(explicit.id)
+ expect(cart.bill_address_id).to eq(default_bill.id)
+ end
+
+ it 'does nothing for guest carts' do
+ guest_cart = create(:cart_with_line_items, store: store, customer: nil)
+
+ described_class.call(cart: guest_cart, params: { email: '[email protected]' })
+
+ expect(guest_cart.reload.ship_address_id).to be_nil
+ end
+ end
+
describe 'billing address does not reset checkout state' do
let(:country) { Spree::Country.find_by(iso: 'US') || create(:country, iso: 'US') }
let!(:state) { country.states.find_by(abbr: 'NY') || create(:state, country: country, abbr: 'NY', name: 'New York') }
diff --git a/spree/core/spec/workflows/spree/carts/complete_spec.rb b/spree/core/spec/workflows/spree/carts/complete_spec.rb
index 7fae2558ed..a6c4e45547 100644
--- a/spree/core/spec/workflows/spree/carts/complete_spec.rb
+++ b/spree/core/spec/workflows/spree/carts/complete_spec.rb
@@ -85,7 +85,6 @@ module Spree
describe 'guest checkout policy' do
it 'fails when the channel forbids guest checkout and the cart has no customer' do
- allow_any_instance_of(Spree::Checkout::Requirements).to receive(:call).and_return([])
allow_any_instance_of(Spree::Cart).to receive(:guest_checkout_disallowed?).and_return(true)
result = described_class.call(cart: ready_cart)
@@ -114,6 +113,125 @@ module Spree
expect(result).to be_success
expect(order.reload.completed_at).to be_present
end
+
+ it 'refuses a canceled draft order' do
+ order.update_columns(status: 'canceled', canceled_at: Time.current)
+
+ result = described_class.call(cart: order)
+ expect(result).to be_failure
+ expect(order.reload.completed_at).to be_nil
+ end
+ end
+
+ describe 'payment failure compensation' do
+ it 'rolls the draft order back and re-points money records to the cart' do
+ # A payment that never completes: processing is a no-op, so coverage
+ # stays below total and the pre-capture rollback arm fires.
+ allow_any_instance_of(Spree::Payment).to receive(:process!)
+ payment = ready_cart.payments.first
+
+ result = described_class.call(cart: ready_cart)
+
+ expect(result).to be_failure
+ expect(result.error.value[:code]).to eq('payment_failed')
+ expect(Spree::Order.where(cart_id: ready_cart.id)).to be_none
+ expect(payment.reload.cart_id).to eq(ready_cart.id)
+ expect(payment.order_id).to be_nil
+ expect(ready_cart.reload.completing_at).to be_nil
+ expect(ready_cart.completed_at).to be_nil
+ end
+ end
+
+ describe 'net-terms completion (payment_pending)' do
+ let(:uncovered_cart) { ::OrderWalkthrough.up_to(:payment, store) }
+
+ it 'does not waive the payment requirement on carts — net terms is a draft-order flow' do
+ result = described_class.call(cart: uncovered_cart, payment_pending: true)
+
+ expect(result).to be_failure
+ expect(result.error.value[:code]).to eq('validation_failed')
+ expect(result.error.value[:errors].map { |error| error[:code] }).to include('payment_required')
+ end
+
+ it 'completes without capturing when the payment is authorized but pending' do
+ uncovered_cart.payments.create!(payment_method: Spree::PaymentMethod.first, amount: uncovered_cart.total, state: 'pending')
+
+ result = described_class.call(cart: uncovered_cart, payment_pending: true)
+
+ expect(result).to be_success
+ expect(result.value.status).to eq('placed')
+ expect(result.value.payment_total).to eq(0)
+ end
+ end
+
+ describe 'crash-window replay' do
+ it 'heals a completion that died between the order commit and the cart stamp' do
+ order = described_class.call(cart: ready_cart).value
+ # Simulate the crash window: order placed, cart stamp lost
+ # (update_all — the readonly completed-cart guard blocks AR writes).
+ Spree::Cart.where(id: ready_cart.id).update_all(completed_at: nil, completing_at: Time.current)
+ crashed_cart = Spree::Cart.find(ready_cart.id)
+
+ result = described_class.call(cart: crashed_cart)
+
+ expect(result).to be_success
+ expect(result.value.id).to eq(order.id)
+ expect(crashed_cart.reload.completed_at).to be_present
+ expect(crashed_cart.completing_at).to be_nil
+ expect(Spree::Order.where(cart_id: crashed_cart.id).count).to eq(1)
+ end
+
+ it 'returns a canceled order from a previous completion without re-finalizing' do
+ order = described_class.call(cart: ready_cart).value
+ order.update_columns(status: 'canceled', canceled_at: Time.current)
+
+ result = described_class.call(cart: ready_cart.reload)
+
+ expect(result).to be_success
+ expect(result.value.status).to eq('canceled')
+ end
+ end
+
+ describe 'before_finalize hook' do
+ after { Spree.hooks.clear! }
+
+ it 'dispatches with the workflow instance before the order places' do
+ seen = nil
+ Spree.hooks.register('carts.complete.before_finalize') do |flow|
+ seen = { order_placed: flow.order.placed?, cart_id: flow.cart.id }
+ end
+
+ described_class.call(cart: ready_cart)
+
+ expect(seen).to eq(order_placed: false, cart_id: ready_cart.id)
+ end
+ end
+
+ describe 'coupon codes' do
+ it 're-points an applied cart coupon code to the order and marks it used' do
+ promotion = create(:promotion_with_item_adjustment, adjustment_rate: 2, kind: :coupon_code, store: store, multi_codes: true, number_of_codes: 1)
+ coupon_code = promotion.coupon_codes.first
+ coupon_code.update!(cart: ready_cart)
+ ready_cart.update_columns(coupon_code: coupon_code.code)
+
+ result = described_class.call(cart: ready_cart)
+
+ expect(result).to be_success
+ expect(coupon_code.reload.state).to eq('used')
+ expect(coupon_code.order_id).to eq(result.value.id)
+ expect(coupon_code.cart_id).to be_nil
+ end
+
+ it 'detaches codes whose promotion did not apply' do
+ promotion = create(:promotion, kind: :coupon_code, store: store)
+ coupon_code = create(:coupon_code, promotion: promotion, cart: ready_cart)
+
+ result = described_class.call(cart: ready_cart)
+
+ expect(result).to be_success
+ expect(coupon_code.reload.state).to eq('unused')
+ expect(coupon_code.order_id).to be_nil
+ end
end
end
end
diff --git a/spree/core/spec/workflows/spree/orders/complete_spec.rb b/spree/core/spec/workflows/spree/orders/complete_spec.rb
new file mode 100644
index 0000000000..9d6acf9556
--- /dev/null
+++ b/spree/core/spec/workflows/spree/orders/complete_spec.rb
@@ -0,0 +1,127 @@
+require 'spec_helper'
+
+module Spree
+ describe Orders::Complete do
+ let(:store) { @default_store }
+ let(:order) { Spree::Order.create(email: '[email protected]') }
+
+ after { Spree::Config.set track_inventory_levels: true }
+
+ it 'is idempotent — an already placed order halts successfully with no side effects' do
+ order.update_columns(completed_at: Time.current, status: 'placed')
+
+ expect(order).not_to receive(:touch)
+ result = described_class.call(order: order)
+
+ expect(result).to be_success
+ expect(result.value).to eq(order)
+ end
+
+ it 'refuses a canceled order' do
+ order.update_columns(status: 'canceled', canceled_at: Time.current)
+
+ expect(described_class.call(order: order)).to be_failure
+ end
+
+ it 'sets completed_at and places the order' do
+ result = described_class.call(order: order)
+
+ expect(result).to be_success
+ expect(order.completed_at).to be_present
+ expect(order.status).to eq('placed')
+ end
+
+ it 'finalizes every fulfillment' do
+ order.shipments.each do |shipment| # rubocop:disable RSpec/IteratedExpectation
+ expect(shipment).to receive(:update!)
+ expect(shipment).to receive(:finalize!)
+ end
+ described_class.call(order: order)
+ end
+
+ it 'decreases the stock for each variant in the fulfillments' do
+ order.shipments.each do |shipment|
+ expect(shipment.stock_location).to receive(:decrease_stock_for_variant)
+ end
+ described_class.call(order: order)
+ end
+
+ it 'marks the fulfillment ready when the order is paid' do
+ Spree::Shipment.create(order: order, stock_location: create(:stock_location))
+ order.shipments.reload
+
+ allow(order).to receive_messages(paid?: true, complete?: true)
+ described_class.call(order: order)
+ order.reload
+
+ expect(order.shipment_state).to eq('ready')
+ end
+
+ it 'does not sell inventory units if track_inventory_levels is false' do
+ Spree::Config.set track_inventory_levels: false
+ expect(Spree::InventoryUnit).not_to receive(:sell_units)
+ described_class.call(order: order)
+ end
+
+ it 'freezes adjustment recalculation (order-level freeze)' do
+ described_class.call(order: order)
+
+ expect(Spree::Adjusters::Promotion).not_to receive(:adjust)
+ order.recalculate_totals!
+ end
+
+ context 'order is considered risky' do
+ before do
+ allow_any_instance_of(Spree::Order).to receive_messages(is_risky?: true)
+ end
+
+ it 'changes state to risky', :events do
+ expect { described_class.call(order: order) }.to change { order.reload.considered_risky }.to(true)
+ end
+
+ context 'and order is approved' do
+ before do
+ allow_any_instance_of(Spree::Order).to receive_messages(approved?: true)
+ end
+
+ it 'leaves the order placed' do
+ described_class.call(order: order)
+ expect(order.status).to eq 'placed'
+ end
+ end
+ end
+
+ context 'events', :events do
+ let(:order) { create(:order_with_line_items, store: store) }
+
+ it 'publishes order.placed with the deprecated order.completed alias' do
+ expect(order).to receive(:publish_event).with('order.placed', hash_including(:notify_customer)).at_least(:once)
+ expect(order).to receive(:publish_event).with('order.completed', hash_including(:notify_customer), { deprecated_alias_of: 'order.placed' }).at_least(:once)
+ allow(order).to receive(:publish_event).with(anything)
+ allow(order).to receive(:publish_event).with(anything, anything)
+
+ described_class.call(order: order, payment_pending: true)
+ end
+
+ it 'enqueues RefreshMetricsJob for each product in the order' do
+ product_count = order.line_items.map { |line_item| line_item.variant.product_id }.uniq.count
+
+ expect do
+ described_class.call(order: order, payment_pending: true)
+ perform_enqueued_jobs(only: Spree::Events::SubscriberJob)
+ end.to have_enqueued_job(Spree::Products::RefreshMetricsJob).exactly(product_count).times
+ end
+ end
+
+ context 'order is not considered risky' do
+ before do
+ allow(order).to receive_messages(is_risky?: false)
+ end
+
+ it 'sets completed_at' do
+ described_class.call(order: order)
+ expect(order.completed_at).to be_present
+ end
+ end
+ end
+end