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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Update plans for Spree 6.0
Damian Legawiec27f73670783a
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8071841ba9..f41c82a331 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -13,7 +13,7 @@ Use `/project:create-plan` and `/project:update-plan` for plan management.Active plans (6.0 target, work pending):- `6.0-multi-vendor-marketplace.md` — Open-source the marketplace core (Vendor, OrderGroup-based order splitting, commission engine with EU commission taxation, `VendorTransfer`/`VendorPayout` ledger + pluggable `PayoutProvider`) per spree/spree#13323. 6.0 headline feature; rebuilds the legacy Enterprise multi-vendor module as native models on the Cart/Order split. Basic Stripe Connect payouts (Express onboarding + on-fulfillment transfers) ship OSS in the monorepo, alongside the Stripe core gateway pulled in from the standalone `spree_stripe` repo (payment-sessions classes only, likely `spree/core` — decisions.md 2026-07-15); Enterprise keeps refund clawbacks/netting, reconciliation, KYC ops, DAC7 payout reports, facilitator taxes + Shopify/WooCommerce vendor apps.-- `6.0-cart-order-split.md` — Cart/Order model separation, polymorphic LineItem+- `6.0-cart-order-split.md` — Cart/Order model separation, dual-FK owner everywhere (`cart_id`/`order_id` exactly-one, `#owner` as method — NOT polymorphic), idempotent copy-on-completion (`Order#cart_id` unique, order-before-payment), Order state machine removed (Checkout::Requirements for steps; payment/fulfillment statuses derived-then-persisted via one recompute service). Expanded 2026-07-27; gates split-adjustments, fulfillment, multi-vendor- `6.0-admin-api.md` — Admin REST API conventions, auth, endpoint list (~300 endpoints)- `6.0-admin-spa.md` — React admin architecture, extension points, table registry, i18n + server-error mapping- `6.0-product-types.md` — Prototype → ProductType rename, MetafieldDefinition schema enforcement@@ -24,8 +24,9 @@ Active plans (6.0 target, work pending):- `6.0-fulfillment-and-delivery.md` — Shipment→Fulfillment, ShippingMethod→DeliveryMethod, drop ShippingCategory, FulfillmentProvider strategy, pickup (merchant StockLocation) + pickup_point (third-party PickupPointProvider)- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename (RefreshToken shipped in 5.4)-- `6.0-tax-provider.md` — Per-Market TaxProvider, replaces TaxRate.adjust + Calculator, drop Zone model (TaxRate gets direct country/state FKs)-- `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider, replaces Estimator + Calculator, DeliveryZone with postal code support+- `6.0-tax-provider.md` — Per-Market TaxProvider, replaces TaxRate.adjust + Calculator; TaxRate gets direct country/state FKs (tax decoupled from Zone; Zone model dropped in 6.0 via `6.0-delivery-zones.md`)+- `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider wrapping Stock::Estimator (calculators stay — 2026-07-27 reversal), `store_id` on ShippingMethod, enriched DeliveryRate (carrier/service/date/metadata)+- `6.0-delivery-zones.md` — Zone → DeliveryZone with postal-code-range/prefix members (country-scoped); owns the full ~183-reference Zone consumer inventory; `Spree::Zone` dropped entirely by end of 6.0 (2026-07-27 — 6.0 is the breaking-change window)- `6.0-rich-text-descriptions.md` — Drop ActionText storage, store HTML in text columns, sanitize on write, serve `description` + `description_html` in API (description_html serializer field shipped in 5.4)- `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). `Spree::Category < Spree::Taxon` alias + Category API surface shipped in 5.5; table rename + Collection pending.@@ -41,11 +42,11 @@ Multi-version plans (some phases shipped, some pending):- `6.0-order-routing.md` — Two-tier extension: pluggable `Spree::OrderRouting::Strategy::Base` + STI subclasses of `Spree::OrderRoutingRule`. Phase 1 (5.5) shipped: `Channel`, `OrderRoutingRule`, strategy base + Rules + Reducer + Legacy, `preferred_stock_location_id` + `channel_id` on Order. Phase 2+ (6.0) layers Catalog/Company on top via `6.0-channels-catalogs-b2b.md`.- `6.0-channels-catalogs-b2b.md` — Channel + ProductPublication (replaces StoreProduct) + single-owner Product (`belongs_to :store`) + Publishing card (legacy admin + SPA) + `Channel#default` boolean shipped in 5.5. Channel-level gated storefront access (`storefront_access` enum + channel-owned `guest_checkout`, both with store fallback, enforced in the v3 Store API) targeted for 5.6. Catalog, Company/CompanyLocation/CompanyContact for B2B **deferred to 6.1** (the B2B release — see `docs/plans/decisions.md` 2026-06-16; filename keeps `6.0-` prefix for stable cross-refs). Multi-store catalogs (historic `Product has_many :stores`) move to the `spree_multi_store` extension.- `5.6-6.0-single-store-promotions-payment-methods.md` — Migrate `Spree::Promotion` + `Spree::PaymentMethod` from multi-store (`has_many :stores` via `spree_promotions_stores` / `spree_payment_methods_stores` join tables) to single-owner `belongs_to :store`, mirroring the 5.5 single-owner Product migration. 5.6 (implemented): `store_id` FK + required-store presence via `Spree::SingleStoreResource`, backfill rake task (loud per-record deprecation on shared records), shared `LegacyMultiStoreSupport` deprecation bridge, deletes the `ResourceController` `store_ids=` seam, deprecates `StoreScopedResource`; multi-store sharing moves to the `spree_multi_store` extension (join tables left intact). 6.0 cleanup: enforce `null: false`, drop join tables + bridges. Paired with `6.0-channels-catalogs-b2b.md`.-- `5.6-project-layout-and-dashboard.md` — React Dashboard Developer Preview packaging + `backend/` → `api/` project layout. Implemented: `<Dashboard />` shell export from `@spree/dashboard` (source-only, relative imports only), monorepo-canonical `packages/dashboard-starter` thin host (embedded standalone into the `@spree/cli` tarball at build time via `scripts/sync-dashboard-starter.mjs` — Vendure-style, no template repo; create-spree-app delegates to the project-local `spree add dashboard`), `spree add dashboard` + create-spree-app dashboard phase (opt-in via `--react-dashboard` while WIP — not prompted; env carries only `VITE_API_PROXY_TARGET` — never secret keys, and never `VITE_SPREE_API_URL`, which would flip the SDK to absolute cross-origin URLs and break dev on CORS), npm release job for `@spree/dashboard{,-ui,-core}` (0.x → `next` tag). Pending: layout rename + `detectApiDir` dual-layout CLI, `spree upgrade layout`; optional public template repo at 6.0 GA.+- `5.6-project-layout-and-dashboard.md` — React Dashboard Developer Preview packaging + `backend/` → `api/` project layout. Implemented: `<Dashboard />` shell export from `@spree/dashboard` (source-only, relative imports only), monorepo-canonical `packages/dashboard-starter` thin host (embedded standalone into the `@spree/cli` tarball at build time via `scripts/sync-dashboard-starter.mjs` — no template repo; create-spree-app delegates to the project-local `spree add dashboard`), `spree add dashboard` + create-spree-app dashboard phase (opt-in via `--react-dashboard` while WIP — not prompted; env carries only `VITE_API_PROXY_TARGET` — never secret keys, and never `VITE_SPREE_API_URL`, which would flip the SDK to absolute cross-origin URLs and break dev on CORS), npm release job for `@spree/dashboard{,-ui,-core}` (0.x → `next` tag). Pending: layout rename + `detectApiDir` dual-layout CLI, `spree upgrade layout`; optional public template repo at 6.0 GA.- `5.6-dashboard-typed-plugin-routes.md` — Plugin file routes compiled into the host's TanStack route tree: `spree.dashboard.routes` marker + virtual-route-config composition in `@spree/dashboard/vite`, `createDashboardRouter` + `<Dashboard router>` ownership inversion, typed cast-free links, cross-package collision pre-flight with package-named errors. Runtime route registry stays for dynamic/in-app cases (catch-all is lowest priority). Implemented; published-tarball spike passed.Pending design work (drafts, no implementation yet):-- `5.7-payment-method-rules.md` — `Spree::PaymentMethodRule` STI on PaymentMethod (Channel / Market / OrderTotal / CustomerGroup rules), mirroring the PromotionRule/PriceRule/OrderRoutingRule pattern. Enforced solely through `Order#collect_frontend_payment_methods` (listing + `Payments::Create` + payment sessions all flow through it); admin/backoffice bypasses; no rules = available everywhere. Dashboard-only management (nested Admin API CRUD + `/payment_method_rules/types` discovery). Supersedes the "no distribution concept" rationale in `5.6-6.0-single-store-promotions-payment-methods.md`; per-channel provider credentials (multiple Stripe accounts, Shopify-style multi-entity) explicitly deferred for grooming — see decisions.md 2026-07-23.+- `5.7-payment-method-rules.md` — `Spree::PaymentMethodRule` STI on PaymentMethod (Channel / Market / OrderTotal / CustomerGroup rules), mirroring the PromotionRule/PriceRule/OrderRoutingRule pattern. Enforced solely through `Order#collect_frontend_payment_methods` (listing + `Payments::Create` + payment sessions all flow through it); admin/backoffice bypasses; no rules = available everywhere. Dashboard-only management (nested Admin API CRUD + `/payment_method_rules/types` discovery). Supersedes the "no distribution concept" rationale in `5.6-6.0-single-store-promotions-payment-methods.md`; per-channel provider credentials (multiple Stripe accounts, multi-entity setups) explicitly deferred for grooming — see decisions.md 2026-07-23.- `5.7-channel-markets.md` — Optional Channel→Markets allowlist (`spree_channel_markets` join, empty = all markets). Enforced in market resolution (`set_market_from_country` + channel-aware `Spree::Current.market` fallback), channel-filtered Store API `/store/markets`, and order-level `market must be served by channel` validation. Composes with `MarketRule` from the payment-method-rules plan.- `5.6-admin-spa-csv-import.md` — Universal dashboard CSV import over the existing `Spree::Import` pipeline (implemented). Admin API v3 surface (create via direct-upload signed blob, `complete_mapping`, `retry_failed_rows`, nested failed-rows index, write-scope gating), `client.imports` SDK resource, dashboard-core `ImportButton` (per-context `<Can>` gating, upload Sheet) + full-window wizard dialog driven by an `?import=` search param, with history under `/settings/imports` (new `audit` settings-nav group). Status via API polling — explicitly no ActionCable/Turbo Streams in the SPA; legacy per-row live feed replaced by polled counters + paginated failed-rows table.- `5.5-6.0-resource-translations-api.md` — Admin API v3 translation management + React dashboard for all `Spree.translatable_resources`. Hybrid: embedded `translations` object on resource update + generic dedicated `…/:id/translations` endpoint (one registry-driven controller), self-describing field discovery, advisory server-side staleness. Canonical `{ locale → { field → value } }` shape (consistent with metafield-translations). Cross-record bulk = CSV import/export generalized across the registry (NOT a JSON bulk endpoint — no competitor ships one). Phase 1 (5.5) API; Phase 2 (6.0) coverage read + CSV generalization + staleness + centralized SPA page; Phase 3 folds in metafields.@@ -60,7 +61,7 @@ Shipped plans:- `5.4-search-provider.md` — Pluggable SearchProvider interface (Database + Meilisearch); PgSearch + `add_search_scope` removed (6.0 MetafieldDefinition faceting still pending)- `5.4-disjunctive-option-faceting.md` — Per-option-type filter params with disjunctive facet counts (`FiltersAggregator` for DB, `merge_disjunctive_facets` for Meilisearch)- `6.0-stock-reservations.md` — Time-limited stock reservations during checkout (PR #13978; Cart/Order split integration + `allocated_count` term still pending for 6.0)-- `5.5-admin-api-key-scopes.md` — Shopify-style `read_*`/`write_*` scopes on `Spree::ApiKey` for app authorization+- `5.5-admin-api-key-scopes.md` — granular `read_*`/`write_*` scopes on `Spree::ApiKey` for app authorization- `5.5-admin-auth-cookie-refresh.md` — Admin SPA refresh token in httpOnly cookie, access token in memory, server-side logout- `5.5-admin-customers-api.md` — Admin Customers + nested addresses/credit_cards/store_credits + CustomerGroups- `5.5-admin-spa-csv-export.md` — Admin API ExportsController + admin-sdk + `useExport` + toolbar export button@@ -380,7 +381,7 @@ For new models, add `publishes_lifecycle_events` concern and create an event serFour credential types, each with its own header and authorization model:- **Publishable keys** (`pk_xxx`) — Store API, `X-Spree-API-Key` header. Identifies the store; permits public/guest endpoints. Safe to expose in client-side code.-- **Secret keys** (`sk_xxx`) — Admin API, `X-Spree-API-Key` header. **Server-to-server only.** Each key carries a list of [Shopify-style scopes](docs/plans/5.5-admin-api-key-scopes.md) (`read_products`, `write_orders`, etc.) that gate which endpoints it can hit. Authorization is scope-based, not CanCanCan-based.+- **Secret keys** (`sk_xxx`) — Admin API, `X-Spree-API-Key` header. **Server-to-server only.** Each key carries a list of [granular scopes](docs/plans/5.5-admin-api-key-scopes.md) (`read_products`, `write_orders`, etc.) that gate which endpoints it can hit. Authorization is scope-based, not CanCanCan-based.- **JWT tokens** — user auth, `Authorization: Bearer <token>` header. Used by both Store API (logged-in customer) and Admin API (logged-in admin user). Admin JWT auth uses **CanCanCan abilities** for authorization, not scopes — this is what the admin SPA uses.- **Guest cart tokens** — `X-Spree-Token` header. Authorizes operations on a specific guest cart.diff --git a/docs/plans/6.0-admin-api.md b/docs/plans/6.0-admin-api.mdindex 7b7ef61e4b..6a240b4039 100644--- a/docs/plans/6.0-admin-api.md+++ b/docs/plans/6.0-admin-api.md@@ -428,7 +428,7 @@ Managed via nested payload on the Option Type (`option_values: [{ id, name, labe- [x] `PATCH /api/v3/admin/orders/:id/resume`- [x] `POST /api/v3/admin/orders/:id/resend_confirmation`-> **6.0:** Order state machine dropped (derived status from line items + fulfillments + payments — see `6.0-cart-order-split.md`). `PATCH /next` and `/advance` no longer apply and have been removed from the 5.x admin API ahead of the 6.0 cart/order split. Cart and Order are separate models; `LineItem.owner` is polymorphic. Order gains `channel_id`, `company_location_id`, `withdrawal_eligible_until` FKs.+> **6.0:** Order state machine dropped (derived status from line items + fulfillments + payments — see `6.0-cart-order-split.md`). `PATCH /next` and `/advance` no longer apply and have been removed from the 5.x admin API ahead of the 6.0 cart/order split. Cart and Order are separate models; `LineItem` owner is the dual-FK pattern (`cart_id`/`order_id` exactly-one, `#owner` method — 2026-07-27). Order gains `channel_id`, `company_location_id`, `withdrawal_eligible_until` FKs.### Items (nested under Orders — matches Store API `/carts/:id/items` convention)- [x] `GET /api/v3/admin/orders/:order_id/items`diff --git a/docs/plans/6.0-cart-order-split.md b/docs/plans/6.0-cart-order-split.mdindex 5348491939..c35ae74489 100644--- a/docs/plans/6.0-cart-order-split.md+++ b/docs/plans/6.0-cart-order-split.md@@ -1,22 +1,273 @@# Cart/Order Split-**Status:** Design finalized, implementation not started-**Target:** Spree 6.0-**Depends on:** API v3 conventions+**Status:** Design finalized (expanded 2026-07-27 from the original stub), implementation not started+**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-27++## Summary++Cart and Order become separate models. A `Spree::Cart` owns the shopping/checkout phase; completing checkout copies it into an immutable `Spree::Order` (`cart.complete!` → `Spree::Carts::Complete`). The Order state machine is removed: checkout progression is answered by the (already shipped) `Spree::Checkout::Requirements`, and order-level payment/fulfillment statuses are **derived-then-persisted** — one recompute service writing indexed columns.++Industry (2026-07-27 review, primary sources): separate cart/order with copy-on-completion is the majority pattern — OSS platform A (Cart module → Order module, parallel tables, cart retained with `completed_at`), OSS platform B (Checkout → Order via `checkoutComplete`, idempotent on `checkout_token`), the hosted market leader (which *deleted* its intermediate Checkout API entirely in 2025 in favor of Cart → Order). OSS platform C is the lone single-entity dissenter, and its workarounds (`active` flag, `orderPlacedAt`, `orderPlacedQuantity` snapshots, `Modifying` states that re-open placed orders) are the argument for splitting.++## What already exists (verified 2026-07-27)++The codebase is further along than the old stub implied — the split formalizes seams that are already drawn:++- **The v3 Store API is already cart-shaped.** `Spree::Carts::{Create,Update,UpsertItems,Complete}` exist with explicit "In Spree 6 …" comments; routes are `/store/carts/...` + read-only `/store/orders/:id`. This plan rewrites `Carts::Complete`'s internals — the public surface barely moves.+- **The API contract is step-shaped, not state-shaped.** `CartSerializer` exposes only `current_step`, `completed_steps`, `requirements`, `warnings` — never raw `state`. `OrderSerializer` exposes `payment_status`/`fulfillment_status`/`completed_at` — no state, no steps.+- **`Spree::Checkout::Requirements` + `Checkout::Registry`** already compute "what's missing to complete" with zero reads of `order.state` (`default_requirements.rb:6-7` says the 6.0 intent verbatim). One fix needed: `Registry#ordered_steps` currently derives ordering from `Order.checkout_step_names` — that circular dependency gets cut (the registry owns its own step list).+- **The query layer already draws the boundary on `completed_at`.** `Order.complete`/`.incomplete` (the dominant scopes) key on `completed_at`, not `state`; `Store#carts`/`#checkouts` are `incomplete`-scoped. Only four raw `where(state:)` sites exist against orders, all trivially re-expressible.+- **`Order#status` (`draft`/`placed`/`canceled`) already exists** and is maintained by `finalize!`/`after_cancel`/`after_resume` — the lifecycle column survives; the checkout `state` column does not.+- **`LineItem` has half the owner pattern already** — `belongs_to :order` with presence validation and a real `order_id` FK. Under the unified dual-FK owner design (Key Decision 2), Phase 1 only adds nullable `cart_id` and relaxes presence to exactly-one; `order_id` stays forever. The old constraint "use `line_item.owner`" was unimplementable until then; `owner` ships as a method.## Key Decisions (do not deviate without discussion)-- Cart and Order become separate models-- LineItem uses polymorphic `owner` (Cart or Order)-- Copy-on-completion semantics: completing checkout copies cart items to order via `cart.complete!` (which calls `Spree::Carts::Complete` service object)-- Order-level state machine removed; status is derived-- No `Spree::Order` state column in new model++### 1. `Spree::Cart` model; Order keeps its table++`Spree::Cart` (prefix `cart_`, `spree_carts`) owns the pre-completion phase: store/market/channel/currency/locale/customer binding (settling today's three inconsistent creation paths — `current_order` creates orders without market/channel/locale and would fail multi-market validation), email, ship/bill address references, `accept_marketing`, special instructions, its own `has_secure_token`, `metadata`, `completed_at`, `completing_at` (completion lock). Carts have **no status column** (OSS platform A: `completed_at` is the only lifecycle marker). Order keeps `spree_orders`; its `state` column is dropped, `status` stays.++### 2. One owner pattern everywhere: dual concrete FKs (`cart_id`/`order_id`, exactly-one) — NOT polymorphic++Supersedes the original stub's "polymorphic `owner`" (decision 2026-07-27). 6.0's design language is concrete FKs over polymorphic type strings (split-adjustments removes `adjustable_type`, typed-stock-movements removes `originator_type`) — LineItem doesn't get to reintroduce the pattern the release removes. So **every** cart-or-order-owned table uses the same shape: nullable `cart_id` + nullable `order_id`, exactly-one validation, `#owner` as a method (`order || cart`). That covers `spree_line_items` (which only gains `cart_id` — `order_id` already exists and **stays permanently**; the cheapest possible migration), the typed money lines (`TaxLine`/`Discount`/`Fee` — split-adjustments), and `Fulfillment`/`DeliveryRate` (fulfillment plan).++**Provenance needs no second FK on the row.** `Order#cart_id` (unique — the idempotency key) links every order to its cart; the retained cart keeps its own rows as the frozen at-checkout snapshot, so "which cart did this come from" is answered through the order, and post-placement additions are distinguishable (rows the order has that its cart never had). Both-columns-set was considered and rejected: order-side copies carrying `cart_id` would collide with the cart's own rows in every `cart.line_items`-style association.++LineItem's 22 internal + 14 external `order` reads move to `owner` (pricing context, tax zone, inventory, promo allocation, guest-token permission checks); order-owned items keep answering `line_item.order` natively.++### 3. Copy-on-completion — copy everything, share nothing++At completion the order receives **copies**: line items (with new IDs; typed money lines re-pointed per the split-adjustments copy contract), fulfillments + selected delivery rates, and **addresses** (never shared rows — OSS platform B copies addresses precisely so a later cart/profile edit can't corrupt order history). The cart is **retained** with `completed_at` + the order link (OSS platform A's choice, not the hosted leader's deletion) — retention is what makes idempotent replay natural and preserves abandoned-cart analytics. The guest token is carried onto the order so the confirmation page works with the credential the guest already holds.++### 4. Idempotent completion (the top gap in the old stub)++Every competitor treats this as load-bearing. `Spree::Carts::Complete`:++- `spree_orders.cart_id` with a **unique index** — stronger than OSS platform B's `filter().first()` under true concurrency.+- On entry: if an order exists for this cart, **return it as success** — a double-clicked Place Order or a retry after a lost response must get the order back, never an error (OSS platform B ships three separate recovery paths for exactly this).+- `cart.with_lock` + `completing_at` guard against parallel attempts.+- **Order created before payment capture** (OSS platform A, verbatim rationale: minimizes the window in which an authorized/captured payment must be rolled back); compensation voids on post-payment failure. Applies to external gateways; offline methods (Check, net terms, COD, manual) have no external window and complete in a single transaction.+- Usage counters (coupon codes, gift cards, promotion `credits_count` inputs) guarded by persisted flags (OSS platform B's `is_voucher_usage_increased`) — counters are the classic double-count victim on retry.+- The **payment-webhook completion path stays** (`Payments::HandleWebhook` → same service): with the unique index + lock, the two-writer race (synchronous complete vs. webhook) is safe by construction, not by the current 30-second job delay.++### 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).++**(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.++**(c) Statuses → derive-then-persist (OSS platform B's hybrid, explicitly not OSS platform A's pure derivation).** OSS platform A derives payment/fulfillment status at read time and has open bugs to show for it (can't filter/sort admin order lists — #14095; status stuck after full return — #13882); the hosted market leader has the analogous `financial_status:expired` filter-index bug. Spree's admin is Ransack-heavy — pure derivation breaks order-list filtering on day one. So: `payment_status` and `fulfillment_status` are **stored, indexed string columns** (names per the normalize plan), recomputed by a single `Spree::Orders::RecomputeStatuses` service triggered from payment/fulfillment/refund/return event subscribers. One writer, many triggers. Rules that competitors learned the hard way: quantize money to currency precision **before** comparing; subtract granted/pending refunds from the total before comparing; include `overcharged` (OSS platform B) and `voided` (the hosted market leader) in the payment domain; define the returns interplay explicitly (where OSS platform A's derivation broke). The `fulfillment_status` domain (incl. `backorder`) is owned by `6.0-fulfillment-and-delivery.md`.++### 6. Order lifecycle stays on Order, without a machine++- `status`: `draft` / `placed` / `canceled` (existing column; `partially_canceled` becomes a derived predicate over child cancellations, not a status value).+- `completed?` ≡ `completed_at.present?`; `canceled?` ≡ status. `can_ship?`, `uneditable?`, `allow_cancel?` re-expressed over `status` + `completed_at` + fulfillment/return data.+- Cancel/resume/approve remain services (`Orders::Cancel`/`Resume`/`Approve` — approve is already machine-free) flipping `status` and running today's side effects (restock/void/refund branches preserved verbatim). `awaiting_return`/`returned` states are **not** carried over — that lifecycle belongs to `6.0-returns-exchanges-claims.md`'s first-class Return models.+- The `confirmation_required?` self-reference (the `|| confirm?` hack from #4117) dies with the machine: whether the confirm/review step exists is computed **from data only** (`Spree::Config[:always_include_confirm_step]` or any selected payment method requiring confirmation). A confirm-stage failure no longer "falls back" to an earlier state — there are no states; the client stays on review with the failure in `requirements`/errors.+- Order `state_changes` audit rows are dropped in favor of lifecycle events (`order.placed`, `order.canceled`, `order.resumed`, `order.approved` — already published today). Payment/fulfillment machines keep their own `StateChange` rows.+- **Price-freeze guarantee** (what OSS platform C's `ArrangingPayment` lock provided): `completing_at` rejects cart mutations while payment is in flight, and the completed Order is immutable per split-adjustments' order-level freeze. Auditable price-at-completion also serves EU Omnibus.++### 7. Cart hygiene — new, and newly necessary++- **Tiered expiry reaper** (none exists today — verified): guest carts 30d, customer carts 90d, empty carts hours — configurable, measured on an indexed `updated_at`, batched. **Carts with money attached (authorized/pending payment sessions or transactions) are never reaped** (OSS platform B's exclusion — never garbage-collect a cart mid-authorization).+- **Cart merging becomes a swappable strategy** (`Spree::Dependencies.cart_merge_strategy`; OSS platform C ships four strategies because there's no universally right answer). The default preserves current `OrderMerger` behavior minus its bugs: no silent dropping of different-currency items without surfacing it, no hard-destroy of the >10 cart overflow with only a log line.++### 8. Legacy `Spree::Cart::*` services removed; `Carts::*` become the registered seam++Of the 14 `Spree::Cart::*` services, 8 are dead weight (DI-registered, zero callers) and are deleted. The 6 with real callers re-home onto the Cart model/`Carts::*` namespace (AddItem/SetQuantity/RemoveLineItem → the carts items flow; Associate; Empty; RemoveOutOfStockItems; CompareLineItems → the merge strategy). `Carts::{Create,Update,UpsertItems}` get DI registration (today only `carts_complete_service` is registered and controllers reference the others as hard constants). `controller_helpers/order.rb`'s `current_order` becomes `current_cart` built through `Carts::Create` (fixing its missing market/channel/locale binding).++### 9. Breaking surface, stated plainly++- `order.state`, the checkout state machine, `checkout_flow`/`insert_checkout_step`/`remove_checkout_step`, `next!`/`advance`, and `can_go_to_state?` are removed. Extension authors migrate to `Checkout::Registry` + requirements.+- Ransack: `state` leaves the whitelist (invisible-but-real surface: any admin table filter or API list query using `state_eq`). `status`, `payment_status`, `fulfillment_status` are filterable stored columns — the replacement is strictly more useful.+- `OrderLock`'s `state_lock_version` optimistic counter is renamed `lock_version` semantics-preserving (it never depended on the state machine, only on the column name).+- `order_walkthrough` + order factories (public `testing_support` API) are rewritten cart-first.+- The emails gem survives untouched except `checkout_state_url(token, :payment)` in the payment-link email → a cart checkout URL.++## Design Details++### Completion (`Spree::Carts::Complete`) — pipeline, edge cases, recovery++Completion is a **three-phase pipeline with explicit transaction boundaries**. External payment I/O never runs inside a DB transaction; everything after a successful charge is small, idempotent, and resumable.++```+PHASE P — PREPARE (one transaction)+ P1. Replay check: completion_result(cart) → return success(order|order_group)+ P2. cart.with_lock; reject if completing_at fresh (409 completion_in_progress);+ treat completing_at older than TTL (default 5 min) as stale → take over+ P3. In-lock recalculation (prices, promotions, tax estimate) — the totals about+ to be charged are computed HERE, not trusted from earlier requests+ P4. Drift guard: if client sent expected_total and it ≠ cart.total+ → 409 cart_changed { current_total } (client re-renders, confirms, retries)+ P5. Carts::Validate — full battery, structured errors (see API contract)+ P6. Final availability check against reservations (extend holds through completion)+ P7. Create Order with status: 'draft' + copies (line items owner re-pointed,+ typed money lines, fulfillments + selected rates, address COPIES,+ email/currency/locale/market/channel, guest token carried, number 'R…');+ write orders.cart_id (unique); stamp completing_at+ — invisible everywhere: storefront lists use placed_orders; the admin+ Drafts list is scoped to cart_id: nil (backoffice draft orders have no+ cart), so a mid-completion 'draft' order never surfaces there++PHASE Y — PAYMENT (transaction boundary depends on the method — see below)+ Y1. Skip when not payment_required? (zero total, or store credit + gift card+ fully cover — the covered-by-credit path must never auto-complete earlier+ than this point; see Carts::Update's try_advance note)+ Y2. Process payments against the DRAFT ORDER's totals, per method class:+ • OFFLINE (Check, on-account/terms, cash-on-delivery, bank transfer,+ manual/backoffice-recorded): no external I/O — the method returns a+ local success response and the payment lands `pending`/`completed`+ per auto_capture?. Runs INSIDE the FINALIZE transaction (no separate+ phase, nothing to compensate).+ • EXTERNAL GATEWAY (payment sessions, redirect/3DS, card capture):+ no transaction; compensation on failure.+ Y3. External failure → compensate: destroy draft order + copies, clear+ completing_at, return 422 payment_failed { code, message } — cart stays+ active, nothing external happened. (Only pre-capture failures compensate+ this way; post-capture failures never destroy the order — see FINALIZE.)++PHASE F — FINALIZE (one transaction; every step idempotent)+ F1. Inventory: finalize units (pending: false), unstock, release stock+ reservations (single home — fixes today's asymmetry where the admin+ completion path never releases reservations)+ F2. Usage counters behind persisted flags: coupon codes, gift card redeem,+ promotion credits (each checks-then-sets its flag — retry-safe)+ F3. Vendor split hook (multi-vendor Phase 3): partition → child orders ++ OrderGroup; completion_result becomes the group+ F4. order.status: 'draft' → 'placed'; cart.completed_at stamped;+ completing_at cleared; RecomputeStatuses+ F5. after_commit: publish order.placed / order.completed (notify_customer+ honored), digital fulfillment via FulfillmentProvider::Digital,+ user-account creation + newsletter subscribe (non-fatal side jobs)+```++**Resumability is structural, not bookkept.** The order's `status: 'draft'` + `cart.completed_at: nil` IS the "finalize pending" marker — no separate completion-state column. A retried `Complete` call resumes: replay check finds the draft order → skips PREPARE, re-verifies payment coverage (Y), re-runs FINALIZE (every step guards itself). Events fire only in `after_commit` of the transaction that flips `draft → placed`, so a rolled-back finalize never leaks an `order.completed` event or confirmation email.++**Per-step idempotency (what makes retry safe):**++| Step | Guard |+|---|---|+| Order creation | unique `orders.cart_id` (DB constraint, not a lookup) |+| Payment | payment records checked before processing (skip when a valid completed payment covers the total — today's `Carts::Complete` guard, kept) |+| Inventory finalize | `pending` flag on units; unstock only pending units |+| Coupon/gift-card/promo counters | persisted per-cart flags, check-then-set |+| Digital links | `find_or_create` per line item **per quantity** (fixes today's non-idempotent one-per-line-item callback) |+| Events/email | fired on the `draft → placed` flip only; `confirmation_delivered?` guard stays |++**Not every payment method is an external gateway.** Offline methods — `PaymentMethod::Check`, B2B on-account/net-terms, cash on delivery, bank transfer, and anything recorded through the manual payments API — already flow through the same `process_payments!` seam but perform **no external I/O**: the method returns a local success response, and `auto_capture?` decides whether the payment lands `pending` (authorized, captured later by an admin when the invoice is settled) or `completed`. Consequences for this pipeline:++- **Offline payments collapse PAYMENT into FINALIZE.** With no network call there is nothing to compensate and no partial-failure window, so the whole completion is a single transaction. The three-phase shape exists for external gateways; offline methods take the degenerate path.+- **`payment_required?` is not "must be paid now".** A net-terms order completes with `payment_total: 0` and a `pending` payment — that is a *successfully completed, unpaid* order, not a failure. Completion must gate on "a valid payment exists covering the total" (today's `pending_payments.any? && unprocessed_payments.empty?` guard), never on `paid?`. `RecomputeStatuses` reports `payment_status: none/authorized`; dunning and capture are post-completion admin/AR concerns.+- **Store credit and gift cards are offline by the same rule** — already true today (`recalculate_store_credit_payment` in P3, store-credit payments voided last on compensation).+- **Mixed offline + external** (deposit on card, remainder on terms): any external component forces the external path; the offline components are processed inside the same phase and voided alongside on compensation.+- **B2B/backoffice orders** created through the Admin API bypass this pipeline's checkout ergonomics but must reuse the same service so idempotency, inventory finalization, and reservation release stay in one place — fixing today's asymmetry where `Orders::Complete` never releases reservations.+- **`allow_checkout_on_gateway_error`** keeps its meaning for external methods only; it must not mask offline failures (which indicate a bug or a rule violation, not a flaky network).++**Payment edge cases (external gateways):**++- **Async success (3DS / redirect / webhook).** Both writers call the same service: the customer's return-page `POST /complete` and `Payments::HandleWebhook`. Whoever runs first creates the order; the other replays it. The webhook keeps its `order.with_lock` + replay check, but safety comes from the unique index — the current 30-second job delay becomes a latency optimization, not a correctness mechanism.+- **Webhook says failed.** Mark the payment session failed; do **not** compensate an order unless one exists in `draft` with no other valid payment — then compensate as Y3. Cart stays active for another attempt.+- **Payment captured, finalize keeps failing** (e.g. DB partition). The order exists as `draft` with a successful payment. **Never auto-refund on transient failure.** A completion-recovery sweeper retries FINALIZE for stale `draft` orders with paid coverage; persistent failures alert operators. This is the precise scenario the order-before-payment ordering minimizes.+- **Partial store credit + external payment.** Store-credit payments are (re)calculated in P3 (`recalculate_store_credit_payment` behavior carries over); the external session covers the remainder; Y2 processes both, store credit last-voided on compensation.+- **Zero-total carts** (100% promo, gift card): Y is skipped entirely; F runs. The "never auto-complete during address updates" rule stays in `Carts::Update#try_advance` — only an explicit `Complete` call reaches this pipeline.+- **Late webhook after cart expiry.** Cannot happen by construction: the reaper never deletes carts with authorized/pending payment sessions (money-safety exclusion, Key Decision 7).++**Drift and mutation guards:**++- `completing_at` rejects cart mutations (`items`, addresses, discounts) with 409 `cart_locked` while payment is in flight — the price-freeze guarantee. TTL-stale locks are reclaimable so a crashed process never bricks a cart.+- Recalculation happens **inside the lock** (P3): expired promotions drop out, price-list changes apply, tax re-estimates. The `expected_total` guard (P4) turns silent drift into an explicit client confirmation loop instead of charging an amount the customer never saw.+- Stock: reservations are held/extended through completion; the P6 check catches reservation-less installs. Backorderable variants complete with backordered units (today's semantics — backorder is a fulfillment status, not a completion failure).+- Optimistic concurrency: `state_lock_version` is renamed `lock_version` with identical increment-on-write semantics; a stale client gets 409 `stale_cart` on mutation, and `Complete` itself relies on the row lock instead.++**Multi-vendor interaction.** The idempotency lookup is `completion_result(cart)`: exactly one of `cart.order` (single-partition — bare order, `cart_id` on it) or `cart.order_group` (multi-partition — `cart_id` on the group, child orders linked through it). The split runs inside FINALIZE (F3), i.e. after payment: a mid-split crash resumes like any finalize failure, and the replay returns the group once it exists.++**API contract (`POST /store/carts/:id/complete`):**++| Outcome | Response |+|---|---|+| Completed (including replay of an already-completed cart) | 200 `{ order }` (or `{ order_group }`) |+| Validation failed | 422 `{ errors: [{ step, field, code, message }] }` — same shape as the `requirements` attribute |+| Payment declined / failed pre-capture | 422 `{ error: { code: 'payment_failed', … } }` |+| Totals changed since client render | 409 `{ error: { code: 'cart_changed', current_total } }` |+| Another completion in flight | 409 `{ error: { code: 'completion_in_progress' } }` — client polls/retries; replay returns the order when done |+| Cart mutated while locked | 409 `cart_locked` (on the mutation endpoints, not on complete) |++### Status recomputation++```ruby+Spree::Orders::RecomputeStatuses.call(order:) # the ONLY writer of both columns+# payment_status: quantized(captured + charged) vs quantized(total − granted_refunds)+# → none/authorized/partially_paid/paid/partially_refunded/refunded/+# overcharged/voided+# fulfillment_status: aggregated from fulfillment records incl. backorder+# (domain owned by the fulfillment plan)+```++Triggered by subscribers on payment, refund, fulfillment, and return events — never inline from controllers.++### Completion side-effect parity checklist++Everything today's `finalize!` + `after_transition to: :complete` chain does is accounted for in the flow above or explicitly relocated: adjustment freeze (→ split-adjustments order-level freeze), payment/shipment status updates (→ RecomputeStatuses), `status: 'placed'`, `completed_at`, update hooks, risk check (`considered_risky` + `order.updated`), `order.completed` event, coupon-code use, gift-card redeem, newsletter subscribe, user-account creation, digital links (→ `FulfillmentProvider::Digital`, idempotent + per-quantity — fixing the current checkout-callback's non-idempotent one-per-line-item behavior), confirmation email (already event-driven via the emails subscriber; unchanged).## Migration Path-- Remove legacy services in `Spree::Cart` namespace, they are blocking us from creating a `Spree::Cart` model, also they are mostly legacy and unused in API v3-- Cart < ApplicationRecord (new)-- Order keeps existing table, state column deprecated++### Phase 1 — schema (additive)++`spree_carts`; nullable `cart_id` on `spree_line_items` (`order_id` stays; presence validation relaxes to exactly-one); `spree_orders.cart_id` (unique); stored status columns per the normalize plan. `spree_orders.state` survives untouched until Phase 4.++### Phase 2 — data (rake task)++Existing **incomplete** orders convert to Cart rows (they *are* today's carts): one Cart per incomplete order carrying token/binding/addresses; line items re-owned to the cart (`cart_id` set, `order_id` nulled); the hollow order row deleted. Incomplete orders mid-payment (valid payment sessions/authorizations) are converted last with their sessions re-linked. Completed orders are untouched except `cart_id: nil`. Batched, idempotent, resumable.++### Phase 3 — model + services++Cart model + recalculation-on-write; `Carts::Complete` rewrite (flow above); Registry step-list ownership; legacy `Cart::*` deletion/re-homing; `current_cart`; merge strategy; reaper; predicates re-expressed (`LINE_ITEM_REMOVABLE_STATES` et al.).++### Phase 4 — remove the machine++Delete `Order::Checkout`, the state column, `checkout_flow` API, order `state_changes` writes; Ransack whitelist swap; RecomputeStatuses + subscribers; the six out-of-band `state` writers (address services etc.) become cart-recalculation triggers.++### Phase 5 — API/SDK/dashboard/docs++Contract is already step-shaped, so this is thin: `carts/fulfillments_controller`'s `cart.next` loop → requirements-driven; serializers unchanged in shape; typelizer/Zod/OpenAPI regeneration; `order_walkthrough`/factories; extension-migration guide (`checkout_flow` → Registry); emails payment-link URL.++### Phase 6 — cleanup (6.1)++Drop deprecation aliases and the migration task. (`spree_line_items.order_id` is NOT dropped — it's half of the permanent dual-FK owner pattern.)## Constraints on Current Work-- Any new code touching line items should use the `line_item.owner`- interface, not `line_item.order` directly-- Don't add new order states — they won't survive the migration++- Any new code touching line items uses `line_item.owner`, not `line_item.order` — `owner` is a method (`order || cart`); until Phase 1 lands it simply returns `order`, so the constraint is implementable today.+- Don't add checkout states, transitions, or `checkout_flow` steps — extend `Checkout::Registry` instead.+- Don't read or filter on `order.state` in new code — use `completed_at`/`status` predicates and the requirements API.+- New money/fulfillment tables are born with the cart/order owner XOR (already honored by split-adjustments and fulfillment plans).+- Don't build on `state_changes` rows where `name: 'order'` — they're going away; subscribe to lifecycle events.++## Resolved Questions++1. **Order before payment** (OSS platform A's ordering) — minimizes authorized-money rollback; compensation voids on post-payment failure.+2. **Cart retained, not deleted** (OSS platform A over the hosted market leader) — idempotency, analytics, debugging.+3. **Statuses stored, not read-time-derived** (OSS platform B over OSS platform A) — with the four hard-won derivation rules above.+4. **`confirmation_required?` self-reference eliminated** — confirm-step existence computed from config + payment-method data only.+5. **Existing incomplete orders migrate to carts** in Phase 2 — no dual-model serving window; the API façade means clients never notice.+6. **Guest token carried** cart → order; permission sets check the same credential.+7. **Order `state_changes` dropped** for lifecycle events; payment/fulfillment audits unaffected.+8. **`awaiting_return`/`returned` are not order statuses** — returns lifecycle belongs to the returns plan.+9. **Completion resumability is structural**: `order.status: 'draft'` + `orders.cart_id` present + `cart.completed_at: nil` is the "finalize pending" marker — no completion-state column. Mid-completion drafts are excluded from the admin Drafts list by `cart_id: nil` scoping (backoffice drafts have no cart).+10. **A completion-recovery sweeper** retries FINALIZE for stale `draft` orders with paid coverage and alerts on persistent failure; transient failures never trigger auto-refund. Pre-capture payment failures compensate by destroying the draft order; post-capture failures never do.+11. **Offline payment methods are first-class, not a gateway special case.** Check, B2B on-account/net-terms, COD, bank transfer, store credit, gift cards, and manual-API-recorded payments perform no external I/O, so PAYMENT collapses into the FINALIZE transaction with nothing to compensate. Completion gates on "a valid payment covers the total", **not** on `paid?` — a net-terms order completes unpaid with a `pending` payment and `payment_status: none/authorized`; capture and dunning are post-completion AR concerns. `allow_checkout_on_gateway_error` applies to external methods only.++## Open Questions++1. **Extension migration window** — does `checkout_flow`/`insert_checkout_step` get a hard removal in 6.0 or a one-release shim that translates registrations into `Checkout::Registry` entries? (Enterprise checkout customizations are the main consumers.)+2. **`partially_canceled`** — today a quasi-state in the `canceled` scopes; proposed as a derived predicate. Confirm no report/export depends on it as a stored value.+3. **Reaper defaults** — 30/90-day tiers are OSS platform B's; confirm against Spree hosting expectations before hardcoding defaults.++## References++- Codebase inventory + competitor research (2026-07-27): checkout-flow anatomy (`order/checkout.rb:42-133` — 14 cart-phase / 8 completion / 11 post-completion callbacks), state-consumer census (public contract is step-shaped; scopes already on `completed_at`), OSS platform A `completeCartWorkflow`, OSS platform B `checkout_complete.py` (idempotency, `is_voucher_usage_increased`, expiry tiers), the hosted market leader Checkout-API shutdown, OSS platform C `default-order-process.ts`+- Cautionary bugs: OSS platform A's repo#14095 (unfilterable derived status), #13882 (status stuck after return), the hosted market leader `financial_status:expired` filter divergence+- Existing seams: `spree/core/app/services/spree/carts/*.rb`, `spree/core/app/models/spree/checkout/{requirements,registry,default_requirements}.rb`, `api/app/serializers/spree/api/v3/cart_serializer.rb`+- Related plans: `6.0-split-adjustments.md`, `6.0-fulfillment-and-delivery.md`, `6.0-multi-vendor-marketplace.md`, `6.0-returns-exchanges-claims.md`, `6.0-normalize-state-to-status.md`, `6.0-stock-reservations.md`diff --git a/docs/plans/6.0-delivery-rate-provider.md b/docs/plans/6.0-delivery-rate-provider.mdindex 359f0ee06d..887fff69ea 100644--- a/docs/plans/6.0-delivery-rate-provider.md+++ b/docs/plans/6.0-delivery-rate-provider.md@@ -2,213 +2,249 @@**Status:** Draft**Target:** Spree 6.0-**Depends on:** Fulfillment & Delivery (6.0-fulfillment-and-delivery.md) for DeliveryMethod rename+**Depends on:** Fulfillment & Delivery (6.0-fulfillment-and-delivery.md) for the DeliveryMethod/DeliveryRate rename. Coordinates with: `6.0-multi-vendor-marketplace.md` (vendor-scoped method filtering — this plan owns the filter), `6.0-cart-order-split.md` (where estimation is invoked pre-completion), `5.6-6.0-single-store-promotions-payment-methods.md` (single-store pattern reused for `store_id`)**Author:** Damian + Claude-**Last updated:** 2026-04-05+**Last updated:** 2026-07-27## Summary-Add a pluggable delivery rate provider interface (`Spree::DeliveryRateProvider::Base`) that abstracts shipping rate calculation behind a clean contract. The default implementation (`Spree::DeliveryRateProvider::Internal`) preserves today's `ShippingCalculator` behavior (flat rate, per-item, weight-based — configured in admin). External providers (EasyPost, ShipStation, Shippo) implement the same interface, enabling real-time carrier rate lookups without monkey-patching.+Add a pluggable delivery rate provider interface (`Spree::DeliveryRateProvider::Base`) that abstracts shipping rate estimation behind a clean contract. The default implementation (`Spree::DeliveryRateProvider::Internal`) delegates to the existing shipping calculators, so behavior is unchanged for every store that doesn't opt in. External providers (EasyPost, ShipStation, Shippo) implement the same interface, enabling real-time carrier rate lookups without monkey-patching `Stock::Estimator`.This follows the same open-closed provider pattern as `SearchProvider` (shipped in 5.4) and `TaxProvider` (planned for 6.0).+**Calculators are kept.** An earlier draft of this plan proposed deleting `ShippingCalculator` and all `Calculator::Shipping::*` classes in favor of a `pricing_type` enum plus `preferred_amount` columns on DeliveryMethod. That is reversed — see "Why calculators stay" below.+## Problem-1. **Calculators can't call external APIs.** `ShippingCalculator.compute_package(package) → BigDecimal` is a synchronous, stateless computation. There's no way to call EasyPost/UPS/FedEx for real-time rates, handle API failures, or cache responses.+1. **Calculators can't call external APIs.** `ShippingCalculator#compute_package(package) → BigDecimal` is a synchronous, stateless computation with no credentials, no error handling, and no caching.++2. **Calculators return a single number.** External carriers return structured results — carrier name, service level, delivery date, tracking capability. A `BigDecimal` can't model "UPS Ground: $8.99, arrives Thu."-2. **Calculators return a single number.** External carriers return multiple service levels (Ground, Express, Overnight) with delivery dates, carrier names, and tracking capabilities. A calculator returns one `BigDecimal` — it can't model "UPS Ground: $8.99, arrives Thu" vs "UPS Express: $24.99, arrives tomorrow".+3. **No lifecycle hooks.** External services need to book a rate on selection and generate labels on fulfillment. Calculators have no post-selection hooks. (`FulfillmentProvider` in `6.0-fulfillment-and-delivery.md` covers post-purchase but not rate estimation.)-3. **No lifecycle hooks.** When a customer selects a rate, external services need to "book" it. When an order ships, they need to create a shipment and generate labels. Calculators have no hooks for these events. (The FulfillmentProvider in `6.0-fulfillment-and-delivery.md` handles post-purchase lifecycle but NOT rate calculation.)+4. **No access to order context.** Calculators receive a `Stock::Package`. External APIs need origin address, destination address, parcel dimensions, declared value, residential/commercial flags.-4. **One calculator per shipping method.** Each `ShippingMethod` has exactly one calculator. But EasyPost returns rates for all carriers/services in one API call. You'd need N shipping methods (one per carrier service) each with a custom calculator that calls the same API — wasteful and fragile.+5. **No seam for a whole-basket API call.** EasyPost returns rates for every carrier and service in one request. Today the only extension point is per-method, so N methods means N calls.-5. **No access to order context.** Calculators receive a `Stock::Package` with items and weights. But external APIs need: origin address (stock location), destination address, package dimensions, declared value, insurance requirements, residential/commercial flag, hazmat indicators.+Note that (1)-(5) are all about the layer *above* the calculator — where rates come from and what shape they have. None of them are complaints about arithmetic, which is all a calculator does.## Current State+Verified against HEAD (`4e5b6fd`, 2026-07-27).+| What exists | Where | What it does ||---|---|---|-| `ShippingCalculator` | Base class | `compute_package(package) → BigDecimal` |-| `Calculator::Shipping::FlatRate` | Built-in | Fixed amount per order |-| `Calculator::Shipping::PerItem` | Built-in | Price × quantity |-| `Calculator::Shipping::FlexiRate` | Built-in | Tiered pricing (first item + additional) |-| `Calculator::Shipping::FlatPercentItemTotal` | Built-in | Percentage of cart total |-| `Calculator::Shipping::PriceSack` | Built-in | Conditional pricing by threshold |-| `Calculator::Shipping::DigitalDelivery` | Built-in | Zero cost for digital products |-| `Stock::Estimator` | Rate engine | Iterates shipping methods, calls calculators, creates ShippingRates |-| `Stock::Package` | Input model | Items + stock location → passed to calculators |-| `ShippingMethod` | Config model | Zone + calculator + display settings |-| `ShippingRate` | Result model | cost + tax_rate + selected flag |+| `ShippingCalculator` | `core/app/models/spree/shipping_calculator.rb:2` | Abstract base; declares `compute_shipment`, `compute_package`, `available?(package)` |+| `Calculator::Shipping::FlatRate` | `.../shipping/flat_rate.rb:5` | Fixed amount, **plus four suppression thresholds** (`minimum`/`maximum_item_total`, `minimum`/`maximum_weight`) that return `nil` to hide the method |+| `Calculator::Shipping::PerItem` | `.../per_item.rb:5` | `preferred_amount × package quantity` |+| `Calculator::Shipping::FlexiRate` | `.../flexi_rate.rb:5` | `first_item` + `additional_item` + `max_items`; delegates to `Spree::Calculator::FlexiRate` |+| `Calculator::Shipping::FlatPercentItemTotal` | `.../flat_percent_item_total.rb:5` | Percentage of item total, with explicit 2dp rounding |+| `Calculator::Shipping::PriceSack` | `.../price_sack.rb:5` | Three-tier: `minimal_amount` threshold selects `normal_amount` or `discount_amount` |+| `Calculator::Shipping::DigitalDelivery` | `.../digital_delivery.rb:5` | Flat amount; **its real content is `available?`** — only offered when every content item is a digital variant |+| `Stock::Estimator` | `core/app/models/spree/stock/estimator.rb` | Filters methods, calls calculators, wraps in ShippingRates, applies VAT gross-up, picks + sorts default |+| `Stock::Package` | `core/app/models/spree/stock/package.rb` | Items + stock location; exposes `item_total`, `weight`, `quantity`, `volume`, `dimension`, `order`, `currency` |+| `ShippingMethod` | `core/app/models/spree/shipping_method.rb` | Zones + calculator + display settings. `has_prefix_id :dm` already |+| `ShippingRate` | `core/app/models/spree/shipping_rate.rb` | `cost` + `tax_rate` + `selected`. `has_prefix_id :dr` already |++The registered calculator set is exactly those six (`core/lib/spree/core/engine.rb:137-144`).### Key flow today+The previous draft of this plan had this diagram wrong. The corrected flow:+```-Checkout::GetShippingRates- → Stock::Coordinator.packages(order)- → Packer → Splitters → Package objects- → Stock::Estimator.shipping_rates(package)- → shipping_methods(package) # filter by zone, availability, currency- → shipping_method.calculator.compute(package) # ONE number per method- → ShippingRate.new(cost: result)- → Customer sees list of rates, selects one+Spree::Shipment#refresh_rates(display_filter) # shipment.rb:344 — PRIMARY path+ → guards: return if shipped?; return [] unless can_get_rates?+ → remembers original_shipping_method_id # :348+ → Stock::Estimator.new(order).shipping_rates(to_package, display_filter)+ → re-selects the previously chosen method if still offered # :355-361++Spree::Stock::Coordinator#packages # coordinator.rb:18+ → build_packages → Packer + Spree.stock_splitters # :24-31, :57-64+ → prioritize_packages → Prioritizer/Adjuster # :44-47+ → estimate_packages → Estimator per package # :49-55++Spree::Stock::Estimator#shipping_rates(package, filter) # estimator.rb:13+ → shipping_methods(package, filter) # :61-71+ filters on available_to_display?, include?(ship_address),+ calculator.available?(package), and calculator currency match+ → shipping_method.calculator.compute(package) # :33 — nil suppresses the method+ → gross_amount(cost, taxation_options_for(method)) # :38 — VAT gross-up+ → ShippingRate.new(cost:, tax_rate: first_tax_rate_for(...))+ → choose_default_shipping_rate (min by cost) + sort # :21-29```-### Why calculators alone can't solve this+Three production entry points reach the Estimator:++1. **`Spree::Shipment#refresh_rates`** (`shipment.rb:351`) — the load-bearing one.+2. **`Spree::OrderRouting::Strategy::Rules#estimate_rates`** (`order_routing/strategy/rules.rb:76`) — shipped 5.5; runs its own packages → prioritize → estimate pipeline parallel to `Coordinator`.+3. **`Spree::Cart::EstimateShippingRates`** (`cart/estimate_shipping_rates.rb:11`) — builds a dummy order, estimates **only `packages.first`** (`:13`).-Same pattern as tax — calculators answer "how much?" but can't answer "what options are available?" or "what happens after selection?":+`Spree::Checkout::GetShippingRates` does **not** call the Estimator directly. It calls `order.create_proposed_shipments` inside a transaction with `create_shipment_tax_charge!`, `set_shipments_cost`, and `apply_free_shipping_promotions` (`checkout/get_shipping_rates.rb:37-45`), guarded by `if order.shipments.empty?` (`:33`).-1. **Stateless per-item** — Calculator gets a Package, returns a BigDecimal. Can't make API calls, handle errors, cache results, or return structured data (carrier, service level, delivery date).-2. **One result per method** — Each ShippingMethod + Calculator = one rate. External APIs return multiple rates per call.-3. **No booking/lifecycle** — After customer selects a rate, external services need to book it, generate labels, track shipment. Calculators have no post-selection hooks.-4. **No provider initialization** — Calculators don't receive API credentials, can't be configured per-store.+## Why calculators stay-**The provider replaces calculators entirely in 6.0:**+The problem statement is about **where rates come from and what shape they arrive in**. A calculator is a small arithmetic object with a preference form. Those are orthogonal concerns, and the provider seam sits cleanly above the calculator seam.++Replacing calculators with a `pricing_type` enum + `preferred_amount` was evaluated and rejected:++- **It can't express what ships today.** A five-case enum (`flat_rate`/`per_item`/`weight`/`percent`/`free`) has no representation for `FlexiRate` (three preferences plus delegation to `Spree::Calculator::FlexiRate`) or `PriceSack` (three-tier). Reaching parity needs roughly twelve loosely-related nullable columns, most meaningless for any given row — a worse model than a typed subclass with its own preferences.+- **It silently drops behavior.** `FlatRate`'s four thresholds and the Estimator's currency gate (`estimator.rb:67-69`) both suppress a method by yielding `nil`. An enum switch that returns `preferred_amount` loses this, changing which methods appear at checkout with no test failing.+- **It breaks every custom calculator with no migration path.** Merchant subclasses of `ShippingCalculator` are a long-standing, documented extension point. An enum is closed by construction — the exact opposite of the open-closed principle this plan invokes.+- **`DigitalDelivery` isn't a pricing type at all.** Its substance is `available?(package)` (`digital_delivery.rb:17-19`), an availability predicate. It doesn't fit a pricing enum even in principle.+- **It buys nothing.** Every motivating problem is solved by the provider layer. Deleting calculators is orthogonal scope that only adds risk.++Calculators remain the mechanism for **internal arithmetic + admin-configurable preferences**. Providers own **where rates come from, what metadata they carry, and what happens after selection**. The Internal provider delegates to the calculator; external providers ignore it.```-Provider (rate calculation)- └─ Internal provider → reads DeliveryMethod pricing config → computes directly- └─ EasyPost provider → EasyPost API → returns multiple DeliveryRate objects+Provider (source + shape of rates)+ └─ Internal → delegates to DeliveryMethod#calculator → BigDecimal → wrapped in an estimate+ └─ EasyPost → EasyPost API → estimates with carrier, service level, delivery date```-The `Calculator` base class, `ShippingCalculator`, `CalculatedAdjustments` concern, and all `Calculator::Shipping::*` classes are removed. The Internal provider implements rate computation directly from DeliveryMethod preferences (flat rate amount, per-item amount, weight thresholds).-## Key Decisions (do not deviate without discussion)-### Provider replaces Stock::Estimator and Calculator entirely+### Provider wraps the Estimator; it does not replace it-- **`Stock::Estimator` is removed.** The provider is the only entry point for delivery rate estimation. Zone filtering and method availability are handled inside the provider (or as shared utilities).-- **`ShippingCalculator` and all `Calculator::Shipping::*` classes are removed.** No more polymorphic `has_one :calculator` on DeliveryMethod.-- **DeliveryMethod becomes pure configuration** — stores name, zone, fulfillment type, pricing preferences (flat amount, per-item amount, weight thresholds, etc.) as preferences or JSON columns. No calculator association.-- **All call sites** that called `Stock::Estimator` (Checkout::GetShippingRates, Cart::EstimateShippingRates) call the provider via `Spree.delivery_rate_provider`.+`Stock::Estimator` **stays**. It owns responsibilities no provider should re-implement per-vendor:-### Provider returns structured rate objects, not BigDecimal+- method filtering (display target, zone `include?`, `calculator.available?`, currency match) — `estimator.rb:61-71`+- VAT gross-up via `Spree::VatPriceCalculation#gross_amount` — `estimator.rb:4, 38`+- tax rate resolution — `estimator.rb:54-59`+- default selection + sorting — `estimator.rb:21-29`-```ruby-provider.estimate_rates(package, delivery_methods)-# → [-# DeliveryRateEstimate.new(-# delivery_method: method,-# cost: 8.99,-# carrier: 'UPS',-# service_level: 'Ground',-# estimated_delivery_date: Date.parse('2026-03-25'),-# metadata: { easypost_rate_id: 'rate_abc' }-# ),-# ...-# ]-```+The provider is invoked at exactly one point: where the Estimator today calls `shipping_method.calculator.compute(package)` (`estimator.rb:33`). That call becomes a provider dispatch. Everything around it is untouched, which is what makes "no behavior change by default" real rather than aspirational.-The Internal provider wraps each `calculator.compute(package)` result in a `DeliveryRateEstimate` with no carrier/service metadata (same as today).+**Corollary:** all three Estimator entry points — `Shipment#refresh_rates`, `OrderRouting::Strategy::Rules`, and `Cart::EstimateShippingRates` — get provider support for free, with no per-call-site changes. A design that bypassed the Estimator would have to update all three, and `OrderRouting::Strategy::Rules` in particular is easy to miss.-### Credentials live in Spree::Integration, not the provider+### Selected-rate preservation is not the provider's business-Providers are stateless strategy objects — they define behavior (estimate rates). They do **not** store credentials. API keys, secrets, and connection config for external services live in `Spree::Integration` subclasses, which provide:+`Shipment#refresh_rates` remembers the previously selected method and re-selects it if still offered (`shipment.rb:348, 355-361`). This is checkout UX, not rate estimation. It stays exactly where it is. **No provider or checkout service may unconditionally `min_by(&:cost).update(selected: true)`** — that would silently reset a customer's or admin's chosen rate on every refresh.-- **Per-store persistence** — credentials stored in the `preferences` column-- **Admin UI** — dynamic forms for non-developer configuration-- **Connection validation** — `can_connect?` hook tests credentials before saving-- **Activation tracking** — `active` boolean flag+### Provider is per delivery method, resolved through the method's store-A provider gem (e.g., `spree_easypost`) ships **both** an Integration subclass and a Provider subclass:+One store can mix providers freely:-```ruby-# Integration — stores credentials, provides admin UI-class Spree::Integrations::EasyPost < Spree::Integration- preference :api_key, :string- preference :mode, :string, default: 'test' # test or production+- "Free Shipping" → `Internal` (FlatRate calculator, amount 0)+- "Standard" → `SpreeEasyPost::DeliveryRateProvider` (UPS Ground)+- "Express" → `SpreeEasyPost::DeliveryRateProvider` (UPS Express)+- "Local Pickup" → `Internal`- def self.integration_group = 'shipping'+```ruby+class Spree::ShippingMethod < Spree.base_class+ # nil / blank → Internal. Calculator association is unchanged.+ def rate_provider_class+ (self[:rate_provider].presence || 'Spree::DeliveryRateProvider::Internal').constantize+ end- def can_connect?- EasyPost::Client.new(api_key: preferred_api_key).address.create(- street1: '417 Montgomery St', city: 'San Francisco', state: 'CA', zip: '94104', country: 'US'- )- true- rescue => e- self.connection_error_message = e.message- false+ def rate_provider+ rate_provider_class.new(self)endend+```-# Provider — behavioral contract, reads credentials from Integration at runtime-class SpreeEasyPost::DeliveryRateProvider < Spree::DeliveryRateProvider::Base- def self.integration_class = 'Spree::Integrations::EasyPost'+Stored as a string column and constantized at call time, mirroring `Spree.search_provider` (`core/lib/spree/core.rb:134-139`).- def self.available_for_store?(store)- store.integrations.active.exists?(type: integration_class)- end+### DeliveryMethod gets `store_id` (this plan owns the migration)- def estimate(package)- # ... rate calculation using client ...- end+The provider needs a store to resolve credentials, because `Spree::Integration` is strictly per-store. **`Spree::ShippingMethod` has no store association today** — no `has_many :stores`, no `store_id`, no `SingleStoreResource` (`shipping_method.rb:25-34`; no `store_id` in `spree_shipping_methods`). It reaches a store only transitively and in one direction, via `Spree::Zone.joins(:shipping_methods)` in `Store#countries_with_shipping_coverage` (`store.rb:342`).- private+`5.6-6.0-single-store-promotions-payment-methods.md` does **not** cover ShippingMethod — it scopes itself to Promotion and PaymentMethod as "the last two multi-store resources" (`:11`), which is accurate precisely because ShippingMethod was never store-scoped at all. So no other plan will supply this.- def client- @client ||= begin- store = delivery_method.stores.first # or however the method resolves its store- integration = store.integrations.active.find_by!(type: self.class.integration_class)- EasyPost::Client.new(api_key: integration.preferred_api_key)- end- end+This plan adds `store_id`, following the established single-owner pattern and advancing the broader goal that every major model carries a `store_id`:++```ruby+class Spree::ShippingMethod < Spree.base_class+ include Spree::SingleStoreResource++ belongs_to :store, class_name: 'Spree::Store'++ validates :store, presence: true, unless: -> { Spree::Config[:disable_store_presence_validation] }end```-**Admin flow:**-1. Admin navigates to Integrations → connects EasyPost (enters API key, tests connection)-2. Admin navigates to DeliveryMethod "Standard Shipping" → selects "EasyPost" as rate provider-3. At runtime, the provider reads credentials from the Integration record+`Spree::SingleStoreResource` (`core/app/models/concerns/spree/single_store_resource.rb`) supplies `scope :for_store`, `before_validation :ensure_store` (assigns `Spree::Current.store` when blank), and a "store can't be changed once set" validation. Same shape as `Promotion` (`promotion.rb:5, 42, 64`) and `PaymentMethod` (`payment_method.rb:8, 25, 28`).++**No join table and no `LegacyMultiStoreSupport` bridge.** Promotion and PaymentMethod needed those because they were migrating *away from* `has_many :stores`. ShippingMethod has no sharing semantics to preserve, so there is nothing to deprecate — this is a pure addition. That also makes it the cheapest of the single-store migrations.++**Interaction with `VendorConcern`.** `ShippingMethod` conditionally includes `Spree::VendorConcern` (`shipping_method.rb:10-12`) for the marketplace. Store ownership and vendor ownership are different axes: the store is the tenant boundary (and the credential scope); the vendor is the seller within it. A vendor's shipping methods belong to the marketplace's store. Coordinate with `6.0-multi-vendor-marketplace.md` before enforcing `null: false`.++### Vendor-scoped methods filter in the Estimator (marketplace)-**Internal providers don't need an Integration.** `Spree::DeliveryRateProvider::Internal` reads DeliveryMethod pricing preferences directly — no external credentials.+`6.0-multi-vendor-marketplace.md` requires per-vendor delivery selection at checkout: line items partition into per-vendor packages **before** the order split, and "a `DeliveryMethod` with `vendor_id` is offered only on that vendor's packages; `vendor_id: nil` methods are marketplace-wide" — and it delegates that filtering to this plan.-**Provider availability depends on Integration status.** The DeliveryMethod admin UI should only offer providers whose Integration is active for that store.+Because the provider wraps the Estimator, this lands in exactly one place: `Estimator#shipping_methods(package, filter)` gains a vendor gate — skip methods whose `vendor_id` is present and differs from the package's vendor; `nil` means marketplace-wide. The `vendor_id` column itself is added by the marketplace plan's schema wave (it replaces today's Enterprise `VendorConcern` decorator seam at `shipping_method.rb:10-12`); this plan owns the filter. Per-package granularity is native here — the Estimator already runs per package, which is exactly the granularity per-vendor selection needs. Single-vendor stores are unaffected (`vendor_id` is nil everywhere, the gate is a no-op).-### Provider is per delivery method+### Credentials live in Spree::Integration-Unlike search (global) and tax (per-market), delivery rate providers are **per delivery method**. One store can have:+Verified shipped and matching this design: `core/app/models/spree/integration.rb`, table `spree_integrations`.-- "Free Shipping" → `Spree::DeliveryRateProvider::Internal` (flat rate: $0)-- "Standard Shipping" → `SpreeEasyPost::DeliveryRateProvider` (UPS Ground rates)-- "Express Shipping" → `SpreeEasyPost::DeliveryRateProvider` (UPS Express rates)-- "Local Pickup" → `Spree::DeliveryRateProvider::Internal` (flat rate: $0)+| Capability | Evidence |+|---|---|+| `preferences` column | schema `t.text "preferences"` |+| `can_connect?` hook | `integration.rb:61-63` |+| `connection_error_message` | `integration.rb:28` (`attr_accessor`, not persisted) |+| `self.integration_group` | `integration.rb:33-35` (used as a `Spree.t` key) |+| Per-store scoping | `include Spree::SingleStoreResource` (:5), `belongs_to :store, touch: true` (:10), `store_id null: false` |+| `active` flag + `.active` scope | schema (`default: false, null: false`), `integration.rb:21` |++Providers are stateless strategy objects and never store credentials. A provider gem ships both an Integration subclass and a Provider subclass:```ruby-class Spree::DeliveryMethod < Spree.base_class- # Replaces the old calculator association- attribute :rate_provider, :string, default: 'Spree::DeliveryRateProvider::Internal'+class Spree::Integrations::EasyPost < Spree::Integration+ preference :api_key, :string+ preference :mode, :string, default: 'test'++ def self.integration_group = 'shipping'- def rate_provider_instance- rate_provider.constantize.new(self)+ def can_connect?+ EasyPost::Client.new(api_key: preferred_api_key).address.create(+ street1: '417 Montgomery St', city: 'San Francisco', state: 'CA', zip: '94104', country: 'US'+ )+ true+ rescue => e+ self.connection_error_message = e.message+ falseendend```-The provider receives the **DeliveryMethod** (not store) — it reads API keys, carrier config, and pricing from the method's preferences/metadata.+Two constraints to design around:-### FulfillmentProvider handles post-purchase, DeliveryRateProvider handles pre-purchase+- **One integration per (store, type)** — `validates :store, presence: true, uniqueness: { scope: :type }` (`integration.rb:16`). A store cannot hold two EasyPost credential sets. Multi-account support is a separate change; see the grooming note in `5.7-payment-method-rules.md`.+- **Core ships no `Spree::Integrations::` namespace** — there is no `core/app/models/spree/integrations/` directory, so `integration_group`, `icon_path`, `integration_name`, and `integration_key` (`:33-47`) are currently unexercised. The EasyPost provider gem would be the first real consumer.-- **DeliveryRateProvider** — "What shipping options are available and how much do they cost?" (checkout)-- **FulfillmentProvider** — "Create a shipment, generate labels, track delivery" (post-purchase)+Internal providers need no Integration.-These are separate concerns. A store might use EasyPost for rates but manual fulfillment, or internal rates but ShipStation for fulfillment.+### Per-request caching uses Spree::Current, not RequestStore-### One rate per delivery method, cached API calls across methods+Multiple DeliveryMethods can share one external provider, and a single API call should serve them all. Use `Spree::Current` (`core/app/models/spree/current.rb`) — an `ActiveSupport::CurrentAttributes` subclass already used for per-request memoization with proper `resets` semantics (`:9`) and lazy-load guards (`:59-66`).-Each DeliveryMethod returns one rate. But multiple DeliveryMethods can share the same external provider (e.g., "UPS Ground" and "UPS Express" both use the EasyPost provider). The provider should cache the API call per package (using `RequestStore` or similar) so a single EasyPost API call serves rates for all UPS methods.+`RequestStore` is used in core in exactly one file (`core/lib/spree/events.rb`) and arrives transitively through Mobility (`mobility-1.3.2` depends on `request_store ~> 1.0`) — it is **not** declared in `spree_core.gemspec`. Two independent actions:-```-DeliveryMethod "UPS Ground" → EasyPost provider → API call (cached) → extract Ground rate-DeliveryMethod "UPS Express" → EasyPost provider → API call (cached) → extract Express rate-DeliveryMethod "Free Shipping"→ Internal provider → flat rate: $0-```+1. **Add `request_store` to `spree_core.gemspec`** regardless of this plan. `events.rb` already depends on it at runtime; relying on a transitive dependency for shipped code is a latent break if Mobility ever drops it.+2. **Still prefer `Spree::Current`** for new provider code — it is the in-repo convention and resets correctly between requests and jobs.## Design Details-### Provider Base Class+### Provider base class```rubymodule Spreemodule DeliveryRateProvider+ # Structured result. `cost` is pre-tax and pre-VAT-gross-up; the Estimator+ # applies gross_amount and tax rate resolution, same as it does for+ # calculator output today.+ DeliveryRateEstimate = Struct.new(+ :cost,+ :carrier,+ :service_level,+ :estimated_delivery_date,+ :estimated_transit_days,+ :metadata,+ keyword_init: true+ )+class Baseattr_reader :delivery_method@@ -216,48 +252,66 @@ module Spree@delivery_method = delivery_methodend- # Estimate delivery rate for a package.- # Returns a DeliveryRateEstimate or nil if not available.+ # Estimate the rate for a package.#- # @param package [Spree::Stock::Package] items + stock location- # @return [DeliveryRateEstimate, nil]+ # @param package [Spree::Stock::Package]+ # @return [DeliveryRateEstimate, nil] nil suppresses this method,+ # matching the calculator contract where nil hides the methoddef estimate(package)raise NotImplementedErrorend- end- DeliveryRateEstimate = Struct.new(- :delivery_method,- :cost,- :carrier,- :service_level,- :estimated_delivery_date,- :estimated_transit_days,- :metadata,- keyword_init: true- )+ # Whether this provider can serve the store at all. Used by the admin UI+ # to hide providers whose Integration isn't connected.+ #+ # @param store [Spree::Store]+ # @return [Boolean]+ def self.available_for_store?(_store)+ true+ end++ # Lifecycle hooks — no-ops by default, mirroring SearchProvider::Base+ # (search_provider/base.rb:41-80). Only #estimate is required.+ def book(_delivery_rate); end+ def release(_delivery_rate); end++ private++ def store+ delivery_method.store+ end++ def integration+ return if self.class.integration_class.blank?++ @integration ||= store.integrations.active.find_by(type: self.class.integration_class)+ end++ def self.integration_class = nil+ endendend```-### Internal Provider (default)+`nil` from `#estimate` suppresses the method — deliberately identical to the calculator contract (`estimator.rb:35`), so `FlatRate`'s thresholds keep working unchanged through the Internal provider.++### Internal provider (default)-Computes rate directly from DeliveryMethod pricing preferences — no Calculator indirection:+The entire body is a delegation. This is the point:```rubymodule Spreemodule DeliveryRateProviderclass Internal < Basedef estimate(package)- cost = compute_cost(package)- return nil unless cost+ cost = delivery_method.calculator.compute(package)+ return nil if cost.nil?DeliveryRateEstimate.new(- delivery_method: delivery_method,cost: cost,carrier: nil,service_level: nil,- estimated_delivery_date: estimated_date,+ estimated_delivery_date: estimated_delivery_date,estimated_transit_days: delivery_method.estimated_transit_business_days_min,metadata: {})@@ -265,36 +319,45 @@ module Spreeprivate- def compute_cost(package)- case delivery_method.pricing_type- when 'flat_rate'- delivery_method.preferred_amount- when 'per_item'- delivery_method.preferred_amount * package.quantity- when 'weight'- delivery_method.preferred_amount * package.weight- when 'percent'- package.item_total * (delivery_method.preferred_amount / 100.0)- when 'free'- 0- end- end-- def estimated_date- return nil unless delivery_method.estimated_transit_business_days_min+ def estimated_delivery_date+ days = delivery_method.estimated_transit_business_days_min+ return nil if days.blank?- delivery_method.estimated_transit_business_days_min.business_days.from_now+ days.business_days.from_now.to_dateendendendend```-`DeliveryMethod#pricing_type` and `#preferred_amount` replace the polymorphic calculator association with simple columns/preferences.+Every calculator — including merchant subclasses — keeps working, thresholds and all. `estimated_transit_business_days_min`/`_max` are existing columns (schema `spree_shipping_methods`), validated at `shipping_method.rb:37-38` and already surfaced through `#delivery_range` (`:92-100`) and `ShippingRate#delivery_range` (`shipping_rate.rb:78-91`).++### Estimator integration++The single dispatch point. Note the filtering, VAT, tax, and sort logic around it is unchanged:-### External Provider Example (EasyPost)+```ruby+def calculate_shipping_rates(package, ui_filter)+ shipping_methods(package, ui_filter).map do |shipping_method|+ estimate = shipping_method.rate_provider.estimate(package)++ next if estimate.nil?++ shipping_method.shipping_rates.new(+ cost: gross_amount(estimate.cost, taxation_options_for(shipping_method)),+ tax_rate: first_tax_rate_for(shipping_method.tax_category),+ carrier: estimate.carrier,+ service_level: estimate.service_level,+ estimated_delivery_date: estimate.estimated_delivery_date,+ metadata: estimate.metadata+ )+ end.compact+end+```-Each EasyPost-backed DeliveryMethod stores its carrier + service in metadata. Note how the provider reads credentials from its `Spree::Integration` record (see "Credentials live in Spree::Integration" above):+`#shipping_methods` (`estimator.rb:61-71`) is untouched, so `calculator.available?(package)` still gates `DigitalDelivery` and the currency check still applies. **`ShippingMethod#calculator` therefore stays required** even for external providers — it supplies `available?`. External providers can use a FlatRate calculator with amount 0 as a no-op; the cost it computes is ignored.++### External provider example (EasyPost)```rubymodule SpreeEasyPost@@ -306,41 +369,32 @@ module SpreeEasyPostenddef estimate(package)- # Get rate for this specific carrier+service from EasyPost- shipment = find_or_create_easypost_shipment(package)- rate = shipment.rates.detect do |r|+ rate = easypost_shipment(package).rates.detect do |r|r.carrier == delivery_method.metadata['carrier'] &&r.service == delivery_method.metadata['service']end-- return nil unless rate+ return nil if rate.nil?Spree::DeliveryRateProvider::DeliveryRateEstimate.new(- delivery_method: delivery_method,cost: rate.rate.to_d,carrier: rate.carrier,service_level: rate.service,estimated_delivery_date: rate.delivery_date,estimated_transit_days: rate.delivery_days,- metadata: { easypost_rate_id: rate.id, easypost_shipment_id: shipment.id }+ metadata: { easypost_rate_id: rate.id, easypost_shipment_id: rate.shipment_id })endprivatedef client- @client ||= begin- store = delivery_method.stores.first- integration = store.integrations.active.find_by!(type: self.class.integration_class)- EasyPost::Client.new(api_key: integration.preferred_api_key)- end+ @client ||= EasyPost::Client.new(api_key: integration.preferred_api_key)end- # Cache the EasyPost shipment per package to avoid duplicate API calls- # (multiple DeliveryMethods may share the same EasyPost provider)- def find_or_create_easypost_shipment(package)- cache_key = "easypost_shipment_#{package.stock_location.id}_#{package.order.id}"- RequestStore.store[cache_key] ||= client.shipment.create(+ # One API call serves every DeliveryMethod sharing this provider within a request.+ def easypost_shipment(package)+ key = [:easypost_shipment, store.id, package.stock_location.id, package.order.id]+ Spree::Current.provider_cache[key] ||= client.shipment.create(from_address: address_from_stock_location(package.stock_location),to_address: address_from_order(package.order),parcel: parcel_from_package(package)@@ -350,181 +404,125 @@ module SpreeEasyPostend```-Admin setup: create DeliveryMethods for each carrier+service, set `rate_provider: 'SpreeEasyPost::DeliveryRateProvider'` and `metadata: { carrier: 'UPS', service: 'Ground' }`.--### Integration Point: Checkout Services+`Spree::Current.provider_cache` is a new `CurrentAttributes` entry (a plain Hash, reset per request) added by this plan.-Each DeliveryMethod's provider is called directly — no Estimator intermediary:+### ShippingRate enrichment-```ruby-class Spree::Checkout::GetDeliveryRates- def call(order:)- order.fulfillments.each do |fulfillment|- package = fulfillment.to_package- methods = available_delivery_methods(order, fulfillment)-- rates = methods.filter_map do |method|- provider = method.rate_provider_instance # each method has its own provider- estimate = provider.estimate(package)- next unless estimate-- fulfillment.delivery_rates.build(- delivery_method: estimate.delivery_method,- cost: estimate.cost,- carrier: estimate.carrier,- service_level: estimate.service_level,- estimated_delivery_date: estimate.estimated_delivery_date,- metadata: estimate.metadata- )- end+New nullable columns on `spree_shipping_rates`: `carrier` (string), `service_level` (string), `estimated_delivery_date` (date), plus the `Spree::Metadata` concern (single `metadata` JSON column per the 2026-03-16 metadata-consolidation decision in decisions.md). `ShippingRate` does **not** currently include `Metadata` (unlike `ShippingMethod` at `:7-8`), so the concern must be added alongside the columns.- # Select cheapest as default- rates.min_by(&:cost)&.update(selected: true) if rates.any?- end- end-end-```+**Constraint to respect:** `spree_shipping_rates` has a *unique* index on `["shipment_id", "shipping_method_id"]` (`spree_shipping_rates_join_index`). One row per (shipment, method) is why each DeliveryMethod yields at most one rate. A provider wanting to expose Ground *and* Express must be configured as two DeliveryMethods — which is also what makes the shared-API-call caching above worthwhile. Do not attempt multi-rate-per-method without first deciding whether to drop that index.-Each DeliveryMethod returns one rate from its provider. The checkout service collects all rates and lets the customer choose.+The Store API already speaks this vocabulary: `Spree::Api::V3::DeliveryRateSerializer` exists and `FulfillmentSerializer` exposes `many :shipping_rates, key: :delivery_rates` (`fulfillment_serializer.rb:55`). New fields are added there and to the admin serializer.## Migration Path-### Phase 1: Provider interface + Internal provider+### Phase 1 — store ownership (independent, ship first)-- Create `Spree::DeliveryRateProvider::Base`, `::Internal`, `::DeliveryRateEstimate`-- Register `Spree.delivery_rate_provider` on Spree module-- Internal provider wraps existing `calculator.compute(package)` — zero behavior change-- **No changes to Estimator yet** — just the interface+- Migration: `add_reference :spree_shipping_methods, :store, null: true, if_not_exists: true`, following `20260628000001_add_store_id_to_spree_promotions.rb`.+- `ShippingMethod` includes `SingleStoreResource`, declares `belongs_to :store` + presence validation gated on `Spree::Config[:disable_store_presence_validation]`.+- Backfill rake task. **Unlike Promotion/PaymentMethod there is no join table to read from**, so ownership is derived: assign `Spree::Store.default` when only one store exists (the overwhelmingly common case); where multiple stores exist, use the zone-overlap signal from `Store#countries_with_shipping_coverage` (`store.rb:342`) and log every ambiguous method loudly rather than guessing silently. Idempotent — skip rows that already have `store_id`.+- Update `shipping_method_factory.rb` and the admin controller (`shipping_methods_controller.rb`) to set/scope by store.+- `null: false` is deferred to the 6.0 cleanup, after the vendor interaction is settled.-### Phase 2: Wire into Estimator+### Phase 2 — provider interface + Internal provider-- Modify `Stock::Estimator#calculate_shipping_rates` to delegate to provider-- Internal provider produces identical results to current calculator flow-- All existing tests pass unchanged+- Add `Base`, `Internal`, `DeliveryRateEstimate`, and `Spree::Current.provider_cache`.+- Add the `rate_provider` string column to `spree_shipping_methods` (nullable; blank means Internal).+- Wire the dispatch in `Estimator#calculate_shipping_rates`.+- **Zero behavior change is the acceptance criterion**: the full existing shipping suite passes untouched. Because Internal delegates to `calculator.compute` and all filtering/VAT/tax/sort logic is unchanged, any diff in rates is a bug.-### Phase 3: Enrich DeliveryRate/ShippingRate model+### Phase 3 — enrich ShippingRate-- Add `carrier`, `service_level`, `estimated_delivery_date`, `metadata` columns to ShippingRate (or DeliveryRate after rename)-- Serialize provider-specific data in metadata (e.g., `easypost_rate_id`)-- Update Store API serializer to expose new fields+- Add `carrier`, `service_level`, `estimated_delivery_date` columns + the `Metadata` concern.+- Populate from `DeliveryRateEstimate` in the Estimator.+- Expose in the Store and Admin serializers; regenerate types via the pipeline in CLAUDE.md.-### Phase 4: Reference external provider+### Phase 4 — admin surface (React dashboard only — no Rails admin in 6.0)-- Document how to build an EasyPost/Shippo provider-- Ship as a how-to guide (like custom-search-provider)+- Admin API v3: `rate_provider` on the delivery-method serializer/permitted params, plus a provider-discovery endpoint (available providers filtered by `available_for_store?(store)`); admin-sdk resource + generated types.+- Dashboard delivery-method page: provider select + schema-driven calculator preference forms (`PreferencesForm`, per the 2026-07-21 routing-rules pattern), `<Can>`-gated, i18n in all locale files.+- The legacy admin's `_calculator_fields.html.erb` and shipping-method form are deleted with `spree/admin` at 6.0 — no work there. (Any 5.x interim wiring may touch them; note the partial is shared with tax rates and promotion actions.)-## Relationship to Other 6.0 Plans+### Phase 5 — reference external provider-### Fulfillment & Delivery (6.0-fulfillment-and-delivery.md)+- Ship an EasyPost provider gem and a how-to guide, mirroring the custom-search-provider doc.-That plan renames models and adds `FulfillmentProvider` for post-purchase lifecycle (create shipment, track, cancel). This plan adds `DeliveryRateProvider` for pre-purchase rate calculation. They're complementary:+## Constraints on Current Work-```-Pre-purchase: DeliveryRateProvider → "How much does shipping cost?"-Post-purchase: FulfillmentProvider → "Create shipment, generate label, track delivery"-```+- **Don't add new shipping calculators for external carrier APIs.** Calculators are for internal arithmetic. Use the provider interface.+- **Don't monkey-patch `Stock::Estimator`.** The provider dispatch is the intended seam.+- **Don't delete or deprecate `ShippingCalculator` or `Calculator::Shipping::*`.** They are load-bearing and staying. `CalculatedAdjustments` is shared with TaxRate and promotion actions; its fate belongs to `6.0-tax-provider.md` and `6.0-split-adjustments.md`, not here.+- **Don't add `pricing_type` / `preferred_amount` columns to ShippingMethod.** Superseded; see "Why calculators stay."+- **New ShippingRate fields should fit the enriched model** (carrier, service_level, estimated_delivery_date, metadata).+- **Never unconditionally set `selected` on refresh.** Preserve the existing behavior at `shipment.rb:355-361`.+- **`FulfillmentProvider` is separate.** Don't mix rate estimation into it.-A DeliveryMethod has both:-- `rate_provider` (for rate calculation) — replaces `calculator` association-- `fulfillment_provider` (for post-purchase) — from fulfillment plan-- Rate provider is per-method (different methods can use different providers)+## Open Questions-### Tax Provider (6.0-tax-provider.md)+1. **Rate caching TTL.** Per-request caching is specified above. Cross-request caching (5-minute TTL for expensive carrier calls) is left to the provider — different APIs have different staleness rules. Revisit if every provider ends up reimplementing it.-Same open-closed pattern:-- Tax: `TaxProvider::Internal` wraps `TaxRate + Calculator::DefaultTax`-- Delivery: `DeliveryRateProvider::Internal` wraps `ShippingMethod.calculator`-- Both have lifecycle methods the internal provider no-ops on+2. **Multi-package rates.** Carriers sometimes discount multi-package shipments. The Estimator processes packages independently (`coordinator.rb:50-53`), and `Cart::EstimateShippingRates` is stricter still — it estimates only `packages.first` (`estimate_shipping_rates.rb:13`), discarding the rest. Keeping one-package-at-a-time for now; a multi-package hook is a later addition.-### Search Provider (shipped in 5.4)+3. **Rate validation at completion.** Rates can expire between checkout and payment. Add `validate_rate(delivery_rate)` to the base class, or re-estimate and compare at completion? Leaning toward a lifecycle hook alongside `book`/`release`.-Established the pattern. All three follow the same open-closed architecture:+4. **Backfill heuristic for multi-store installs.** The zone-overlap signal in Phase 1 is imperfect where several stores share a zone. Is loud logging plus manual reassignment sufficient, or should the task refuse to guess and require an explicit mapping?-| | Search | Tax | Delivery Rates |-|---|---|---|---|-| **Scope** | Global (`Spree.search_provider`) | Per-Market (`Market#tax_provider`) | Per-method (`DeliveryMethod#rate_provider`) |-| **Replaces** | Ransack/ILIKE | `TaxRate.adjust` + Calculator | `Stock::Estimator` + Calculator |-| **Internal** | Database (SQL) | Reads TaxRate data directly | Reads DeliveryMethod prefs directly |-| **External** | Meilisearch | Avalara / TaxJar | EasyPost / Shippo |-| **Calculators** | N/A | Removed in 6.0 | Removed in 6.0 |-| **Credentials** | `Spree::Integration` | `Spree::Integration` | `Spree::Integration` |+## Relationship to Other 6.0 Plans-All external providers follow the same credential pattern: credentials live in a `Spree::Integration` subclass (per-store, admin-managed), the provider reads them at runtime. See "Credentials live in Spree::Integration" section above.+### Fulfillment & Delivery (`6.0-fulfillment-and-delivery.md`)-### DeliveryZone replaces Zone for shipping+Renames the domain (ShippingMethod → DeliveryMethod, ShippingRate → DeliveryRate, Shipment → Fulfillment) and adds `FulfillmentProvider` for post-purchase lifecycle.-The current generic `Zone` (country or state members) is replaced by `DeliveryZone` which adds postal code range support:+```+Pre-purchase: DeliveryRateProvider → "What are the options and what do they cost?"+Post-purchase: FulfillmentProvider → "Create the shipment, generate a label, track it"+```-```ruby-class Spree::DeliveryZone < Spree.base_class- has_prefix_id :dz+A DeliveryMethod carries both `rate_provider` and `fulfillment_provider`. Note the API layer **already** uses the new vocabulary — `DeliveryRateSerializer`, `DeliveryMethodSerializer`, and the `Spree.api.delivery_*` registrations (`api/lib/spree/api/dependencies.rb:127-128, 209, 213`) all ship today, and the models already carry `has_prefix_id :dm` / `:dr`. Only the model/table names are outstanding.- has_many :delivery_zone_members, dependent: :destroy- has_many :delivery_method_zones, dependent: :destroy- has_many :delivery_methods, through: :delivery_method_zones+**Sequencing:** that plan drops `ShippingCategory`, which is both a stock splitter (`engine.rb:156`) and the discriminator behind `ShippingMethod#digital?` / `#requires_zone_check?` / `.digital` (`shipping_method.rb:42, 57, 128`). Those read `calculator.is_a?(DigitalDelivery)`. Since this plan keeps calculators, that coupling is preserved rather than broken — but if the fulfillment plan introduces a `kind`/`fulfillment_type` discriminator, these three call sites plus `MEMOIZED_METHODS` (`:17`) should move to it.- validates :name, presence: true+### Cart/Order Split (`6.0-cart-order-split.md`)- def include?(address)- delivery_zone_members.any? { |member| member.match?(address) }- end-end+Checkout — and therefore rate estimation — happens on the **Cart** under copy-on-completion semantics. This plan is deliberately agnostic: it changes only the inside of the Estimator, which runs per package wherever checkout invokes it. Where packages, delivery rates, and the selected rate live pre-completion (and how they copy to the order at `cart.complete!`) is owned by the cart-order-split and fulfillment plans; nothing in the provider contract assumes an `Order`.-class Spree::DeliveryZoneMember < Spree.base_class- belongs_to :delivery_zone-- # Polymorphic: country, state, or postal code range- attribute :member_type, :string # 'country', 'state', 'postal_code'- belongs_to :country, class_name: 'Spree::Country', optional: true- belongs_to :state, class_name: 'Spree::State', optional: true-- # For postal code ranges- attribute :postal_code_from, :string- attribute :postal_code_to, :string-- def match?(address)- case member_type- when 'country'- address.country_id == country_id- when 'state'- address.state_id == state_id- when 'postal_code'- address.zipcode.to_s >= postal_code_from.to_s &&- address.zipcode.to_s <= postal_code_to.to_s- end- end-end-```+### Tax Provider (`6.0-tax-provider.md`)-This enables delivery scenarios that the current Zone model can't handle:-- "Free delivery to postcodes 10001-10099" (local delivery)-- "Express available in London only" (state + postal code)-- "International shipping to EU countries" (country-level, same as today)+Same open-closed pattern. Note the coupling: `Stock::Estimator` depends on `Order#tax_zone` for both VAT gross-up (`estimator.rb:38`) and tax rate resolution (`:54-59`), so the shipping path is affected by tax-side Zone changes. This also answers the tax plan's open question about shipping-rate tax display: it stays Estimator-side (`gross_amount` + `tax_rate` on the rate), not in the delivery-rate provider.-Tax doesn't use zones at all — TaxRate links directly to country/state (see `6.0-tax-provider.md`). The generic `Spree::Zone` model is **dropped entirely** in 6.0. A shared data migration (rake task `spree:migrate_zones`, defined in the Tax Provider plan) converts existing Zone records used by ShippingMethod/DeliveryMethod into `DeliveryZone` records, and Zone records used by TaxRate into direct country/state FKs. After migration, `spree_zones` and `spree_zone_members` tables are removed.+### Search Provider (shipped 5.4)-## Constraints on Current Work+The reference implementation. `Spree.search_provider` / `search_provider=` at `core/lib/spree/core.rb:134-139`, string-valued and constantized by the caller; `SearchProvider::Base` at `core/app/models/spree/search_provider/base.rb`.-- **Don't add new shipping calculators for external carrier APIs.** The calculator pattern can't support them properly. Use the provider interface instead.-- **Don't monkey-patch Stock::Estimator.** The provider interface is the intended seam.-- **New ShippingRate/DeliveryRate fields should be designed for the enriched model** (carrier, service_level, estimated_delivery_date, metadata).-- **FulfillmentProvider is separate.** Don't mix rate calculation into the fulfillment provider.+| | Search | Tax | Delivery Rates |+|---|---|---|---|+| **Scope** | Global (`Spree.search_provider`) | Per-Market | Per-method (`DeliveryMethod#rate_provider`) |+| **Initialized with** | `store` (`base.rb:12`) | market | `delivery_method` (store via `delivery_method.store`) |+| **Wraps** | Ransack/ILIKE | `TaxRate.adjust` + Calculator | `Stock::Estimator` + Calculator |+| **Internal** | Database (SQL) | Reads TaxRate data | Delegates to the existing calculator |+| **External** | Meilisearch | Avalara / TaxJar | EasyPost / Shippo |+| **Calculators** | N/A | Decided in tax plan | **Kept** |+| **Credentials** | `Spree::Integration` | `Spree::Integration` | `Spree::Integration` |-## Open Questions+`SearchProvider::Base` raises `NotImplementedError` only for the two required methods and no-ops the rest (`:41-80`) — the delivery `Base` above mirrors that.-1. **Rate caching.** External API calls during checkout are expensive (~500ms). Should the provider cache rates for a configurable TTL (e.g., 5 minutes)? Or should caching be the provider's responsibility? Leaning toward provider responsibility — different APIs have different caching needs.+### Zones (`6.0-delivery-zones.md`)-2. **Multi-package rates.** Some carriers offer discounts for shipping multiple packages together. Should the provider receive all packages at once, or one at a time? Current Estimator processes packages independently. Leaning toward provider receives one package at a time (simpler, matches current flow), with a future enhancement for multi-package optimization.+Zone replacement is **not this plan's scope, but it ships in 6.0**. The earlier draft asserted `Spree::Zone` is "dropped entirely" while owning none of the ~183 non-spec references (`Spree::Current.zone`, `Market#tax_zone`, `Order#tax_zone`, `VatPriceCalculation`, `Pricing::Context`, permission sets, admin CRUD, the `Zone.global` factory monkey-patch every `:shipping_method` factory depends on). That inventory now has a dedicated owner: `6.0-delivery-zones.md` (2026-07-27 — 6.0 is the breaking-change window; this does not wait for 6.1).-3. **Rate validation at completion.** Rates can expire between checkout and payment. Should the provider have a `validate_rate(shipping_rate)` method called at order completion? Or re-estimate and compare?+Impact here is minimal by design: the zone check inside `Estimator#shipping_methods` swaps from `ShippingMethod#include?` over `Spree::Zone` to the same-shaped check over `DeliveryZone`; the provider interface never sees zones. Sequencing: this plan's phases don't wait for delivery-zones — the Estimator filter swap happens in that plan's Phase C.## References-- Current estimator: `spree/core/app/models/spree/stock/estimator.rb`-- Current calculators: `spree/core/app/models/spree/calculator/shipping/`-- Current shipping method: `spree/core/app/models/spree/shipping_method.rb`-- Current shipping rate: `spree/core/app/models/spree/shipping_rate.rb`-- Stock coordinator: `spree/core/app/models/spree/stock/coordinator.rb`-- Fulfillment plan: `6.0-fulfillment-and-delivery.md`-- Tax provider plan: `6.0-tax-provider.md`-- Search provider (reference implementation): `spree/core/app/models/spree/search_provider/`+- Estimator: `spree/core/app/models/spree/stock/estimator.rb`+- Calculators: `spree/core/app/models/spree/calculator/shipping/`+- Shipping method: `spree/core/app/models/spree/shipping_method.rb`+- Shipping rate: `spree/core/app/models/spree/shipping_rate.rb`+- Coordinator: `spree/core/app/models/spree/stock/coordinator.rb`+- Shipment refresh path: `spree/core/app/models/spree/shipment.rb:344-361`+- Order routing estimator: `spree/core/app/models/spree/order_routing/strategy/rules.rb:76`+- Integration: `spree/core/app/models/spree/integration.rb`+- SingleStoreResource: `spree/core/app/models/concerns/spree/single_store_resource.rb`+- Single-store backfill precedent: `spree/core/lib/tasks/single_store_associations.rake`+- Search provider (reference): `spree/core/app/models/spree/search_provider/`+- Related plans: `6.0-fulfillment-and-delivery.md`, `6.0-tax-provider.md`, `5.6-6.0-single-store-promotions-payment-methods.md`, `6.0-multi-vendor-marketplace.md`diff --git a/docs/plans/6.0-delivery-zones.md b/docs/plans/6.0-delivery-zones.mdnew file mode 100644index 0000000000..9153e9647b--- /dev/null+++ b/docs/plans/6.0-delivery-zones.md@@ -0,0 +1,121 @@+# Delivery Zones (Zone → DeliveryZone)++**Status:** Draft+**Target:** Spree 6.0+**Depends on:** `6.0-tax-provider.md` Phase 5 (tax decoupled from Zone — prerequisite for dropping the model), `6.0-fulfillment-and-delivery.md` Phase 1 (`spree_delivery_method_zones` born pointing at DeliveryZone). Coordinates with: `6.0-delivery-rate-provider.md` (the Estimator's zone check swaps to DeliveryZone matching; provider interface unaffected).+**Author:** Damian + Claude+**Last updated:** 2026-07-27++## Summary++Replace the generic `Spree::Zone` with `Spree::DeliveryZone`, adding postal-code-range members, and drop `Zone`/`ZoneMember` entirely by the end of 6.0. Reaffirmed 2026-07-27: 6.0 is the one breaking-change window — this does not wait for 6.1.++An earlier revision descoped this because the Zone removal surface (~183 non-spec references) had no owner: the tax plan covered only TaxRate FKs, the delivery-rate plan covered only shipping. **This plan is that owner.** Tax-side decoupling stays in `6.0-tax-provider.md` (TaxRate country/state FKs, tax readers rewritten onto `TaxRate.for_address`); everything else Zone touches is inventoried and assigned here.++Postal-code zones unlock what Zone structurally cannot express: "free local delivery to postcodes 10001–10099", "express in central Warsaw only", "no islands surcharge zone" — table-stakes for European local-delivery and courier setups, and a gap against carrier-level zone support in hosted platforms.++## Key Decisions (do not deviate without discussion)++- **`Spree::DeliveryZone` + `Spree::DeliveryZoneMember`**, prefix ids `dz_` / `dzm_`. Member is typed by `member_type`: `country` (FK), `state` (FK), or `postal_code` (`country_id` FK + `postal_code_from`/`postal_code_to` range, or a single `postal_code_prefix`). A zone mixes member types freely.+- **Postal matching is prefix-or-range, always country-scoped** (resolved 2026-07-27). Numeric-format countries (US, DE, PL, FR…) support lexicographic ranges on normalized codes (strip spaces/dashes, upcase); ranges are **gated by a numeric-postal country allowlist** — validation rejects range members for countries outside it. Non-numeric formats (UK, CA, NL, IE) get **prefix lists only** (`SW1`, `EC`, `M5V` — how merchants actually think there; UK outward codes and CA FSAs are inherently prefix-shaped). No per-country matcher strategies and no glob wildcards at launch: `DeliveryZoneMember#match?(address)` is one Ruby method with normalization in one place (`Spree::Address#normalized_zipcode`), so per-country matchers can be layered in later with zero schema change if real demand appears.+- **Empty zone list on a DeliveryMethod = worldwide** (unchanged semantics from today's zone-less methods).+- **`Spree::Zone` and `Spree::ZoneMember` are dropped in 6.0** — tables, models, `Country#zones`/`State#zones`, admin CRUD, factories. Nothing may keep a Zone reference past this plan's final phase.+- **`Spree::Current.zone` / `Pricing::Context` lose the zone dimension.** The browsing tax context becomes market/country-based (`Market#default_country` + `TaxRate.for_address`), per `6.0-tax-provider.md`. `Spree::Current.tax_country` (ISO) replaces `Spree::Current.zone` as the request-context attribute; `Pricing::Context` keys on country, not zone.+- **`Zone.global` factory pattern is retired.** The `factories.rb` monkey-patch and `shipping_method_factory`'s `zones { [Spree::Zone.global] }` are replaced by zone-less methods (worldwide by default) — most specs don't care about geography; the few that do build an explicit `:delivery_zone`.++## Design Details++```ruby+class Spree::DeliveryZone < Spree.base_class+ has_prefix_id :dz+ include Spree::Metadata++ has_many :members, class_name: 'Spree::DeliveryZoneMember', dependent: :destroy+ has_many :delivery_method_zones, class_name: 'Spree::DeliveryMethodZone', dependent: :destroy+ has_many :delivery_methods, through: :delivery_method_zones++ validates :name, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }++ def include?(address)+ members.any? { |m| m.match?(address) }+ end+end++class Spree::DeliveryZoneMember < Spree.base_class+ has_prefix_id :dzm++ belongs_to :delivery_zone, class_name: 'Spree::DeliveryZone', inverse_of: :members+ belongs_to :country, class_name: 'Spree::Country', optional: true+ belongs_to :state, class_name: 'Spree::State', optional: true++ validates :member_type, presence: true # 'country' | 'state' | 'postal_code'+ # postal_code members: country required + exactly one of prefix / from+to range++ def match?(address)+ case member_type+ when 'country' then address.country_id == country_id+ when 'state' then address.state_id == state_id+ when 'postal_code' then address.country_id == country_id && postal_match?(address.normalized_zipcode)+ end+ end+end+```++`DeliveryMethod#include?(address)` iterates `delivery_zones` instead of `zones`; the check stays where it is (inside `Estimator#shipping_methods` filtering, per the delivery-rate plan — no seam moves).++### Zone consumer inventory and ownership++Verified 2026-07-27 (~183 non-spec references: core/app 109, core/lib 37, admin/app 37):++| Surface | Owner |+|---|---|+| `TaxRate` zone FK, `TaxRate.match`, tax display readers (`Order#tax_zone`, `Spree::Current.zone`/`default_tax_zone`, `Market#tax_zone`, `VatPriceCalculation` taxation options, `Stock::Estimator#taxation_options_for`/`first_tax_rate_for`) | `6.0-tax-provider.md` Phase 5 (rewritten onto `TaxRate.for_address` / `Spree::Current.tax_country`) |+| `ShippingMethod has_many :zones`, `#include?`, `spree_shipping_method_zones` | **This plan** (join re-pointed to DeliveryZone; born correct if fulfillment Phase 1 lands first) |+| `Spree::Pricing::Context` zone dimension, `Spree::Current` zone attribute + resets | **This plan** (country-based, with tax-provider) |+| Admin `zones_controller` + views, `@available_zones` in shipping-method form, nav/table registry entries | **This plan** (replaced by DeliveryZones CRUD + picker) |+| Permission sets (`default_customer`, `configuration_management`) | **This plan** |+| `Country#zones` / `State#zones` / `ZoneMember` | **This plan** (removed) |+| `Store#countries_with_shipping_coverage` (`Zone.joins(:shipping_methods)`) | **This plan** (rewritten on DeliveryZone members) |+| `CountryToTimezone` service | **This plan** — verify actual Zone dependency at implementation; rewrite or leave if zone-free |+| Factories: `Zone.global` monkey-patch, `zone_factory`, `zone_member_factory`, `shipping_method_factory`, `order_walkthrough`, `market_factory` | **This plan** (worldwide-by-default methods; explicit `:delivery_zone` factory) |+| Seeds referencing zones | **This plan** |++## Migration Path++### Phase A — model + tables (after fulfillment Phase 1)++`spree_delivery_zones`, `spree_delivery_zone_members` (typed members, country-scoped postal columns). `spree_delivery_method_zones` is born (or re-pointed) with `delivery_zone_id`.++### Phase B — data migration (rake `spree:migrate_zones_to_delivery_zones`)++For each Zone referenced by a shipping/delivery method: create a DeliveryZone with the same name/description and copy members (country→country, state→state). Zones referenced only by TaxRate are handled by the tax plan's task; zones referenced by neither are logged and skipped. Idempotent, batched.++### Phase C — consumers++Admin API v3 delivery-zone CRUD (+ nested on delivery method) with admin-sdk resource and a **React dashboard** page under delivery settings (zone list + typed-member editor incl. postal ranges/prefixes; the legacy Rails `zones_controller` + views are deleted with `spree/admin` at 6.0, not rebuilt). Estimator/DeliveryMethod matching, `Spree::Current.tax_country` + `Pricing::Context` country key (jointly with tax-provider), `Store#countries_with_shipping_coverage`, permission sets, factories + test support, seeds, type pipeline regeneration.++### Phase D — drop (end of 6.0)++Drop `spree_zones` + `spree_zone_members`, remove `Zone`/`ZoneMember` models, `Country#zones`/`State#zones`, zone factories and the `Zone.global` monkey-patch. Grep-clean: zero `Spree::Zone` references outside the migration task.++## Constraints on Current Work++- **No new `Spree::Zone` references anywhere.** New geographic eligibility goes through DeliveryZone (shipping) or `TaxRate.for_address` (tax).+- **Don't build UI against the zones admin** — it's being replaced.+- **Address normalization goes through `Address#normalized_zipcode`** — don't scatter zipcode munging.++## Resolved Questions++1. **Non-numeric postal formats: prefix lists only at launch** (2026-07-27). Ranges are allowlist-gated to numeric-format countries; UK/CA/NL/IE merchants configure prefixes. Per-country matcher strategies were considered and deferred — matching is a single Ruby method, so they remain a non-breaking internal upgrade.+2. **Zipcode-sensitive rates: recalculation-on-write, no new machinery** (2026-07-27). `Carts::Update` already rebuilds delivery proposals on address change (`6.0-cart-order-split.md` recalculation-on-write); the one-page auto-save checkout PATCHes the address on zipcode blur and re-renders the delivery options returned in the same response. No dedicated non-persisting estimate endpoint, and zone definitions are never exposed to the client for pre-filtering. One addition: the cart-page mini-estimator (`Cart::EstimateShippingRates` and its successor) gains an optional `zipcode` param so pre-address estimates are postal-aware too.++## Open Questions++None at this time.++## References++- Descope reversal: decisions.md 2026-07-27 (amended — back in 6.0 per user decision)+- Consumer inventory source: delivery-rate-provider verification review 2026-07-27+- Related plans: `6.0-tax-provider.md`, `6.0-fulfillment-and-delivery.md`, `6.0-delivery-rate-provider.md`+- Current model: `spree/core/app/models/spree/zone.rb`, `spree/core/app/models/spree/zone_member.rb`diff --git a/docs/plans/6.0-fulfillment-and-delivery.md b/docs/plans/6.0-fulfillment-and-delivery.mdindex 1317b8e665..5245e9b2ad 100644--- a/docs/plans/6.0-fulfillment-and-delivery.md+++ b/docs/plans/6.0-fulfillment-and-delivery.md@@ -2,740 +2,318 @@**Status:** Draft**Target:** Spree 6.0-**Depends on:** ProductType (6.0-product-types.md), Normalize state→status (6.0-normalize-state-to-status.md), Typed Stock Movements (6.0-typed-stock-movements.md)+**Depends on:** `6.0-product-types.md` (`fulfillment_types` addendum 2026-07-27 — ProductType replaces ShippingCategory; **hard blocker**, `Spree::ProductType` does not exist yet), `6.0-cart-order-split.md` (where fulfillments/rates live pre-completion), `6.0-order-routing.md` (packages come from `for_allocation`), `6.0-normalize-state-to-status.md`. Coordinates with: `6.0-delivery-rate-provider.md` (owns `store_id` on DeliveryMethod; calculators stay per decisions.md 2026-07-27), `5.5-6.0-display-on-to-boolean.md` (`storefront_visible` lands in the same migration wave), `6.0-multi-vendor-marketplace.md` (`vendor_id`, lifecycle events, `delivery_amount`). Gates: `6.0-split-adjustments.md` and `6.0-typed-stock-movements.md` are born with `fulfillment_id` — **this plan's Phase 1 must land before both**.**Author:** Damian + Claude-**Last updated:** 2026-03-26+**Last updated:** 2026-07-27## Summary-Rename the shipping domain to use delivery/fulfillment vocabulary, drop ShippingCategory (replaced by ProductType), and add a FulfillmentProvider strategy interface for extensible fulfillment types (shipping, pickup, digital, local delivery, custom).+Rename the shipping domain to delivery/fulfillment vocabulary, drop ShippingCategory (replaced by `ProductType#fulfillment_types`), and add a FulfillmentProvider strategy interface for extensible fulfillment types (shipping, pickup, pickup point, digital, local delivery, custom).-This is three changes in one:+Three changes in one:1. **Rename** — Shipment → Fulfillment, ShippingMethod → DeliveryMethod, ShippingRate → DeliveryRate, InventoryUnit → FulfillmentItem-2. **Drop ShippingCategory** — ProductType.fulfillment_types controls delivery eligibility-3. **Add FulfillmentProvider** — strategy interface for 3rd-party integrations (EasyPost, ShipStation, etc.) and custom fulfillment types+2. **Drop ShippingCategory** — `ProductType#fulfillment_types` + `DeliveryMethod#fulfillment_type` control delivery eligibility+3. **Add FulfillmentProvider** — strategy interface for 3rd-party integrations and custom fulfillment types; replaces the broken `ShipmentHandler` name-constantize mechanism-## Problem+**Calculators are NOT touched by this plan.** The 2026-07-27 decision (decisions.md) keeps `ShippingCalculator` + `Calculator::Shipping::*`; rate estimation is the delivery-rate-provider plan's domain. **Zone replacement ships in 6.0 via `6.0-delivery-zones.md`** — this plan's Phase 1 births `spree_delivery_method_zones` pointing at `DeliveryZone` (born correct, never re-migrated).-1. **"Shipping" vocabulary is too narrow.** Shipment, ShippingMethod, ShippingRate, ShippingCategory — all assume carrier delivery. Click-and-collect, digital delivery, local courier, and in-store fulfillment don't fit. Digital delivery is currently hacked via a special Calculator subclass (`DigitalDelivery`) rather than being a proper fulfillment type.+## Already shipped (verified 2026-07-27, HEAD 4e5b6fd)-2. **ShippingCategory is a redundant model.** It exists solely to answer "which delivery methods are available for this product?" — but ProductType already defines what a product is. Adding `fulfillment_types` to ProductType eliminates an entire model + join table.+This plan is being implemented ahead of itself — the following exists today and must NOT be redone:-3. **No provider abstraction.** There's no interface for 3rd-party fulfillment services. Integrations (EasyPost, ShipStation) have to monkey-patch Shipment or wrap the Calculator. A clean provider interface enables plug-and-play fulfillment integrations.+- **API v3 speaks the new vocabulary over the old models**: `FulfillmentSerializer`, `DeliveryMethodSerializer`, `DeliveryRateSerializer` (+ Admin variants), `fulfillments` routes and controllers (store carts + admin orders), dual old/new registrations in `api/lib/spree/api/dependencies.rb:111-128, 191-213`. `FulfillmentSerializer` already emits `status` (from `state`), `fulfilled_at` (from `shipped_at`), and a **computed** `fulfillment_type` (`digital? ? 'digital' : 'shipping'`).+- **Prefix IDs claimed**: `ful_` (Shipment), `dm_` (ShippingMethod), `fi_` (InventoryUnit), `dr_` (via `Shipment#selected_delivery_rate_id`, whose YARD comment cites this plan).+- **Order aliases**: `alias_attribute :fulfillment_status, :shipment_state` and `alias_attribute :delivery_total, :shipment_total` (`order.rb:211-213`) — the Phase 1 column renames must remove these aliases in the same change.+- **`Spree::Fulfillments::Create` service** (`core/app/services/spree/fulfillments/create.rb`), registered as `Spree.fulfillment_create_service`.+- **StockLocation pickup columns** (shipped 2026-05-08): `kind`, `pickup_enabled`, `pickup_stock_policy`, `pickup_ready_in_minutes`, `pickup_instructions` + indexes. **Do not re-add.**+- **admin-sdk generated types are already clean** (zero `shipment` references); `packages/dashboard/src` still has 8 files on old vocabulary.-4. **InventoryUnit is a misleading name.** It represents "items in a fulfillment" — every competitor calls this FulfillmentItem or FulfillmentLine.+Outstanding: model/table/column renames, the eligibility rework, FulfillmentProvider, lifecycle events, and the legacy-admin/emails surfaces.## Entity Rename Map-| Current (5.4) | 6.0 | Prefix ID | Table |+| Current (5.x) | 6.0 | Prefix ID | Table ||---|---|---|---|-| `Spree::Shipment` | `Spree::Fulfillment` | `ful_` | `spree_fulfillments` |-| `Spree::ShippingMethod` | `Spree::DeliveryMethod` | `dm_` | `spree_delivery_methods` |+| `Spree::Shipment` | `Spree::Fulfillment` | `ful_` (shipped) | `spree_fulfillments` |+| `Spree::ShippingMethod` | `Spree::DeliveryMethod` | `dm_` (shipped) | `spree_delivery_methods` || `Spree::ShippingRate` | `Spree::DeliveryRate` | `dr_` | `spree_delivery_rates` |-| `Spree::ShippingMethodZone` | `Spree::DeliveryMethodZone` | — | `spree_delivery_method_zones` |-| `Spree::InventoryUnit` | `Spree::FulfillmentItem` | `fi_` | `spree_fulfillment_items` |-| `Spree::ShippingCategory` | Dropped | — | `spree_shipping_categories` dropped |-| `Spree::ShippingMethodCategory` | Dropped | — | `spree_shipping_method_categories` dropped |+| `Spree::ShippingMethodZone` | `Spree::DeliveryMethodZone` | — | `spree_delivery_method_zones` (born joining `Spree::DeliveryZone` — see `6.0-delivery-zones.md`) |+| `Spree::InventoryUnit` | `Spree::FulfillmentItem` | `fi_` (shipped) | `spree_fulfillment_items` |+| `Spree::FulfilmentChanger` (sic) | `Spree::FulfillmentChanger` | — | (PORO — fixes the single-L/double-L collision) |+| `Spree::ShipmentHandler` | removed → `FulfillmentProvider` | — | — |+| `Spree::ShippingCategory` | Dropped (Phase 6) | — | `spree_shipping_categories` dropped in 6.1 |+| `Spree::ShippingMethodCategory` | Dropped | — | `spree_shipping_method_categories` dropped in 6.1 || — (new) | `Spree::DeliveryMethodStockLocation` | — | `spree_delivery_method_stock_locations` |+**Fulfillment numbers:** existing `H`-prefixed numbers are opaque identifiers and stay untouched (unique index on `number`); new fulfillments generate `F`-prefixed numbers. No data migration.+## Key Decisions (do not deviate without discussion)### Naming-- **Fulfillment** = the physical/digital act of getting items to the customer. The record that tracks "these items are being delivered." Replaces Shipment.-- **DeliveryMethod** = the option presented to the customer at checkout ("Standard Shipping", "Express", "In-Store Pickup", "Digital Download"). Replaces ShippingMethod.-- **DeliveryRate** = the price quote for a delivery method on a specific fulfillment. Replaces ShippingRate.-- **FulfillmentItem** = an item within a fulfillment (variant + quantity). Replaces InventoryUnit.-- **FulfillmentProvider** = strategy class that handles the mechanics of creating/tracking/canceling a fulfillment with a 3rd-party or internal system. New.--### ProductType replaces ShippingCategory--ProductType gains a `fulfillment_types` array column:--```ruby-class Spree::ProductType < Spree.base_class- # Array of allowed fulfillment types for products of this type- # Default: ['shipping']- # Examples: ['shipping', 'pickup'], ['digital'], ['shipping', 'pickup', 'pickup_point', 'local_delivery']- attribute :fulfillment_types, default: ['shipping']+- **Fulfillment** = the act of getting items to the customer; the record tracking it. Replaces Shipment.+- **DeliveryMethod** = the option presented at checkout. Replaces ShippingMethod.+- **DeliveryRate** = the price quote for a delivery method on a fulfillment. Replaces ShippingRate.+- **FulfillmentItem** = an item within a fulfillment (variant + quantity — the `quantity` column and its validation already exist on InventoryUnit today). Replaces InventoryUnit.+- **FulfillmentProvider** = strategy handling create/track/cancel mechanics per fulfillment type. New; replaces `ShipmentHandler` (whose name-constantize factory can never match — no subclass exists and the seeded method name "Digital Delivery" can't constantize).- validates :fulfillment_types, presence: true-end-```+### ProductType replaces ShippingCategory — and `Package#shipping_methods` is the real thing being replaced-Products without a ProductType default to `['shipping']` (backward compatible).+ShippingCategory's load-bearing job is not the model — it's `Stock::Package#shipping_methods` (`package.rb:73-80`), which intersects delivery methods *through categories* and is the **sole input** to `Stock::Estimator#shipping_methods`. Drop the category without replacing this and mixed carts get zero rates, tripping `ensure_available_shipping_rates` and blocking checkout (asserted by `order_routing/strategy/parity_spec.rb:426-452`).-At checkout, available delivery methods are filtered:-```ruby-# Collect all fulfillment types needed by items in the cart-required_types = order.line_items.map { |li| li.product.product_type&.fulfillment_types || ['shipping'] }.flatten.uniq+Replacement semantics:-# Find delivery methods matching those types-DeliveryMethod.where(fulfillment_type: required_types).eligible_for(order)-```+- `ProductType#fulfillment_types` (JSON array, default `['shipping']`; see the 2026-07-27 addendum in `6.0-product-types.md`). Products without a ProductType default to `['shipping']` — the reconciliation between optional ProductType and today's effectively-mandatory ShippingCategory (`Product` presence-validates + auto-assigns one today, `product.rb:133, 153, 945-951`).+- `DeliveryMethod#fulfillment_type` (single string) must be **included in every package item's** `fulfillment_types` for the method to be eligible.+- `Package#eligible_delivery_methods` replaces `Package#shipping_methods`: intersect items' fulfillment types, then subtract per-product exclusions. `Product.excluded_delivery_method_ids` (JSON array column, jsonb-guarded) covers the rare restriction case ("fragile item can't ship express") without a dedicated model.+- `Stock::Splitter::ShippingCategory` → `Stock::Splitter::FulfillmentType` — packages stay homogeneous by fulfillment type, so mixed carts (physical + digital) still split automatically. `Splitter::Digital` folds into it.+- The eligibility seam stays **inside `Stock::Estimator#shipping_methods`** (per the delivery-rate-provider plan, which owns filtering — including the marketplace vendor gate). This plan changes the *inputs* to that filter, not its location. No separate `DeliveryMethods::Available` service.-For mixed carts (physical + digital), separate fulfillments are created automatically — one per fulfillment type.+### The digital discriminator moves off the calculator class-**Edge case: method-level restrictions.** If a specific product needs to exclude certain delivery methods (e.g., fragile item can't use express), use `Product.excluded_delivery_method_ids` (simple array column or M2M) — checked at rate calculation time. This replaces the rare ShippingCategory-as-restriction use case without a dedicated model.+`ShippingMethod#digital?`, `#requires_zone_check?`, and the `.digital` scope currently test `calculator.is_a?(DigitalDelivery)` (`shipping_method.rb:42, 57, 128`; memoized via `MEMOIZED_METHODS :17`), and `Product#digital?` derives through a four-hop chain (product → category → methods → calculator class). All of these move to columns: `DeliveryMethod#fulfillment_type == 'digital'` and `ProductType#digital?`. The `DigitalDelivery` calculator stays (calculators are kept) but becomes a plain zero-cost calculator — its `available?` gating is superseded by fulfillment-type eligibility. `Seeds::DigitalDelivery` updates to set `fulfillment_type: 'digital'`.### Fulfillment types are open strings-```ruby-class Spree::DeliveryMethod < Spree.base_class- # Built-in types- FULFILLMENT_TYPES = %w[shipping pickup pickup_point digital local_delivery].freeze-- # Open string — developers can register custom types- validates :fulfillment_type, presence: true-- # No inclusion validation — extensible via:- # Spree.fulfillment_types << 'same_day_courier'-end-```--- `shipping` — carrier delivery to customer's address-- `pickup` — customer collects from merchant's own location (store, warehouse)-- `pickup_point` — carrier delivers to third-party point (InPost locker, DHL ServicePoint, UPS Access Point), customer collects there-- `digital` — digital download, no physical delivery-- `local_delivery` — merchant delivers within a local radius+`shipping`, `pickup` (merchant location), `pickup_point` (third-party point — InPost locker, DHL ServicePoint), `digital`, `local_delivery` built in; extensible via `Spree.fulfillment_types << 'same_day_courier'`. No inclusion validation.### FulfillmentProvider is a strategy (not a DB model)```rubyclass Spree::FulfillmentProvider::Base- # Can this provider handle this fulfillment?- def can_fulfill?(fulfillment)- true- end-- # Create the fulfillment with 3rd-party (e.g., call EasyPost/ShipStation)- # Returns hash with tracking info: { tracking_number: '...', tracking_url: '...' }- def create_fulfillment(fulfillment)- raise NotImplementedError- end-- # Cancel a fulfillment with 3rd-party- def cancel_fulfillment(fulfillment)- raise NotImplementedError- end-- # Get tracking URL for a fulfillment- def tracking_url(fulfillment)- nil- end-- # Get shipping label documents- def documents(fulfillment)- []- end-end-```--Built-in providers:-- `Spree::FulfillmentProvider::Manual` — admin manually marks as shipped (default, current behavior)-- `Spree::FulfillmentProvider::Digital` — auto-generates DigitalLink on order completion-- `Spree::FulfillmentProvider::Pickup` — marks ready-for-pickup at merchant location-- `Spree::FulfillmentProvider::PickupPoint` — marks ready-for-pickup at third-party point (carrier handles routing)--3rd-party examples:-- `SpreeEasyPost::FulfillmentProvider` — creates EasyPost shipments, returns labels-- `SpreeShipStation::FulfillmentProvider` — pushes to ShipStation API--DeliveryMethod stores the provider class name:-```ruby-class Spree::DeliveryMethod < Spree.base_class- # String class name of the provider- # Default: 'Spree::FulfillmentProvider::Manual'- attribute :fulfillment_provider, :string, default: 'Spree::FulfillmentProvider::Manual'-- def provider- @provider ||= fulfillment_provider.constantize.new- end-end-```--Registration:-```ruby-# config/initializers/spree.rb-Spree.fulfillment_types << 'same_day_courier'-Spree.fulfillment_providers << MyApp::FulfillmentProvider::SameDayCourier-```--### Pickup & Pickup Point architecture--Industry consensus (Shopify, Medusa, Saleor): merchant pickup locations are stock locations with a flag, not a separate model. Spree follows this.--**Two distinct pickup scenarios:**--| Scenario | `fulfillment_type` | Location source | Address stored on Fulfillment |-|---|---|---|---|-| **Merchant pickup** (collect from store) | `pickup` | `StockLocation` with `pickup_enabled: true` | None — `stock_location_id` already has the address |-| **Third-party pickup point** (InPost, DHL locker) | `pickup_point` | Provider API → ephemeral results | `pickup_point_data` JSON — frozen snapshot of selected point |--#### StockLocation changes (merchant pickup)--> **Status: shipped.** The pickup-related columns and the `country_iso=` /-> `state_abbr=` setters landed alongside the Admin API for stock locations-> (PR shipped 2026-05-08). The rename work and the `pickup_point` /-> `PickupPointProvider` machinery in this plan are still pending.--```ruby-class Spree::StockLocation < Spree.base_class- KINDS = %w[warehouse store fulfillment_center].freeze-- attribute :kind, :string, default: 'warehouse'- attribute :pickup_enabled, :boolean, default: false- attribute :pickup_stock_policy, :string, default: 'local' # 'local' or 'any'- attribute :pickup_ready_in_minutes, :integer # e.g., 120 (2 hours)- attribute :pickup_instructions, :text-- scope :pickup_enabled, -> { where(pickup_enabled: true) }+ def can_fulfill?(fulfillment) = true+ def create_fulfillment(fulfillment) = raise(NotImplementedError) # → { tracking_number:, tracking_url: }+ def cancel_fulfillment(fulfillment) = raise(NotImplementedError)+ def tracking_url(fulfillment) = nil+ def documents(fulfillment) = []end```-- `kind` — categorizes the location (warehouse, store, fulfillment_center). Open string, extensible.-- `pickup_enabled` — whether customers can collect from this location.-- `pickup_stock_policy` — `'local'` means only items physically in stock at this location can be picked up. `'any'` means items can be transferred from other locations (ship-to-store).-- `pickup_ready_in_minutes` — estimated lead time shown to customer.-- `pickup_instructions` — displayed after order placement ("Enter through the back door").+Built-ins: `Manual` (default — current admin-driven behavior), `Digital`, `Pickup`, `PickupPoint`. Third-party: `SpreeEasyPost::FulfillmentProvider`, `SpreeShipStation::FulfillmentProvider`. Stored as a string class name on DeliveryMethod, constantized at call time. Registered via `Spree.fulfillment_providers`.-#### PickupPointProvider interface (third-party pickup points)+**Digital auto-fulfillment is new behavior, not a refactor.** Today digital shipments sit at `ready` until an admin clicks Ship (`Shipment#shippable?` exists precisely for that button), and DigitalLinks are created by a checkout state-machine callback (`checkout.rb:87-89` — nested inside `if states[:payment]`, non-idempotent, one link per line item regardless of quantity). `FulfillmentProvider::Digital` takes over both: on order completion it fires `fulfill!` directly and generates DigitalLinks idempotently, per quantity. This also gives the multi-vendor ledger its "digital vendor order earns immediately after payment" path.-Third-party pickup points (InPost, DHL ServicePoint, UPS Access Point) are **not** stored in the database. There are 20,000+ InPost lockers in Poland alone — these are fetched from carrier APIs at checkout time and returned as ephemeral value objects.+### Lifecycle events are first-class (multi-vendor ledger depends on them)-```ruby-# Value object — not persisted-Spree::PickupPointOption = Struct.new(- :external_id, # "inpost-PL-WAW-42"- :name, # "InPost Locker PL-WAW-42"- :provider, # "inpost"- :address, # { street:, city:, postal_code:, country_code:, lat:, lng: }- :opening_hours, # optional- :kind, # "locker", "servicepoint", "store"- :metadata, # provider-specific data- keyword_init: true-)-```+`Fulfillment` gets `publishes_lifecycle_events` plus explicit transition events: `fulfillment.ready`, `fulfillment.fulfilled`, `fulfillment.canceled`, `fulfillment.resumed`. Order-level: when the last fulfillment reaches `fulfilled`, publish `order.fulfilled` — the signal `6.0-multi-vendor-marketplace.md`'s `vendor_transfer.due` subscriber keys on ("all the vendor order's fulfillments fulfilled"). `Order#fully_fulfilled?` is the matching queryable predicate.-```ruby-module Spree- module PickupPointProvider- class Base- attr_reader :delivery_method-- def initialize(delivery_method)- @delivery_method = delivery_method- end-- # Returns nearby pickup points for a given address- # @param address [Spree::Address] customer's address (or lat/lng)- # @param limit [Integer] max results- # @return [Array<PickupPointOption>]- def find_nearby(address:, limit: 10)- raise NotImplementedError- end-- # Validates a selected point is still available- # @param external_id [String]- # @return [PickupPointOption, nil]- def find_by_external_id(external_id)- raise NotImplementedError- end- end- end-end-```--DeliveryMethod stores the pickup point provider class (only for `pickup_point` type):--```ruby-class Spree::DeliveryMethod < Spree.base_class- attribute :pickup_point_provider, :string # 'SpreeInpost::PickupPointProvider', nil for non-pickup-point methods-- def pickup_point_provider_instance- return nil unless pickup_point_provider.present?- pickup_point_provider.constantize.new(self)- end-end-```+**Webhook contract break:** today `Shipment` publishes `shipment.*` events and webhooks (`Shipment::Webhooks`, `Shipment::CustomEvents`). Event names rename with the model; 6.0 dual-emits `shipment.shipped` alongside `fulfillment.fulfilled` for one release with a deprecation note in webhook docs, dropped in 6.1.-#### How the selected pickup point is stored+### Vendor axis (marketplace)-When the customer selects a third-party pickup point, its data is frozen as JSON on the Fulfillment. No FK — the data is ephemeral from the provider:+`vendor_id` (nullable) on DeliveryMethod — the column ships in the marketplace plan's schema wave; this plan's model carries `belongs_to :vendor, optional: true`, replacing the Enterprise `VendorConcern` decorator seam (`shipping_method.rb:10-12`). Semantics (owned by the delivery-rate plan's Estimator filter): `vendor_id` present → offered only on that vendor's packages; `nil` → marketplace-wide. Store vs vendor are different axes: store = tenant + credential scope (`store_id`, owned by the delivery-rate plan), vendor = seller within it.-```ruby-class Spree::Fulfillment < Spree.base_class- # For pickup_point fulfillments — stores the selected point snapshot- attribute :pickup_point_data, :json- # {- # external_id: "inpost-PL-WAW-42",- # name: "InPost Locker PL-WAW-42",- # provider: "inpost",- # address: { street: "ul. Marszałkowska 1", city: "Warsaw", postal_code: "00-001", country_code: "PL" }- # }-end-```+`DeliveryMethodStockLocation` validates vendor consistency: when both the method and the stock location carry a `vendor_id`, they must match — otherwise one vendor's pickup counter could serve another vendor's items. Pickup stock checks are **package-scoped**, never `order.variants`. `pickup_stock_policy: 'any'` (ship-to-store transfers) is incompatible across vendor boundaries and is refused when the location is vendor-owned.-#### Store API: pickup point selection flow+### Owner is cart-or-order-```-1. GET /delivery_methods?fulfillment_type=pickup_point- → Returns delivery methods that use pickup point providers+Checkout — where fulfillments and delivery rates are created and selected — happens on the **Cart** under copy-on-completion semantics. `Fulfillment` and `DeliveryRate` follow the split-adjustments house pattern: nullable `cart_id` / `order_id` with an exactly-one validation, re-pointed at `Spree::Carts::Complete` (and again at vendor split). The exact shape is confirmed when `6.0-cart-order-split.md` is fleshed out (Open Question 1) — but `belongs_to :order` hard-required is known-wrong and must not be implemented.-2. GET /delivery_methods/:id/pickup_points?latitude=52.23&longitude=21.01- → Calls the method's PickupPointProvider.find_nearby- → Returns list of PickupPointOption objects+### `Fulfillment#delivery_amount` (commission base)-3. POST /checkout/select_delivery_method- { delivery_method_id: "dm_xxx", pickup_point_external_id: "inpost-PL-WAW-42" }- → Validates point via provider.find_by_external_id- → Stores pickup_point_data on Fulfillment-```+`delivery_amount = cost + discounts.sum(:amount)` — the selected rate's cost net of fulfillment-attached `Discount` rows (negative, from `6.0-split-adjustments.md`). This is the base `6.0-multi-vendor-marketplace.md` uses for `include_shipping` commission (`CommissionLine` fulfillment-scoped). `cost` remains the denormalized column it is today.-#### Store API: merchant pickup flow+### Status semantics — corrected against the real machine-```-1. GET /delivery_methods?fulfillment_type=pickup- → Returns delivery methods for merchant pickup+The rename is `shipped` → `fulfilled` (column `state` → `status` per the normalize plan), **preserving** today's guards and hooks, which the earlier draft dropped:-2. GET /delivery_methods/:id/pickup_locations- → Returns StockLocations with pickup_enabled that have stock for cart items+- `ready` keeps its `determine_state == 'ready'` guard (the #2040 fix — no ready fulfillments on unpaid orders).+- `pend` (`ready → pending`) stays — used when an order becomes unpayable again.+- `resume` keeps both conditional targets (`canceled → ready` when `determine_state` says so, else `canceled → pending`).+- `ready_for_pickup` is cancelable (`cancel` accepts it) and reachable from `ready` (not just `pending`).+- All `after_transition` hooks survive: restock/unstock, `StateChange` audit rows, events + webhooks (renamed per above).+- The three `update_columns` escape hatches that bypass the machine (`update_amounts`, `Shipment#update!`, `ShipmentHandler#update_order_shipment_state`) are rewritten to go through the machine or explicitly documented as freeze-safe.-3. POST /checkout/select_delivery_method- { delivery_method_id: "dm_xxx", stock_location_id: "sl_abc" }- → Sets fulfillment.stock_location_id-```+**Order rollup keeps `backorder`.** The earlier draft omitted it; `backorder` short-circuits the whole computation and feeds `Order#allow_cancel?` and the `not_shipped` scope. Domain of `Order#fulfillment_status`: `backorder`, `canceled`, `partial`, `pending`, `ready`, `fulfilled` (renamed from `shipped`), plus nil. `ready_for_pickup`/`picked_up` roll up as `ready`/`fulfilled`. Computation semantics are otherwise unchanged (including the `[canceled, X]` collapse rules).-#### Summary table+### Pickup location selection flows through order routing-| | **Merchant pickup** | **Third-party pickup point** |-|---|---|---|-| `fulfillment_type` | `pickup` | `pickup_point` |-| Location model | `StockLocation` (with `pickup_enabled`) | None — ephemeral from provider API |-| Provider interface | N/A (built-in) | `PickupPointProvider::Base` |-| Stored on Fulfillment | `stock_location_id` (existing FK) | `pickup_point_data` (JSON) |-| Stock validation | Yes (`pickup_stock_policy: 'local'` or `'any'`) | No (carrier handles routing) |-| Address for customer | `stock_location.address` | `pickup_point_data['address']` |+A customer's merchant-pickup choice writes `Order#preferred_stock_location_id`, so it flows through the existing `PreferredLocation` routing rule (`6.0-order-routing.md`) instead of bypassing routing with a direct `stock_location_id` write. `Fulfillment#stock_location` always comes from the routing strategy's `for_allocation` packages — never a bare `detect`.## Design Details-### DeliveryMethod model+### DeliveryMethod```rubyclass Spree::DeliveryMethod < Spree.base_classhas_prefix_id :dmacts_as_paranoid- include Spree::SingleStoreResource- include Spree::CalculatedAdjustments # pricing calculator (unchanged)+ include Spree::SingleStoreResource # store_id: migration owned by 6.0-delivery-rate-provider.md+ include Spree::CalculatedAdjustments # calculators STAY — decisions.md 2026-07-27include Spree::Metafieldsinclude Spree::Metadata- include Spree::DisplayOn++ belongs_to :store, class_name: 'Spree::Store'+ belongs_to :vendor, class_name: 'Spree::Vendor', optional: true # marketplace; nil = marketplace-wide+ belongs_to :tax_category, -> { with_deleted }, class_name: 'Spree::TaxCategory', optional: truehas_many :delivery_rates, class_name: 'Spree::DeliveryRate', inverse_of: :delivery_methodhas_many :fulfillments, through: :delivery_rates+ has_many :delivery_method_zones, class_name: 'Spree::DeliveryMethodZone', dependent: :destroy+ has_many :delivery_zones, through: :delivery_method_zones, class_name: 'Spree::DeliveryZone' # 6.0-delivery-zones.md+ has_many :delivery_method_stock_locations, class_name: 'Spree::DeliveryMethodStockLocation', dependent: :destroy+ has_many :pickup_locations, through: :delivery_method_stock_locations, source: :stock_location- has_many :delivery_method_zones, class_name: 'Spree::DeliveryMethodZone'- has_many :zones, through: :delivery_method_zones-- # Pickup: which locations can customers collect from?- has_many :delivery_method_stock_locations, class_name: 'Spree::DeliveryMethodStockLocation'- has_many :pickup_locations, through: :delivery_method_stock_locations,- source: :stock_location, class_name: 'Spree::StockLocation'-- belongs_to :tax_category, -> { with_deleted }, class_name: 'Spree::TaxCategory', optional: true-- validates :name, :display_on, :fulfillment_type, presence: true- validates :estimated_transit_business_days_min, numericality: { greater_than_or_equal_to: 1 }, allow_nil: true- validates :estimated_transit_business_days_max, numericality: { greater_than_or_equal_to: 1 }, allow_nil: true+ # storefront_visible boolean replaces Spree::DisplayOn (5.5-6.0-display-on-to-boolean.md,+ # converted in this plan's Phase 1 wave). Do NOT include Spree::DisplayOn.+ validates :name, :fulfillment_type, presence: true+ validates :estimated_transit_business_days_min, :estimated_transit_business_days_max,+ numericality: { greater_than_or_equal_to: 1 }, allow_nil: true- # Fulfillment type: open stringattribute :fulfillment_type, :string, default: 'shipping'attribute :fulfillment_provider, :string, default: 'Spree::FulfillmentProvider::Manual'- attribute :pickup_point_provider, :string # only for pickup_point type, e.g. 'SpreeInpost::PickupPointProvider'+ attribute :pickup_point_provider, :string # only for pickup_point type+ # rate_provider string column comes from 6.0-delivery-rate-provider.mdscope :by_fulfillment_type, ->(type) { where(fulfillment_type: type) }- scope :shipping, -> { by_fulfillment_type('shipping') }- scope :pickup, -> { by_fulfillment_type('pickup') }- scope :pickup_point, -> { by_fulfillment_type('pickup_point') }- scope :digital, -> { by_fulfillment_type('digital') }- scope :local_delivery, -> { by_fulfillment_type('local_delivery') }-- # Geographic eligibility (unchanged logic, new method name)- def include?(address)- return true if digital?- return true unless zones.any?-- zones.includes(:zone_members).any? { |zone| zone.include?(address) }- end- def digital?- fulfillment_type == 'digital'- end+ def digital? = fulfillment_type == 'digital'+ def pickup? = fulfillment_type == 'pickup'+ def pickup_point? = fulfillment_type == 'pickup_point'+ def requires_address? = !digital? && !pickup?- def pickup?- fulfillment_type == 'pickup'- end-- def pickup_point?- fulfillment_type == 'pickup_point'- end-- def requires_address?- !digital? && !pickup?- end-- def pickup_point_provider_instance- return nil unless pickup_point_provider.present?- pickup_point_provider.constantize.new(self)- end-- def provider- @provider ||= fulfillment_provider.constantize.new- end+ def provider = @provider ||= fulfillment_provider.constantize.newend```-### Fulfillment model (renamed from Shipment)+### Fulfillment```rubyclass Spree::Fulfillment < Spree.base_classhas_prefix_id :ful+ include Spree::Metadata- belongs_to :order, class_name: 'Spree::Order', touch: true- belongs_to :address, class_name: 'Spree::Address', optional: true # nil for pickup/digital+ publishes_lifecycle_events++ # Owner — exactly one (cart pre-completion, order after; re-pointed at Carts::Complete)+ belongs_to :order, class_name: 'Spree::Order', touch: true, optional: true+ belongs_to :cart, class_name: 'Spree::Cart', optional: true+ belongs_to :address, class_name: 'Spree::Address', optional: true # nil for pickup/digitalbelongs_to :stock_location, -> { with_deleted }, class_name: 'Spree::StockLocation'- # For pickup_point fulfillments — frozen snapshot of selected third-party point- attribute :pickup_point_data, :json+ attribute :pickup_point_data, :json # frozen snapshot of the selected third-party point+ attribute :fulfillment_type, :string # copied from selected delivery methodhas_many :fulfillment_items, class_name: 'Spree::FulfillmentItem', dependent: :delete_all- has_many :variants, through: :fulfillment_itemshas_many :delivery_rates, -> { order(:cost) }, class_name: 'Spree::DeliveryRate', dependent: :delete_all- has_many :delivery_methods, through: :delivery_rateshas_one :selected_delivery_rate, -> { where(selected: true) }, class_name: 'Spree::DeliveryRate'+ has_many :discounts, class_name: 'Spree::Discount', dependent: :destroy # split-adjustments+ has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy- # Copied from selected delivery method for easy querying- attribute :fulfillment_type, :string-- # State machine (uses status per normalize plan)- # Unified naming — no "shipped" (too narrow), use "fulfilled"+ # status column (normalize plan). Guards + hooks preserved from today's machine — see Key Decisions.state_machine :status, initial: :pending do- event :ready do- transition from: :pending, to: :ready- end- event :fulfill do- transition from: %i[ready canceled], to: :fulfilled- end- event :cancel do- transition to: :canceled, from: %i[pending ready]- end- event :resume do- transition from: :canceled, to: :pending- end- # Pickup-specific- event :mark_ready_for_pickup do- transition from: :pending, to: :ready_for_pickup- end- event :mark_picked_up do- transition from: :ready_for_pickup, to: :fulfilled- end- end-- after_transition to: :fulfilled, do: :set_fulfilled_at-- scope :by_fulfillment_type, ->(type) { where(fulfillment_type: type) }- scope :digital, -> { by_fulfillment_type('digital') }- scope :pickup, -> { by_fulfillment_type('pickup') }- scope :pickup_point, -> { by_fulfillment_type('pickup_point') }- scope :shipping, -> { by_fulfillment_type('shipping') }-- def digital?- fulfillment_type == 'digital'- end-- def pickup?- fulfillment_type == 'pickup'- end-- def pickup_point?- fulfillment_type == 'pickup_point'- end-- def delivery_method- selected_delivery_rate&.delivery_method- end-end-```--### FulfillmentItem model (renamed from InventoryUnit)--```ruby-class Spree::FulfillmentItem < Spree.base_class- has_prefix_id :fi-- belongs_to :variant, -> { with_deleted }, class_name: 'Spree::Variant'- belongs_to :order, class_name: 'Spree::Order'- belongs_to :fulfillment, class_name: 'Spree::Fulfillment', touch: true, optional: true- belongs_to :line_item, class_name: 'Spree::LineItem'-- has_many :return_items, class_name: 'Spree::ReturnItem', inverse_of: :fulfillment_item-- validates :quantity, numericality: { greater_than: 0 }-- state_machine :status, initial: :on_hand do- event :fill_backorder do- transition to: :on_hand, from: :backordered- end- event :ship do- transition to: :shipped, if: :allow_ship?- end- event :return do- transition to: :returned, from: :shipped- end- end-- scope :backordered, -> { where(status: 'backordered') }- scope :on_hand, -> { where(status: 'on_hand') }- scope :shipped, -> { where(status: 'shipped') }- scope :returned, -> { where(status: 'returned') }-end-```--### Order associations (after)--```ruby-class Spree::Order < Spree.base_class- has_many :fulfillments, class_name: 'Spree::Fulfillment', dependent: :destroy- has_many :fulfillment_items, class_name: 'Spree::FulfillmentItem', dependent: :destroy-- # Convenience- def digital_fulfillments- fulfillments.digital+ event(:ready) { transition from: :pending, to: :ready, if: ->(f) { f.determine_state(f.order) == 'ready' } }+ event(:pend) { transition from: :ready, to: :pending }+ event(:fulfill) { transition from: %i[ready ready_for_pickup canceled], to: :fulfilled }+ event(:cancel) { transition from: %i[pending ready ready_for_pickup], to: :canceled }+ event(:resume) { transition from: :canceled, to: :ready, if: ->(f) { f.determine_state(f.order) == 'ready' }+ transition from: :canceled, to: :pending }+ event(:mark_ready_for_pickup) { transition from: :ready, to: :ready_for_pickup }end+ # after_transition hooks: restock/unstock, StateChange audit, set_fulfilled_at,+ # fulfillment.* events + webhooks (dual-emit shipment.* for one release)- def requires_delivery?- line_items.any? { |li| li.product.product_type&.fulfillment_types&.include?('shipping') }- end-end-```+ def delivery_method = selected_delivery_rate&.delivery_method-### ProductType integration--```ruby-class Spree::ProductType < Spree.base_class- # From 6.0-product-types.md, plus:- attribute :fulfillment_types, default: ['shipping']-- validates :fulfillment_types, presence: true-- def digital?- fulfillment_types == ['digital']- end-- def requires_shipping?- fulfillment_types.include?('shipping')- end+ # Commission base for multi-vendor include_shipping (cost net of fulfillment discounts)+ def delivery_amount = cost + discounts.sum(:amount)end```-Product convenience (replaces `shipping_category` checks):-```ruby-class Spree::Product < Spree.base_class- # Remove: belongs_to :shipping_category- # ProductType handles delivery eligibility+`FulfillmentItem` is today's `InventoryUnit` renamed — the `quantity` column, its `greater_than: 0` validation, the split/extract machinery, and `has_many :return_items` (FK renamed `inventory_unit_id → fulfillment_item_id`) all carry over unchanged.- def digital?- product_type&.digital? || false- end+### Store API flows (pickup)- def fulfillment_types- product_type&.fulfillment_types || ['shipping']- end-end-```--### Checkout: delivery method selection--```ruby-# Available delivery methods for an order-class Spree::DeliveryMethods::Available- def call(order:)- # Collect fulfillment types from all items- required_types = order.line_items- .includes(product: :product_type)- .flat_map { |li| li.product.fulfillment_types }- .uniq-- methods = order.store.delivery_methods- .active- .where(fulfillment_type: required_types)- .select { |dm| dm.include?(order.ship_address) }-- # For pickup methods, filter by stock availability at pickup locations- methods.select do |dm|- if dm.pickup?- dm.pickup_locations.any? { |loc| loc.stocks_all?(order.variants) }- else- true- end- end- end-end-```+Merchant pickup: `GET /delivery_methods?fulfillment_type=pickup` → `GET /delivery_methods/:id/pickup_locations` (pickup-enabled StockLocations with package-scoped stock) → select with `stock_location_id`, which writes `Order#preferred_stock_location_id` (routing rule picks it up). Third-party points: `GET /delivery_methods/:id/pickup_points?latitude=&longitude=` (calls the method's `PickupPointProvider#find_nearby`; ephemeral value objects, never persisted) → select with `pickup_point_external_id` → validated via `find_by_external_id`, frozen into `fulfillment.pickup_point_data`. `PickupPointProvider::Base` + `PickupPointOption` struct as previously designed.## Migration Path-### Phase 1: Table renames+Phase 1 as previously drafted was one ~20-operation migration; per CLAUDE.md (data transformations never in migrations) and the verification findings it is now split. **The earlier draft's migration is void** — it re-added shipped columns, targeted the nonexistent `spree_product_types`, and migrated a `spree_store_shipping_methods` join table that has never existed (see decisions.md 2026-03-16 correction).-```ruby-class RenamShippingToDeliveryAndFulfillment < ActiveRecord::Migration[7.2]- def change- rename_table :spree_shipments, :spree_fulfillments- rename_table :spree_shipping_methods, :spree_delivery_methods- rename_table :spree_shipping_rates, :spree_delivery_rates- rename_table :spree_shipping_method_zones, :spree_delivery_method_zones- rename_table :spree_inventory_units, :spree_fulfillment_items-- # Rename FK columns- rename_column :spree_delivery_rates, :shipment_id, :fulfillment_id- rename_column :spree_delivery_rates, :shipping_method_id, :delivery_method_id- rename_column :spree_fulfillment_items, :shipment_id, :fulfillment_id- rename_column :spree_delivery_method_zones, :shipping_method_id, :delivery_method_id-- # Add fulfillment_type to delivery_methods- add_column :spree_delivery_methods, :fulfillment_type, :string, null: false, default: 'shipping'- add_column :spree_delivery_methods, :fulfillment_provider, :string, null: false, default: 'Spree::FulfillmentProvider::Manual'- add_index :spree_delivery_methods, :fulfillment_type-- # Pickup point provider on delivery methods (only for pickup_point type)- add_column :spree_delivery_methods, :pickup_point_provider, :string-- # Add fulfillment_type to fulfillments (copied from selected delivery method)- add_column :spree_fulfillments, :fulfillment_type, :string-- # Pickup point data on fulfillments (frozen snapshot of selected third-party point)- add_column :spree_fulfillments, :pickup_point_data, :json-- # Add fulfillment_types to product_types (from product-types plan)- add_column :spree_product_types, :fulfillment_types, :string, null: false, default: 'shipping'- # Stored as comma-separated or JSON array depending on DB-- # Pickup locations join table- create_table :spree_delivery_method_stock_locations do |t|- t.references :delivery_method, null: false- t.references :stock_location, null: false- t.timestamps- end- add_index :spree_delivery_method_stock_locations,- [:delivery_method_id, :stock_location_id],- unique: true, name: 'idx_dm_stock_locations_unique'-- # StockLocation: pickup capabilities- add_column :spree_stock_locations, :kind, :string, null: false, default: 'warehouse'- add_column :spree_stock_locations, :pickup_enabled, :boolean, null: false, default: false- add_column :spree_stock_locations, :pickup_stock_policy, :string, null: false, default: 'local'- add_column :spree_stock_locations, :pickup_ready_in_minutes, :integer- add_column :spree_stock_locations, :pickup_instructions, :text- add_index :spree_stock_locations, :pickup_enabled-- # Fulfillment: rename shipped_at → fulfilled_at- rename_column :spree_fulfillments, :shipped_at, :fulfilled_at-- # Order: rename shipment_state, shipment_total- rename_column :spree_orders, :shipment_state, :fulfillment_status- rename_column :spree_orders, :shipment_total, :delivery_total-- # SingleStoreResource: add store_id to delivery_methods (replacing join table)- add_column :spree_delivery_methods, :store_id, :bigint- add_index :spree_delivery_methods, :store_id- end-end-```+### Phase 0 — gates-### Phase 2: Data migration (rake task)+- `6.0-product-types.md` shipped (with the fulfillment_types addendum).+- `6.0-cart-order-split.md` fleshed out enough to confirm the owner shape (Open Question 1).+- `6.0-delivery-rate-provider.md` Phase 1 (`store_id`) — independent, can land before or after.+- `6.0-typed-stock-movements.md` confirmed born with `fulfillment_id` (dependency inverted from the earlier draft).-```ruby-rake spree:migrate_shipping_to_delivery-```+### Phase 1a — renames (schema only)++- Tables per the rename map; FK columns: `delivery_rates.{shipment_id→fulfillment_id, shipping_method_id→delivery_method_id}`, `fulfillment_items.shipment_id→fulfillment_id`, `delivery_method_zones.shipping_method_id→delivery_method_id`, **`return_items.inventory_unit_id→fulfillment_item_id`** (missed by the earlier draft), `orders.{shipment_state→fulfillment_status, shipment_total→delivery_total}` (removing the shipped aliases in the same change).+- `display_on` → `storefront_visible` boolean on `spree_delivery_methods`, jointly with `5.5-6.0-display-on-to-boolean.md` Phase 2 (answering its coordination request).+- Rename affected indexes (`spree_shipping_rates_join_index` — keep its uniqueness, it's the one-rate-per-method invariant).-1. Set fulfillment_type on delivery methods:- - Methods with DigitalDelivery calculator → fulfillment_type: 'digital',- fulfillment_provider: 'Spree::FulfillmentProvider::Digital'- - All others → fulfillment_type: 'shipping' (default)+### Phase 1b — new columns/tables (additive)-2. Copy fulfillment_type to existing fulfillments from their selected delivery method+- `delivery_methods`: `fulfillment_type` (null: false, default 'shipping', indexed), `fulfillment_provider` (null: false, default Manual), `pickup_point_provider`.+- `fulfillments`: `fulfillment_type`, `pickup_point_data` (JSON, jsonb-guarded), `cart_id` (per owner decision).+- `spree_delivery_method_stock_locations` join (unique on the pair).+- `products.excluded_delivery_method_ids` (JSON, jsonb-guarded).+- NOT here: StockLocation pickup columns (shipped), `store_id` (delivery-rate plan), `vendor_id` (marketplace wave).-3. Migrate ShippingCategory → ProductType.fulfillment_types:- - Products with "Digital" ShippingCategory → ensure ProductType with fulfillment_types: ['digital']- - Products with other ShippingCategories → fulfillment_types: ['shipping']- - Remove shipping_category_id from products+### Phase 2 — data rake tasks (`spree:migrate_shipping_to_delivery`)-4. Migrate store scoping:- - For each StoreShippingMethod join, set delivery_method.store_id = store_id- - Methods linked to multiple stores: duplicate the record (one per store)- - Drop spree_store_shipping_methods join table+1. **Polymorphic/stored strings** (missed entirely by the earlier draft): `spree_state_changes.stateful_type` + `name`, `spree_adjustments.adjustable_type`, `spree_stock_movements.originator_type` — `'Spree::Shipment'` → `'Spree::Fulfillment'`.+2. `fulfillment_type` backfill: methods with a `DigitalDelivery` calculator → `'digital'` + `FulfillmentProvider::Digital`; all others `'shipping'`. Copy to existing fulfillments from their selected method.+3. ShippingCategory → ProductType: digital categories → `Digital` ProductType (`fulfillment_types: ['digital']`) assigned to their products (the sanctioned one-time assignment per the product-types addendum); everything else rides the `['shipping']` default — no ProductType auto-created.+4. `display_on` value conversion (`both`/`front_end` → visible), per the display-on plan.-5. Drop spree_shipping_categories and spree_shipping_method_categories tables+Batched, idempotent, resumable — same guarantees as the split-adjustments migration.-### Phase 3: Model renames + deprecation aliases+### Phase 3 — model renames + behavior-- All model files renamed-- Deprecation aliases for one release:- ```ruby- Spree::Shipment = Spree::Fulfillment- Spree::ShippingMethod = Spree::DeliveryMethod- Spree::ShippingRate = Spree::DeliveryRate- Spree::InventoryUnit = Spree::FulfillmentItem- Spree::ShippingCategory = nil # removed, not aliased- ```-- Update all serializers, controllers, services, factories, specs+- Model/file renames + one-release deprecation aliases (`Spree::Shipment = Spree::Fulfillment` etc.). ShippingCategory gets **no alias** — referencing it raises `NameError` (the earlier draft's `= nil` would produce confusing `NoMethodError`s instead).+- `FulfilmentChanger` → `FulfillmentChanger`; `ShipmentHandler` removed in favor of providers.+- Fix raw-SQL/table-name literals that survive renames silently until query time: `reverse_chronological`, `with_free_shipping_promotion?`, `Package#shipping_categories` SQL, `determine_state` string literals.+- `Package#eligible_delivery_methods` + `Splitter::FulfillmentType`; digital discriminator moved to columns; `Product#digital?`/`#fulfillment_types` on ProductType; remove ShippingCategory validations/auto-assign from Product **in this phase** (the column drops in 6.1 — products must stay saveable in between).+- Order rollup rename with `backorder` preserved; CanCanCan grants; permitted attributes; seeds (incl. `Seeds::DigitalDelivery` and the hardcoded `'Digital'`/`'Default'` store category readers); factories (`product_factory` assigns a shipping category to every product — whole-suite impact).-### Phase 4: FulfillmentProvider interface+### Phase 4 — providers + events-- Create `Spree::FulfillmentProvider::Base`, `::Manual`, `::Digital`, `::Pickup`, `::PickupPoint`-- Create `Spree::PickupPointProvider::Base` and `Spree::PickupPointOption` struct-- Wire providers into Fulfillment state machine transitions-- Update `Spree.fulfillment_providers` registry+- `FulfillmentProvider::{Base,Manual,Digital,Pickup,PickupPoint}` wired into transitions; `PickupPointProvider::Base` + option struct; `Spree.fulfillment_providers` / `Spree.fulfillment_types` registries.+- Lifecycle events + `order.fulfilled`; `shipment.*` → `fulfillment.*` webhook migration with one-release dual-emit.+- DigitalLink creation moves from the checkout callback into `FulfillmentProvider::Digital` (idempotent, per-quantity).-### Phase 5: API + serializer updates+### Phase 5 — remaining surfaces-- All API endpoints renamed: `/shipments` → `/fulfillments`, `/shipping_methods` → `/delivery_methods`, `/shipping_rates` → `/delivery_rates`-- New fields: `fulfillment_type`, `pickup_locations`, `pickup_point_provider` on delivery methods-- New fields: `pickup_point_data` on fulfillments-- New endpoint: `GET /delivery_methods/:id/pickup_locations` (merchant pickup — returns StockLocations)-- New endpoint: `GET /delivery_methods/:id/pickup_points?latitude=X&longitude=Y` (third-party — calls PickupPointProvider)-- Run typelizer pipeline+- API: switch `FulfillmentSerializer#fulfillment_type` from computed to column-backed; pickup endpoints (`/pickup_locations`, `/pickup_points`); `storefront_visible` exposure; regenerate the type pipeline. (Most serializer/route work already shipped — see "Already shipped".)+- **Emails gem** (20 files — never mentioned in the earlier draft): `shipment_mailer`, subscriber, templates → fulfillment vocabulary.+- Dashboard (8 files still on `shipment` vocabulary) + CSV import/export contract (`shipping_category` is a documented public column — importers get a mapping + deprecation window) + user docs. The legacy Rails admin's 26 shipping files are **deleted with `spree/admin` at 6.0**, not renamed — admin fulfillment management lives in the dashboard via Admin API/SDK.-### Phase 6: Cleanup (6.1)+### Phase 6 — cleanup (6.1)-- Remove all deprecation aliases-- Drop `spree_shipping_categories` table-- Drop `shipping_category_id` from `spree_products`-- Remove ShippingCategory model entirely+- Drop deprecation aliases, `spree_shipping_categories` + `spree_shipping_method_categories`, `products.shipping_category_id`, dual-emitted `shipment.*` events, the dangling `admin_shipping_category_serializer` / v2 platform registrations.## Constraints on Current Work-- **Use "delivery method" and "fulfillment" in all new API v3 code.** Don't introduce new `shipping_method` or `shipment` references.-- **Don't add new features to ShippingCategory.** It's being dropped.-- **New calculator subclasses should not encode fulfillment type.** `DigitalDelivery` calculator pattern is being replaced by `fulfillment_type` column.-- **Don't add new InventoryUnit features.** They'll need to be migrated to FulfillmentItem.+- **Use "delivery method" / "fulfillment" in all new API v3 code.** No new `shipping_method` / `shipment` references. New tables referencing shipments are born with `fulfillment_id`.+- **Don't add features to ShippingCategory or InventoryUnit** — both are being replaced.+- **Don't include `Spree::DisplayOn` in new models** (display-on plan constraint); use `storefront_visible`.+- **Don't build on `ShipmentHandler`** — it's removed; fulfillment mechanics belong to providers.+- **Don't touch calculators here** — kept per decisions.md 2026-07-27; rate estimation belongs to the delivery-rate-provider plan. Zone→DeliveryZone belongs to `6.0-delivery-zones.md` (this plan only births the join table correctly).## Resolved Questions-1. **Unified fulfillment status naming.** Rename `shipment_state` → `fulfillment_status` on Order. Rename `shipped_at` → `fulfilled_at` on Fulfillment. Status values become fulfillment-neutral: `pending`, `ready`, `fulfilled` (replaces `shipped`), `canceled`. Pickup-specific: `ready_for_pickup`, `picked_up` (both map to `fulfilled` in the order-level rollup). Digital: auto-transitions to `fulfilled` on order completion. Mixed carts: all fulfillments must reach `fulfilled`/`picked_up` for order `fulfillment_status` to be `fulfilled`. Any partial = `partially_fulfilled`.--2. **SingleStoreResource for both DeliveryMethod and PaymentMethod.** Drop the multi-store join table pattern (`StorePaymentMethod`, `StoreShippingMethod`). Both become `belongs_to :store` with `SingleStoreResource` concern. In practice, different stores have different currencies, zones, and provider accounts — sharing the same config across stores is rare and creates more complexity than it saves. If a merchant wants the same config on two stores, they create two records. This also applies to PaymentMethod — add a separate decision to `decisions.md` for that change.--3. **`fulfillment_types` as JSON column on ProductType.** JSON works across PostgreSQL, MySQL, and SQLite. Stored as `["shipping", "pickup"]`. Rails handles serialization automatically with `serialize :fulfillment_types, coder: JSON` or `attribute :fulfillment_types, :json, default: ['shipping']`.+1. **Fulfillment status naming + rollup.** `shipped` → `fulfilled` (`fulfilled_at`); Order column → `fulfillment_status` with domain `backorder | canceled | partial | pending | ready | fulfilled` (+ nil) — `backorder` **stays** (earlier draft wrongly dropped it). `ready_for_pickup`/`picked_up` roll up as `ready`/`fulfilled`. Guards, `pend`, conditional `resume`, and all transition hooks are preserved.+2. **Store scoping is NOT this plan's.** `store_id` on DeliveryMethod is owned by `6.0-delivery-rate-provider.md` Phase 1 (greenfield + derived backfill — there was never a join table; see decisions.md 2026-03-16 correction). The earlier draft's PaymentMethod claim is obsolete — that shipped in 5.6 and was amended 2026-07-23 (`PaymentMethodRule`).+3. **`fulfillment_types` as JSON column on ProductType** (jsonb-guarded), owned by the `6.0-product-types.md` addendum.+4. **Lifecycle events**: `fulfillment.{ready,fulfilled,canceled,resumed}` + `order.fulfilled`; one-release dual-emit of legacy `shipment.*` webhooks.+5. **Digital auto-fulfillment** is new behavior implemented by `FulfillmentProvider::Digital` (fires `fulfill!` + DigitalLinks on completion); today nothing auto-fulfills.+6. **`delivery_amount`** = `cost + fulfillment discounts` — the multi-vendor `include_shipping` commission base.+7. **Pickup selection routes through `Order#preferred_stock_location_id`** and the `PreferredLocation` routing rule; stock checks are package-scoped; `pickup_stock_policy: 'any'` refused for vendor-owned locations.+8. **Fulfillment numbers**: existing `H` numbers stay; new records use `F`.## Open Questions-None at this time.+1. ~~Owner shape~~ — **resolved 2026-07-27** with the cart-order-split expansion: dual `cart_id`/`order_id` exactly-one is the unified pattern (LineItem included, no polymorphism); Phase 1b's `cart_id` is unblocked.+2. **Webhook dual-emit window** — is one release enough for `shipment.*` subscribers, or does Enterprise need a longer bridge?+3. **`ready_for_pickup` in the Store API** — expose as its own status or map onto `ready` with `fulfillment_type` disambiguating?## References-- Current shipping models: `spree/core/app/models/spree/shipping_method.rb`, `spree/core/app/models/spree/shipment.rb`, `spree/core/app/models/spree/shipping_category.rb`-- Related plan: `6.0-product-types.md` (ProductType gains fulfillment_types)-- Related plan: `6.0-typed-stock-movements.md` (stock movements reference Fulfillment instead of Shipment)-- Related plan: `6.0-normalize-state-to-status.md` (Fulfillment uses status column)+- Current models: `spree/core/app/models/spree/{shipment,shipping_method,shipping_category,inventory_unit}.rb`+- Real state machine + hooks: `shipment.rb:73-110`; rollup: `order_updater.rb:140-178`; number generator: `shipment.rb:7`+- Eligibility gate being replaced: `stock/package.rb:73-80` + `stock/estimator.rb:61-71`; parity spec: `spec/models/spree/order_routing/strategy/parity_spec.rb:426-452`+- Shipped API surface: `api/app/serializers/spree/api/v3/fulfillment_serializer.rb`, `api/lib/spree/api/dependencies.rb:111-128`+- Related plans: `6.0-product-types.md` (fulfillment_types addendum), `6.0-delivery-rate-provider.md`, `6.0-cart-order-split.md`, `6.0-order-routing.md`, `6.0-split-adjustments.md`, `6.0-typed-stock-movements.md`, `6.0-returns-exchanges-claims.md`, `6.0-multi-vendor-marketplace.md`, `5.5-6.0-display-on-to-boolean.md`, `decisions.md` (2026-07-27 calculators/Zone; 2026-03-16 corrected store-scoping)diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.mdindex 4144843adc..06fbc1fcb9 100644--- a/docs/plans/6.0-multi-vendor-marketplace.md+++ b/docs/plans/6.0-multi-vendor-marketplace.md@@ -2,9 +2,9 @@**Status:** Draft — design in progress, implementation not started**Target:** Spree 6.0 (the "Marketplace" release)-**Depends on:** `6.0-cart-order-split.md` (Cart/Order split + polymorphic `LineItem#owner` — **currently a stub; must be fleshed out before Phase 3 design freezes**), `6.0-split-adjustments.md` (TaxLine/Discount/Fee replace polymorphic Adjustment), `6.0-order-routing.md` (per-seller stock location), `6.0-fulfillment-and-delivery.md` (Fulfillment/DeliveryMethod vocabulary, per-vendor delivery selection), `6.0-admin-spa.md` (vendor panel composition), `6.0-admin-api.md` (Marketplace endpoints)+**Depends on:** `6.0-cart-order-split.md` (Cart/Order split + dual-FK `LineItem` owner (`cart_id`/`order_id`, `#owner` method) — **expanded 2026-07-27; Phase 3 design can now freeze against it**), `6.0-split-adjustments.md` (TaxLine/Discount/Fee replace polymorphic Adjustment), `6.0-order-routing.md` (per-seller stock location), `6.0-fulfillment-and-delivery.md` (Fulfillment/DeliveryMethod vocabulary, per-vendor delivery selection), `6.0-admin-spa.md` (vendor panel composition), `6.0-admin-api.md` (Marketplace endpoints)**Author:** Damian + Claude-**Last updated:** 2026-07-14+**Last updated:** 2026-07-27## Summary@@ -234,7 +234,7 @@ Legacy vendor scoping deliberately **not** carried over: `spree_payments.vendor_```textSpree::Cart (one, mixed)- └─ line_items (polymorphic owner = Cart) ← 6.0-cart-order-split.md+ └─ line_items (owner: cart_id set, order_id nil) ← 6.0-cart-order-split.mdcart.complete! → Spree::Carts::Complete → splits by vendor│@@ -255,7 +255,7 @@ The `OrderGroup` owns the customer + single payment + shared addresses; each chi- **Trigger & gate:** explicit call inside `Spree::Carts::Complete`, after payment authorization. The gate is **more than one fulfillment partition** — line items partition by the `vendor_id` snapshot, with `nil` (the operator's own first-party items) forming its own partition, and the split + `OrderGroup` happen **only when ≥ 2 partitions exist**. A mixed cart of vendor A + first-party items splits into two child orders (one with `vendor_id: nil`). A single-partition cart — all first-party, or all one vendor — completes as a **bare order exactly as today**: no group, no `PaymentSplit`; when that partition is a vendor's, the order still carries `vendor_id` and commission + ledger apply unchanged (Phase 2's compute-only mode is exactly this). Not a state-machine callback — and not the legacy shape either: the legacy module splits **~30 seconds after checkout** in a background job, leaving a window where the parent order exists un-split. 6.0 splits synchronously inside completion, so the checkout response already returns the finished `OrderGroup` and no `splitted`-pending state ever exists.- **Partition key:** `line_item.vendor_id`, denormalized from `variant.product.vendor` when the item is added (matching legacy behavior). Denormalization is load-bearing, not an optimization: the split, vendor ability scoping, and vendor order lists all key on it. Because product ownership *can* change while an item sits in a cart, `Carts::Complete` revalidates each line's `vendor_id` against the product's current vendor before partitioning and refreshes stale lines (re-running package/delivery validation) — the same cart-revalidation class as price or availability drift.- **Per-vendor delivery selection happens at checkout, before the split.** Today's Enterprise checkout already groups packages by vendor and lets the customer pick a delivery method per vendor package (user docs: multi-vendor-checkout); 6.0 keeps that UX. The cart's packages come from `6.0-order-routing.md` (`for_allocation` — vendor items allocate from that vendor's stock location), delivery options per package come from `6.0-delivery-rate-provider.md` filtered to the package's vendor: a `DeliveryMethod` with `vendor_id` is offered only on that vendor's packages; `vendor_id: nil` methods are marketplace-wide. The chosen method + rate travel with the package into that vendor's child order at split. **This is a hard requirement on the cart/order-split checkout design** (see Constraints).-- **Move semantics:** line items, their tax lines / discounts / fees (`6.0-split-adjustments.md`), fulfillment items, and fulfillments are assigned to the correct child `Order` (created from the cart partition). Stock location per child comes from the routing strategy, not a bare `detect`.+- **Move semantics:** line items, their tax lines / discounts / fees (`6.0-split-adjustments.md`), fulfillment items, and fulfillments are assigned to the correct child `Order` (created from the cart partition); the owner FK on every typed line is rewritten to the child order. **Order-level `Fee` rows** (both adjustable FKs nil — e.g. a payment surcharge; allowed per split-adjustments 2026-07-27) prorate across child orders by item totals using the same largest-remainder rule as order-level discount distribution, their tax lines following the fee. Stock location per child comes from the routing strategy, not a bare `detect`.- **Group status:** derived, not a column. The `OrderGroup` is "fully fulfilled" when all its orders are, "partially canceled" when some are, etc. — computed across `order_group.orders`, replacing the legacy `all_shipments`/`splitted?`/`cancel_parent_order` workarounds (which existed only because the legacy parent was itself an `Order`).### OrderGroup model@@ -576,7 +576,7 @@ This is **new OSS code**, not a rename of existing core — there is no in-placeEven before this lands, work touching adjacent areas should:- **Cart/Order split (`6.0-cart-order-split.md`)**: keep `cart.complete!`/`Spree::Carts::Complete` as the single completion entry point — the vendor split hooks in there. Do not reintroduce an order-level `after_transition` extension surface; multi-vendor must not depend on one. When fleshing out the checkout flow on Cart, design delivery selection **per package** (packages come from order routing) — the multi-vendor checkout needs one delivery choice per vendor package before completion, and payments must be attachable to an `OrderGroup`, not only to an `Order`.-- **Split adjustments (`6.0-split-adjustments.md`)**: keep `TaxLine`/`Discount`/`Fee` strictly line-item- or fulfillment-attached (already the resolved design — order-level discounts distribute to line items) so every adjustment re-homes unambiguously to one child order during the split. Do **not** add a commission/marketplace `Fee` kind — commission is `Spree::CommissionLine`, off-order (Decision 2); `Fee` stays buyer-facing.+- **Split adjustments (`6.0-split-adjustments.md`)**: `TaxLine` and `Discount` stay strictly line-item- or fulfillment-attached (order-level discounts distribute to line items at application time), so they re-home unambiguously to one child order during the split. `Fee` may additionally be **order-level** (payment surcharge, COD — resolved 2026-07-27); at split, order-level fees prorate across child orders by item totals (largest-remainder), tax lines following the fee. Do **not** add a commission/marketplace `Fee` kind — commission is `Spree::CommissionLine`, off-order (Decision 2); `Fee` stays buyer-facing.- **Inventory operations (`6.0-inventory-operations.md`)**: the procurement model is `Spree::Supplier` — never reuse `Spree::Vendor` (reserved for marketplace sellers) for purchase-order sources. See `decisions.md` 2026-07-14.- **External-store sync stays Enterprise**: do **not** add external store/resource models, associations, or callbacks to core (no `external_store` on Vendor, no external product/order/category tables, no platform sync hooks). The Shopify/WooCommerce connection layer is an Enterprise concern that decorates core's Vendor from outside; core only needs to stay decorable (events + the onboarding task registry are the seams it plugs into).- **Fulfillment & delivery (`6.0-fulfillment-and-delivery.md`)**: the ledger trigger is defined against Fulfillment ("all fulfillments fulfilled"), and `DeliveryMethod` gets an optional `vendor_id` — keep the fulfillment-status surface queryable per order (child orders fulfill independently) and don't assume one order per checkout in fulfillment UIs.diff --git a/docs/plans/6.0-product-types.md b/docs/plans/6.0-product-types.mdindex 862f30dbb7..cb33036e34 100644--- a/docs/plans/6.0-product-types.md+++ b/docs/plans/6.0-product-types.md@@ -2,9 +2,9 @@**Status:** Draft**Target:** Spree 6.0-**Depends on:** Metafields system (shipped in 5.4), Taxon → Category rename (6.0)+**Depends on:** Metafields system (shipped in 5.4), Taxon → Category rename (6.0). Consumed by: `6.0-fulfillment-and-delivery.md` (fulfillment_types replaces ShippingCategory — that plan cannot ship before this one)**Author:** Damian + Claude-**Last updated:** 2026-03-26+**Last updated:** 2026-07-27## Summary@@ -34,7 +34,8 @@ This closes Spree's biggest functional gap in catalog modeling, while building o- **Prefix ID: `pt_`.** Replaces `proto_`.- **No shared value pools in this phase.** Metafield values remain per-resource strings (no shared AttributeValue rows). Faceted filtering via shared pools is a future enhancement tracked in Open Questions.- **ProductType is optional.** Products without a type work exactly as today. Type enforcement is additive, not breaking.-- **ProductType is immutable on product after creation.** Changing a product's type would invalidate its metafield values. Block type changes once metafields are assigned.+- **ProductType is immutable on product after creation.** Changing a product's type would invalidate its metafield values. Block type changes once metafields are assigned. One-time exception: the 6.0 data migrations may assign an initial type to products that have none (see fulfillment-types addendum below) — immutability applies from then on.+- **ProductType carries `fulfillment_types`** (addendum 2026-07-27, required by `6.0-fulfillment-and-delivery.md`) — see "Fulfillment types" under Design Details. This makes ProductType the replacement for `ShippingCategory`, so `6.0-fulfillment-and-delivery.md` now hard-depends on this plan shipping first.## Design Details@@ -257,6 +258,28 @@ When editing a ProductType:2. Removing an option type removes it from products (blocked if variants use values from it)3. UI shows affected product count before confirming destructive changes+### Fulfillment types (addendum 2026-07-27)++`ShippingCategory` is dropped in 6.0 (`6.0-fulfillment-and-delivery.md`); its only real job — "which delivery methods may serve this product?" — moves here:++```ruby+class Spree::ProductType < Spree.base_class+ # JSON array (jsonb-guarded per CLAUDE.md), e.g. ["shipping"], ["digital"],+ # ["shipping", "pickup", "local_delivery"]+ attribute :fulfillment_types, default: ['shipping']++ validates :fulfillment_types, presence: true++ def digital? = fulfillment_types == ['digital']+ def requires_shipping? = fulfillment_types.include?('shipping')+end+```++- **Products without a ProductType default to `['shipping']`** — this is the reconciliation between optional ProductType and today's effectively-mandatory ShippingCategory (every product presence-validates one). Most of the catalog rides the default and needs no type.+- The fulfillment plan's data migration creates/assigns types **only where the category carried signal** — i.e. products in a digital shipping category get a `Digital` ProductType (`fulfillment_types: ['digital']`). This is the sanctioned one-time initial assignment noted in Key Decisions; it does not violate immutability, which governs *changes* after a type is set.+- `Product#digital?` / `#fulfillment_types` re-implement on top of this (they currently derive from ShippingCategory → calculator class, a four-hop chain).+- Delivery-method eligibility semantics (matching `fulfillment_types` against `DeliveryMethod#fulfillment_type`, per-product exclusions) are owned by `6.0-fulfillment-and-delivery.md`, not this plan.+## Migration Path### Phase 1: Rename (non-breaking)diff --git a/docs/plans/6.0-split-adjustments.md b/docs/plans/6.0-split-adjustments.mdindex 27cb6cb8b1..4cb7fd3804 100644--- a/docs/plans/6.0-split-adjustments.md+++ b/docs/plans/6.0-split-adjustments.md@@ -2,75 +2,102 @@**Status:** Draft**Target:** Spree 6.0-**Depends on:** None (standalone)+**Depends on:** `6.0-cart-order-split.md` (owner semantics — typed lines are written during the cart phase and copied on completion), `6.0-fulfillment-and-delivery.md` Phase 1 (tables are born with `fulfillment_id`, never migrated from `shipment_id`). Consumed by: `6.0-tax-provider.md` (providers write TaxLine), `6.0-multi-vendor-marketplace.md` (typed lines re-home at order split), `6.0-returns-exchanges-claims.md`, `6.0-normalize-state-to-status.md`.**Author:** Damian + Claude-**Last updated:** 2026-03-16+**Last updated:** 2026-07-27## Summary-Replace the polymorphic `Spree::Adjustment` model with three typed models: `TaxLine`, `Discount`, and `Fee`. Each has concrete foreign keys to its source (no polymorphic `source_type`/`source_id`), enabling eager loading and eliminating the N+1 queries that make the current adjustment system slow.+Replace the polymorphic `Spree::Adjustment` model with three typed models: `TaxLine`, `Discount`, and `Fee`. Each has concrete foreign keys to its source and its adjustable, enabling DB-level integrity, SQL joins, indexed queries, and structural (not opt-in) eager loading.-The `Spree.adjusters` extensibility pattern is preserved — developers register custom adjusters that write to the appropriate typed table.+The primary rationale is **data modeling**: today one table represents six different things — additional tax, included tax, competing promotions, shipping discounts, manual admin adjustments (which can be positive surcharges), and custom extension source types — and ~a dozen `Order` methods dispatch on `source_type`/`eligible` string matching to tell them apart. Every major platform (the hosted market leader, OSS platform A, OSS platform B, OSS platform C) models these as distinct typed structures; none uses a generic polymorphic adjustments table. OSS platform A is near-literal precedent for this design (`order_line_item_tax_line`, `order_line_item_adjustment` tables with concrete FKs).++The `Spree.adjusters` extensibility pattern is preserved for discounts and fees. Tax writing moves to the `TaxProvider` seam (see `6.0-tax-provider.md`) — this plan provides the table providers write to.## Problem-### 1. Polymorphic source prevents eager loading+### 1. One table does too many jobs-`Adjustment` has `belongs_to :source, polymorphic: true` where source can be `TaxRate`, `PromotionAction`, or `ReturnAuthorization`. Rails cannot `includes(:source)` on a polymorphic association — every `adjustment.source` triggers a lazy load. With 12-15 adjustments per order, each recalculation does 12-15 individual source queries.+The same `spree_adjustments` row represents:+- Tax (from TaxRate — included in price or additional)+- Promotions (from PromotionAction, competes with other promos)+- Shipping discounts (from FreeShipping PromotionAction — deliberately persisted even at zero amount)+- Manual admin adjustments (source-less, order-level, may be **positive** surcharges)+- Return credits (legacy `ReturnAuthorization` rows — no longer written)+- Unknown custom source types from extensions (special-cased by the admin order summary)-### 2. Polymorphic adjustable adds complexity+Scopes like `tax`, `promotion`, `shipping`, `price` filter by string-matching `source_type` or `adjustable_type`, and ~12 `Order` reader methods (`order_level_promo_total`, `shipping_discount`, `valid_promotion_ids`, `cart_promo_total`, `has_free_shipping?`, …) dispatch on class-name strings plus the `eligible` flag. The record's meaning is not knowable from its shape.-`belongs_to :adjustable, polymorphic: true` (LineItem or Shipment) means you can't do a simple JOIN from line items to their adjustments without going through `all_adjustments` on the order.+### 2. Polymorphic FKs prevent structural guarantees-### 3. One table does too many jobs+`belongs_to :source, polymorphic: true` and `belongs_to :adjustable, polymorphic: true` mean: no DB-level referential integrity, no SQL JOINs from line items to their adjustments, and eager loading that works only where a call site remembers to preload (Rails *can* preload polymorphic associations, and three call sites do — but the recalculation path in `Adjuster::Promotion` and `Adjuster::Tax` doesn't, so every recalc lazy-loads `source` and `source.promotion` per adjustment row). With typed tables the fast path is the default path, not a per-call-site opt-in.-The same `spree_adjustments` row represents:-- Tax (from TaxRate, may be included or additional)-- Promotions (from PromotionAction, competes with other promos)-- Shipping discounts (from FreeShipping PromotionAction)-- Manual adjustments (no source)-- Return credits (from ReturnAuthorization)+### 3. Eligible-flag bookkeeping-Scopes like `tax`, `promotion`, `shipping`, `price` all filter by string-matching `source_type` or `adjustable_type` — unindexed class name comparisons.+Promotion competition is resolved by writing **all** candidate adjustments, then flipping losers with `update_all(eligible: false)` and re-deriving eligibility on every recalculation (`Adjuster::Promotion`, `Adjustment#update!`). A dozen downstream readers must remember to filter `.eligible`. No competitor persists losing candidates — the hosted leader's engine discards unchosen candidates, OSS platform B's DB unique constraint makes them unstorable, OSS platform A and OSS platform C recompute-and-replace.-### 4. Recalculation is N+1 heavy+### 4. The state machine is a misplaced, leaky freeze-`AdjustmentsUpdater` iterates each adjustment and calls `adjustment.update!` → `source.compute_amount(target)` → loads the source → for promotions, loads `source.promotion` → checks `promotion.eligible?(target)`. Each step is a lazy load.+The open/closed state machine is today the **only** mechanism protecting money on completed orders: `Adjustment#update!` early-returns when `closed?`, while `OrderUpdater` recalculates unconditionally — order completion does *not* lock recalculation. And the freeze leaks: `TaxRate.adjust` destroy-and-recreates tax adjustments even on completed orders when a line item changes. Per-row state is the wrong altitude — every competitor enforces immutability at the **order** level (OSS platform B gates recalculation by order status; the hosted market leader keeps `original*`/`current*` snapshots; OSS platform A versions rows). The replacement is an order-level recalculation freeze, which must exist **before** the state machine is removed (see Resolved Question 7).-### 5. State machine is unnecessary+### 5. Spree is the industry outlier-The open/closed state machine exists to freeze adjustments on completed orders. But order completion already locks the order — per-adjustment state is redundant bookkeeping.+Every developer or integration arriving from the hosted market leader, OSS platform A, OSS platform B, or OSS platform C must first learn `source_type`/`adjustable_type`/`eligible`/`state` semantics that exist nowhere else. The v3 API currently exposes a mixed `adjustments` array that forces clients to re-implement the same string dispatch.-### Current blast radius+### Current blast radius (verified 2026-07-27)| What | Where ||------|-------|-| `spree_adjustments` table | 1 table, ~15 columns |-| `Spree::Adjustment` model | 130 lines |-| `AdjustmentsUpdater` | Orchestrates all recalculation |-| 3 Adjusters | Tax, Promotion, Base |-| `PromotionAccumulator` | Best-promo selection |-| `AdjustmentSource` concern | Included by TaxRate, 3 PromotionActions |-| Order, LineItem, Shipment | All have `has_many :adjustments` + 6 denormalized total columns each |+| `spree_adjustments` table | 13 columns |+| `Spree::Adjustment` model | 131 lines, 20 scopes, state machine |+| `Adjustable::AdjustmentsUpdater` | Two-pass orchestration (non-tax → persist taxable totals → tax) |+| Adjusters | `Adjuster::Tax`, `Adjuster::Promotion` registered; `Adjuster::Base` abstract. (`PromotionAccumulator` is dead code — zero callers; delete freely.) |+| `AdjustmentSource` concern | TaxRate + 3 PromotionActions, incl. deleted-source handling |+| Order, LineItem, Shipment | `has_many :adjustments` + **6** denormalized columns each: `adjustment_total`, `promo_total`, `included_tax_total`, `additional_tax_total`, `taxable_adjustment_total`, `non_taxable_adjustment_total`; plus `pre_tax_amount` on line items/shipments |+| Core consumers | ~166 references across ~30 files: promotion handlers (usage limits count eligible adjustments), coupon handlers, `OrderMerger`, `Cart::Empty`, refund calculators (`DefaultRefundAmount` reads order-level eligible rows), CanCanCan permission sets |+| Admin API v3 | Read-only `/admin/orders/:id/adjustments` endpoints, `Admin::AdjustmentSerializer`, `?expand=adjustments` on order/line_item/fulfillment serializers |+| SDK / SPA | admin-sdk `orders.adjustments` resource, generated TS/Zod types, dashboard order page |+| Legacy admin | Full CRUD + open/close toggle on manual adjustments, order summary renders unknown source types |+| Emails | `_purchased_items_table` partials iterate `.eligible` adjustments with `source_type` checks |+| Tests / docs | ~41 core + 14 api + 10 admin spec files; `adjustments.mdx`, `custom-promotion.mdx` |++## Industry Alignment++Findings from the 2026-07-27 competitor review (the hosted market leader Admin API, OSS platform A source, OSS platform B source, OSS platform C source):++| Concern | Spree 6.0 | The hosted market leader | OSS platform A | OSS platform B | OSS platform C |+|---|---|---|---|---|---|+| Tax | Typed rows: amount + rate + nullable `tax_rate_id` + `provider_id` | Embedded snapshots (title, rate), no FK | Typed tables; rate + nullable `tax_rate_id` + `provider_id` + `data` | No tax rows; net/gross columns | Embedded JSON (rate only) |+| Discounts | Typed rows, promo FKs + code snapshot | Application (intent) + per-line allocation | Typed adjustment rows, `code` + `promotion_id` | Typed rows, SET_NULL FKs + snapshots | Embedded JSON, string source |+| Fees | First-class taxable `Fee`, line/fulfillment/order scoped | None merchant-facing (Duty/AdditionalFee are platform-only, **taxed**) | None (adjustments are `CHECK >= 0` discounts) | None | `Surcharge` table, **taxed**, order-level only |+| Order-level discounts | Prorated to lines | Prorated to lines (+ intent record) | Prorated to lines | One order row + prorated totals | Prorated to lines (largest-remainder) |+| Losers persisted | No | No | No (stacks all valid) | No (DB constraint) | No (replace on recompute) |+| Per-row state | None | None | None | None | None |++Validated by all four: typed structures over polymorphic, winner-only persistence, no per-row state machine, order-level discounts prorated to lines. Deliberate Spree divergences: we persist tax **amounts** in queryable rows (OSS platform A/OSS platform C store rate only and derive — SQL-aggregable totals are the point of this plan), and `Fee` is line-item-granular (only OSS platform C has a fee primitive at all, and it's order-level only) — a genuine differentiator; the hosted market leader staff confirm apps on their platform cannot add charges at all.## Key Decisions (do not deviate without discussion)- **Three typed models** replace one polymorphic model:- - `Spree::TaxLine` — tax charges, concrete FK to `tax_rate_id`- - `Spree::Discount` — promotions and manual discounts, concrete FK to `promotion_action_id` (nullable for manual)- - `Spree::Fee` — extensible charges (custom fees, surcharges, future use), no polymorphic source+ - `Spree::TaxLine` — tax charges. **Nullable** `tax_rate_id` (set by the Internal tax provider, nil for external providers), plus self-describing snapshot columns: `rate` (decimal), `label`, `provider_id` (string), `data` (JSON, provider payloads — jurisdiction breakdowns, facilitator-liability info). Rows stay meaningful after a TaxRate is deleted or an external provider computed them.+ - `Spree::Discount` — promotion and manual discounts. Nullable `promotion_action_id`/`promotion_id` FKs (`dependent: :nullify` from the promotion side) plus provenance snapshots: `code`, `value` + `value_type` (the input, e.g. 10%), `kind`. Amount is **enforced** `<= 0` (validation + DB CHECK), and adjusters clamp so combined discounts never push an adjustable's net below zero.+ - `Spree::Fee` — extensible charges (surcharge, handling, gift wrap, COD, payment fees). `kind` required, amount `>= 0`. **Fees are taxable**: `TaxLine` accepts `fee_id` as an adjustable (EU VAT applies to surcharges — both competitor fee primitives, the hosted leader's Duty/AdditionalFee and OSS platform C's Surcharge, carry tax lines).++- **Concrete adjustable FKs, fulfillment vocabulary.** TaxLine and Discount belong to exactly one of `line_item` / `fulfillment` (TaxLine additionally: `fee`). Tables are born with `fulfillment_id` per `6.0-fulfillment-and-delivery.md` — no new `shipment` references. `Fee` may additionally be **order-level** (both FKs nil) — the canonical fee use cases (payment surcharge, COD, small-order fee) belong to no line; at vendor split, order-level fees prorate across child orders by item totals (coordinate with `6.0-multi-vendor-marketplace.md`, which currently assumes strict line/fulfillment attachment).-- **Concrete FKs to line_item and shipment** (not polymorphic adjustable). TaxLines and Discounts belong directly to either a `line_item` or a `shipment` via separate nullable FKs. This enables simple `includes(:tax_lines)` on LineItem.+- **Owner is cart-or-order, not order-only.** Discounts and tax estimates are computed during the **cart** phase (`6.0-cart-order-split.md`). Typed lines carry nullable `cart_id` / `order_id` with an exactly-one validation, mirroring the adjustable XOR. `Spree::Carts::Complete` copies typed lines to the order alongside line items (copy-on-completion), re-pointing `line_item_id` to the new order line items. New code derives the owner via the adjustable (`line_item.owner`), never assumes `order`.-- **All three models belong to `order`** directly — for order-level queries (`order.tax_lines`, `order.discounts`).+- **Tax writing belongs to the TaxProvider, not TaxRate.** `TaxRate.adjust` is removed by `6.0-tax-provider.md`; this plan must not reimplement it. `Spree.tax_provider.estimate(owner, items)` writes TaxLines with **replace-all set semantics** (delete the target's stale lines, write fresh ones) — this is also what prevents stale tax after an address change. `TaxRate` becomes pure configuration read by the Internal provider. `Spree.adjusters` covers **discounts and fees only**.-- **Remove the state machine.** No open/closed states. Adjustments on completed orders are immutable by convention (enforced at the service layer, not per-row state).+- **Remove the state machine — after the order-level freeze exists.** No open/closed states, no `status` column on the new tables. Precondition (hard, sequenced before Phase 3): `OrderUpdater` refuses adjustment recalculation on completed orders; post-placement changes go through explicit admin actions that write typed rows directly. The admin open/close toggle is dropped with that CRUD replacement. See Resolved Question 7.-- **Remove `eligible` flag.** The "best promo wins" logic writes only the winning discount. Losers are not stored as ineligible rows — they simply don't exist. Simpler data, fewer writes.+- **Remove the `eligible` flag; 6.0 ships winner-only, stacking-ready — stacking itself lands in 6.1** (decision 2026-07-27, retargeted same day: stacking is purely additive, so it doesn't need the 6.0 breaking window and 6.0 is already loaded). What 6.0 guarantees so 6.1 is cheap: the schema permits multiple Discount rows per adjustable (already true), clamping + prorate-over-the-*remaining*-discounted-base ship with order-level distribution (Resolved Question 1), and the winner-only policy is **isolated in one adjuster seam** (candidate computation returns all candidates; selection is a single method). 6.1 adds hosted-leader-style `Promotion#combines_with` flags (per class: item/order/shipping — combining candidates all persist, non-combining compete winner-takes-all, default off) plus dashboard UI and API fields — no migration, no adjuster rewrite. Only applied discounts are persisted; losers are recomputed from candidates on every recalculation, so "reinstatement" needs no stored rows and no `eligible` flag. Promotion usage-limit accounting (`Promotion#credits_count`, per-user checks) is re-specified to count Discount rows / distinct orders.-- **Keep `Spree.adjusters` registry** for extensibility. Custom adjusters write to `Fee` (or `Discount` for custom discount types). Registration pattern unchanged.+- **Keep `Spree.adjusters`** with a new base class `Spree::Adjusters::Base` (the old `Spree::Adjustable::Adjuster::*` namespace is removed). Custom adjusters write `Fee` or `Discount` rows.-- **Denormalized totals on LineItem/Shipment/Order stay.** The `included_tax_total`, `additional_tax_total`, `promo_total`, `adjustment_total` columns remain — they're the performance optimization. But they're now computed from typed tables, not from polymorphic filter scopes.+- **Denormalized totals stay** — all of them: `adjustment_total`, `promo_total`, `included_tax_total`, `additional_tax_total`, `taxable_adjustment_total`, `non_taxable_adjustment_total` on Order/LineItem/Fulfillment, `pre_tax_amount` on LineItem/Fulfillment, plus new `fee_total` on Order. Recomputed from typed tables. The **two-pass ordering is preserved**: discount/fee adjusters run first and persist the discounted taxable base, then the tax provider estimates on discounted amounts (`pre_tax_amount` is maintained during estimate).++- **All models include `Spree::Metadata`** per house convention.## Design Details@@ -78,106 +105,105 @@ The open/closed state machine exists to freeze adjustments on completed orders.```rubyclass Spree::TaxLine < Spree.base_class+ include Spree::Metadata+has_prefix_id :tl- belongs_to :order, class_name: 'Spree::Order', inverse_of: :tax_lines- belongs_to :tax_rate, class_name: 'Spree::TaxRate'+ # Owner — exactly one (copied cart → order at completion)+ belongs_to :order, class_name: 'Spree::Order', optional: true, inverse_of: :tax_lines+ belongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :tax_lines++ # Source — nil for externally-computed tax; snapshots below keep the row self-describing+ belongs_to :tax_rate, class_name: 'Spree::TaxRate', optional: true- # Concrete adjustable — one of these is set, not both+ # Adjustable — exactly onebelongs_to :line_item, class_name: 'Spree::LineItem', optional: true- belongs_to :shipment, class_name: 'Spree::Shipment', optional: true+ belongs_to :fulfillment, class_name: 'Spree::Fulfillment', optional: true+ belongs_to :fee, class_name: 'Spree::Fee', optional: truevalidates :amount, numericality: true+ validates :rate, numericality: { greater_than_or_equal_to: 0 }validates :label, presence: true+ validate :exactly_one_ownervalidate :exactly_one_adjustable- # Replaces adjustment.included? — tax can be included in price or additional+ # Tax included in price vs additional. Per-row (mixed regimes on one order),+ # richer than the hosted leader's order-level taxes_included.attribute :included, :boolean, default: falsescope :included_in_price, -> { where(included: true) }scope :additional, -> { where(included: false) }scope :for_line_items, -> { where.not(line_item_id: nil) }- scope :for_shipments, -> { where.not(shipment_id: nil) }-- def adjustable- line_item || shipment- end-- private-- def exactly_one_adjustable- if line_item_id.blank? && shipment_id.blank?- errors.add(:base, 'must belong to a line item or shipment')- elsif line_item_id.present? && shipment_id.present?- errors.add(:base, 'cannot belong to both a line item and shipment')- end- end+ scope :for_fulfillments, -> { where.not(fulfillment_id: nil) }+ scope :for_fees, -> { where.not(fee_id: nil) }end```+Columns beyond the FKs: `amount`, `rate` (decimal snapshot — enables rate-grouped tax reports and receipts even after TaxRate deletion), `label`, `included`, `provider_id` (string, e.g. `'internal'`, `'avalara'`), `data` (JSON — provider payloads such as jurisdiction breakdowns; jsonb where supported).++**Write contract:** providers use replace-all set semantics per estimate — delete the target items' existing TaxLines, insert fresh ones. No unique-index-based upsert identity (it only works for Internal-provider lines); plain indexes on the FKs.+### Discount```rubyclass Spree::Discount < Spree.base_class+ include Spree::Metadata+has_prefix_id :disc- belongs_to :order, class_name: 'Spree::Order', inverse_of: :discounts+ belongs_to :order, class_name: 'Spree::Order', optional: true, inverse_of: :discounts+ belongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :discounts++ # Source — nullified on promotion deletion; code/value snapshots keep history meaningfulbelongs_to :promotion_action, class_name: 'Spree::PromotionAction', optional: truebelongs_to :promotion, class_name: 'Spree::Promotion', optional: true- # Concrete adjustable — always one of these (order-level discounts distributed to line items)+ # Adjustable — exactly one (order-level discounts are distributed to line items)belongs_to :line_item, class_name: 'Spree::LineItem', optional: true- belongs_to :shipment, class_name: 'Spree::Shipment', optional: true+ belongs_to :fulfillment, class_name: 'Spree::Fulfillment', optional: true- validates :amount, numericality: true # always negative (credit)+ validates :amount, numericality: { less_than_or_equal_to: 0 } # + DB CHECK constraintvalidates :label, presence: true+ validate :exactly_one_ownervalidate :exactly_one_adjustablescope :for_line_items, -> { where.not(line_item_id: nil) }- scope :for_shipments, -> { where.not(shipment_id: nil) }- scope :automatic, -> { joins(:promotion).where(spree_promotions: { kind: 'automatic' }) }+ scope :for_fulfillments, -> { where.not(fulfillment_id: nil) }scope :manual, -> { where(promotion_action_id: nil) }-- def adjustable- line_item || shipment- end-- def promotion?- promotion_action_id.present?- end-- def manual?- promotion_action_id.nil?- endend```-### Fee (extensible)+Columns beyond the FKs: `amount` (≤ 0), `label`, `kind` (`'promotion'`, `'manual'`, `'loyalty'`, …), and provenance snapshots: `code` (the coupon code — "how much did SUMMER10 move" becomes one indexed query), `value` + `value_type` (`'percent'` / `'flat'` — the input, for "10% off" display; OSS platform B precedent). Orders outlive promotions: FKs are `dependent: :nullify` from the promotion side, snapshots keep the rows meaningful.++**FreeShipping** writes a `Discount` on the fulfillment (`amount = -cost`) and persists the row **even at zero amount** — `Order#has_free_shipping?` tests row existence; the zero-skip pattern used elsewhere does not apply to this action.++### Fee (extensible, taxable)```rubyclass Spree::Fee < Spree.base_class+ include Spree::Metadata+has_prefix_id :fee- belongs_to :order, class_name: 'Spree::Order', inverse_of: :fees+ belongs_to :order, class_name: 'Spree::Order', optional: true, inverse_of: :fees+ belongs_to :cart, class_name: 'Spree::Cart', optional: true, inverse_of: :fees- # Concrete adjustable+ # Adjustable — optional: both nil ⇒ order-level fee (payment surcharge, COD, small-order fee)belongs_to :line_item, class_name: 'Spree::LineItem', optional: true- belongs_to :shipment, class_name: 'Spree::Shipment', optional: true+ belongs_to :fulfillment, class_name: 'Spree::Fulfillment', optional: true++ has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroyvalidates :amount, numericality: { greater_than_or_equal_to: 0 }validates :label, presence: true- validates :kind, presence: true # e.g., 'surcharge', 'handling', 'gift_wrap'-- scope :for_line_items, -> { where.not(line_item_id: nil) }- scope :for_shipments, -> { where.not(shipment_id: nil) }-- def adjustable- line_item || shipment- end+ validates :kind, presence: true # 'surcharge', 'handling', 'gift_wrap', 'payment', ...+ validate :exactly_one_ownerend```-### Order associations+Fees participate in tax: the tax provider estimates over line items, fulfillments, **and fees**, writing `TaxLine(fee_id: …)` rows. Ad-hoc credits are *not* negative fees — they are manual `Discount`s (unlike OSS platform C's Surcharge, which overloads both directions).++### Associations```rubyclass Spree::Order < Spree.base_class@@ -185,303 +211,202 @@ class Spree::Order < Spree.base_classhas_many :discounts, class_name: 'Spree::Discount', dependent: :destroyhas_many :fees, class_name: 'Spree::Fee', dependent: :destroy- # Convenience through-associationshas_many :line_item_tax_lines, through: :line_items, source: :tax_lineshas_many :line_item_discounts, through: :line_items, source: :discounts- has_many :shipment_tax_lines, through: :shipments, source: :tax_lines- has_many :shipment_discounts, through: :shipments, source: :discounts+ has_many :fulfillment_tax_lines, through: :fulfillments, source: :tax_lines+ has_many :fulfillment_discounts, through: :fulfillments, source: :discountsend+# Spree::Cart gets the same three has_many. LineItem and Fulfillment get+# tax_lines / discounts / fees (dependent: :destroy).```-### LineItem / Shipment associations+### Recalculation-```ruby-class Spree::LineItem < Spree.base_class- has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy- has_many :discounts, class_name: 'Spree::Discount', dependent: :destroy- has_many :fees, class_name: 'Spree::Fee', dependent: :destroy+`Adjustable::AdjustmentsUpdater` and `Adjustable::Adjuster::*` are replaced. `OrderUpdater` (and its cart counterpart) runs:- # Denormalized totals stay — recomputed from typed tables- # included_tax_total, additional_tax_total, promo_total, adjustment_total-end+```ruby+def recalculate_adjustments+ return if order.completed? # the order-level freeze — see Resolved Question 7-class Spree::Shipment < Spree.base_class- has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy- has_many :discounts, class_name: 'Spree::Discount', dependent: :destroy- has_many :fees, class_name: 'Spree::Fee', dependent: :destroy+ run_discount_and_fee_adjusters # Spree.adjusters — writes Discount/Fee rows,+ # persists discounted taxable base + fee_total+ Spree.tax_provider.estimate(order, taxable_items) # writes TaxLine rows (replace-all)+ update_totals_from_typed_tables # single grouped SUMs per table — no N+1end```-### Recalculation (new)--The `AdjustmentsUpdater` is replaced by typed updaters that can eager-load their sources:+Totals become set-based queries (`order.tax_lines.for_line_items.group(:included).sum(:amount)`, `order.discounts.sum(:amount)`, `order.fees.sum(:amount)`), preserving the discount-before-tax ordering and maintaining `taxable_adjustment_total` / `non_taxable_adjustment_total` / `pre_tax_amount` for the refund calculators that consume them.-```ruby-class Spree::OrderUpdater- def update_adjustment_total- # Each updater works with concrete associations — no N+1- update_tax_totals- update_discount_totals- update_fee_totals- update_order_total- end+Consumers that today string-match `source_type`/`eligible` are rewritten against typed associations: `Promotion#credits_count` counts distinct orders with that promotion's discounts; `PromotionHandler::Coupon` and `CouponCodesHandler` query `order.discounts`; `CreateItemAdjustments`' cross-adjustable negative-total guard reads `order.discounts.sum(:amount)`; `DefaultRefundAmount` reads the line item's own discounts (proportional distribution makes the order-level weighting obsolete — see Resolved Question 1); `OrderMerger` re-points owner + line_item FKs; `Cart::Empty` deletes the cart's typed rows.- private+### Promotion application (winner-only in 6.0, stacking-ready for 6.1)- def update_tax_totals- # Single query: SUM tax_lines grouped by included flag- line_item_taxes = order.tax_lines.for_line_items.group(:included).sum(:amount)- shipment_taxes = order.tax_lines.for_shipments.group(:included).sum(:amount)+6.0 behavior is winner-takes-all per adjustable — today's semantics. The policy is deliberately isolated: candidate computation returns **all** candidates and selection is one method, so 6.1's `combines_with` partition (combining candidates all apply, clamped and prorated over the remaining discounted base; non-combining compete) replaces only that method:- order.included_tax_total = (line_item_taxes[true] || 0) + (shipment_taxes[true] || 0)- order.additional_tax_total = (line_item_taxes[false] || 0) + (shipment_taxes[false] || 0)- end+```ruby+class Spree::Adjusters::Promotion < Spree::Adjusters::Base+ def update+ candidates = compute_all_promo_amounts(adjustable) # in memory, sources preloaded+ best = candidates.min_by { |c| c[:amount] } # most negative wins+ return adjustable.discounts.where(kind: 'promotion').destroy_all unless best- def update_discount_totals- # Single query- order.promo_total = order.discounts.sum(:amount) # always negative- end+ adjustable.discounts.where(kind: 'promotion')+ .where.not(promotion_action_id: best[:promotion_action].id).destroy_all- def update_fee_totals- order.fee_total = order.fees.sum(:amount)+ adjustable.discounts.find_or_initialize_by(+ promotion_action: best[:promotion_action], kind: 'promotion'+ ).update!(+ amount: clamp(best[:amount], adjustable), # net can never go below zero+ label: best[:label], code: best[:code],+ value: best[:value], value_type: best[:value_type],+ promotion: best[:promotion_action].promotion+ )endend```-### TaxRate (source side changes)+Promotion action classes move to `Spree::PromotionActions::*` per decisions.md 2026-03-16; `CreateItemAdjustments` → `CreateItemDiscounts` as part of that rename wave.++### Extensibility```ruby-class Spree::TaxRate < Spree.base_class- # Remove: include Spree::AdjustmentSource- has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :nullify-- def self.adjust(order, items)- # Bulk compute all tax lines for all items in one pass- applicable_rates = match(order.tax_zone)- return if applicable_rates.empty?-- items.each do |item|- applicable_rates.each do |rate|- amount = rate.compute_amount(item)- next if amount.zero?-- item.tax_lines.find_or_initialize_by(tax_rate: rate, order: order).tap do |tl|- tl.amount = amount- tl.included = rate.included_in_price?- tl.label = rate.adjustment_label(amount)- tl.save!- end- end- end- end-end-```+# config/initializers/spree.rb+Spree.adjusters << MyApp::Adjusters::GiftWrap-### PromotionAction (source side changes)+class MyApp::Adjusters::GiftWrap < Spree::Adjusters::Base+ def update+ return unless adjustable.respond_to?(:gift_wrap?) && adjustable.gift_wrap?-```ruby-class Spree::Promotion::Actions::CreateItemAdjustments < Spree::PromotionAction- # Remove: include Spree::AdjustmentSource- has_many :discounts, class_name: 'Spree::Discount', foreign_key: :promotion_action_id-- def perform(order:, **_args)- # Best-promo logic: compute amount, only write if this is the best- order.line_items.each do |line_item|- amount = compute_amount(line_item)- next if amount.zero?-- line_item.discounts.find_or_initialize_by(- promotion_action: self,- promotion: promotion,- order: order- ).tap do |disc|- disc.amount = amount- disc.label = "#{promotion.name} (#{promotion.code})"- disc.save!- end- end+ adjustable.fees.find_or_initialize_by(kind: 'gift_wrap').update!(+ amount: 5.99, label: 'Gift wrapping'+ )+ # No manual totals bookkeeping — OrderUpdater sums typed tables,+ # and the tax provider taxes the fee in the same recalculation pass.endend```-### Best-promo selection (simplified)+Custom discounts follow the same pattern writing `Discount` (`kind: 'loyalty'`, etc.). The legacy custom-`source_type` seam (unknown sources rendered by the admin order summary) maps to `Fee#kind` / `Discount#kind` grouping.-Instead of writing all competing promo adjustments and then marking losers as `eligible: false`, we compute all candidates and only persist the winner:+### Manual discounts and fees (back-office)-```ruby-class Spree::Adjustable::Adjuster::Promotion < Spree::Adjustable::Adjuster::Base- def update- candidates = compute_all_promo_amounts(adjustable)- # candidates: [{ promotion_action: ..., amount: -5.00, label: ... }, ...]+The legacy "manual adjustment with a label" splits by sign, keeping both directions of today's capability:- best = candidates.min_by { |c| c[:amount] } # most negative = biggest discount- return unless best+- **Compensation / goodwill** (scratched package, late delivery, price-match): manual `Discount(kind: 'manual')`. The admin targets either a **specific line item** (the damaged item) or the **whole order** — order-level manual discounts distribute proportionally to line items at creation time using the same largest-remainder rule as order-level promotions (Resolved Question 1), so vendor splitting and per-line refund math keep working.+- **Surcharge** (customs, handling, phone-order fee): manual `Fee` — order-level or attached to a line/fulfillment. Taxed by the provider like any fee.- # Delete any existing non-winning discounts for this adjustable- adjustable.discounts.where.not(promotion_action_id: best[:promotion_action].id).destroy_all+On **paid** orders, decreasing the total creates an outstanding credit — the recommended tool there is a partial `Refund` (see `6.0-returns-exchanges-claims.md`); the manual-discount path remains available through the explicit post-placement edit flow (Resolved Question 7) for pre-capture corrections and draft/backoffice orders.- # Upsert the winner- adjustable.discounts.find_or_initialize_by(- promotion_action: best[:promotion_action],- order: adjustable.order- ).update!(amount: best[:amount], label: best[:label], promotion: best[:promotion_action].promotion)- end-end-```+### Admin management surface (API / SDK / Dashboard)-No `eligible` flag, no write-then-update-all. Only the winner is stored.+Typed rows are managed through the Admin API v3, not just read:-### Extensibility+| Resource | Surface | Writes |+|---|---|---|+| `/admin/orders/:order_id/tax_lines` | index, get | **Read-only.** Tax is provider-computed; edits happen by changing the order (address, items, fees) which re-runs `estimate`. No hand-edited tax rows (no competitor allows this either). |+| `/admin/orders/:order_id/discounts` | full CRUD | Manual discounts only (`kind: 'manual'`). Promotion-sourced rows are read-only — the promotion engine owns them and would overwrite edits on recalculation (attempts return 422). |+| `/admin/orders/:order_id/fees` | full CRUD | Manual fees. Adjuster-written fees are recomputed on recalculation and should not be hand-edited. |-Custom adjustment types register as adjusters and write to `Fee`:+Conventions per `6.0-admin-api.md`: flat params, prefixed IDs, secret-key scopes (`read_orders`/`write_orders`) or JWT + CanCanCan (abilities granted on the three typed models replace today's `Spree::Adjustment` grants). Mutations run the order recalculation (totals, tax re-estimate on the changed base) — these endpoints **are** the explicit admin edit path from Resolved Question 7, so they work on completed orders where blind recalculation does not.-```ruby-# config/initializers/spree.rb-Spree.adjusters << MyApp::Adjustable::Adjuster::GiftWrap+- **admin-sdk**: `client.orders.taxLines.{list,get}`, `client.orders.discounts.{list,get,create,update,delete}`, `client.orders.fees.{list,get,create,update,delete}`, with generated TS/Zod types replacing the `orders.adjustments` resource.+- **React Dashboard**: the order detail page replaces the legacy adjustments list with typed panels — tax summary grouped by rate/label, fees list, discounts list — plus "Add fee" and "Add discount" actions (amount or percent via `value`/`value_type`, target picker: whole order / specific line item), `<Can>`-gated, forms per the dashboard conventions (RHF + Zod, `mapSpreeErrorsToForm`, i18n keys in all locale files). This supersedes the legacy admin's generic adjustment form and open/close toggle.-# app/models/my_app/adjustable/adjuster/gift_wrap.rb-class MyApp::Adjustable::Adjuster::GiftWrap < Spree::Adjustable::Adjuster::Base- def update- return unless adjustable.respond_to?(:gift_wrap?) && adjustable.gift_wrap?+## Migration Path- adjustable.fees.find_or_initialize_by(kind: 'gift_wrap', order: adjustable.order).tap do |fee|- fee.amount = 5.99- fee.label = 'Gift wrapping'- fee.save!- end+### Sequencing (cross-plan)- @totals[:non_taxable_adjustment_total] += 5.99- end-end-```+1. `6.0-cart-order-split.md` — owner semantics + `Spree::Carts::Complete` (gating dependency)+2. `6.0-fulfillment-and-delivery.md` Phase 1 + `6.0-normalize-state-to-status.md` — vocabulary, so the new tables are born correct+3. **This plan** (Phase 0 freeze → tables → data migration → model migration → API)+4. `6.0-tax-provider.md` — providers become the sole TaxLine writers (never implement a "TaxRate.adjust writes TaxLines" step; at most a short-lived shim inside the Internal provider)+5. `6.0-returns-exchanges-claims.md`, then `6.0-multi-vendor-marketplace.md` order splitting (consumes typed lines)-For custom discount types, same pattern with `Discount`:+### Phase 0: Preconditions-```ruby-class MyApp::Adjustable::Adjuster::LoyaltyDiscount < Spree::Adjustable::Adjuster::Base- def update- points = adjustable.order.user&.loyalty_points || 0- return if points.zero?+- Order-level recalculation freeze in `OrderUpdater` (refuse adjustment recalculation on completed orders), with explicit admin edit paths (manual Fee/Discount CRUD) as the sanctioned post-placement mutation route. Built and tested **before** any state-machine removal.+- Cart/order owner semantics finalized (see Depends on).- discount_amount = [points * 0.01, adjustable.amount * 0.1].min+### Phase 1: Create new tables- adjustable.discounts.find_or_initialize_by(kind: 'loyalty', order: adjustable.order).tap do |disc|- disc.amount = -discount_amount- disc.label = "Loyalty discount (#{points} pts)"- disc.save!- end- end-end-```+Key schema points (full migration authored at implementation time):-## Migration Path+- `spree_tax_lines`: `cart_id`/`order_id` (nullable, XOR), `tax_rate_id` (**nullable**), `line_item_id`/`fulfillment_id`/`fee_id` (nullable, XOR), `amount` + `rate` decimals (`null: false`), `label null: false`, `included` boolean `null: false`, `provider_id` string, `data` JSON (jsonb-guarded), `metadata` JSON. Plain FK indexes; **no** unique upsert identity.+- `spree_discounts`: owner XOR FKs, `promotion_action_id`/`promotion_id` (nullable), `line_item_id`/`fulfillment_id` (XOR), `amount null: false` + `CHECK (amount <= 0)`, `label null: false`, `kind`, `code`, `value`, `value_type`, `metadata` JSON. Index on `code`.+- `spree_fees`: owner XOR FKs, `line_item_id`/`fulfillment_id` (both nullable — both nil = order-level), `amount null: false` + `CHECK (amount >= 0)`, `label null: false`, `kind null: false`, `metadata` JSON. Index on `[order_id, kind]`.+- `spree_orders.fee_total` column.-### Phase 1: Create new tables+### Phase 2: Data migration (rake task, never in-migration)-```ruby-class CreateTypedAdjustmentTables < ActiveRecord::Migration[7.2]- def change- create_table :spree_tax_lines do |t|- t.references :order, null: false- t.references :tax_rate, null: false- t.references :line_item- t.references :shipment- t.decimal :amount, precision: 10, scale: 2, null: false- t.string :label, null: false- t.boolean :included, null: false, default: false- t.timestamps- end-- add_index :spree_tax_lines, [:line_item_id, :tax_rate_id], unique: true,- where: 'line_item_id IS NOT NULL', name: 'idx_tax_lines_line_item_rate'- add_index :spree_tax_lines, [:shipment_id, :tax_rate_id], unique: true,- where: 'shipment_id IS NOT NULL', name: 'idx_tax_lines_shipment_rate'-- create_table :spree_discounts do |t|- t.references :order, null: false- t.references :promotion_action- t.references :promotion- t.references :line_item- t.references :shipment- t.decimal :amount, precision: 10, scale: 2, null: false- t.string :label, null: false- t.string :kind # 'promotion', 'manual', 'loyalty', etc.- t.timestamps- end-- add_index :spree_discounts, [:line_item_id, :promotion_action_id], unique: true,- where: 'line_item_id IS NOT NULL', name: 'idx_discounts_line_item_action'-- create_table :spree_fees do |t|- t.references :order, null: false- t.references :line_item- t.references :shipment- t.decimal :amount, precision: 10, scale: 2, null: false- t.string :label, null: false- t.string :kind, null: false- t.timestamps- end-- add_index :spree_fees, [:order_id, :kind]- end-end-```+For each `spree_adjustments` row:-### Phase 2: Data migration (rake task)+| Source | Destination |+|---|---|+| `Spree::TaxRate` | `TaxLine` (copy rate from the TaxRate; `provider_id: 'internal'`) |+| `Spree::PromotionAction`, eligible | `Discount` (kind `'promotion'`, snapshot code/value from the promotion) |+| `Spree::PromotionAction`, `eligible: false` | skip (losers are not migrated) |+| nil source, amount < 0 | `Discount` (kind `'manual'`) |+| nil source, amount ≥ 0 | `Fee` (kind `'surcharge'`, order-level) |+| `Spree::ReturnAuthorization` | skip — legacy rows; their orders are marked **recalculation-frozen** (totals no longer reproducible from typed tables) |+| unknown custom source | `Fee` (kind derived from source class name; original class recorded in `metadata`) |-```ruby-# rake spree:migrate_adjustments-#-# For each adjustment in spree_adjustments:-# source_type == 'Spree::TaxRate' → create TaxLine-# source_type == 'Spree::PromotionAction' → create Discount (only eligible ones)-# source_type == nil (manual) → create Discount (kind: 'manual')-# source_type == 'Spree::ReturnAuthorization' → skip (returns handled by Refund model)-# anything else → create Fee-#-# Map adjustable_type:-# 'Spree::LineItem' → set line_item_id-# 'Spree::Shipment' → set shipment_id-# 'Spree::Order' → distribute proportionally to line_items (order-level discounts)-```+Order-level rows (`adjustable_type == 'Spree::Order'`): promotion and manual discounts distribute proportionally to line items (largest-remainder — see Resolved Question 1); manual surcharges become order-level Fees as-is.++**Upgrade path for existing orders:**++- **Additive schema first.** The new tables + `fee_total` land as normal migrations (no locks on `spree_adjustments`); the backfill runs separately as the rake task — batched by order, idempotent, resumable — never inside a migration. Stores upgrade, boot, then backfill online.+- **Completed orders are never recalculated.** The task re-expresses detail rows as typed rows; order-level denormalized totals and the grand total are left byte-for-byte untouched, so no customer-visible amount changes during upgrade. Combined with the order-level freeze (Resolved Question 7), historical totals stay stable afterwards too.+- **Per-order reconciliation.** After converting an order, the task asserts the typed sums match the legacy totals (`promo_total`, tax totals). Orders that don't reconcile (pre-existing data drift, skipped RA rows) are logged and marked recalculation-frozen rather than force-balanced.+- **Line-level caveat:** distributing order-level discounts updates per-line totals on historical orders (order totals unchanged), which shifts per-line exports and future partial-refund weighting for past data. The task logs affected orders.+- **In-flight carts/incomplete orders** don't need faithful conversion — the new engine recalculates them from scratch on first touch.+- **Rollback window:** `spree_adjustments` stays intact and read-only through all of 6.0 as the audit + rollback reference (typed tables can be dropped and re-derived by re-running the task). The 6.1 table drop is the point of no return.### Phase 3: Model migration-- Replace `Spree::Adjustment` with `TaxLine`, `Discount`, `Fee`-- Remove `AdjustmentSource` concern-- Remove `CalculatedAdjustments` concern usage for adjustments-- Update `OrderUpdater` to use typed queries-- Update `TaxRate.adjust` to write `TaxLine` records-- Update `PromotionAction` subclasses to write `Discount` records-- Remove `Adjustable::AdjustmentsUpdater`, `Adjustable::Adjuster::*`, `PromotionAccumulator`-- Add new typed adjusters+- New models + `Spree::Adjusters::Base`; remove `Adjustment`, `AdjustmentSource`, `Adjustable::AdjustmentsUpdater`, `Adjustable::Adjuster::*`, `PromotionAccumulator` (dead), `CalculatedAdjustments` usage for adjustments+- `OrderUpdater` typed recalculation with freeze guard + two-pass ordering; cart counterpart+- Promotion side: `PromotionActions::*` write Discounts (winner-only, clamped); usage-limit accounting, coupon handlers, `CouponCodesHandler`, `OrderPromotion#amount`, FreeShipping zero-amount semantics, `CreateItemAdjustments` negative-total guard+- Tax side: Internal provider writes TaxLines (replace-all); `TaxRate` keeps no write path+- Order/LineItem/Fulfillment readers rewritten (`order_level_promo_total`, `shipping_discount`, `valid_promotion_ids`, `cart_promo_total`, `has_free_shipping?`, `fully_discounted?`, `taxable_amount`, …); `OrderMerger`, `Cart::Empty`, refund calculators+- CanCanCan permission sets: grants on `TaxLine`/`Discount`/`Fee` replace `Spree::Adjustment`+- Factories + specs (~65 files), `docs/developer/core-concepts/adjustments.mdx`, `custom-promotion.mdx`-### Phase 4: API + serializer updates+### Phase 4: API + serializer + SDK + admin surfaces-- `adjustment` responses become typed: `tax_lines`, `discounts`, `fees` in serializers-- Order serializer includes totals derived from typed tables-- LineItem serializer includes nested `tax_lines` and `discounts`+- Admin API v3: `/admin/orders/:id/{tax_lines,discounts,fees}` endpoints replace `/adjustments` — tax_lines read-only, discounts/fees full CRUD for manual rows (see "Admin management surface"); typed serializers; `?expand=` updates on order/line_item/fulfillment serializers. Store API is already insulated (never exposed Adjustment rows)+- Full type pipeline: typelizer → Zod → integration specs → OpenAPI; admin-sdk `orders.adjustments` → `orders.{taxLines,discounts,fees}` resources; dashboard order page typed panels + add-fee/add-discount forms. Admin SDK is unreleased — break cleanly, no bridge+- Legacy Rails admin ships no replacement — `spree/admin` is removed at 6.0 (React dashboard only); its adjustment CRUD/toggle/summary views are deleted surface, counted in blast radius but not rebuilt. The dashboard order page (above) is the admin UI+- Emails: `_purchased_items_table` partials iterate typed associations+- Event payloads follow the serializer change automatically (`Publishable` resolves V3 serializers)### Phase 5: Cleanup (6.1)-- Drop `spree_adjustments` table-- Remove `Spree::Adjustment` model-- Remove all legacy scopes and methods+- Drop `spree_adjustments`, remove legacy scopes/aliases and the migration rake task## Constraints on Current Work-- **Don't add new adjustment source types.** New fee/discount types should be designed for the typed model.-- **Don't rely on `source_type` string matching.** New code should use the `tax`, `promotion` scopes which will be replaced by typed table queries.-- **Don't add new state machine transitions to Adjustment.** The state machine is being removed.-- **Keep denormalized totals on LineItem/Shipment/Order.** These stay — they're the performance optimization.+- **Don't add new adjustment source types or rely on `source_type` string matching.** New fee/discount types should be designed for the typed model.+- **Don't add state machine transitions to Adjustment.** It's being removed.+- **Don't build new features on `TaxRate.adjust` or `AdjustmentSource`.** The tax write path moves to the provider seam.+- **New code touching line items uses `line_item.owner`**, not `line_item.order` (cart/order split constraint).+- **No new `shipment` references** — fulfillment vocabulary (fulfillment plan constraint).+- **Keep denormalized totals on LineItem/Shipment/Order** — all of them, including `taxable_adjustment_total` / `non_taxable_adjustment_total` and `pre_tax_amount`; they're the performance optimization.## Resolved Questions-1. **Order-level discounts.** Order-level promotion amounts are **distributed proportionally across line items** at application time. No order-level discount records with nil FKs. Every `Discount` always belongs to a `line_item` or `shipment`. This is the industry-standard approach — it simplifies tax calculation (tax applies to the discounted per-item amount), partial refunds (each item knows its actual discount), and accounting. The `CreateAdjustment` promotion action (order-level) distributes its amount across line items weighted by `line_item.amount / order.item_total`.--2. **Return credits.** Separate domain — return credits are **not** modeled as `Discount`. Returns, exchanges, and claims will be addressed as first-class entities in a dedicated 6.0 plan (see: Claims/Exchanges as first-class entities). Return refunds flow through the `Refund` model and payment system, not through the adjustment/discount system.+1. **Order-level discounts** are distributed proportionally across line items at application time — no order-level Discount rows. Matches the hosted market leader/OSS platform A/OSS platform C. Math (specified now because refunds will depend on it): **largest-remainder** distribution so shares sum exactly to the promotion amount (OSS platform C's `prorate()`); the proration base is each line's **remaining discounted amount** (already-applied discounts subtracted — OSS platform A's stacking guard); weights are **frozen at placement** so partial cancellations don't redistribute discount money between lines (OSS platform C issue #4811). The order-level view is reconstructible via `GROUP BY promotion_action_id` — meaningful because `code`/`value` are snapshotted on every row.+2. **Return credits** are not Discounts — returns flow through the Refund model (`6.0-returns-exchanges-claims.md`). Legacy `ReturnAuthorization` adjustments are skipped at migration and their orders marked recalculation-frozen.+3. **`fee_total` on Order.** Order total formula: `total = item_total + delivery_total + fee_total + additional_tax_total + promo_total` (`delivery_total` per the fulfillment plan's rename).+4. **Fees are taxable** via `TaxLine#fee_id`. EU VAT applies to surcharges/gift wrap/handling; both competitor fee primitives carry tax lines. Fee tax stays itemized in the same reporting pipeline.+5. **Order-level fees are legal** (both adjustable FKs nil). At vendor split they prorate across child orders by item totals.+6. **Promotion stacking targets 6.1; 6.0 ships winner-only, stacking-ready.** Stacking (`Promotion#combines_with`, the hosted leader's model; OSS platform A/OSS platform C stack-with-caps validate the mechanics) is purely additive — no schema change (multiple Discount rows per adjustable are already legal), no breaking window needed. 6.0's obligations: clamping + remaining-base proration land with order-level distribution, and winner-only selection stays isolated in one adjuster method so 6.1 slots in the `combines_with` partition without touching persistence.+7. **State machine replacement = order-level freeze.** `OrderUpdater` refuses adjustment recalculation on completed orders (OSS platform B's status-gating model); post-placement changes go through explicit admin actions writing typed rows. The open/close toggle is dropped with the manual-adjustment CRUD replacement. The freeze ships before the state machine is removed. Deleted sources need no special handling — nullify + snapshots keep rows valid.+8. **Tax write path is provider-owned** (`6.0-tax-provider.md`). Replace-all set semantics per estimate; `Spree.adjusters` covers discounts/fees only.+9. **Manual admin adjustments** map to typed rows: negative → `Discount(kind: 'manual')`, positive → order-level `Fee(kind: 'surcharge')`. Going forward the admin creates them directly: manual discounts target a specific line item or the whole order (distributed proportionally, same largest-remainder rule as promotions); manual fees may be order-level. On paid orders, compensation is preferably a partial `Refund` — a total decrease after capture creates an outstanding credit — but the manual-discount path remains available via the explicit edit flow.+10. **Discount provenance survives promotion deletion**: `code`/`value`/`value_type` snapshots + `dependent: :nullify` (OSS platform B's SET_NULL-plus-snapshot pattern).+11. **Post-placement admin edits** happen through the typed CRUD endpoints (see "Admin management surface"): manual fees and discounts are created/edited directly and trigger recalculation on the changed base; tax lines are never hand-edited — tax follows from the order's state via the provider.-3. **`fee_total` on Order.** Add `fee_total` column to `spree_orders`. Explicit and consistent with the existing `promo_total`, `shipment_total` pattern. Order total formula becomes: `total = item_total + shipment_total + fee_total + additional_tax_total + promo_total`.+12. **Owner shape confirmed** (2026-07-27, with the cart-order-split expansion): the dual `cart_id`/`order_id` exactly-one pattern is the unified owner design for LineItem, the typed lines here, and Fulfillment/DeliveryRate — one pattern everywhere, `#owner` as a method, no polymorphism. Provenance flows through `Order#cart_id`.## Open Questions@@ -491,6 +416,6 @@ None at this time.- Current adjustment model: `spree/core/app/models/spree/adjustment.rb`- Current recalculation: `spree/core/app/models/spree/adjustable/adjustments_updater.rb`-- Current order updater: `spree/core/app/models/spree/order_updater.rb`- `AdjustmentSource` concern: `spree/core/app/models/concerns/spree/adjustment_source.rb`-- Related plan: `6.0-cart-order-split.md`+- Related plans: `6.0-cart-order-split.md`, `6.0-tax-provider.md`, `6.0-fulfillment-and-delivery.md`, `6.0-multi-vendor-marketplace.md`, `6.0-returns-exchanges-claims.md`, `6.0-admin-api.md`, `decisions.md` (2026-03-16 STI namespacing, state→status)+- Competitor review (2026-07-27): OSS platform A `packages/modules/{cart,order}/src/models/*-tax-line.ts`, `*-adjustment.ts` (typed tables, nullable `tax_rate_id` + `provider_id` + `data`); OSS platform C `surcharge.entity.ts` (taxable surcharges), `prorate.ts` (largest-remainder), issue #4811 (frozen proration weights); the hosted market leader Admin GraphQL `Order.taxLines` / `DiscountApplication` / `DiscountAllocation` / `AdditionalFee`; OSS platform B `saleor/discount/models.py` (SET_NULL + snapshots, winner-only via DB constraint)diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.mdindex a5c7c8643d..30724764ec 100644--- a/docs/plans/6.0-tax-provider.md+++ b/docs/plans/6.0-tax-provider.md@@ -4,7 +4,7 @@**Target:** Spree 6.0**Depends on:** Split Adjustments (6.0-split-adjustments.md) for TaxLine model, Channels/Catalogs/B2B (6.0-channels-catalogs-b2b.md) for Company.tax_exempt**Author:** Damian + Claude-**Last updated:** 2026-04-05+**Last updated:** 2026-07-27## Summary@@ -100,7 +100,7 @@ provider.void(order) # → cancels committed tax document, no-op for### Provider writes TaxLine records directly-With the split-adjustments plan (6.0), tax results are written as `Spree::TaxLine` records with concrete FKs. The provider creates/updates these records — the same data model regardless of whether tax was computed internally or by Avalara.+With the split-adjustments plan (6.0), tax results are written as `Spree::TaxLine` records — the same data model regardless of whether tax was computed internally or by Avalara. TaxLine is **self-describing**: `tax_rate_id` is nullable (set only by the Internal provider — external providers reference no local rate row and never synthesize one), and every row snapshots `rate`, `label`, `provider_id`, plus a `data` JSON column for provider payloads (jurisdiction breakdowns). Writes use **replace-all set semantics** per estimate: delete the target items' existing tax lines, insert fresh ones — this is also what prevents stale tax after an address change.Before split-adjustments ships, the provider writes `Spree::Adjustment` records (backward compatible).@@ -179,7 +179,7 @@ end### Provider is per-Market-Markets represent regional commerce operations. Each market can have its own tax provider, matching how Shopify and Medusa handle it:+Markets represent regional commerce operations. Each market can have its own tax provider, matching how the hosted market leader and OSS platform A handle it:```rubyclass Spree::Market < Spree.base_class@@ -218,7 +218,7 @@ class Spree::TaxRate < Spree.base_classend```-No zones, no zone members, no indirect lookups. This matches Shopify (rates per country/region) and Medusa (TaxRegion per country/province).+No zones, no zone members, no indirect lookups. This matches the hosted market leader (rates per country/region) and OSS platform A (TaxRegion per country/province).```ruby# TaxRate.for_address(address) — finds applicable rates@@ -230,7 +230,7 @@ scope :for_address, ->(address) {State-level rates override country-level (more specific wins). A rate with `country=US, state=CA` takes precedence over `country=US, state=nil` for California addresses.-The generic `Spree::Zone` model is **dropped entirely** in 6.0. A data migration (rake task) converts existing Zone records into `TaxRate` country/state FKs (for tax) and `DeliveryZone` records (for shipping, see `6.0-delivery-rate-provider.md`). After migration, `spree_zones` and `spree_zone_members` tables are removed.+**Tax stops using Zone; the Zone model itself survives 6.0** (decision 2026-07-27, superseding the earlier "dropped entirely"). A data migration (rake task) converts Zone records used by TaxRate into direct country/state FKs, and `zone_id` comes off TaxRate. The generic `Spree::Zone` stays for shipping (`ShippingMethod has_many :zones`) and the request-context surface (`Spree::Current.zone`, `Market#tax_zone`, factories) — the delivery-rate-provider plan descoped its `DeliveryZone` replacement after a review found ~183 unowned references. Full Zone removal gets its own future plan with a complete consumer inventory.This matches the natural scope hierarchy (all external providers store credentials in `Spree::Integration` — see above):@@ -336,9 +336,12 @@ module Spreeitems.each do |item|applicable_rates = rates.select { |r| r.tax_category_id == item.tax_category_id }+ # Replace-all set semantics (split-adjustments write contract):+ # stale lines from rates that no longer match are removed with the rest+ item.tax_lines.destroy_allapplicable_rates.each do |rate|amount = compute_tax(rate, item)- upsert_tax_line(order, item, rate, amount)+ create_tax_line(order, item, rate, amount)endendend@@ -356,13 +359,16 @@ module Spreeendend- def upsert_tax_line(order, item, rate, amount)- # Creates or updates TaxLine (6.0) for this item + rate- tax_line = item.tax_lines.find_or_initialize_by(tax_rate: rate, order: order)- tax_line.amount = amount- tax_line.included = rate.included_in_price?- tax_line.label = rate.name- tax_line.save!+ def create_tax_line(order, item, rate, amount)+ item.tax_lines.create!(+ order: order,+ tax_rate: rate, # internal lines keep the FK — SQL joinability+ rate: rate.amount, # snapshot — row survives rate edits/deletion+ amount: amount,+ included: rate.included_in_price?,+ label: rate.name,+ provider_id: 'internal'+ )enddef clear_tax(order, items)@@ -401,18 +407,22 @@ module SpreeTaxAvalara# Call Avalara APIresponse = client.create_transaction(request)- # Write TaxLine records from response+ # Write TaxLine records from response — self-describing rows,+ # no local TaxRate is referenced or synthesized (tax_rate_id stays nil)+ items.each { |item| item.tax_lines.destroy_all }+response.lines.each do |avalara_line|item = find_item(items, avalara_line.line_number)next unless item- upsert_tax_line(+ item.tax_lines.create!(order: order,- item: item,+ rate: avalara_line.rate,amount: avalara_line.tax,included: avalara_line.tax_included,label: avalara_line.tax_name,- tax_rate: find_or_create_rate(avalara_line)+ provider_id: 'avalara',+ data: { 'jurisdictions' => avalara_line.details })end@@ -637,34 +647,28 @@ end### Phase 4: Adapt to Split AdjustmentsWhen `6.0-split-adjustments.md` ships:-- Internal provider writes `TaxLine` records instead of `Adjustment` records-- External providers also write `TaxLine` records-- Adjuster reads from `tax_lines` instead of `adjustments.tax`-- `TaxRate.adjust` internally updated to create TaxLines+- Internal provider writes `TaxLine` records instead of `Adjustment` records (with `tax_rate_id` + `rate`/`label`/`provider_id` snapshots)+- External providers also write `TaxLine` records — self-describing, `tax_rate_id` nil, never synthesizing local TaxRate rows+- `OrderUpdater` reads totals from `tax_lines` instead of `adjustments.tax`+- `TaxRate.adjust` is **not** reimplemented on top of TaxLines — the provider is the only write path (split-adjustments Resolved Question 8)-### Phase 5: Drop Zone model + data migration+### Phase 5: Decouple tax from Zone (Zone model stays)-Coordinate with `6.0-delivery-rate-provider.md` — both plans share this migration:+Tax-side only — shipping keeps Zone untouched (see the Zones section of `6.0-delivery-rate-provider.md`; full Zone removal is deferred to its own plan):```ruby-# rake spree:migrate_zones+# rake spree:migrate_tax_zones## For each Zone used by TaxRate:# Extract country/state from ZoneMembers → set TaxRate.country_id / TaxRate.state_id directly# (Zone with multiple countries = one TaxRate per country)-#-# For each Zone used by ShippingMethod (DeliveryMethod):-# Create DeliveryZone + DeliveryZoneMembers from ZoneMembers-#-# After migration:-# Drop spree_zones and spree_zone_members tables-# Remove Zone, ZoneMember models```- Add `country_id` and `state_id` columns to `spree_tax_rates`- Run data migration rake task- Remove `zone_id` FK from TaxRate-- Drop `spree_zones` and `spree_zone_members` tables (shared with Delivery Rate Provider plan)+- Rewrite the tax-side zone readers against direct address matching (`TaxRate.for_address`): `Order#tax_zone`, `Spree::Current.zone`/`default_tax_zone`, `Market#tax_zone` — these feed pre-address tax display and Estimator VAT options, so they move to the provider/`for_address` path rather than being deleted+- `spree_zones` / `spree_zone_members` tables are **not** dropped in 6.0### Phase 6: Reference external provider (separate gem)diff --git a/docs/plans/6.0-typed-stock-movements.md b/docs/plans/6.0-typed-stock-movements.mdindex 48df07a891..b22399b90b 100644--- a/docs/plans/6.0-typed-stock-movements.md+++ b/docs/plans/6.0-typed-stock-movements.md@@ -4,7 +4,9 @@**Target:** Spree 6.0**Depends on:** Stock Reservations (6.0-stock-reservations.md), Remove Master Variant (6.0-remove-master-variant.md), Cart/Order Split (6.0-cart-order-split.md)**Author:** Damian + Claude-**Last updated:** 2026-03-22+**Last updated:** 2026-07-27++> **Vocabulary note (2026-07-27):** the new `spree_stock_movements` columns are born with **`fulfillment_id`** (never `shipment_id`) per `6.0-fulfillment-and-delivery.md` — same born-correct rule as the split-adjustments tables. Every `shipment_id` below reads as `fulfillment_id`; the backfill still matches legacy rows on `originator_type IN ('Spree::Shipment', 'Spree::Fulfillment')`.## Summarydiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 2cf42b4a1b..3cfb9e9e03 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,12 +1,33 @@+## 2026-07-27: One owner pattern for cart/order-scoped rows — dual concrete FKs, not polymorphic++The cart-order-split stub's "polymorphic `LineItem#owner`" is superseded. Every+cart-or-order-owned table uses the same shape: nullable `cart_id` + nullable+`order_id` with an exactly-one validation, and `#owner` as a plain method+(`order || cart`). Applies to `spree_line_items`, the typed money lines+(TaxLine/Discount/Fee), and Fulfillment/DeliveryRate.++Why: 6.0's design language is concrete FKs over polymorphic type strings+(split-adjustments removes `adjustable_type`/`source_type`,+typed-stock-movements removes `originator_type`) — reintroducing polymorphism+on the schema's highest-traffic table in the same release would be incoherent.+It's also the cheapest migration: `spree_line_items.order_id` already exists+and stays permanently; only a nullable `cart_id` is added, and every existing+`line_item.order` read keeps working for order-owned rows.++Provenance ("which cart did this order row come from") needs no second FK on+the row: `Order#cart_id` (unique — the completion idempotency key) links order+to cart, and the retained cart keeps its own rows as the frozen at-checkout+snapshot, so post-placement additions are distinguishable. Both-columns-set+was considered and rejected — order-side copies carrying `cart_id` would+collide with the cart's own rows in every `cart.line_items`-style association.+## 2026-07-23: Payment-method eligibility rules + Channel→Markets allowlist target 5.7; multi-credential grooming deferredMerchant asks (wholesale net payment vs DTC Stripe, installments above anorder-total threshold, market-bound payment methods, channels limited to-certain markets) plus a four-platform review (Vendure channel-scoped-PaymentMethods + `PaymentMethodEligibilityChecker`, Medusa region-scoped-payment providers, Saleor per-channel payment apps, Shopify Payment-Customization Functions + the May-2026 per-market multi-entity Shopify-Payments) settled three things:+certain markets) plus a four-platform review (OSS platform C channel-scoped+PaymentMethods + `PaymentMethodEligibilityChecker`, OSS platform A region-scoped+payment providers, OSS platform B per-channel payment apps, the hosted leader's Payment Customization Functions + the May-2026 per-market multi-entity payments product) settled three things:1. **`5.7-payment-method-rules.md`** — `Spree::PaymentMethodRule` STI(Channel / Market / OrderTotal / CustomerGroup rules), mirroring the@@ -21,11 +42,11 @@ Payments) settled three things:resolution, the Store API markets reference endpoints, and ordervalidation. Composes with `MarketRule` above.3. **Deferred for grooming: multiple provider credentials / legal entities- in one store** (two Stripe accounts split by channel or market, Shopify's+ in one store** (two Stripe accounts split by channel or market, the hosted leader'smulti-entity model). Candidate shapes — separate PaymentMethod records per- channel/market (Vendure/Medusa style; needs the Admin API `types`+ channel/market (OSS platform C/OSS platform A style; needs the Admin API `types`"already installed" filter relaxed) vs per-channel credential mapping on- one record (Saleor style) — plus the legal-entity attribution question+ one record (OSS platform B style) — plus the legal-entity attribution question(per-entity payouts, compliance, reporting). No plan yet; do not implement.## 2026-07-21: Order routing rules get admin management in the React dashboard only@@ -128,7 +149,7 @@ Resolution: **the marketplace owns the `Vendor` name.** It is locked publicly(spree/spree#13323, the user docs' "Vendors" area, the legacy Enterprise gem's`ven_` prefix and its production data). The inventory-operations model is renamed**`Spree::Supplier`** (`spree_suppliers`, prefix `sup_`, `/api/v3/admin/suppliers`) —-matching Shopify's purchase-order vocabulary and standard ERP terminology. They+matching the hosted leader's purchase-order vocabulary and standard ERP terminology. Theyare different lifecycles: a supplier is an address-book entry the merchant buysstock from; a vendor is an onboarded selling party with users, commission, andpayouts.@@ -162,8 +183,8 @@ rebuilt as native core models on top of the 6.0 Cart/Order split.`Spree::StockItem` → `Spree::StockLevel`, `spree_stock_items` → `spree_stock_levels`.Prefix ID: `si_` → `sl_`.-Every other platform uses "level" for this concept — Shopify (`InventoryLevel`),-Medusa (`InventoryLevel`), Vendure (`StockLevel`), Saleor (`Stock`). "Item" sounds+Every other platform uses "level" for this concept — the hosted market leader (`InventoryLevel`),+OSS platform A (`InventoryLevel`), OSS platform C (`StockLevel`), OSS platform B (`Stock`). "Item" soundslike a physical object; "level" correctly describes "the quantity of a variant ata location."@@ -200,20 +221,26 @@ Single migration renames all 11 columns. Model associations updated:`belongs_to :user` → `belongs_to :customer` with `class_name: Spree.customer_class`.## 2026-03-16: PaymentMethod and DeliveryMethod become SingleStoreResource-Both PaymentMethod and DeliveryMethod (renamed from ShippingMethod) switch from-multi-store join tables (`StorePaymentMethod`, `StoreShippingMethod`) to+Both PaymentMethod and DeliveryMethod (renamed from ShippingMethod) switch to`SingleStoreResource` with direct `belongs_to :store`.In practice, different stores have different currencies, zones, and provideraccounts — sharing the same payment/delivery config across stores is rare.If a merchant wants the same config on two stores, they create two records.-Changes:-- Add `store_id` column to `spree_payment_methods` and `spree_delivery_methods`-- Data migration: for each join record, set `store_id`; duplicate methods linked- to multiple stores-- Drop `spree_store_payment_methods` and `spree_store_shipping_methods` join tables-- Both models include `Spree::SingleStoreResource` concern+**Corrected 2026-07-27:** the original entry claimed both models migrate away+from multi-store join tables (`StorePaymentMethod`, `StoreShippingMethod`).+That was only half true — `spree_store_shipping_methods` / a+`StoreShippingMethod` model **never existed**; ShippingMethod has always been+globally scoped (no store association of any kind). The PaymentMethod half was+real and shipped in 5.6 (`5.6-6.0-single-store-promotions-payment-methods.md`).+For ShippingMethod/DeliveryMethod, `store_id` is therefore a **greenfield+addition with a derived backfill** (no join table to read from), owned by+`6.0-delivery-rate-provider.md` Phase 1 — the provider needs the store to+resolve `Spree::Integration` credentials. Backfill: `Store.default` for+single-store installs; zone-overlap heuristic + loud logging for multi-store.+Note this is a behavior change for multi-store installs (globally-visible+methods become single-store), not a mechanical migration.## 2026-03-16: Fix promotion rule/action STI namespacingRename `Spree::Promotion::Rules::*` → `Spree::PromotionRules::*` and@@ -269,7 +296,7 @@ This makes the two-system boundary razor-sharp:- Custom Fields (storefront_visible: false) = admin-only structured data- Metadata = private developer-owned data (never exposed)-Matches Vendure (`public: boolean`) and Saleor (`visibleInStorefront: boolean`).+Matches OSS platform C (`public: boolean`) and OSS platform B (`visibleInStorefront: boolean`).Ships with the 6.0 model rename wave. See `5.4-6.0-custom-fields-rename.md`.## 2026-03-16: Consolidate metadata — drop public_metadata, keep metadata JSON column@@ -297,3 +324,61 @@ Metadata for machines, metafields/custom fields for humans.Considered Action Text. Rejected for API-first performance —serializing rich text adds overhead for every product response.Also in the new Admin UI we will use TipTap for rich text editing.++## 2026-07-27: Delivery rate provider wraps the Estimator — shipping calculators stay++Reverses the original `6.0-delivery-rate-provider.md` key decision to delete+`ShippingCalculator` + `Calculator::Shipping::*` in favor of a `pricing_type`+enum. The enum cannot reach parity (FlexiRate/PriceSack inexpressible, FlatRate+suppression thresholds and DigitalDelivery's `available?` predicate lost) and+breaks every merchant calculator subclass with no migration path.++Instead the provider is dispatched at the single point where `Stock::Estimator`+calls `calculator.compute(package)`; the Estimator keeps method filtering, VAT+gross-up, tax resolution, and default selection. `Internal` delegates to the+calculator — zero behavior change is the acceptance criterion. All three+Estimator entry points (Shipment#refresh_rates, OrderRouting::Strategy::Rules,+Cart::EstimateShippingRates) get provider support with no per-site changes.+Accepted asymmetry: the tax provider still removes its calculators — tax+calculators were pure math with no merchant extension surface; shipping+calculators are a documented extension point.++## 2026-07-27: Zone → DeliveryZone ships in 6.0, owned by a dedicated plan++A review found the old "drop Spree::Zone entirely" wording in the tax and+delivery-rate plans had no owner for ~183 non-spec references+(`Spree::Current.zone` / `default_tax_zone`, `Market#tax_zone`,+`Order#tax_zone`, `VatPriceCalculation`, `Pricing::Context`, permission sets,+admin Zone CRUD, and the `Zone.global` factory monkey-patch every+`:shipping_method` factory depends on). Briefly scoped back the same day, then+**reinstated for 6.0 by user decision — 6.0 is the one breaking-change window;+big re-architecture does not wait for 6.1.**++Final shape: tax decouples via `6.0-tax-provider.md` Phase 5 (TaxRate direct+country/state FKs, tax readers rewritten onto `TaxRate.for_address` /+`Spree::Current.tax_country`); everything else is owned by the new+`6.0-delivery-zones.md` — `DeliveryZone` + typed members with country-scoped+postal-code ranges/prefixes, admin CRUD swap, factories rework+(worldwide-by-default methods, `Zone.global` retired), and the final+`spree_zones`/`spree_zone_members` drop at end of 6.0.++## 2026-07-27: Promotion stacking targets 6.1; 6.0 ships winner-only but stacking-ready++Stacking is among the most-requested features. Initially slated for 6.0 (the+discount engine is being rewritten there anyway), retargeted to 6.1 the same+day: stacking is **purely additive** — no schema change, no breaking window+needed — and 6.0 is already the heaviest release in Spree's history. Deferring+costs nothing structurally because the expensive prerequisites ship in 6.0+regardless (`6.0-split-adjustments.md`): typed Discount tables that permit+multiple rows per adjustable, per-adjustable clamping, and+prorate-over-the-remaining-discounted-base (needed for order-level+distribution either way), with winner-only selection isolated in a single+adjuster method.++6.1 adds: hosted-leader-style `Promotion#combines_with` flags (per class —+item/order/shipping; combining candidates all apply clamped, non-combining+compete winner-takes-all, **default off** so migrated promotions keep today's+behavior), dashboard UI, API fields. Industry: the hosted market leader combinesWith+(merchant-controlled), OSS platform A stacks all valid with caps, OSS platform C stacks+priority-ordered, OSS platform B winner-only — merchant control is the differentiated+middle.