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.

Merge branch '6-0-dev' into feature/v-3514

Łukasz Adamczykdcd1a1f99de4
diff --cc docs/plans/decisions.md
index 4615283fe7,b5cb811aba..ea67637255
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@@ -409,123 -608,313 +608,434 @@@ spree-starter installs onto `spree_cust
and **no customer resets their password** (task aborts loudly if
`Devise.pepper` is set).
+## 2026-07-29: Phase 2 user→customer data migration — copy-preserving-id, in-place admins, single clash-aware migration
+
+Implementing Phase 2 of `6.0-platform-auth.md` settled several mechanics.
+
+**Customers are a row copy, admins are in place.** The 6.0 split is already
+two-table (`spree_users`=customers, `spree_admin_users`=admins; admin-ness is a
+polymorphic `spree_role_users.user_type`, not a table). So `spree_customers` is a
+**new** table and its data comes from copying `spree_users` — it cannot be a
+`rename_table` (the create migration always runs, so the target already exists;
+fresh installs have no `spree_users`; and `spree_users` carries Devise cruft).
+`spree_admin_users` keeps its table **and** its class name `Spree::AdminUser`, so
+admins never move — the task only backfills `password_digest` from the legacy
+`encrypted_password`.
+
+**Copy preserves primary keys** so the already-renamed `customer_id` FKs
+(2026-03-16 entry) still resolve with no id remap. This is the first repo task to
+insert explicit ids, so it also **resets the Postgres sequence** afterward
+(`reset_pk_sequence!`, guarded to PG) — no prior precedent because taxon→category
+preserved ids via `rename_table`. With ids preserved, the only polymorphic fixups
+are **type-string re-points** `Spree::User` → `Spree.customer_class` on
+`spree_role_users`, `spree_refresh_tokens`, `spree_user_identities`,
+`spree_api_keys` (`created_by_type` + `revoked_by_type`), and
+`spree_customer_group_users` (whose type column renamed `user_type` →
+`customer_type` with the 2026-03-16 FK rename — **must** be re-pointed too or
+memberships dangle); admin-typed rows stay. The task reads the legacy table **by
+name only** (never `LegacyUser`, deleted once all phases ship together), aborts on
+`Devise.pepper` (and, since Devise is gone in 6.0 and a pepper can't be
+introspected, aborts when Devise is absent unless `CONFIRM_NO_PEPPER=true`),
+preflight-aborts on blank-email or email-conflict rows (`SKIP_INVALID_ROWS=true`
+to skip), and leaves `spree_users` in place as a safety net.
+
+**Single clash-aware create migration.** The two Phase-1 create migrations merged
+into `20260728000000_create_spree_customers_and_admin_users` — a **non-colliding**
+name, because `install:migrations` de-dupes engine migrations by name and every
+existing app already has a `create_spree_admin_users`, so the gem's same-named
+migration is skipped and never runs on upgrades. The merged migration creates
+`spree_customers` cleanly and guards the admin side
+(`create … unless table_exists?`, `add_column :password_digest unless
+column_exists?`). `password_digest` is **added alongside** `encrypted_password`,
+never a rename — nothing is lost, and the backfill has both columns to read.
+
+**Path B is a recipe, not gem code.** Keeping a custom user model needs no new
+concern: on the app's own model, `include Spree::CustomerMethods` +
+`has_secure_password validations: false` + `alias_attribute :password_digest,
+:encrypted_password` (or a column rename). The alias must live on the app model —
+a blanket alias in `CustomerMethods` would shadow the default `Spree::Customer`'s
+real `password_digest` and break `has_secure_password` on it.
+
+The 5.6→6.0 upgrade guide (`docs/developer/upgrades/5.6-to-6.0.mdx`) doesn't exist
+yet (6.0 in-dev); Path A/B developer guidance currently lives in the task's `desc`,
+the `5_6_to_6_0` manifest notes, and this plan. It moves to the mdx when the full
+6.0 upgrade guide is authored.
+
+## 2026-07-29: Account lockout enforced in the auth strategy; thresholds config-driven
+
+Phase 4 of `6.0-platform-auth.md` was mostly already shipped (RefreshToken issue/rotate/revoke,
+login/refresh/logout endpoints, Rails `rate_limit` throttling). The remaining gap was that the
+lockout methods on Customer/AdminUser were **dead code** — nothing in the login path called them.
+
+Decisions made wiring it up:
+
+**Enforcement lives in `EmailPasswordStrategy`, not the controllers.** The strategy is the single
+point both store and admin login flow through, and it's the only layer that holds the user object on
+a *failed* password (the controllers get a generic failure). So `authenticate` checks `locked?`
+before validating, `record_failed_attempt!` on a bad password, and `reset_failed_attempts!` on
+success. All calls are `respond_to?`-guarded so a Path-B custom `customer_class` without the lockout
+methods still authenticates.
+
+**Thresholds moved to `Spree::Config`, logic to a shared concern.** The identical
+`locked?`/`record_failed_attempt!`/`reset_failed_attempts!` on both models (with hardcoded `5` /
+`30.minutes`) were extracted into `Spree::AccountLockout` (core concern) reading
+`Spree::Config[:max_failed_login_attempts]` (5) and `[:lockout_duration]` (1800s). These are **core**
+prefs (not `Spree::Api::Config`) because the concern lives on core models, which can't depend on the
+API config.
+
+**Distinct lockout message** ("Account temporarily locked. Try again later.") over a generic
+invalid-credentials response — industry-common, and login is already rate-limited so the marginal
+enumeration signal is low. It's a single return string, easily switched to the generic message if a
+stricter anti-enumeration posture is wanted (Spree's login/password-reset are otherwise
+anti-enumeration).
+
+**Refresh-token hashing at rest was declined** (tokens are already random + expiring; login
+throttled). **Admin `logout` gained a `rate_limit`** to match the store side. Following the repo's
+rate-limit spec convention, no throttle-*trip* test was added (those depend on the test cache store);
+the existing specs cover response format/headers/config.
+
+## 2026-07-29: Devise fully removed from core/api; legacy models deleted, table kept
+
+Phases 5 & 6 of `6.0-platform-auth.md`, scoped to `spree/core` + `spree/api` (spree/admin removed
+wholesale by `6.0-admin-spa.md`; the spree-starter / 5b changes are a separate pass).
+
+**Legacy models deleted, `spree_users` table retained.** `Spree::LegacyUser` /
+`Spree::LegacyAdminUser` are gone (no runtime fallback — `Spree.customer_class` has no default,
+`Role` is dynamic, and only four specs named the constant, all repointed to `Spree.customer_class`).
+The `spree_users` **table** is deliberately kept as the Phase 2 migration's safety net — its teardown
+is a separate later operator task, and the 4.3 baseline migration still materializes it on fresh
+installs.
+
+**Devise bridges removed, not kept.** Both `Spree::AdminUserMethods::DeviseNotifications` and
+`CustomerMethods::SkipPasswordValidation` were deleted. They were inert on the gem's
+`has_secure_password` models: admin auth emails flow through the `admin_user.password_reset_requested`
+event subscriber → `AdminUserMailer` (not `send_devise_notification`), and password-less
+admin-created customers rely on `has_secure_password validations: false` rather than a
+`password_required?` override. The `defined?(Devise)` guards in the migrate-users rake task are the
+one Devise reference kept — they're defensive checks for installs migrating *off* Devise.
+
+**`spree:install` scaffolds no auth by default.** With the generators deleted, the root-gem install
+generator's `--authentication` default moved to `nil` (was `devise`): a plain install writes no auth
+helpers because the gem owns auth (`Spree::Customer`/`Spree::AdminUser` + the initializer sets the
+class names). `dummy` stays available and is what the test harness passes explicitly via
+`common_rake`, so `test_app` is unaffected.
+
+**Deprecation aliases kept to 6.1.** The earlier Phase 6 plan to drop the `user_class` alias in 6.0
+is superseded — `Spree.user_class`, `Spree::UserMethods`, `Spree::DeprecatedCustomerAlias`, and the
+`:user`/`:admin_user` factory aliases all remain through 6.0 (in-code comments already tag them 6.1).
+
+**Docs.** The Devise-as-default pages were rewritten around gem-owned auth + the custom-model recipe,
+and `Spree.user_class` references swept to `Spree.customer_class`. `Spree::OauthAccessToken` is a
+no-op (extracted upstream). Deferred: the 6.0 upgrade guide, the `spree_users` teardown task, and the
+unrelated search-area `multi_search` alias removal.
++
+ ## 2026-07-28: Core-rewrite implementation decisions (cart/order split + fulfillment + split adjustments)
+
+ Interactive review settled everything blocking implementation start; task
+ sequencing lives in `docs/plans/6.0-core-rewrite-tasks.md` (7 waves, data
+ rake tasks last).
+
+ 1. **ProductType prerequisite is the minimal Phase 1 slice** — rename +
+ store ownership + `fulfillment_types` + `Product#product_type_id`. The
+ rest of `6.0-product-types.md` (custom-field-definition join, live
+ template propagation, its API/dashboard) ships as its own effort.
+ 2. **`spree_admin` is dropped from the spree-starter Gemfile on the 6.0
+ line.** The legacy admin's adjustments/checkout screens hard-break when
+ `Spree::Adjustment` and the Order state machine are removed; rather than
+ limp on aliases, the dev server stops loading the gem — the React
+ dashboard is the only admin. The gem stays in the monorepo untouched
+ (it's already out of the CI matrix) until its 6.0 deletion; one-release
+ constant aliases (`Spree::Shipment = Spree::Fulfillment`, …) still ship
+ for extensions and the emails gem.
+ 3. **`checkout_flow`/`insert_checkout_step` are hard-removed in 6.0** — no
+ translation shim (machine transitions have no `Checkout::Registry`
+ equivalent); migration guide instead.
+ 4. **`DeliveryRate` carries no owner columns** — it derives `owner` through
+ its fulfillment. The dual-FK pattern covers LineItem, the typed money
+ lines, and Fulfillment; rates were never directly order-linked.
+ 5. **Cart reaper defaults: guest 30d, customer 90d, empty carts 48h**
+ (config preferences; carts with authorized/pending payment sessions are
+ never reaped, unconditionally).
+ 6. **`shipment.*` webhooks dual-emit for exactly one release**, dropped in 6.1.
+ 7. **`ready_for_pickup` is a first-class Store API status** (not mapped
+ onto `ready`); the order-level rollup still reports `ready`.
+ 8. **`partially_canceled` becomes a derived predicate** over child
+ cancellations, not a stored status value.
+
+ ## 2026-07-29: Delivery methods stay regional; a reference multi-carrier rate provider ships in the monorepo
+
+ Question raised during 6.0 review: does one carrier method (e.g. UPS) need
+ per-market rates/calculators, or is "UPS (Europe)" + "UPS (North America)" as
+ separate `DeliveryMethod` rows a modeling smell?
+
+ Competitor survey says the split IS the industry shape — every platform
+ regionalizes the sellable method and shares only the carrier integration:
+
+ - **Shopify**: rates live inside Shipping Zones (per profile); a zone rate is
+ a manual definition or a "participant" of a globally-registered
+ CarrierService. No cross-zone method entity exists.
+ - **Medusa v2**: a Shipping Option belongs to exactly one Service Zone plus a
+ fulfillment provider module; flat prices come from the pricing module
+ (per currency/region), `calculated` delegates to the provider.
+ - **Saleor**: Shipping Methods live inside Shipping Zones with per-channel
+ price listings; external carriers are Shipping Apps returning dynamic
+ methods per checkout.
+ - **Vendure**: ShippingMethod is standalone (eligibility checker + calculator
+ strategies) but channel-scoped — idiomatically still one method per region.
+
+ **Decision 1 — no cross-market method entity.** `DeliveryMethod` +
+ `DeliveryZone` already matches the consensus: method rows are cheap and
+ regional; carrier logic is shared one level down. Built-in calculators carry a
+ single `preferred_currency`, so multi-currency stores need per-market methods
+ regardless. Nothing to build.
+
+ **Decision 2 — the monorepo ships one reference `DeliveryRateProvider`**
+ backed by a multi-carrier aggregator (Shippo or EasyPost — pick pending API/
+ pricing review), mirroring the Stripe reference-gateway decision (2026-07-15).
+ One integration returns live UPS/FedEx/DHL/USPS rates, which dissolves the
+ per-carrier-per-market method sprawl for the majority of installs: one
+ "Carrier shipping" method per market, the provider returns whatever serves the
+ address. It also makes the reference implementation the first real consumer of
+ the `6.0-delivery-rate-provider.md` interface — validating the seam the way
+ payment sessions were validated by Stripe. Built-in calculators remain the
+ manual-rate path for the minority (2026-07-27 reversal unchanged).
+
+ ## 2026-07-29: Geo modeling — Markets, DeliveryZones and StockLocations stay disjoint
+
+ Two follow-up questions from the same 6.0 review: should Markets link to
+ DeliveryZones, and should StockLocations link to DeliveryZones? Competitor
+ survey on both:
+
+ **Markets ↔ delivery zones.** Shopify (Markets vs profile shipping zones) and
+ Medusa (Regions vs service zones) keep them fully disjoint — independent
+ country lists, merchant coordinates, and Shopify's "market country with no
+ shipping coverage" dead-end is a known sore point of that camp. Saleor links
+ shipping zones to *channels* (m:n + per-channel price listings); Vendure
+ reuses one country-granular Zone entity as channel defaults for tax and
+ shipping — the unified model, bought at the cost of country-only granularity.
+
+ **Decision: stay disjoint.** Two structural reasons resist merging across
+ every platform surveyed: granularity (markets are country-level commercial
+ units; delivery coverage legitimately goes sub-country — states, postal
+ prefixes/ranges, remote-island carve-outs) and cardinality (one EU market
+ maps naturally onto several delivery zones — standard / remote / oversized).
+ Spree already carries a stronger coordination guardrail than the disjoint
+ camp: `MarketCountry#country_covered_by_shipping_zone` refuses market
+ countries the store cannot deliver to. The channel axis heads the Saleor
+ direction separately via `5.7-channel-markets.md`. If more convenience is
+ ever wanted, it is a dashboard affordance ("create delivery zone from this
+ market's countries"), never a schema link.
+
+ **Stock locations ↔ delivery zones.** Here the industry splits 3–1 the other
+ way: Shopify's delivery profiles nest location groups that each own their
+ zones+rates; Medusa roots the whole hierarchy at the stock location
+ (StockLocation → FulfillmentSet → ServiceZone → ShippingOption); Saleor links
+ warehouses ↔ shipping zones m:n and allocates stock through that link. Only
+ Vendure leaves origin/coverage coordination to code (allocation strategies).
+
+ **Decision: no StockLocation↔DeliveryZone schema link — compose it at the
+ method level.** Spree expresses per-origin coverage as
+ DeliveryMethod↔StockLocation (the `spree_delivery_method_stock_locations`
+ join shipped in the 6.0 rename migration, currently dormant/unwired) times
+ DeliveryMethod↔DeliveryZone — "UPS EU ships from the Poland warehouse" is a
+ method restricted to that location with EU zones. That is Shopify's
+ location-group→zones expressiveness without a third geo entity. Wiring the
+ dormant join (association + Estimator/Coordinator filtering + admin API
+ exposure) is follow-up work on `6.0-fulfillment-and-delivery.md`, which
+ already uses the table for pickup locations. The Medusa/Saleor-style
+ allocation question — *choosing* the warehouse by destination — is the order
+ routing seam (`6.0-order-routing.md` strategies), not geo schema.
+
+ ## 2026-07-29: Delivery-method eligibility moves out of calculators into DeliveryMethodRule
+
+ Dashboard review surfaced min/max item-total and weight bounds rendering
+ inside the rate-calculator preference form. They are eligibility, not
+ pricing — and structurally worse than they look: the four bounds exist only
+ on `Calculator::Shipping::FlatRate` (no other calculator has them), are
+ enforced by `compute_package` returning nil rather than the
+ `available?(package)` hook the Estimator consults, and would be silently
+ LOST on provider-priced methods once `6.0-delivery-rate-provider.md` lands
+ (the provider bypasses the calculator that carries them).
+
+ Competitors uniformly separate the concerns: Shopify puts weight/price
+ conditions on the zone rate, Saleor uses method columns (+ per-channel price
+ bounds), Medusa v2 attaches typed ShippingOptionRule records, Vendure gives
+ ShippingMethod an eligibility-checker strategy parallel to its calculator.
+
+ **Decision:** `Spree::DeliveryMethodRule` STI on DeliveryMethod — the fifth
+ instance of the house rule pattern and the symmetric sibling of
+ `5.7-payment-method-rules.md` (ItemTotal + Weight first; Channel/Market/
+ CustomerGroup later, in lockstep with the payment set). One enforcement
+ seam: the Estimator's method filter, so calculator- and provider-priced
+ methods obey the same eligibility; no admin-bypass concept (the Estimator is
+ the only rate source, and these are logistics constraints). FlatRate's
+ bound preferences become a one-release deprecation bridge with a data task.
+ Plan: `6.0-delivery-method-rules.md` — targeted 6.0 directly; per the same
+ review, the pending 5.7 plans are expected to retarget 6.0 (skipping a 5.7
+ release for a faster 6.0 launch). Open questions resolved interactively the
+ same day: WeightRule uses the store's implicit unit (raw-number comparison,
+ legacy parity); rules are method-scoped only (no zone context — per-region
+ bounds are separate methods); Phase 1 ships with the 6.0 core-rewrite
+ finishing work, Channel/Market/CustomerGroup later with payment rules.
+
+
+ ## 2026-07-29 — Admin discount application follows the Saleor shape
+
+ How should an admin apply a discount to an order in the dashboard? Competitor
+ survey: Shopify draft orders take only **manual** discounts (order- or
+ line-level custom amount/percent with a reason) — codes are a checkout
+ concept the buyer redeems; Medusa admin drafts accept **promotion codes**
+ directly; Saleor drafts take **both** a voucher code and a manual order
+ discount stored as its own discount object.
+
+ **Decision:** the Saleor shape, split by lifecycle. Draft orders accept
+ discount codes post-creation via `POST /admin/orders/:id/discount_codes`
+ (same `PromotionHandler::Coupon` path and pending semantics as the
+ storefront cart endpoint — a real-but-not-yet-eligible code is stored and
+ activates on recalculation); completed orders refuse codes (recalculation
+ is frozen) and take **manual typed Discount rows** through the existing
+ `/admin/orders/:id/discounts` CRUD (`Orders::AddManualDiscount`,
+ largest-remainder distribution, `resum_typed_totals!`). The dashboard's
+ promotion picker is sugar over the code path — picking a coupon promotion
+ fills in its code; it is not a separate application mechanism. The coupon
+ handler now always reports ineligibility with the retryable status code so
+ endpoints can tell a not-yet-qualifying code from an invalid one.
+
+
+ ## 2026-07-29 — `order.placed` replaces `order.completed`; carts get their own events
+
+ Competitor survey (Shopify, BigCommerce, Medusa v2, Saleor, Vendure): every
+ platform with a separate cart entity namespaces its events (`carts/*`,
+ `cart.*`, `CHECKOUT_*`), and "order created" then means *placed* only where
+ drafts live in their own namespace (`draft_orders/*`, `DRAFT_ORDER_*`).
+ Medusa — the same single-Order-model shape as ours — uses an explicit
+ `order.placed`, and reserves `order.completed` for "fulfillment finished",
+ a direct collision with our historical name.
+
+ **Decisions:** carts publish `cart.created/updated/deleted` (5.x
+ abandonment-signal parity). The placement event is renamed
+ `order.completed` → **`order.placed`** — newcomers are the primary
+ audience and the old name misleads anyone arriving from Medusa. Per the
+ one-release bridge convention, 6.0 dual-emits: `order.completed` still
+ fires with an identical payload and `deprecated_alias_of: 'order.placed'`
+ in the event metadata (wildcard subscribers dedupe on it); the alias is
+ dropped in 6.1. The dashboard event picker offers only `order.placed`. `order.created` keeps meaning "order row exists" (admin drafts
+ included). Admin confirmation resends publish the targeted
+ `order.resend_confirmation_email` instead of re-blasting the placement
+ event. Order payloads carry `cart_id` (BigCommerce `store/cart/converted`
+ parity) so abandonment flows can cancel on conversion. Server-side
+ abandonment detection (BigCommerce `store/cart/abandoned`) explicitly
+ skipped. No separate draft-order entity and no `is_draft` boolean —
+ `status = 'draft'` already encodes it (`cart_id` does NOT: the completion
+ pipeline's draft copy has a cart_id while briefly draft; admin drafts
+ have none).
+
+
+ ## 2026-07-29 — Spree 6.0 requires Rails 8.1 (7.2 support dropped)
+
+ The core gemspec already pins `rails >= 8.1, < 8.2` and the deprecation
+ bridges lean on Rails 8.1's `deprecated:` association option across every
+ 6.0 rename twin — supporting 7.2 would mean hand-rolled warn-wrappers for
+ all of them on a platform whose security support ends 2026-08-09, before
+ 6.0 GA. Rails 8.1 (Oct 2025, supported to Oct 2027) also unlocks
+ ActiveJob Continuations for resumable long-running jobs (upgrade data
+ migrations, imports, bulk operations — the durable-steps half of a
+ Medusa-style workflow story; compensation logic stays ours, e.g.
+ `Carts::Complete`). Existing stores upgrade Rails to 8.1 on the 5.6 line
+ first, then take 6.0 — 5.6 remains the bridge release. CI: the MySQL
+ lanes were the designated old-Rails coverage (`RAILS_VERSION: 7.2.0`) and
+ could no longer bundle; they now run 8.1 like the rest — MySQL itself
+ stays fully supported.
+
+
+ ## 2026-07-29 — Every major model carries a store_id; DeliveryZone bound now, StockLocation next
+
+ Ratifies the principle already stated in `6.0-delivery-rate-provider.md`
+ (DeliveryMethod gets `store_id` there) as a standing convention: new
+ models carrying store-specific data always `belongs_to :store` through
+ `Spree::SingleStoreResource`; only genuinely global reference data stays
+ unscoped. Store binding also closes cross-store lookup holes structurally
+ — admin controllers scope `current_store.<resources>` instead of relying
+ on ability scoping alone (see the Strix findings on delivery-method
+ bindings, 2026-07-29).
+
+ Applied immediately to **DeliveryZone** — an unreleased 6.0 table, so the
+ creation migration gained `store_id NOT NULL` + per-store name uniqueness
+ in place, with zero bridge cost. **DeliveryMethod and StockLocation**
+ (released tables) landed on the same branch via the 5.6 single-store
+ pattern: nullable `store_id` + `SingleStoreResource`, per-store seeds,
+ manifest backfill task assigning the default store, `null: false` in
+ 6.1. (Cross-store sharing is not preserved anywhere — `spree_multi_store`
+ is legacy and unsupported.) Admin lookups and runtime pickers (Estimator, Coordinator, order
+ routing) all go through the store associations
+ (`store.delivery_methods` / `store.stock_locations`) — strict semantics;
+ the manifest backfill is a required upgrade step before checkout. **TaxRate and
+ TaxCategory** follow inside the tax-provider plan's implementation
+ (noted there). Stock availability (`Stock::Quantifier`) intentionally
+ stays location-global until the 6.1 NOT NULL work — correct for
+ single-store installs, revisited with multi-store.
+
+
+ ## 2026-07-30 — Credential homes follow cardinality: Integration for store-level connections, PaymentMethod rows for merchant entities
+
+ Provider architecture is three layers: store-owned commerce config rows
+ (DeliveryMethod, PaymentMethod), stateless registry-keyed provider code
+ (FulfillmentProvider/DeliveryRateProvider/tax engines — never hold
+ credentials), and `Spree::Integration` as the per-store credentialed
+ vendor connection (one row per store+type, `can_connect?`, admin
+ listing). Where credentials live is decided by cardinality, and the two
+ domains are deliberately opposite:
+
+ - **Delivery/vendor APIs — one connection, many methods.** An EasyPost
+ account rates every method; config rows multiply, the connection does
+ not. Credentials belong on the Integration singleton; provider gems
+ ship an Integration subclass + a stateless provider pair
+ (`6.0-delivery-rate-provider.md`).
+ - **Payments — one credential set per merchant entity, several per
+ store.** Two Stripe accounts are two merchants of record (separate
+ settlement and liability), selected per market at checkout — exactly
+ what PaymentMethod rows model, gated by MarketRule once
+ `5.7-payment-method-rules.md` lands. Credentials stay on the method
+ row; converging them onto Integration would fight its store+type
+ uniqueness and is explicitly NOT planned.
+
+ Consequence for tax (`6.0-tax-provider.md`): "one Stripe connection
+ serves payments and Stripe Tax" only holds single-entity. Under multiple
+ merchants of record, tax liability follows the charging entity per
+ market — a Stripe Tax provider must resolve credentials consistently
+ with the market's selected payment entity, not via a store-singleton
+ Integration lookup.
+
+
+ ## 2026-07-30 — Reference providers: Stripe (payments), Avalara (tax), EasyPost-or-Shippo (delivery)
+
+ One first-party reference implementation per provider seam, each
+ exercising its layer's canonical shape from the credential-cardinality
+ entry above: **Stripe** for payments (monorepo move per 2026-07-15 —
+ credentials on PaymentMethod rows, multi-entity capable), **Avalara**
+ for tax (the enterprise standard, matching the enterprise-seller target;
+ Integration subclass for store credentials + stateless provider writing
+ TaxLines with `provider_id: 'avalara'`; the built-in `'internal'` engine
+ stays the OSS default), and the **EasyPost-or-Shippo** multi-carrier
+ gem for delivery rates (pick still pending; Integration + provider
+ pair). Stripe Tax remains buildable by third parties but is not the
+ reference — and carries the merchant-of-record caveat recorded above.
+
+
+ ## 2026-07-30 — Service workflows: one step DSL, Carts::Complete as the stress test
+
+ Services, sagas, extension hooks and events unify under a declared step
+ DSL evolved from ServiceModule in place (plan:
+ `6.0-service-workflows.md`, targeted 6.0). Medusa's workflows are the DX
+ benchmark; the runtime stays plain Ruby in Rails transactions — no
+ engine, no execution-state tables. Explicit transaction/io_step
+ boundaries, per-step compensation, in-transaction `hook` extension
+ points and declared `emit` events; the consistency doctrine (step →
+ sync subscriber → async subscriber) ships as documentation.
+ **Carts::Complete is the reference implementation and acceptance test:**
+ the cart→order swap already exercises every hard property (in-lock
+ verification, out-of-transaction payment I/O, compensation, replay
+ idempotency, sweeper resume) and its spec battery must pass unmodified
+ after the retrofit. Durable flows compile onto ActiveJob Continuations
+ in Phase 2 (imports, upgrade migrations, payout runs) and may land
+ post-GA without blocking the DSL.
diff --cc spree/api/app/controllers/spree/api/v3/base_controller.rb
index 6973f64037,b24861ac15..8cf16f5499
--- a/spree/api/app/controllers/spree/api/v3/base_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/base_controller.rb
@@@ -42,8 -42,30 +42,30 @@@ module Spre
protected
+ # Guest authorization for a specific order or cart. Defined here
+ # because Store::BaseController and Store::ResourceController anchor
+ # parallel inheritance branches — both need it.
+ def order_token
+ request.headers['x-spree-token']
+ end
+
+ # Renders a failed service/workflow Result: validation errors become a
+ # 422 field-error payload, anything else a plain service error. Shared
+ # by both APIs — Store endpoints surface workflow failures (a rejected
+ # return, a vetoed cart add) the same way Admin ones do.
+ def render_result_error(result)
+ error = result.error
+ errors = error.respond_to?(:value) ? error.value : error
+
+ if errors.is_a?(ActiveModel::Errors)
+ render_validation_error(errors)
+ else
+ render_service_error(error)
+ end
+ end
+
# Override to use current_user from JWT authentication
- # @return [Spree.user_class]
+ # @return [Spree.customer_class]
def spree_current_user
current_user
end
diff --cc spree/api/spec/controllers/spree/api/v3/store/orders_controller_spec.rb
index ced385c31b,69f89fe19a..13f1d513f9
--- a/spree/api/spec/controllers/spree/api/v3/store/orders_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/store/orders_controller_spec.rb
@@@ -32,8 -32,37 +32,37 @@@ RSpec.describe Spree::Api::V3::Store::O
end
end
+ context 'with the cart handle after completion' do
+ let(:cart) { create(:cart_with_line_items, store: store) }
+ let!(:completed_order) do
+ create(:completed_order_with_totals, user: nil, store: store, cart_id: cart.id, token: cart.token)
+ end
+
+ before { cart.update_columns(completed_at: Time.current) }
+
+ # The storefront keeps the cart id through checkout; after completion
+ # the same handle + cart token must resolve the resulting order.
+ it 'resolves the order created from that cart' do
+ request.headers['x-spree-token'] = cart.token
+
+ get :show, params: { id: cart.prefixed_id }
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['id']).to eq(completed_order.prefixed_id)
+ expect(json_response['number']).to eq(completed_order.number)
+ end
+
+ it 'returns not found without the matching token' do
+ request.headers['x-spree-token'] = 'wrong-token'
+
+ get :show, params: { id: cart.prefixed_id }
+
+ expect(response).to have_http_status(:not_found)
+ end
+ end
+
context 'with spree token' do
- let(:guest_order) { create(:completed_order_with_totals, user: nil, store: store) }
+ let(:guest_order) { create(:completed_order_with_totals, customer: nil, store: store) }
it 'returns the order for guest with valid token' do
request.headers['x-spree-token'] = guest_order.token
diff --cc spree/core/app/models/concerns/spree/customer_methods.rb
index ce9fc9836c,0000000000..fba22a9c61
mode 100644,000000..100644
--- a/spree/core/app/models/concerns/spree/customer_methods.rb
+++ b/spree/core/app/models/concerns/spree/customer_methods.rb
@@@ -1,308 -1,0 +1,308 @@@
+module Spree
+ module CustomerMethods
+ extend ActiveSupport::Concern
+
+ include Spree::PrefixedId
+ include Spree::Metafields
+ include Spree::Metadata
+ include Spree::UserAddress
+ include Spree::UserPaymentSource
+ include Spree::UserReporting
+ include Spree::UserRoles
+ include Spree::RansackableAttributes
+ include Spree::Searchable
+ include Spree::Publishable
+
+ included do
+ has_prefix_id :cust # Stripe: cus_
+
+ # Enable lifecycle events for user models
+ publishes_lifecycle_events
+
+ # Password reset token (Rails 7.1+ signed token, no DB column needed)
+ # Token auto-invalidates when password changes (salt changes)
+ # Expiration is configurable via Spree::Config.customer_password_reset_expires_in (in minutes)
+ generates_token_for :password_reset, expires_in: Spree::Config.customer_password_reset_expires_in.minutes do
+ # `try` rather than `&.`: a model that lacks the method/column entirely
+ # must fall through rather than raise NameError. `password_salt` covers
+ # has_secure_password (which derives it from password_digest);
+ # `encrypted_password` covers a legacy bcrypt column on a custom model.
+ try(:password_salt)&.last(10) || try(:encrypted_password)&.last(10)
+ end
+
+ # we need to have this callback before any dependent: :destroy associations
+ # https://github.com/rails/rails/issues/3458
+ before_validation :clone_billing_address, if: :use_billing?
+ before_destroy :check_completed_orders
+
+ after_save_commit :sync_newsletter_subscription_with_marketing_consent,
+ if: :saved_change_to_accepts_email_marketing?
+
+ attr_accessor :use_billing
+
+ has_person_name
+ normalizes :email, :first_name, :last_name, with: ->(value) { value&.to_s&.squish&.presence }
+ acts_as_taggable_on :tags
+
+ def tags=(tags)
+ self.tag_list = tags
+ end
+
+ #
+ # Associations
+ #
+ has_many :promotion_rule_users, class_name: 'Spree::PromotionRuleUser', foreign_key: :customer_id, dependent: :destroy
+ has_many :promotion_rules, through: :promotion_rule_users, class_name: 'Spree::PromotionRule'
+ has_many :orders, foreign_key: :customer_id, class_name: 'Spree::Order'
+ has_many :carts, -> { incomplete }, foreign_key: :customer_id, class_name: 'Spree::Order'
+ has_many :completed_orders, -> { complete }, foreign_key: :customer_id, class_name: 'Spree::Order'
+ has_many :store_credits, class_name: 'Spree::StoreCredit', foreign_key: :customer_id, dependent: :destroy
+ has_many :wishlists, class_name: 'Spree::Wishlist', foreign_key: :customer_id, dependent: :destroy
+ has_many :wished_items, through: :wishlists, source: :wished_items
+ has_many :gateway_customers, class_name: 'Spree::GatewayCustomer', foreign_key: :customer_id
+ has_many :gift_cards, class_name: 'Spree::GiftCard', foreign_key: :customer_id, dependent: :destroy
+ has_many :customer_group_users, class_name: 'Spree::CustomerGroupUser', as: :customer, dependent: :destroy
+ has_many :customer_groups, through: :customer_group_users, class_name: 'Spree::CustomerGroup'
+ has_many :identities, class_name: 'Spree::UserIdentity', as: :user, dependent: :destroy
+ belongs_to :ship_address, class_name: 'Spree::Address', optional: true
+ belongs_to :bill_address, class_name: 'Spree::Address', optional: true
+
+ # Replaces the customer's group membership. Accepts both prefixed IDs and
+ # raw integer IDs. Only groups belonging to the current store are
+ # assigned — ids from another store are dropped, preventing cross-store
+ # membership. Mirrors +Spree::Product#category_ids=+.
+ def customer_group_ids=(ids)
+ decoded_ids = Array(ids).filter_map do |id|
+ id.to_s.include?('_') ? Spree::CustomerGroup.decode_prefixed_id(id) : id
+ end
+ super(Spree::CustomerGroup.for_store(Spree::Current.store).where(id: decoded_ids).ids)
+ end
+
+ #
+ # Attachments
+ #
+ has_one_attached :avatar, service: Spree.public_storage_service_name
+ has_rich_text :internal_note
+
+ #
+ # Attributes
+ #
+ attr_accessor :confirm_email, :terms_of_service
+
+ def self.find_by_password_reset_token(token)
+ find_by_token_for(:password_reset, token)
+ end
+
+ def self.find_by_password_reset_token!(token)
+ find_by_token_for!(:password_reset, token)
+ end
+
+ def self.search(query)
+ return none if query.blank?
+
+ # `search_condition` handles sanitization itself — it escapes LIKE
+ # wildcards for plain columns and compares encrypted columns by
+ # equality. Pass the raw query so it can branch correctly.
+ conditions = []
+ conditions << search_condition(self, :email, query)
+ conditions << search_condition(self, :first_name, query)
+ conditions << search_condition(self, :last_name, query)
+
+ full_name = NameOfPerson::PersonName.full(query.to_s.strip)
+
+ if full_name.first.present? && full_name.last.present?
+ conditions << search_condition(self, :first_name, full_name.first)
+ conditions << search_condition(self, :last_name, full_name.last)
+ end
+
+ where(conditions.reduce(:or))
+ end
+
+ # Backward compatibility alias — remove in Spree 6.0
+ def self.multi_search(query) = search(query)
+
+ self.whitelisted_ransackable_associations = %w[bill_address ship_address addresses tags spree_roles orders customer_groups]
+ self.whitelisted_ransackable_attributes = %w[id email first_name last_name phone accepts_email_marketing
+ created_at updated_at last_sign_in_at]
+ self.whitelisted_ransackable_scopes = %w[search multi_search with_min_total_spent]
+
+ scope :with_min_total_spent, ->(amount) {
- joins(:orders).where(spree_orders: { state: 'complete' }).
++ joins(:orders).where.not(spree_orders: { completed_at: nil }).
+ group("#{table_name}.id").
+ having('SUM(spree_orders.total) >= ?', amount.to_d)
+ }
+
+ # Precomputes orders_count, total_spent, and last_order_completed_at via a
+ # single aggregate join so list endpoints avoid 4 queries per user. The
+ # values land on the user as virtual attributes.
+ scope :with_order_aggregates, -> {
+ order_table = Spree::Order.table_name
+ select(
+ "#{table_name}.*, " \
+ "COALESCE(orders_agg.orders_count, 0) AS orders_count, " \
+ "COALESCE(orders_agg.total_spent, 0) AS total_spent, " \
+ "orders_agg.last_order_completed_at AS last_order_completed_at"
+ ).joins(
+ "LEFT JOIN (" \
+ "SELECT customer_id, COUNT(*) AS orders_count, SUM(total) AS total_spent, MAX(completed_at) AS last_order_completed_at " \
+ "FROM #{order_table} " \
- "WHERE state = 'complete' AND customer_id IS NOT NULL " \
++ "WHERE completed_at IS NOT NULL AND customer_id IS NOT NULL " \
+ "GROUP BY customer_id" \
+ ") orders_agg ON orders_agg.customer_id = #{table_name}.id"
+ )
+ }
+
+ def self.with_email(query)
+ where("#{table_name}.email LIKE ?", "%#{query}%")
+ end
+
+ def self.with_address(query, address = :ship_address)
+ left_outer_joins(address).
+ where("#{Spree::Address.table_name}.firstname like ?", "%#{query}%").
+ or(left_outer_joins(address).where("#{Spree::Address.table_name}.lastname like ?", "%#{query}%"))
+ end
+
+ def self.with_email_or_address(email, address)
+ left_outer_joins(:addresses).
+ where("#{Spree::Address.table_name}.firstname LIKE ? or #{Spree::Address.table_name}.lastname LIKE ? or #{table_name}.email LIKE ?",
+ "%#{address}%", "%#{address}%", "%#{email}%")
+ end
+
+ # We override this method because we cannot use for_store on users because it will return admin users
+ def self.for_store(store)
+ self
+ end
+ end
+
+ # Returns the last incomplete spree order for the current store
+ # @param [Spree::Store] store
+ # @param [Hash] options
+ # @option options [Array<Symbol>] :includes
+ # @return [Spree::Order]
+ def last_incomplete_spree_order(store, options = {})
+ orders.where(store: store).incomplete.not_canceled.
+ includes(options[:includes]).
+ order('created_at DESC').
+ first
+ end
+
+ # Returns the total available store credit for the current store per currency
+ # @param [Spree::Store] store
+ # @param [String] currency
+ # @return [Float]
+ def total_available_store_credit(currency = nil, store = nil)
+ store ||= Store.default
+ currency ||= store.default_currency
+
+ # When the association is already loaded (e.g. preloaded via the admin
+ # API's scope_includes), filter in memory to avoid an N+1 — but mirror
+ # the query branch exactly: non-gift-card credits, scoped to the store
+ # and currency. A gift card is identified by its originator_type.
+ if store_credits.loaded?
+ store_credits.
+ select { |sc| sc.originator_type != 'Spree::GiftCard' && sc.store_id.to_s == store.id.to_s && sc.currency == currency }.
+ sum(&:amount_remaining)
+ else
+ store_credits.without_gift_card.for_store(store).where(currency: currency).to_a.sum(&:amount_remaining)
+ end
+ end
+
+ # Returns the available store credits for the current store per currency
+ # @param [Spree::Store] store
+ # @return [Array<Spree::Money>]
+ def available_store_credits(store)
+ store ||= Store.default
+
+ store_credits.for_store(store).pluck(:currency).uniq.each_with_object([]) do |currency, arr|
+ arr << Spree::Money.new(total_available_store_credit(currency, store), currency: currency)
+ end
+ end
+
+ # Returns the default wishlist for the current store
+ # if no default wishlist exists, it creates one
+ # @param [Spree::Store] current_store
+ # @return [Spree::Wishlist]
+ def default_wishlist_for_store(current_store)
+ wishlists.find_by(is_default: true, store_id: current_store.id) || ActiveRecord::Base.connected_to(role: :writing) do
+ wishlists.create!(store: current_store, is_default: true, name: Spree.t(:default_wishlist_name))
+ end
+ end
+
+ # Returns true if the user can be deleted
+ # Customers can be deleted if they have no completed orders
+ # @return [Boolean]
+ def can_be_deleted?
+ orders.complete.none?
+ end
+
+ # Returns the CSV row representation of the user
+ # @param [Spree::Store] store
+ # @return [Array<String>]
+ def to_csv(_store = nil)
+ Spree::CSV::CustomerPresenter.new(self).call
+ end
+
+ # Returns the full name of the user
+ # @return [String]
+ def full_name
+ name&.full
+ end
+
+ def event_serializer_class
+ 'Spree::Api::V3::CustomerSerializer'.safe_constantize
+ end
+
+ def event_prefix
+ if self.class == Spree.admin_user_class && Spree.admin_user_class != Spree.customer_class
+ 'admin'
+ else
+ 'user'
+ end
+ end
+
+ # @param store [Spree::Store] store to scope the lookup to; defaults to the current store
+ # @return [Spree::NewsletterSubscriber, nil] this user's newsletter subscriber for the given store
+ def newsletter_subscriber(store = Spree::Current.store)
+ return unless store
+
+ Spree::NewsletterSubscriber.for_store(store).find_by(customer_id: id)
+ end
+
+ private
+
+ def check_completed_orders
+ raise Spree::Core::DestroyWithOrdersError if !spree_admin? && orders.complete.present?
+ end
+
+ def clone_billing_address
+ if bill_address && ship_address.nil?
+ self.ship_address = bill_address.clone
+ else
+ ship_address.attributes = bill_address.attributes.except('id', 'updated_at', 'created_at')
+ end
+ true
+ end
+
+ def use_billing?
+ use_billing.in?([true, 'true', '1'])
+ end
+
+ # Scrambles the email and names of the user
+ def scramble_email_and_names
+ self.email = "#{SecureRandom.uuid}@example.net"
+ self.first_name = 'Deleted'
+ self.last_name = 'User'
+ self.login = email if has_attribute?(:login)
+ save
+ end
+
+ def sync_newsletter_subscription_with_marketing_consent
+ if accepts_email_marketing?
+ Spree::NewsletterSubscriber.subscribe(email: email, customer: self)
+ else
+ # Only remove the subscriber for the current store, mirroring the store-scoped subscribe path.
+ newsletter_subscriber&.destroy
+ end
+ end
+ end
+end
diff --cc spree/core/app/models/concerns/spree/purchase/store_credits.rb
index 6b3d933bcc,8893e4f292..9219198806
--- a/spree/core/app/models/concerns/spree/purchase/store_credits.rb
+++ b/spree/core/app/models/concerns/spree/purchase/store_credits.rb
@@@ -14,23 -16,20 +16,20 @@@ module Spre
end
alias covered_by_store_credit covered_by_store_credit?
- # Returns the total amount of store credits available to the customer associated with the order.
- # Returns only store credit for this store and same currency as order
+ # Only store credit for this store and the record's currency.
#
- # @return [BigDecimal] The total amount of store credits available to the customer associated with the order.
+ # @return [BigDecimal]
def total_available_store_credit
- return 0.0 unless user
+ return 0.0 unless customer
- user.total_available_store_credit(currency, store)
+ customer.total_available_store_credit(currency, store)
end
- # Returns the available store credits for the customer associated with the order.
- #
- # @return [Array<Spree::StoreCredit>] The available store credits for the customer associated with the order.
+ # @return [Array<Spree::StoreCredit>]
def available_store_credits
- return Spree::StoreCredit.none if user.nil?
+ return Spree::StoreCredit.none if customer.nil?
- user.store_credits.for_store(store).where(currency: currency).available.sort_by(&:amount_remaining).reverse
+ customer.store_credits.for_store(store).where(currency: currency).available.sort_by(&:amount_remaining).reverse
end
def could_use_store_credit?
@@@ -54,10 -47,12 +47,12 @@@
end
def total_applicable_store_credit
- if payment? || confirm? || complete?
+ # Once payments exist (or the record completed), report what was
+ # actually applied; before that, what could be applied.
+ if completed? || payments.valid.any?
total_applied_store_credit
else
- [total, user.try(:total_available_store_credit) || 0.0].min
+ [total, customer.try(:total_available_store_credit) || 0.0].min
end
end
diff --cc spree/core/app/models/spree/address.rb
index 3c45c4abe6,1503bdbf62..27d7100bf5
--- a/spree/core/app/models/spree/address.rb
+++ b/spree/core/app/models/spree/address.rb
@@@ -42,12 -42,12 +42,13 @@@ module Spre
belongs_to :country, class_name: 'Spree::Country'
belongs_to :state, class_name: 'Spree::State', optional: true
# we need a safe operator here as Address is added to metafield_enabled_resources in Engine
- belongs_to :user, class_name: Spree.user_class&.name, optional: true, touch: true
+ belongs_to :customer, class_name: Spree.customer_class&.name, optional: true, touch: true
+ include Spree::DeprecatedCustomerAlias
- has_many :shipments, inverse_of: :address
+ has_many :fulfillments, class_name: 'Spree::Fulfillment', inverse_of: :address
+ has_many :shipments, class_name: 'Spree::Fulfillment', foreign_key: :address_id, deprecated: true
- after_initialize :set_default_values, if: -> { new_record? && user.present? }
+ after_initialize :set_default_values, if: -> { new_record? && customer.present? }
before_validation :normalize_country
before_validation :normalize_state
@@@ -368,9 -381,9 +382,9 @@@
end
def unassign_from_incomplete_orders
- orders = Spree::Order.incomplete.where(user_id: user_id)
+ orders = Spree::Order.incomplete.where(customer_id: customer_id)
- orders.where(ship_address_id: id).update_all(ship_address_id: nil, state: 'address', updated_at: Time.current)
- orders.where(bill_address_id: id).update_all(bill_address_id: nil, state: 'address', updated_at: Time.current)
+ orders.where(ship_address_id: id).update_all(ship_address_id: nil, updated_at: Time.current)
+ orders.where(bill_address_id: id).update_all(bill_address_id: nil, updated_at: Time.current)
end
end
end
diff --cc spree/core/app/models/spree/newsletter_subscriber.rb
index d5ec1633d1,6f70666b35..10ac703bd2
--- a/spree/core/app/models/spree/newsletter_subscriber.rb
+++ b/spree/core/app/models/spree/newsletter_subscriber.rb
@@@ -16,10 -16,7 +16,9 @@@ module Spre
#
# Associations
#
- belongs_to :user, optional: true, class_name: Spree.user_class&.name
+ belongs_to :customer, optional: true, class_name: Spree.customer_class&.name
- belongs_to :store, class_name: 'Spree::Store', required: true
+
+ include Spree::DeprecatedCustomerAlias
#
# Validations
@@@ -46,9 -43,9 +45,9 @@@
#
self.whitelisted_ransackable_attributes = %w[email verified_at]
self.whitelisted_ransackable_scopes = %w[verified unverified]
-
+
def accepts_email_marketing
- return user.accepts_email_marketing if user.present?
+ return customer.accepts_email_marketing if customer.present?
verified?
end
diff --cc spree/core/app/models/spree/order.rb
index 3310c1217e,200684db70..27a65da7e0
--- a/spree/core/app/models/spree/order.rb
+++ b/spree/core/app/models/spree/order.rb
@@@ -79,43 -83,33 +83,33 @@@ module Spre
order
end
- # 5.5 API naming bridges (DB columns rename in 6.0)
- alias_attribute :discount_total, :promo_total
- alias display_discount_total display_promo_total
- alias_attribute :customer_note, :special_instructions
- alias_attribute :total_quantity, :item_count
-
- MONEY_THRESHOLD = 100_000_000
- MONEY_VALIDATION = {
- presence: true,
- numericality: {
- greater_than: -MONEY_THRESHOLD,
- less_than: MONEY_THRESHOLD,
- allow_blank: true
- },
- format: { with: /\A-?\d+(?:\.\d{1,2})?\z/, allow_blank: true }
- }.freeze
-
- POSITIVE_MONEY_VALIDATION = MONEY_VALIDATION.deep_dup.tap do |validation|
- validation.fetch(:numericality)[:greater_than_or_equal_to] = 0
- end.freeze
-
- NEGATIVE_MONEY_VALIDATION = MONEY_VALIDATION.deep_dup.tap do |validation|
- validation.fetch(:numericality)[:less_than_or_equal_to] = 0
- end.freeze
-
- checkout_flow do
- go_to_state :address
- go_to_state :delivery, if: ->(order) { order.delivery_required? }
- go_to_state :payment, if: ->(order) { order.payment? || order.payment_required? }
- go_to_state :confirm, if: ->(order) { order.confirmation_required? }
- go_to_state :complete
- end
-
- self.whitelisted_ransackable_associations = %w[shipments customer created_by approver canceler promotions bill_address ship_address line_items store channel tags]
+ # Standardized column names (renamed in 6.0); legacy readers stay as
+ # aliases one release.
+ alias_attribute :promo_total, :discount_total
+ alias display_promo_total display_discount_total
+ alias_attribute :item_count, :total_quantity
+
+ # @deprecated The column is +customer_note+ since 6.0; removed in 6.1.
+ def special_instructions
+ Spree::Deprecation.warn('Spree::Order#special_instructions is deprecated and will be removed in Spree 6.1. Use #customer_note instead.')
+ customer_note
+ end
+
+ # @deprecated See {#special_instructions}; removed in 6.1.
+ def special_instructions=(value)
+ Spree::Deprecation.warn('Spree::Order#special_instructions= is deprecated and will be removed in Spree 6.1. Use #customer_note= instead.')
+ self.customer_note = value
+ end
+
+ # lock_version (renamed from state_lock_version) drives the API's manual
+ # optimistic concurrency (compare client-sent version, 409 on mismatch) —
+ # Rails auto-locking must not raise on internal saves.
+ self.lock_optimistically = false
+
- self.whitelisted_ransackable_associations = %w[fulfillments shipments user created_by approver canceler promotions bill_address ship_address line_items store channel tags]
++ self.whitelisted_ransackable_associations = %w[fulfillments shipments customer created_by approver canceler promotions bill_address ship_address line_items store channel tags]
self.whitelisted_ransackable_attributes = %w[
- completed_at email number state status payment_state shipment_state
- total item_total item_count considered_risky channel_id currency
+ completed_at email number status payment_status payment_state fulfillment_status shipment_state delivery_total
+ total item_total total_quantity considered_risky channel_id currency coupon_code
]
self.whitelisted_ransackable_scopes = %w[complete incomplete refunded partially_refunded search multi_search]
@@@ -143,11 -133,24 +133,21 @@@
self.tag_list = tags
end
- ASSOCIATED_USER_ATTRIBUTES = [:user_id, :email, :bill_address_id, :ship_address_id]
+ ASSOCIATED_USER_ATTRIBUTES = [:customer_id, :email, :bill_address_id, :ship_address_id]
+ # @deprecated Use {Spree::Purchase::PaymentProcessing#payment_methods};
+ # removed in 6.1.
+ def collect_frontend_payment_methods
+ Spree::Deprecation.warn('Spree::Order#collect_frontend_payment_methods is deprecated and will be removed in Spree 6.1. Use #payment_methods instead.')
+ payment_methods
+ end
+
- # 6.0 forward-compat: User→Customer rename. Column stays user_id in 5.x.
- alias_attribute :customer_id, :user_id
+ include Spree::DeprecatedCustomerAlias
- belongs_to :user, class_name: "::#{Spree.user_class}", optional: true, autosave: true
- alias_method :customer, :user
- alias_method :customer=, :user=
+ belongs_to :customer, class_name: "::#{Spree.customer_class}", optional: true, autosave: true
+ # The cart this order was completed from (unique — the completion
+ # idempotency key). Backoffice draft orders have no cart.
+ belongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :order
belongs_to :created_by, class_name: "::#{Spree.admin_user_class}", optional: true
belongs_to :approver, class_name: "::#{Spree.admin_user_class}", optional: true
belongs_to :canceler, class_name: "::#{Spree.admin_user_class}", optional: true
@@@ -550,9 -482,9 +479,9 @@@
end
# Associates the specified user with the order.
- # Delegates to {Spree::Cart::Associate} service.
+ # Delegates to {Spree::Carts::Associate} service.
#
- # @param user [Spree.user_class] the user to associate with the order
+ # @param user [Spree.customer_class] the user to associate with the order
# @param override_email [Boolean] whether to override the order email with the user's email
# @return [Spree::ServiceModule::Result]
def associate_user!(user, override_email = true)
diff --cc spree/core/app/models/spree/payment_session.rb
index 59a1464138,f329cf0eab..9284400852
--- a/spree/core/app/models/spree/payment_session.rb
+++ b/spree/core/app/models/spree/payment_session.rb
@@@ -10,9 -10,10 +10,10 @@@ module Spre
publishes_lifecycle_events
- belongs_to :order, class_name: 'Spree::Order'
+ belongs_to :order, class_name: 'Spree::Order', optional: true
+ belongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :payment_sessions
belongs_to :payment_method, class_name: 'Spree::PaymentMethod'
- belongs_to :customer, class_name: Spree.user_class.to_s, optional: true
+ belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true
has_one :payment, class_name: 'Spree::Payment',
foreign_key: :response_code,
@@@ -122,11 -158,11 +158,11 @@@
end
def set_defaults_from_order
- return unless order
+ return unless owner
- self.amount ||= order.total_minus_store_credits if amount.blank? || amount.zero?
- self.currency ||= order.currency
- self.customer ||= order.customer
+ self.amount ||= owner.total_minus_store_credits if amount.blank? || amount.zero?
+ self.currency ||= owner.currency
- self.customer ||= owner.user
++ self.customer ||= owner.customer
end
end
end
diff --cc spree/core/app/models/spree/permission_sets/default_customer.rb
index 90091cdb48,6b36b0585a..8a91479dbc
--- a/spree/core/app/models/spree/permission_sets/default_customer.rb
+++ b/spree/core/app/models/spree/permission_sets/default_customer.rb
@@@ -29,21 -29,31 +29,29 @@@ module Spre
# Order management for the user's own orders
can :create, Spree::Order
can :show, Spree::Order do |order, token|
- order.user == user || order.token && token == order.token
+ order.customer == user || order.token && token == order.token
end
can :update, Spree::Order do |order, token|
- !order.completed? && (order.user == user || order.token && token == order.token)
+ !order.completed? && (order.customer == user || order.token && token == order.token)
end
+ # Cart management — the checkout owner since the cart/order split
+ can :create, Spree::Cart
+ can :show, Spree::Cart do |cart, token|
+ cart.customer == user || cart.token && token == cart.token
+ end
+ can [:update, :destroy], Spree::Cart do |cart, token|
+ !cart.completed? && (cart.customer == user || cart.token && token == cart.token)
+ end
+
# Line item management
can :create, Spree::LineItem do |line_item, token|
- line_item.order.customer == user || line_item.order.token && token == line_item.order.token
- end
- can :update, Spree::LineItem do |line_item, token|
- !line_item.order.completed? && (line_item.order.customer == user || line_item.order.token && token == line_item.order.token)
+ owner = line_item.owner
- owner_user = owner.is_a?(Spree::Cart) ? owner.customer : owner.user
- owner_user == user || owner.token && token == owner.token
++ owner.customer == user || owner.token && token == owner.token
end
- can :destroy, Spree::LineItem do |line_item, token|
- !line_item.order.completed? && (line_item.order.customer == user || line_item.order.token && token == line_item.order.token)
+ can [:update, :destroy], Spree::LineItem do |line_item, token|
+ owner = line_item.owner
- owner_user = owner.is_a?(Spree::Cart) ? owner.customer : owner.user
- !owner.completed? && (owner_user == user || owner.token && token == owner.token)
++ !owner.completed? && (owner.customer == user || owner.token && token == owner.token)
end
# User account management - available to all users (including guests for their own record)
diff --cc spree/core/app/services/spree/addresses/update.rb
index 4ee848e971,232889e06c..b1b4df75d0
--- a/spree/core/app/services/spree/addresses/update.rb
+++ b/spree/core/app/services/spree/addresses/update.rb
@@@ -62,12 -62,12 +62,12 @@@ module Spre
old_address_id = address.id
address.destroy!
- if new_address.user.present?
+ if new_address.customer.present?
- default_billing = address.user_default_billing? || default_billing
- default_shipping = address.user_default_shipping? || default_shipping
+ default_billing = address.is_default_billing? || default_billing
+ default_shipping = address.is_default_shipping || default_shipping
assign_to_user_as_default(
- user: new_address.user,
+ user: new_address.customer,
address_id: new_address.id,
default_billing: default_billing,
default_shipping: default_shipping
@@@ -90,9 -90,9 +90,9 @@@
end
def reassign_incomplete_orders(old_address_id, new_address)
- orders = Spree::Order.incomplete.where(user_id: new_address.user_id)
+ orders = Spree::Order.incomplete.where(customer_id: new_address.customer_id)
- orders.where(ship_address_id: old_address_id).update_all(ship_address_id: new_address.id, state: 'address', updated_at: Time.current)
- orders.where(bill_address_id: old_address_id).update_all(bill_address_id: new_address.id, state: 'address', updated_at: Time.current)
+ orders.where(ship_address_id: old_address_id).update_all(ship_address_id: new_address.id, updated_at: Time.current)
+ orders.where(bill_address_id: old_address_id).update_all(bill_address_id: new_address.id, updated_at: Time.current)
end
def defaults_changed?(address, default_billing, default_shipping)
diff --cc spree/core/app/services/spree/carts/update.rb
index 191addc291,e6ef48c9dd..6d244c07c4
--- a/spree/core/app/services/spree/carts/update.rb
+++ b/spree/core/app/services/spree/carts/update.rb
@@@ -80,11 -100,21 +100,21 @@@ module Spre
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
+ return unless cart.customer
decoded = Spree::Address.decode_prefixed_id(prefixed_id)
- decoded ? cart.user.addresses.find_by(id: decoded)&.id : nil
+ decoded ? cart.customer.addresses.find_by(id: decoded)&.id : nil
end
def assign_market
diff --cc spree/core/config/locales/en.yml
index 75e68c9f08,5da52537fd..e8459366c0
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@@ -274,14 -275,10 +275,18 @@@ en
base:
card_expired: Card has expired
expiry_invalid: Card expiration is invalid
+ spree/customer:
+ attributes:
+ bill_address_id:
+ belongs_to_other_user: belongs to other user
+ deprecated_in_completed_order: deprecated in completed order
+ ship_address_id:
+ belongs_to_other_user: belongs to other user
+ deprecated_in_completed_order: deprecated in completed order
+ spree/exchange_line_item:
+ attributes:
+ new_variant:
+ must_differ_from_original: must be different from the item being returned
spree/gift_card:
attributes:
base:
diff --cc spree/core/lib/spree/testing_support/factories/payment_factory.rb
index 419f4b54fe,744727e571..b0667ed7b8
--- a/spree/core/lib/spree/testing_support/factories/payment_factory.rb
+++ b/spree/core/lib/spree/testing_support/factories/payment_factory.rb
@@@ -29,7 -29,7 +29,7 @@@ FactoryBot.define d
end
factory :store_credit_payment, class: Spree::Payment, parent: :payment do
- payment_method { create(:store_credit_payment_method, store: order.store) }
- source { create(:store_credit, store: order.store, customer: order.customer) }
+ payment_method { create(:store_credit_payment_method, store: (order || cart).store) }
- source { create(:store_credit, store: (order || cart).store, user: (order || cart).customer) }
++ source { create(:store_credit, store: (order || cart).store, customer: (order || cart).customer) }
end
end
diff --cc spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
index 14c525d9b3,41d41030df..985d7fb318
--- a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
+++ b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml
@@@ -53,30 -53,91 +53,119 @@@ steps
Idempotent. Multi-tenant installs run the per-tenant override shipped by
spree_multi_tenant.
+ - id: migrate_users_to_customers
+ name: "Move users onto the gem-owned Customer/AdminUser models"
+ task: "spree:upgrade:migrate_users_to_customers"
+ notes: |
+ Copies the legacy Devise user table (default spree_users) into
+ spree_customers, preserving ids so the renamed customer_id foreign keys
+ still resolve and mapping encrypted_password -> password_digest, then
+ re-points every polymorphic reference that named the old customer class
+ (default Spree::User) to Spree::Customer — the user_type columns plus
+ customer_type on customer-group memberships — and backfills password_digest
+ on spree_admin_users.
+
+ Precondition: NO Devise pepper. encrypted_password is a plain bcrypt digest
+ that has_secure_password reads directly only when unpeppered; the task
+ aborts if Devise.pepper is set. Because Devise is gone in 6.0 a former
+ pepper can't be introspected, so when Devise is absent the task aborts until
+ you confirm none was used with CONFIRM_NO_PEPPER=true. Peppered / SSO /
+ non-bcrypt installs keep a custom customer_class instead (see the 5.6-to-6.0
+ upgrade guide) and skip this step.
+
+ Source rows with a blank email, or whose email is already owned by a
+ different customer, abort the task with their ids — reconcile them or pass
+ SKIP_INVALID_ROWS=true to skip and continue.
+
+ Idempotent. The source table is left in place as a safety net — drop it
+ manually once the migration is verified. Override the source with
+ SOURCE_USER_TABLE / SOURCE_USER_TYPE and batch size with BATCH_SIZE.
++
+ - id: migrate_shipping_to_delivery
+ name: "Backfill fulfillment & delivery naming"
+ task: "spree:migrate_shipping_to_delivery"
+ notes: |
+ Rewrites stored 'Spree::Shipment' class-name strings (state changes,
+ stock movements, legacy adjustments), renames the terminal fulfillment
+ status 'shipped' -> 'fulfilled', backfills fulfillment_type and the
+ fulfillment provider on delivery methods (DigitalDelivery calculators
+ become digital + the Digital provider) and copies the type onto existing
+ fulfillments, assigns the Digital product type to products in
+ digital-only shipping categories, and converts display_on into the
+ storefront_visible boolean. Idempotent.
+
+ - id: migrate_zones_to_delivery_zones
+ name: "Convert delivery zones"
+ task: "spree:migrate_zones_to_delivery_zones"
+ notes: |
+ Converts legacy Spree::Zone rows referenced by delivery methods into
+ Spree::DeliveryZone records with typed country/state members and
+ re-points the join rows. Run immediately after db:migrate, before
+ creating new delivery zones, so unmigrated ids stay unambiguous.
+ Tax-scoped zones are left for the tax-provider migration; unreferenced
+ shipping zones are logged and skipped. Idempotent via a
+ migrated_from_zone_id marker.
+
+ - id: migrate_adjustments_to_typed_rows
+ name: "Convert adjustments to typed rows"
+ task: "spree:migrate_adjustments_to_typed_rows"
+ notes: |
+ Converts legacy spree_adjustments into TaxLine / Discount / Fee rows:
+ tax-rate rows become tax lines with rate snapshots, eligible promotion
+ rows become discounts (order-level amounts distributed across line items
+ largest-remainder), sourceless rows map by sign to manual discounts or
+ surcharges, and unknown sources become fees with provenance metadata.
+ Order totals are never modified; per-order reconciliation freezes and
+ logs any order whose typed sums don't match its stored totals.
+ ReturnAuthorization adjustments freeze the order for the returns
+ migration. spree_adjustments stays intact as the rollback source.
+ Idempotent — orders that already have typed rows are skipped.
+
+ - id: backfill_delivery_and_stock_store_ids
+ name: "Bind delivery methods and stock locations to the default store"
+ task: "spree:backfill_delivery_and_stock_store_ids"
+ notes: |
+ Delivery methods and stock locations carry a store_id in Spree 6.
+ Unassigned rows go to the default store; additional stores manage
+ their own records afterwards. The NOT NULL constraints land in 6.1.
+ Idempotent.
+
+ - id: backfill_order_markets
+ name: "Backfill order markets"
+ task: "spree:backfill_order_markets"
+ notes: |
+ Market is mandatory in Spree 6. Assigns the store's default market to
+ orders that predate markets. Channel needs no step here — the 5.4→5.5
+ manifest's channels step already backfills channel_id on every upgrade
+ path. Run before the cart conversion so converted carts inherit
+ resolved values. The NOT NULL constraints on spree_orders land in 6.1.
+ Idempotent.
+
+ - id: migrate_incomplete_orders_to_carts
+ name: "Convert incomplete orders to carts"
+ task: "spree:migrate_incomplete_orders_to_carts"
+ notes: |
+ The final flip: every order that never completed nor canceled becomes a
+ Spree::Cart with the same token, binding, addresses and totals. Line
+ items, payments, payment sessions, reservations, coupon codes, applied
+ promotions and typed adjustment rows are re-owned onto the cart and the
+ hollow order row is deleted. Orders holding payment sessions convert
+ last. Completed and canceled orders are untouched. Run AFTER
+ migrate_adjustments_to_typed_rows so the typed rows exist to re-own.
+
+ - id: migrate_calculator_bounds_to_delivery_method_rules
+ name: "Convert calculator eligibility bounds to delivery method rules"
+ task: "spree:migrate_calculator_bounds_to_delivery_method_rules"
+ notes: |
+ Folds the FlatRate calculator's min/max item-total and weight
+ preferences into DeliveryMethodRule rows (eligibility separated from
+ pricing — see 6.0-delivery-method-rules.md) and clears the migrated
+ preferences so they aren't double-enforced. Run after
+ migrate_shipping_to_delivery. Idempotent.
+
+ - id: product_types_backfill
+ name: "Backfill product type store ownership"
+ task: "spree:product_types:backfill"
+ notes: |
+ Assigns store-less product types to the default store, removes orphaned
+ option-type joins, and resets product counters. Idempotent.
diff --cc spree/core/spec/models/spree/credit_card_spec.rb
index 82d8f3af1a,f30786368c..f5e78e3af4
--- a/spree/core/spec/models/spree/credit_card_spec.rb
+++ b/spree/core/spec/models/spree/credit_card_spec.rb
@@@ -175,8 -175,15 +175,15 @@@ describe Spree::CreditCard, type: :mode
expect(build_duplicate(payment_method: create(:credit_card_payment_method))).to be_valid
end
+ it 'allows the same fingerprint for guest payment sources' do
+ create(:credit_card, user: nil, payment_method: payment_method,
+ fingerprint: 'FZqjhq46SWprIY8i', month: 11, year: 2030)
+
+ expect(build_duplicate(user: nil)).to be_valid
+ end
+
it 'does not enforce uniqueness when the fingerprint is missing' do
- create(:credit_card, user: user, payment_method: payment_method, fingerprint: nil, month: 11, year: 2030)
+ create(:credit_card, customer: user, payment_method: payment_method, fingerprint: nil, month: 11, year: 2030)
expect(build_duplicate(fingerprint: nil)).to be_valid
end
diff --cc spree/core/spec/models/spree/order_spec.rb
index af4e6cd6c7,88a7b68ef9..dc20954861
--- a/spree/core/spec/models/spree/order_spec.rb
+++ b/spree/core/spec/models/spree/order_spec.rb
@@@ -11,9 -11,9 +11,9 @@@ describe Spree::Order, type: :model d
let(:user) { create(:user) }
let!(:store) { @default_store }
- let(:order) { create(:order, customer: user, store: store) }
+ let(:order) { create(:order, user: user, store: store) }
- before { allow(Spree::LegacyUser).to receive_messages(current: build(:user)) }
+ before { allow(Spree.customer_class).to receive_messages(current: build(:user)) }
it_behaves_like 'metadata'
diff --cc spree/core/spec/services/spree/addresses/update_spec.rb
index ccf3a7445b,fe89618733..3428a7bfbc
--- a/spree/core/spec/services/spree/addresses/update_spec.rb
+++ b/spree/core/spec/services/spree/addresses/update_spec.rb
@@@ -122,10 -122,10 +122,10 @@@ RSpec.describe Spree::Addresses::Updat
end
context 'when order is passed' do
- let(:order) { create(:order, user: user, state: 'delivery', ship_address: address, bill_address: address) }
+ let(:order) { create(:order, customer: user, state: 'delivery', ship_address: address, bill_address: address) }
it 'updates order to address state' do
- expect { result }.to change { order.reload.state }.from('delivery').to('address')
+ expect { result }.not_to raise_error
end
end
@@@ -224,10 -224,10 +224,10 @@@
end
context 'when order with deleted address is passed' do
- let(:order) { create(:order, user: user, state: 'delivery', ship_address: address, bill_address: address) }
+ let(:order) { create(:order, customer: user, state: 'delivery', ship_address: address, bill_address: address) }
it 'updates order to address state' do
- expect { result }.to change { order.reload.state }.from('delivery').to('address')
+ expect { result }.not_to raise_error
end
it 'updates order ship address' do