Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Add claude skills around planning + add 6.0 plans (#13781)

Damian Legawieceee64cf86452
diff --git a/.claude/agents/architect.md b/.claude/agents/architect.md
new file mode 100644
index 0000000000..58f4e87a46
--- /dev/null
+++ b/.claude/agents/architect.md
@@ -0,0 +1,17 @@
+You are the architecture planning agent for Spree Commerce.
+
+Your job is to create, review, and maintain feature plans in `docs/plans/`.
+
+When creating plans:
+- Always use the template at `docs/plans/_template.md`
+- Cross-reference existing plans for dependencies and conflicts
+- Focus heavily on the "Constraints on Current Work" section
+- Think about migration paths from the current codebase
+- Consider API v3 conventions documented in `docs/plans/6.0-store-api-v3.md`
+- Focus on open–closed principle, flexibility and extensibility are key principles to follow
+
+When reviewing code changes:
+- Check if any active plan's constraints are being violated
+- Flag when implementation diverges from a finalized plan
+
+Always update root CLAUDE.md when adding or changing plan status.
diff --git a/.claude/commands/create-plan.md b/.claude/commands/create-plan.md
new file mode 100644
index 0000000000..3387ab1adc
--- /dev/null
+++ b/.claude/commands/create-plan.md
@@ -0,0 +1,13 @@
+Create a new architecture/feature plan document.
+
+Plan topic: $ARGUMENTS
+
+Follow this process:
+1. Read the plan template at `docs/plans/_template.md`
+2. Create a new plan file in `docs/plans/` with a kebab-case filename
+3. Fill in all sections based on our discussion and any existing context
+4. Update the "Architecture Plans" section in the root `CLAUDE.md` to include the new plan
+5. If the plan affects specific areas of the codebase, add cross-references in relevant directory-level CLAUDE.md files
+
+The filename should follow the pattern: `{release}-{feature-slug}.md`
+(e.g., `6.0-cart-order-split.md`, `future-mcp-server.md`)
diff --git a/.claude/commands/reviews-plans.md b/.claude/commands/reviews-plans.md
new file mode 100644
index 0000000000..264b48db34
--- /dev/null
+++ b/.claude/commands/reviews-plans.md
@@ -0,0 +1,9 @@
+Review all active architecture plans relevant to the current task.
+
+Context: $ARGUMENTS
+
+1. Read the "Architecture Plans" section from root `CLAUDE.md`
+2. Based on the context provided, identify which plans are relevant
+3. Read those specific plan files
+4. Summarize the key constraints that apply to the current work
+5. Flag any conflicts between plans or open questions that might block progress
diff --git a/.claude/commands/update-plan.md b/.claude/commands/update-plan.md
new file mode 100644
index 0000000000..15b651fbfa
--- /dev/null
+++ b/.claude/commands/update-plan.md
@@ -0,0 +1,10 @@
+Update an existing plan document.
+
+Instructions: $ARGUMENTS
+
+1. List all plans in `docs/plans/` (excluding `_template.md`)
+2. Identify the relevant plan based on the instructions
+3. Read the current plan content
+4. Apply the requested changes while preserving the document structure
+5. Update the `Last updated` date
+6. If status changed, update the reference in root `CLAUDE.md`
diff --git a/.claude/settings.local.json b/.claude/settings.local.json
new file mode 100644
index 0000000000..df3a85bcec
--- /dev/null
+++ b/.claude/settings.local.json
@@ -0,0 +1,37 @@
+{
+ "permissions": {
+ "allow": [
+ "Bash",
+ "Read",
+ "Edit",
+ "Write",
+ "Glob",
+ "Grep",
+ "WebFetch",
+ "WebSearch",
+ "Task",
+ "mcp__*"
+ ],
+ "deny": [
+ "Bash(sudo *)",
+ "Bash(rm -rf /*)",
+ "Bash(rm -rf ~/*)",
+ "Bash(chmod 777 *)",
+ "Read(~/.ssh/*)",
+ "Read(~/.gnupg/*)",
+ "Read(~/.aws/*)",
+ "Read(~/.config/gcloud/*)",
+ "Read(**/.env)",
+ "Read(**/.env.*)",
+ "Read(**/secrets/*)",
+ "Read(**/*credential*)",
+ "Read(**/*password*)",
+ "Edit(~/.ssh/*)",
+ "Edit(~/.gnupg/*)",
+ "Edit(~/.aws/*)",
+ "Write(~/.ssh/*)",
+ "Write(~/.gnupg/*)",
+ "Write(~/.aws/*)"
+ ]
+ }
+}
diff --git a/.gitignore b/.gitignore
index 6ffb4cce37..68bb15beeb 100644
--- a/.gitignore
+++ b/.gitignore
@@ -53,8 +53,7 @@ server/db/migrate
TODO
brakeman-*.*
*/app/assets/builds
-.claude
-*/.claude
+.claude/worktrees
**/node_modules
packages/*/package-lock.json
.turbo
diff --git a/CLAUDE.md b/CLAUDE.md
index 39b3ec0b53..61be7dc183 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1,184 +1,156 @@
-# Claude Code Rules for Spree Commerce Development
-
-## General Development Guidelines
-
-### Framework & Architecture
-
-- Spree backend is built on Ruby on Rails and follows MVC architecture
-- All Spree backend code must be namespaced under `Spree::` module
-- Spree is distributed as Rails engines with separate packages:
- - **Core packages (required):** `spree_core` (models, services, business logic, events engine, pricing engine), `spree_api` (Store API, Admin API (soon!), HTTP Webhooks)
- - **Optional packages:** `spree_admin` (admin dashboard), `spree_emails` (transactional emails)
-- Most users run Spree in headless mode with custom frontends using the Store API
+# Spree Commerce — Development Rules
+
+## Plans & Architecture Decisions
+
+All feature plans live in `docs/plans/` using the template at `docs/plans/_template.md`. Never create plans elsewhere.
+
+When proposing significant architectural changes:
+1. Check existing plans in `docs/plans/` for conflicts
+2. Create or update a plan using the template before implementing
+3. Pay special attention to "Constraints on Current Work" sections — these apply even when you're not implementing that plan directly
+
+Use `/project:create-plan` and `/project:update-plan` for plan management.
+
+Current plans:
+- `6.0-cart-order-split.md` — Cart/Order model separation, polymorphic LineItem
+- `6.0-admin-spa.md` — React admin architecture, plugin system
+- `6.0-product-types.md` — Prototype → ProductType rename, MetafieldDefinition schema enforcement
+- `6.0-remove-master-variant.md` — Eliminate is_master, add default_variant_id FK on Product
+- `6.0-split-adjustments.md` — Replace polymorphic Adjustment with TaxLine, Discount, Fee
+- `6.0-stock-reservations.md` — Time-limited stock reservations during checkout
+- `6.0-typed-stock-movements.md` — Replace generic StockMovement with typed kinds + concrete FKs
+- `6.0-normalize-state-to-status.md` — Rename state → status on Payment, Shipment, InventoryUnit, ReturnAuthorization, GiftCard
+- `6.0-fulfillment-and-delivery.md` — Shipment→Fulfillment, ShippingMethod→DeliveryMethod, drop ShippingCategory, FulfillmentProvider strategy
+- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain
+- `6.0-channels-catalogs-b2b.md` — Channel, Catalog, ProductListing (replaces StoreProduct), Company/CompanyLocation/CompanyContact for B2B
+- `5.x-store-api-bridges.md` — Bridge 6.0 naming into 5.5 Store API (fulfillments, delivery, status, remove master_variant)
+
+## Monorepo Structure
+
+| Directory | Description |
+|---|---|
+| `spree/core` | Ruby gem — models, services, business logic (`spree_core`) |
+| `spree/api` | Ruby gem — Store & Admin REST APIs (`spree_api`) |
+| `spree/emails` | Ruby gem — transactional emails (`spree_emails`, optional) |
+| `packages/sdk` | `@spree/sdk` — TypeScript Store API client |
+| `packages/admin-sdk` | `@spree/admin-sdk` — TypeScript Admin API client (private) |
+| `packages/sdk-core` | `@spree/sdk-core` — shared HTTP/retry/error layer (private) |
+| `packages/next` | `@spree/next` — Next.js server actions, data helpers, middleware |
+| `packages/cli` | `@spree/cli` — Docker-based project management CLI |
+| `packages/create-spree-app` | `create-spree-app` — project scaffolding |
+| `server/` | Rails app that mounts Spree gems and serves the API |
+
+---
+
+## Backend (Ruby)
+
+### Architecture Principles
+
+- All code namespaced under `Spree::` module
- Follow Rails conventions and the Rails Security Guide
-- Prefer Rails idioms and standard patterns over custom solutions
-- Use RESTful action names
-- Enforce CanCanCan permission checks, for listings always use `accessible_by(current_ability, :show)` scope, for other actions always perform `authorize!` check
-- For better security always use scope fetching, eg. `current_user.orders` instead of `Spree::Order`
-- Use Ransack for filtering and searching https://activerecord-hackery.github.io/ransack/getting-started/search-matches/
-- Use Pagy for pagination https://github.com/ddnexus/pagy
+- RESTful routes and action names
+- CanCanCan for authorization: listings use `accessible_by(current_ability, :show)`, other actions use `authorize!`
+- Always use scope fetching for security (e.g. `current_store.orders` not `Spree::Order`)
+- Ransack for filtering/searching, Pagy for pagination
+- Business logic belongs in models and concerns, not controllers
+- Use services only when necessary — prefer standard Rails models and concerns
+- Do not call `Spree::User` directly, use `Spree.user_class`; same for `Spree.admin_user_class`
### Code Organization
-- Place all models in `app/models/spree/` directory
-- Place all controllers in `app/controllers/spree/` directory
-- Place all services in `app/services/spree/` directory
-- Place all mailers in `app/mailers/spree/` directory
-- Place all API serializers in `app/serializers/spree/` directory
-- Place all helpers in `app/helpers/spree/` directory
-- Place all jobs in `app/jobs/spree/` directory
-- Place all presenters in `app/presenters/spree/` directory
-- Use consistent file naming: `spree/product.rb` for `Spree::Product` class
-- Group related functionality into concerns when appropriate
-- Do not call `Spree::User` directly, use `Spree.user_class` instead
-- Do not call `Spree::AdminUser` directly, use `Spree.admin_user_class` instead
-- Split big models in modules/concerns, keep them organized by topic
-
-### Spree::Current class
-
-`Spree::Current` is a class that provides access to the current store, currency, and locale. It is available in models, controllers, jobs and services. Each value is set per request.
-
-`Spree::Current.store` — current store
-`Spree::Current.currency` — current currency
-`Spree::Current.locale` — current locale
-
-## Naming Conventions & Structure
-
-### Classes & Modules
-
-```ruby
-# ✅ Correct naming
-module Spree
- class Product < Spree.base_class
- end
-end
-
-module Spree
- module Admin
- class ProductsController < ResourceController
- end
- end
-end
-
-# ❌ Incorrect - missing namespace
-class Product < ApplicationRecord
-end
-```
+All backend code lives inside `spree/` engine directories following Rails conventions:
-Always inherit from `Spree.base_class` when creating models.
+- `app/models/spree/`, `app/controllers/spree/`, `app/services/spree/`, `app/serializers/spree/`, `app/subscribers/spree/`, `app/mailers/spree/`, `app/jobs/spree/`, `app/helpers/spree/`, `app/presenters/spree/`
+- File naming matches class: `spree/product.rb` → `Spree::Product`
+- Split large models into concerns, organized by topic
-### File Paths
+### Spree::Current
-- Models: `app/models/spree/product.rb`
-- Controllers: `app/controllers/spree/admin/products_controller.rb`
+Per-request context available in models, controllers, jobs, and services:
-## Model Development
+- `Spree::Current.store` — current store
+- `Spree::Current.currency` — current currency
+- `Spree::Current.locale` — current locale
-### Model Patterns
+### Models
-- Use ActiveRecord associations appropriately, always pass `class_name` and `dependent` options
-- Implement concerns for shared functionality
-- Use scopes for reusable query patterns
-- Include `Spree::Metafields` concern for models that need metadata support
-- Don't use enums, use string columns instead
-- For models that require state machine, please use https://github.com/state-machines/state_machines-activerecord gem, default column should be `status`, legacy models use `state`
-- Don't ever cast IDs to integer, we need to support also UUIDs so please always treat IDs as strings
+- Inherit from `Spree.base_class`
+- Always pass `class_name` and `dependent` on associations
+- Include `Spree::Metafields` for metadata support
+- Use string columns instead of enums
+- State machines: use `state_machines-activerecord` gem, default column `status` (legacy uses `state`)
+- Never cast IDs to integer — always treat as strings (UUID support)
+- Uniqueness validations: always use `scope: spree_base_uniqueness_scope`
```ruby
-# ✅ Good model structure
class Spree::Product < Spree.base_class
include Spree::Metafields
-
+
has_many :variants, class_name: 'Spree::Variant', dependent: :destroy
-
scope :available, -> { where(available_on: ..Time.current) }
-
+
validates :name, presence: true
validates :slug, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }
end
```
-For uniqueness validation, always use `scope: spree_base_uniqueness_scope`
-
-## Controller Development
-
-### Controller Inheritance
+### Migrations
-- Admin controllers inherit from `Spree::Admin::ResourceController` which handles most of CRUD operations
-- Store API controllers inherit from `Spree::Api::V3::Store::ResourceController` which handles all CRUD operations for store resources
+- Target version: `ActiveRecord::Migration[7.2]` (Rails 7.2 support)
+- No foreign key constraints
+- No default values
+- Always add `null: false` on required columns
+- One migration per feature when possible
+- Data transformations go in rake tasks, never in migrations
+- Soft delete: use `paranoia` gem, add `deleted_at` column yourself
-### Parameter Handling
-
-- Always use strong parameters
-- Always use `Spree::PermittedAttributes` to define allowed parameters for each resource
-
-## API Development
-
-Spree API v3 provides RESTful endpoints organized into two scopes:
-
-- **Store API** (`/api/v3/store/`) - Customer-facing endpoints for cart, checkout, products, and accounts
-- **Admin API** (`/api/v3/admin/`) - Administrative endpoints for managing orders, products, and store settings
+```ruby
+class CreateSpreeMetafields < ActiveRecord::Migration[7.2]
+ def change
+ create_table :spree_metafields do |t|
+ t.string :key, null: false
+ t.text :value, null: false
+ t.string :kind, null: false
+ t.string :visibility, null: false
+ t.references :resource, polymorphic: true, null: false
+ t.timestamps
+ end
-### Prefixed IDs
+ add_index :spree_metafields, [:resource_type, :resource_id, :key, :visibility],
+ name: 'index_spree_metafields_on_resource_and_key_and_visibility'
+ end
+end
+```
-All API v3 responses use Stripe-style prefixed IDs (e.g., `prod_86Rf07xd4z`, `variant_k5nR8xLq`, `or_m3Rp9wXz`). This is a critical convention:
+### API Controllers
-- **Always return prefixed IDs** in API responses — never expose raw integer/UUID IDs
-- **Always accept prefixed IDs** in API request parameters (e.g., `variant_id`, `product_id`)
-- The `BaseSerializer` automatically converts the primary `id` attribute to a prefixed ID
-- For association IDs in serializers, explicitly use `object.association&.prefixed_id`
-- In controllers, use `find_by_prefix_id!` for lookups — the base `ResourceController` does this automatically for `params[:id]`
+#### Hierarchy
-```ruby
-# ✅ Correct - serializer returning prefixed IDs for associations
-attribute :variant_id do |line_item|
- line_item.variant&.prefixed_id
-end
+- **Base:** `Spree::Api::V3::ResourceController` — CRUD, pagination (Pagy), Ransack, CanCanCan, prefixed ID lookups, HTTP caching
+- **Store API:** `Spree::Api::V3::Store::ResourceController` — publishable API key auth
+- **Admin API:** `Spree::Api::V3::Admin::ResourceController` — secret API key auth
-# ✅ Correct - controller looking up by prefixed ID
-@variant = current_store.variants.find_by_prefix_id!(params[:variant_id])
+#### Key overridable methods
-# ❌ Incorrect - exposing raw IDs in API
-attribute :variant_id # This would return the raw integer ID
-```
+`model_class`, `serializer_class` (use `Spree.api.serializer_name`), `scope` (call `super` and chain), `find_resource`, `permitted_params`, `collection_includes`
-### Flat Request/Response Structure
+#### Flat request/response structure
-API v3 uses a **flat parameter structure** — no nested Rails-style params wrapping:
+API v3 uses flat params — no nested Rails-style wrapping. The base controller auto-infers from `Spree::PermittedAttributes`:
```ruby
-# ✅ Correct - flat params (API v3 style)
+# ✅ Flat params
def permitted_params
params.permit(Spree::PermittedAttributes.product_attributes)
end
-# ❌ Incorrect - nested Rails params (not used in API v3)
+# ❌ Nested params — not used in API v3
def permitted_params
params.require(:product).permit(:name, :description, :slug)
end
```
-The base `ResourceController` automatically infers permitted attributes from `Spree::PermittedAttributes`:
-
-```ruby
-# Automatically maps ProductsController -> Spree::PermittedAttributes.product_attributes
-def permitted_params
- params.permit(permitted_attributes)
-end
-```
-
-Responses are also flat JSON objects, not wrapped in a root key.
-
-### API Controllers
-
-#### Controller Hierarchy
-
-- **Base:** `Spree::Api::V3::ResourceController` — provides standard CRUD, pagination (pagy), Ransack filtering, authorization (CanCanCan), prefixed ID lookups, and HTTP caching
-- **Store API:** `Spree::Api::V3::Store::ResourceController` — adds publishable API key authentication
-- **Admin API:** `Spree::Api::V3::Admin::ResourceController` — adds secret API key authentication
-
```ruby
-# ✅ Store API controller
module Spree::Api::V3::Store
class ProductsController < ResourceController
protected
@@ -198,484 +170,260 @@ module Spree::Api::V3::Store
end
```
-#### Key ResourceController Methods
+### Prefixed IDs
-Override these in subclasses to customize behavior:
+All API v3 uses Stripe-style prefixed IDs (e.g. `prod_86Rf07xd4z`, `variant_k5nR8xLq`):
-- `model_class` — the ActiveRecord model class
-- `serializer_class` — the Alba serializer (use `Spree.api.serializer_name` for configurable references)
-- `scope` — base scope for queries (call `super` and chain)
-- `find_resource` — resource lookup (defaults to `scope.find_by_prefix_id!(params[:id])`)
-- `permitted_params` — allowed request parameters
-- `collection_includes` — eager loading associations for index action
+- Always return prefixed IDs in responses — never expose raw IDs
+- Always accept prefixed IDs in request params
+- `BaseSerializer` auto-converts the primary `id`; for associations use `object.association&.prefixed_id`
+- Controllers use `find_by_prefix_id!` (automatic in base `ResourceController`)
+- Event payloads also use prefixed IDs
-### Serializers
+```ruby
+# ✅ Serializer
+attribute :variant_id do |line_item|
+ line_item.variant&.prefixed_id
+end
-API v3 uses [Alba serializers](https://github.com/okuramasafumi/alba) located in `api/app/serializers/spree/api/v3/`. We have separate serializers for Store and Admin APIs:
+# ❌ Exposes raw ID
+attribute :variant_id
+```
-- **Store serializers** (`app/serializers/spree/api/v3/`) - Customer-facing, limited data
-- **Admin serializers** (`app/serializers/spree/api/v3/admin/`) - Full access, extends store serializers
+### Serializers (Alba)
-Admin serializers inherit from store serializers and add additional fields.
+Located in `api/app/serializers/spree/api/v3/`. Store and Admin APIs have separate serializers; Admin extends Store:
```ruby
-# Store serializer - customer-facing
+# Store serializer
module Spree::Api::V3
class ProductSerializer < BaseSerializer
typelize purchasable: :boolean, in_stock: :boolean, price: 'number | null'
-
attributes :id, :name, :description, :slug, :price
end
end
-# Admin serializer - extends store with admin-only fields
+# Admin serializer — extends store
module Spree::Api::V3::Admin
class ProductSerializer < V3::ProductSerializer
typelize cost_price: 'number | null', private_metadata: 'Record<string, unknown> | null'
-
attributes :status, :cost_price, :private_metadata
end
end
```
-Never use `typelize_from` in serializers — this causes serializers to connect to the database.
+- `typelize attr: :type` for computed/delegated attribute types
+- Never use `typelize_from` — it connects to the database
+- Customize via inheritance + `Spree.api.product_serializer = 'MyApp::ProductSerializer'`
-### Serializer DSL
-
-- `typelize attr: :type` — define types for computed/delegated attributes
-- Use `Spree.api.serializer_name` for configurable serializer references
-- Customize serializers by inheriting from the default and configuring via `Spree.api`:
-
-```ruby
-# Custom serializer
-module MyApp
- class ProductSerializer < Spree::Api::V3::ProductSerializer
- attribute :custom_field
- end
-end
-
-# Configure in initializer
-Spree.api.product_serializer = 'MyApp::ProductSerializer'
-```
-
-### TypeScript Type Generation
-
-We use [typelizer](https://github.com/skryukov/typelizer) to generate TypeScript types from Alba serializers:
-
-- Types are generated to `sdk/src/types/generated/`
-- Store types: `StoreProduct`, `StoreOrder`, etc.
-- Admin types: `AdminProduct`, `AdminOrder`, etc.
-- Run `bundle exec rake typelizer:generate` to regenerate types every time you make changes to serializers
-
-### API Authentication
-
-- **Publishable API keys** (`spree_pk_xxx`) — used for Store API, passed via `Authorization: Bearer` header
-- **Secret API keys** (`sk_xxx`) — used for Admin API, passed via `Authorization: Bearer` header
-- **User authentication** — JWT tokens, passed via `Authorization: Bearer <token>` header
-- **Guest cart tokens** — passed via `X-Spree-Token` header for guest checkout
-
-```ruby
-# Creating API keys
-store_api_key = Spree::ApiKey.create!(name: 'My Storefront', key_type: :publishable, store: Spree::Current.store)
-admin_api_key = Spree::ApiKey.create!(name: 'Admin Integration', key_type: :secret, store: Spree::Current.store)
-```
-
-### OpenAPI generation
-
-Store API Open API specitication is generated using rswag gem, and stored in `docs/api-reference/store.yaml` file.
-To generate the OpenAPI specification, run the following command:
-
-```bash
-bundle exec rake rswag:specs:swaggerize
-```
-
-It will use Rspec integration tests from `spree/api/spec/integration`.
-
-## Events System
-
-When adding new functionality that other parts of the system (or external integrations) might need to react to, fire events using Spree's event system:
+### Events System
```ruby
order.publish_event('order.completed')
```
-Place subscriber classes in `app/subscribers/spree/` directory:
+Subscribers go in `app/subscribers/spree/`:
-```ruby app/subscribers/spree/order_completed_subscriber.rb
+```ruby
module Spree
class OrderCompletedSubscriber < Spree::Subscriber
subscribes_to 'order.complete'
def handle(event)
- order_id = event.payload['id']
- order = Spree::Order.find_by_prefix_id(order_id)
+ order = Spree::Order.find_by_prefix_id(event.payload['id'])
return unless order
-
- # Your custom logic here
ExternalService.notify_order_placed(order)
end
end
end
```
-For new models that publish events, please add `publishes_lifecycle_events` concern to the model.
-
-You also need to create an event serializer for the model, see [Events](docs/developer/core-concepts/events.mdx) for more details.
-
-## Dependencies System
-
-When building services that users might want to swap out, register them in `Spree::Dependencies`:
-
-```ruby
-# In the dependency configuration
-Spree::Dependencies.cart_add_item_service = 'Spree::Cart::AddItem'
-```
-
-This allows users to replace services without modifying core code.
+For new models, add `publishes_lifecycle_events` concern and create an event serializer.
-## Admin Development
+### API Authentication
-When adding new resources to the admin, you need to register tables and navigation.
+- **Publishable keys** (`pk_xxx`) — Store API, via `X-Spree-API-Key` header
+- **Secret keys** (`sk_xxx`) — Admin API, via `X-Spree-API-Key` header
+- **JWT tokens** — user auth, via `Authorization: Bearer <token>` header
+- **Guest cart tokens** — via `X-Spree-Token` header
-### Admin Tables
+### Dependencies System
-For rendering records lists in Admin always use [Admin Tables](docs/developer/admin/tables.mdx)
-Register new tables in `admin/config/initializers/spree_admin_tables.rb`:
+Register swappable services in `Spree::Dependencies`:
```ruby
-Rails.application.config.after_initialize do
- # Register the table
- Spree.admin.tables.register(:gift_cards, model_class: Spree::GiftCard, search_param: :multi_search)
-
- # Add columns
- Spree.admin.tables.gift_cards.add :code,
- label: :code,
- type: :string,
- sortable: true,
- filterable: true,
- default: true,
- position: 10
-
- Spree.admin.tables.gift_cards.add :balance,
- label: :balance,
- type: :currency,
- sortable: true,
- default: true,
- position: 20
-
- Spree.admin.tables.gift_cards.add :status,
- label: :status,
- type: :custom,
- filter_type: :status,
- sortable: true,
- filterable: true,
- default: true,
- position: 30,
- partial: 'spree/admin/tables/columns/gift_card_status'
-end
+Spree::Dependencies.cart_add_item_service = 'Spree::Cart::AddItem'
```
-Column types: `:string`, `:currency`, `:date`, `:datetime`, `:boolean`, `:custom` (requires `partial`)
-
-### Admin Navigation
+### Security
-Register navigation items in `admin/config/initializers/spree_admin_navigation.rb`:
-
-```ruby
-Rails.application.config.after_initialize do
- # Sidebar navigation
- sidebar_nav = Spree.admin.navigation.sidebar
-
- # Simple item
- sidebar_nav.add :reports,
- label: :reports,
- url: :admin_reports_path,
- icon: 'chart-bar',
- position: 60,
- if: -> { can?(:manage, Spree::Report) }
-
- # Item with submenu
- sidebar_nav.add :products,
- label: :products,
- url: :admin_products_path,
- icon: 'package',
- position: 30,
- if: -> { can?(:manage, Spree::Product) } do |products|
-
- products.add :price_lists,
- label: :price_lists,
- url: :admin_price_lists_path,
- position: 10,
- if: -> { can?(:manage, Spree::PriceList) }
-
- products.add :stock,
- label: :stock,
- url: :admin_stock_items_path,
- position: 20,
- if: -> { can?(:manage, Spree::StockItem) }
- end
+- CanCanCan permission checks on all actions
+- `Spree::PermittedAttributes` for parameter allowlists
+- Use `Spree.user_class` / `Spree.admin_user_class` — never reference user models directly
+- Use `spree.` route engine prefix in views and controllers
- # Settings navigation
- settings_nav = Spree.admin.navigation.settings
-
- settings_nav.add :payment_methods,
- label: :payments,
- url: :admin_payment_methods_path,
- icon: 'credit-card',
- position: 70,
- active: -> { controller_name == 'payment_methods' },
- if: -> { can?(:manage, Spree::PaymentMethod) }
-
- # Tab navigation (for pages with tabs)
- tax_tabs_nav = Spree.admin.navigation.tax_tabs
-
- tax_tabs_nav.add :tax_rates,
- label: :tax_rates,
- url: :admin_tax_rates_path,
- position: 10,
- if: -> { can?(:manage, Spree::TaxRate) }
-end
-```
+### Performance
-Navigation options:
-- `label` - Translation key or string
-- `url` - Route helper symbol or lambda
-- `icon` - Tabler icon name (see https://tabler.io/icons)
-- `position` - Sort order (lower = higher)
-- `if` - Lambda for conditional display
-- `active` - Lambda for active state detection
-- `badge` - Lambda returning badge text
-- `badge_class` - CSS class for badge
+- Use `includes`/`preload` to avoid N+1 queries (`ar_lazy_preload` gem also active)
+- Use `Rails.cache` for expensive operations; use `cache_key_with_version` for custom keys
+- Proper database indexing
-## Testing
+### I18n
-Always run tests before committing changes. Always run tests after making changes.
+- Use `Spree.t` for translations
+- Keep translations in `config/locales/en.yml` — no duplication across files
-### Test Application
+### Documentation
-To run tests you need to create test app with `bundle exec rake test_app` in every gem directory (eg. admin, api, core, etc.)
+- Re-generate OpenAPI spec after API changes: `bundle exec rake rswag:specs:swaggerize`
+- OpenAPI spec: `docs/api-reference/store.yaml` (generated from `spree/api/spec/integration`)
+- Update developer docs in `docs/developer/` when relevant
-This will create a dummy rails application and run migrations. If there's already a dummy app in the gem directory, you can skip this step.
+---
-### Test Structure
+## Frontend (TypeScript)
-- Use RSpec for testing and Factory Bot for creating test data
-- As much as you can use build vs create for Factories to speed up tests
-- Be very pragmatic, and don't over-engineer tests, don't repeat same tests in multiple places, tests must be fast
-- Create test app with `bundle exec rake test_app` in every gem directory (eg. admin, api, core, etc.)
-- Place specs in appropriate directories matching app structure
-- For controller specs always add `render_views` to the test
-- For controller spec authentication use `stub_authorization!`
-- Don't create test scenarios for standard rails validation, only for custom validations
-- For time-based testing / operations use `Timecop` gem
-- Be pragmatic, and don't over-engineer tests, don't repeat same tests in multiple places
+### Workspace Setup
-```ruby
-# ✅ Proper spec structure
-require 'spec_helper'
-
-RSpec.describe Spree::Product, type: :model do
- let(:product) { create(:product) }
-
- describe '#custom_method' do
- it 'returns expected result' do
- expect(product.custom_method).to eq('EXPECTED')
- end
- end
-end
-```
+Managed with **pnpm** workspace + **Turbo** for task orchestration. All packages use **Tsup** for building and **Vitest** for testing.
-### Factory Usage
-
-- Use `create` for persisted objects in tests
-- Use `build` for non-persisted objects, recommended as it's much faster than `create`
-- Add new factories in `lib/spree/testing_support/factories/`
-
-```ruby
-# ✅ Proper factory usage
-let(:product) { create(:product, name: 'Test Product') }
-let(:variant) { build(:variant, product: product) }
+```bash
+pnpm install # install all workspace deps
+pnpm build # build all packages (Turbo-cached)
+pnpm test # run all package tests
+pnpm typecheck # TypeScript validation across all packages
```
-## Security
-
-### Authentication & Authorization
+### @spree/sdk — Store API Client
-- Follow Rails Security Guide principles
-- Define permissions in Permission Sets, see [Permissions](/docs/developer/customization/permissions.mdx) for more details
-- Implement proper authorization checks with CanCanCan
-- Validate all user inputs
-- In Admin controllers inheriting from `Spree::Admin::ResourceController` will automatically secure all actions
-- Authentication is handled by app developers, by default we provide Devise installer, always use `Spree.user_class` to access the user model for Customers and `Spree.admin_user_class` to access the user model for Admins
+TypeScript SDK for the customer-facing Store API v3.
-### Parameter Security
+**Structure:**
+- `src/client.ts` — `createClient()` factory, `ClientConfig` interface
+- `src/store-client.ts` — all REST endpoints as resource classes (`client.products.list()`, `client.carts.create()`, etc.)
+- `src/types/generated/` — auto-generated TypeScript types from Alba serializers
+- `src/zod/generated/` — auto-generated Zod schemas for runtime validation
-- Never permit mass assignment without validation
-- Spree uses `Spree::PermittedAttributes` to define allowed parameters for each resource globally
-- Use allowlists, not blocklists for parameters
-- Sanitize user inputs appropriately
+**Patterns:**
+- Flat resource pattern: `client.products.list()`, `client.carts.items.create()`
+- Auth modes: publishable key (guest), JWT (customer)
+- Automatic retry with exponential backoff
+- `SpreeError` class with code, status, details
+- Ransack query params transformed via `transformListParams()` in sdk-core
-## Database & Migrations
+**Testing:** Vitest + MSW (Mock Service Worker) for HTTP mocking. Tests in `tests/`.
-### Migration Patterns
-
-- Follow Rails migration conventions
-- Use proper indexing for performance
-- Do not include foreign key constraints
-- Use descriptive migration names with timestamps
-- Try to limit number of migrations to 1 per feature
-- Avoid using default values in migrations
-- Always add `null: false` to required columns
-- Always try to combine multiple migrations into one if possible when developing a new feature
-- If new feature require transformation of existing data please add a rake task to do the transformation, never do it in a migration
-- Add unique indexes to columns that are used for uniqueness validation
-- By default add `deleted_at` column to all tables that have soft delete functionality (we use `paranoia` gem)
-- For migrations please use 7.2 as the target version as we still support Rails 7.2
-
-```ruby
-# ✅ Proper migration structure
-class CreateSpreeMetafields < ActiveRecord::Migration[7.2]
- def change
- create_table :spree_metafields do |t|
- t.string :key, null: false
- t.text :value, null: false
- t.string :kind, null: false
- t.string :visibility, null: false
- t.references :resource, polymorphic: true, null: false
- t.timestamps
- end
-
- add_index :spree_metafields, [:resource_type, :resource_id, :key, :visibility],
- name: 'index_spree_metafields_on_resource_and_key_and_visibility'
- end
-end
+```bash
+cd packages/sdk
+pnpm build # tsup build (CJS + ESM)
+pnpm test # vitest
+pnpm generate:zod # regenerate Zod schemas from TS types
+pnpm typecheck
```
-### Database Design
+### @spree/admin-sdk — Admin API Client
-- Use appropriate column types and constraints
-- Implement proper foreign key relationships
-- Consider indexing for query performance
-- Use polymorphic associations when appropriate
+Same patterns as `@spree/sdk` but for the Admin API. Supports both secret key (server-to-server) and JWT (admin SPA) authentication. Private package.
-## Frontend Development
+### @spree/sdk-core — Shared HTTP Layer
-### Admin Interface
+Private package providing `createRequestFn()`, `SpreeError`, retry logic, and Ransack param transformation. Used internally by both SDKs.
-- Use Spree's admin styling conventions
-- Use as much as possible Turbo Rails features (Hotwire)
-- Use Stimulus controllers for JavaScript interactions
-- Please use [Admin Components](docs/developer/admin/components.mdx) for elements such as dialogs, drawers, dropdowns, and more.
-- Please use [Spree::Admin::FormBuilder](docs/developer/admin/form-builder.mdx) methods for form fields
-- For rendering record lists please use [Admin Tables](docs/developer/admin/tables.mdx)
+### @spree/next — Next.js Integration
-For create new resource form:
+Server actions, data helpers, cookie-based auth, and middleware for Next.js 15+ / React 19+.
-```erb
-<!-- ✅ Proper admin form structure -->
-<%= render 'spree/admin/shared/new_resource' %>
-```
+**Structure:**
+- `src/config.ts` — `initSpreeNext()`, `getClient()` singleton (auto-inits from `SPREE_API_URL` + `SPREE_PUBLISHABLE_KEY` env vars)
+- `src/actions/` — `"use server"` mutations: cart, auth, addresses, orders, payments, locale
+- `src/data/` — pure async read functions: products, categories, countries, currencies, locales, markets
+- `src/cookies.ts` — HTTPOnly cookie management (cart token, JWT, locale)
+- `src/auth-helpers.ts` — `withAuthRefresh()` for automatic 401 → token refresh → retry
+- `src/middleware.ts` — `createSpreeMiddleware()` for route-based locale/country detection
-For edit resource form:
+**Patterns:**
+- Data functions (`src/data/`) are pure reads — apps wrap with React 19 `"use cache"` as needed
+- Server actions (`src/actions/`) handle mutations + automatic auth refresh
+- Cookie auth: separate tokens for cart (guest) and JWT (customer)
-```erb
-<%= render 'spree/admin/shared/edit_resource' %>
-```
+**Testing:** Vitest. Tests in `tests/`.
-And the re-usable form partial should be in `app/views/spree/admin/products/_form.html.erb`, eg.
-
-```erb
-<div class="card mb-6">
- <div class="card-header">
- <h5 class="card-title">
- <%= Spree.t(:general_settings) %>
- </h5>
- </div>
-
- <div class="card-body">
- <%= f.spree_text_field :name %>
- <%= f.spree_rich_text_area :description %>
- <%= f.spree_check_box :active %>
- </div>
-</div>
+```bash
+cd packages/next
+pnpm build # tsup (ESM only, 3 build configs)
+pnpm test
+pnpm typecheck
```
-## Performance & Best Practices
+**Peer deps:** `@spree/sdk >= 0.10.1`, `next >= 15.0.0`, `react >= 19.0.0`
-### Query Optimization
+### Type Generation Pipeline
-- We're using ar_lazy_preload gem to avoid N+1 queries, however please use includes/preload to avoid N+1 queries as much as possible
-- Implement proper database indexing
-- Use scopes for reusable query logic
-- Consider caching for expensive operations
+When changing Alba serializers, run the full pipeline:
-```ruby
-# ✅ Optimized queries
-products = Spree::Product.includes(:variants, :thumbnail)
- .where(available_on: ..Time.current)
- .order(:name)
+```bash
+cd spree/api && bundle exec rake typelizer:generate # 1. TS types from serializers
+cd packages/sdk && pnpm generate:zod # 2. Zod schemas from TS types
+cd spree/api && bundle exec rspec spec/integration/ # 3. Integration tests
+bundle exec rake rswag:specs:swaggerize # 4. OpenAPI spec
+cd packages/sdk && pnpm test # 5. SDK tests
```
-### Caching
+- TypeScript types → `packages/sdk/src/types/generated/` (Store) and `packages/admin-sdk/src/types/generated/` (Admin)
+- Zod schemas → `packages/sdk/src/zod/generated/`
+- Store types: `StoreProduct`, `StoreOrder`, etc. Admin types: `AdminProduct`, `AdminOrder`, etc.
-- Use Rails caching mechanisms appropriately (via `Rails.cache`)
-- Cache expensive calculations and queries, however caching one query is not recommended
-- Implement cache invalidation strategies, use Rails `cache_key_with_version` when constructing custom cache keys
-- Consider fragment caching for views
+### Changesets & Versioning
-### Code Quality
+Published packages use **Changesets** for versioning. Place changeset files in the package's `.changeset/` directory.
-- Follow Ruby style guidelines
-- Keep methods small and focused
-- Use meaningful variable and method names
-- Write self-documenting code with appropriate comments
-- Avoid deep nesting and complex conditionals
-- Avoid business logic in controllers, move that to models and use concerns
-- Use services only when necessary, we should as much as we possible use standard Rails models and Concerns
-- Use concerns for reusable code
+---
-## Documentation & Comments
+## Testing
-### Code Documentation
+Always run tests before committing changes.
-- Document complex business logic
-- Explain non-obvious code patterns
-- Use YARD documentation format for public APIs
-- Keep comments up-to-date with code changes
-- Please check and update documentation in docs/developer
-- Always re-generate OpenAPI documentation using rswag when changing API
+### Backend (Ruby — RSpec)
-## Error Handling
+Each engine has its own test suite:
-### Exception Management
+```bash
+cd spree && bundle install # shared deps
+cd core && bundle install # engine deps
+bundle exec rake test_app # create dummy Rails app (skip if already exists)
+bundle exec rspec # run full suite
+bundle exec rspec spec/models/spree/state_spec.rb # single file
+bundle exec rspec spec/models/spree/state_spec.rb:7 # single test
+```
-- Use Rails error reporter - https://guides.rubyonrails.org/error_reporting.html
-- Use appropriate exception classes
-- Provide meaningful error messages
-- Implement proper error recovery where possible
+Default DB is SQLite3. For PostgreSQL:
-```ruby
-# ✅ Proper error handling
-def process_payment
- payment_service.call
-rescue Spree::PaymentProcessingError => e
- Rails.error.report e
- flash[:error] = I18n.t('spree.payment_processing_failed')
- false
-end
+```bash
+DB=postgres DB_USERNAME=postgres DB_PASSWORD=password DB_HOST=localhost bundle exec rake test_app
```
-This document should be updated as Spree evolves and new patterns emerge. Always refer to the official Spree documentation for the most current practices and guidelines.
+**Parallel runs:**
-## Routes
+```bash
+bundle exec rake parallel_setup # create worker DBs
+bundle exec parallel_rspec spec # run in parallel
+bundle exec parallel_rspec -n 4 spec # with worker count
+```
-- Always use `spree.` routes engine when using routes in views and controllers
+Re-run `parallel_setup` after schema changes.
-## Internationalization
+**Test guidelines:**
+- RSpec + Factory Bot
+- Prefer `build` over `create` for speed
+- Factories live in `lib/spree/testing_support/factories/`
+- Pragmatic — no tests for standard Rails validations, only custom ones
+- Controller specs: always add `render_views`, use `stub_authorization!` for auth
+- Time-based tests: use `Timecop`
+- Don't over-engineer or repeat tests
-- Use Rails 18n for internationalization
-- Use `Spree.t` for translations
-- Please keep admin translations in `admin/config/locales/en.yml`
-- Please keep all other translations in `config/locales/en.yml`
-- Please do not repeat translations in multiple files, use `Spree.t` instead
-- Please try to use existing translations as much as possible
+### Frontend (TypeScript — Vitest)
+
+```bash
+cd packages/sdk && pnpm test # SDK tests (uses MSW for HTTP mocking)
+cd packages/next && pnpm test # Next.js helper tests
+```
diff --git a/docs/plans/5.x-store-api-bridges.md b/docs/plans/5.x-store-api-bridges.md
new file mode 100644
index 0000000000..739f65d640
--- /dev/null
+++ b/docs/plans/5.x-store-api-bridges.md
@@ -0,0 +1,231 @@
+# Store API 5.x Bridges for 6.0
+
+**Status:** Design finalized, implementation not started
+**Target:** Spree 5.5 (next minor)
+**Depends on:** None — all changes are serializer/controller renames on existing models
+**Author:** Damian + Claude
+**Last updated:** 2026-03-16
+
+## Summary
+
+Introduce 6.0 Store API naming NOW in 5.5, with breaking changes. No aliases, no deprecation periods — clean breaks. This gives storefront developers the final API shape before models are renamed in 6.0.
+
+The approach: change the **API surface** (serializers, response keys, endpoint paths) in 5.x while the **models** stay unchanged until 6.0. Serializers are the translation layer.
+
+## Scope
+
+Only changes where the API field/endpoint name changes between 5.x and 6.0. Purely additive features (new endpoints, new fields, new resources) ship with their 6.0 plan and don't need bridging.
+
+## Changes
+
+### 1. Remove master_variant, use default_variant only
+
+**Plan:** `6.0-remove-master-variant.md`
+
+Already done in current API:
+- `default_variant_id` field on ProductSerializer ✓
+- `expand=default_variant` on ProductSerializer ✓
+
+Remove now (5.5):
+- Remove `expand=master_variant` from ProductSerializer
+- Remove `is_master` field from VariantSerializer
+
+```ruby
+# ProductSerializer — REMOVE:
+one :master,
+ key: :master_variant,
+ resource: Spree.api.variant_serializer,
+ if: proc { expand?('master_variant') }
+
+# VariantSerializer — REMOVE:
+# is_master attribute (no longer exposed)
+```
+
+**SDK:** Remove `StoreVariant.is_master` from TypeScript types. Remove `expand=master_variant` from SDK methods.
+
+### 2. Shipments → Fulfillments, Shipping → Delivery
+
+**Plan:** `6.0-fulfillment-and-delivery.md`
+
+Rename in serializers (model stays `Shipment` until 6.0):
+
+| Before (5.4) | After (5.5) | Serializer change |
+|---|---|---|
+| `shipments` (nested in Cart/Order) | `fulfillments` | Change `key:` on association |
+| `shipping_rates` (nested in Shipment) | `delivery_rates` | Change `key:` on association |
+| `shipping_method` (nested in ShipmentSerializer) | `delivery_method` | Change `key:` on association |
+| `ShipmentSerializer` fields: `state`, `tracking`, `shipped_at` | `status`, `tracking`, `fulfilled_at` | Rename attributes |
+| `ShippingMethodSerializer` | Rename to `DeliveryMethodSerializer` | New file, delegates to same model |
+| `ShippingRateSerializer` | Rename to `DeliveryRateSerializer` | New file, delegates to same model |
+| `shipment_state` (on Order) | `fulfillment_status` | Rename attribute |
+| `ship_total` / `display_ship_total` (on Cart/Order) | `delivery_total` / `display_delivery_total` | Rename attributes |
+
+**New fields added:**
+- `fulfillment_type` on ShipmentSerializer (returns `'shipping'` or `'digital'` based on current shipping method)
+- `fulfilled_at` (alias for `shipped_at`)
+
+**Endpoint renames:**
+```
+# Before
+GET/PATCH /api/v3/store/carts/:id/shipments
+# After
+GET/PATCH /api/v3/store/carts/:id/fulfillments
+```
+
+Rename controller file: `Carts::ShipmentsController` → `Carts::FulfillmentsController`.
+
+```ruby
+# routes
+namespace :carts do
+ resources :fulfillments, only: [:index, :update]
+end
+```
+
+**Cart/Order serializer changes:**
+
+```ruby
+# CartSerializer — rename keys
+many :shipments, # model association unchanged
+ key: :fulfillments, # API key changes
+ resource: Spree.api.shipment_serializer # serializer handles field renames
+
+# Rename money fields
+attribute :delivery_total do |order|
+ order.shipment_total
+end
+attribute :display_delivery_total do |order|
+ Spree::Money.new(order.shipment_total, currency: order.currency).to_s
+end
+# Remove: ship_total, display_ship_total
+```
+
+**SDK:** Rename `StoreShipment` → `StoreFulfillment`, `StoreShippingMethod` → `StoreDeliveryMethod`, `StoreShippingRate` → `StoreDeliveryRate`. Update `client.carts.shipments` → `client.carts.fulfillments`.
+
+### 3. State → Status everywhere
+
+**Plan:** `6.0-normalize-state-to-status.md`
+
+Models still use `state` column until 6.0. Serializers translate:
+
+| Serializer | Before (5.4) | After (5.5) |
+|---|---|---|
+| ShipmentSerializer | `state` | `status` (reads `object.state`) |
+| PaymentSerializer | `state` | `status` (reads `object.state`) |
+| GiftCardSerializer | `state` | `status` (reads `object.state`) |
+| OrderSerializer | `shipment_state` | `fulfillment_status` (reads `object.shipment_state`) |
+| OrderSerializer | `payment_state` | `payment_status` (reads `object.payment_state`) |
+
+```ruby
+# ShipmentSerializer (becoming FulfillmentSerializer in API)
+attribute :status do |shipment|
+ shipment.state
+end
+# Remove: state attribute
+
+# OrderSerializer
+attribute :fulfillment_status do |order|
+ order.shipment_state
+end
+attribute :payment_status do |order|
+ order.payment_state
+end
+# Remove: shipment_state, payment_state attributes
+```
+
+**SDK:** Rename `state` → `status` on `StoreFulfillment`, `StorePayment`, `StoreGiftCard`. Rename `shipment_state` → `fulfillment_status`, `payment_state` → `payment_status` on `StoreOrder`.
+
+### 4. Adjustment totals naming
+
+**Plan:** `6.0-split-adjustments.md`
+
+The model split (Adjustment → TaxLine, Discount, Fee) happens in 6.0. But the serialized totals can be renamed now for clarity:
+
+| Before (5.4) | After (5.5) | On |
+|---|---|---|
+| `adjustment_total` | `adjustment_total` | Cart/Order — **keep as-is** (sum of all adjustments) |
+| `ship_total` / `display_ship_total` | `delivery_total` / `display_delivery_total` | Cart/Order (covered in #2 above) |
+
+**Add new field:**
+- `fee_total` / `display_fee_total` on Cart/Order (returns `0` until Fee model exists in 6.0)
+
+`adjustment_total` stays — it's a genuine total across all adjustment types and renaming it would break every storefront's price breakdown display without adding clarity.
+
+### 5. Classification → ProductCategory (naming only)
+
+**Plan:** `6.0-replace-taxons-with-categories.md`
+
+The Store API already uses `categories` naming. No serializer changes needed. The `Classification` model rename is internal.
+
+## Migration Checklist
+
+### File renames (5.5)
+
+```
+# Serializers
+shipment_serializer.rb → fulfillment_serializer.rb
+shipping_method_serializer.rb → delivery_method_serializer.rb
+shipping_rate_serializer.rb → delivery_rate_serializer.rb
+media_serializer.rb — already done in 5.4 ✓
+
+# Controllers
+carts/shipments_controller.rb → carts/fulfillments_controller.rb
+
+# Serializer field changes (no file rename, just content)
+cart_serializer.rb — rename nested keys (fulfillments, delivery_total)
+order_serializer.rb — rename fields (fulfillment_status, payment_status, delivery_total)
+product_serializer.rb — remove master_variant expand
+variant_serializer.rb — remove is_master
+payment_serializer.rb — state → status
+gift_card_serializer.rb — state → status
+```
+
+### Route renames (5.5)
+
+```
+/carts/:id/shipments → /carts/:id/fulfillments
+```
+
+### SDK type renames (5.5)
+
+```
+StoreShipment → StoreFulfillment
+StoreShippingMethod → StoreDeliveryMethod
+StoreShippingRate → StoreDeliveryRate
+StoreVariant.is_master → removed
+StoreOrder.shipment_state → StoreOrder.fulfillment_status
+StoreOrder.payment_state → StoreOrder.payment_status
+StoreOrder.ship_total → StoreOrder.delivery_total
+```
+
+### Pipeline after changes
+
+```bash
+cd spree/api && bundle exec rake typelizer:generate # regenerate TS types
+cd packages/sdk && pnpm generate:zod # regenerate Zod schemas
+cd spree/api && bundle exec rspec spec/integration/ # integration tests
+bundle exec rake rswag:specs:swaggerize # OpenAPI spec
+cd packages/sdk && pnpm test # SDK tests
+cd packages/next && pnpm test # Next.js tests
+```
+
+## What stays unchanged (bridges already done or not needed)
+
+| Feature | Status |
+|---|---|
+| `images` → `media` | Done in 5.4 (PR #13778) ✓ |
+| `taxons` → `categories` | Already using `categories` in API ✓ |
+| `expand=default_variant` | Already exists ✓ |
+| `default_variant_id` on products | Already exists ✓ |
+| ProductType, Collections, Stock Reservations, Returns/Claims, Channels/Catalogs | Purely additive — ship with 6.0 |
+
+## Constraints on Current Work
+
+- **All new Store API code must use the 5.5 naming.** No `shipment`, `shipping_method`, `state`, `master_variant` in new endpoints.
+- **SDK examples and docs must use new naming** after this ships.
+- **Admin API is not affected by this plan.** Admin serializers may keep old naming until 6.0 model renames happen (or can be bridged separately).
+
+## References
+
+- Prior art: `5.4-6.0-product-media-system.md` (same bridge pattern: API naming changed in 5.4, model renamed in 6.0)
+- All 6.0 plans in `docs/plans/6.0-*.md`
+- Store API inventory: 32 endpoint groups, 56 serializers
diff --git a/docs/plans/6.0-admin-spa.md b/docs/plans/6.0-admin-spa.md
new file mode 100644
index 0000000000..5b5a6d7fb4
--- /dev/null
+++ b/docs/plans/6.0-admin-spa.md
@@ -0,0 +1,41 @@
+# Admin SPA
+
+**Status:** Design finalized, implementation not started
+**Target:** Spree 6.0
+**Depends on:** API v3 conventions
+
+## Key Decisions (do not deviate without discussion)
+- Drop thee rails admin panel entirely
+- Create new Vite/TanStack React admin UI
+- Use Admin API and Admin SDK
+- Use Shadcn UI components
+- No server-side rendering
+
+## Migration Path
+- Remove `spree/admin` engine
+- Create new `packages/admin`
+
+## Architecture
+
+We should use conventions when handling forms, lists, and other UI components to reduce boilerplate and make it easier for developers to extend the admin dashboard.
+
+* Build & Dev: Vite (obvious choice for a pure client-side SPA — fast HMR, clean config, outputs static files you can bundle into the Rails gem or deploy standalone)
+* Routing: TanStack Router — type-safe routes, file-based convention, built-in loader pattern pairs perfectly with TanStack Query for prefetching on navigation
+* Data Fetching: TanStack Query — handles caching, background refetches, optimistic updates. Your @spree/admin-sdk becomes the query function layer. Wrap SDK methods as custom hooks (useProducts, useOrder, etc.)
+* Forms: React Hook Form + Zod for validation schemas. Zod schemas can mirror your API contracts, and if you're auto-generating types from OpenAPI specs, you can derive Zod schemas from the same source
+* UI: shadcn/ui + Tailwind. Copy-paste ownership model means your plugin authors can extend or override components without fighting a component library's abstraction
+* Auth: For JWT — store the access token in memory (React context/state), refresh token in an httpOnly cookie if possible, or memory as fallback. TanStack Router's beforeLoad guards check auth state before rendering protected routes. A simple AuthProvider context that exposes login(), logout(), getToken() and injects the token into the SDK client instance
+* State: You likely don't need a global state library. TanStack Query covers server state, React Hook Form covers form state, and a small AuthContext covers the session. If something edges toward complex client-only state later, Zustand is the lightest option that won't fight you
+* Linting/Formatting: Biome — single tool, fast, no ESLint/Prettier config sprawl
+* Testing: Vitest + React Testing Library for unit/integration, Playwright for E2E
+
+## Extension points
+
+Developers will be able to extend the admin dashboard by adding custom pages, components, and logic.
+
+There are 3 main areas where developers can extend the admin dashboard:
+
+1. Navigation - needs to be configurable via registry
+2. Tables - record listing, eg. products, orders. Developers need to be able to customize table columns and filters.
+3. Pages - developers should be able to add custom pages, extend routes, and add custom logic.
+3. Components - developers should be able to add custom components and extend existing ones. Developers should be able to inject their own components into existing pages, eg. new fields on product form page.
diff --git a/docs/plans/6.0-cart-order-split.md b/docs/plans/6.0-cart-order-split.md
new file mode 100644
index 0000000000..5348491939
--- /dev/null
+++ b/docs/plans/6.0-cart-order-split.md
@@ -0,0 +1,22 @@
+# Cart/Order Split
+
+**Status:** Design finalized, implementation not started
+**Target:** Spree 6.0
+**Depends on:** API v3 conventions
+
+## 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
+
+## 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
+
+## 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
diff --git a/docs/plans/6.0-channels-catalogs-b2b.md b/docs/plans/6.0-channels-catalogs-b2b.md
new file mode 100644
index 0000000000..1fbf21f958
--- /dev/null
+++ b/docs/plans/6.0-channels-catalogs-b2b.md
@@ -0,0 +1,595 @@
+# Channels, Catalogs & B2B Companies
+
+**Status:** Draft
+**Target:** Spree 6.0
+**Depends on:** ProductType (6.0-product-types.md), PriceList system (existing)
+**Author:** Damian + Claude
+**Last updated:** 2026-03-16
+
+## Summary
+
+Add three new concepts to Spree's multi-store architecture:
+
+- **Channel** — lightweight distribution surface within a Store (online, POS, Meta, wholesale portal). Controls where products are sold and how orders are attributed.
+- **Catalog** — product assortment + optional pricing override. Controls what's available and at what price for a specific audience (B2B tier, VIP group, regional assortment).
+- **Company** — B2B customer hierarchy (Company → CompanyLocation → CompanyContact) for businesses with multiple buyers and offices.
+
+`StoreProduct` is replaced by **ProductListing** — the join between Product and Channel that says "this product is listed on this channel."
+
+## Problem
+
+1. **No product visibility control within a store.** `StoreProduct` is binary — a product is in a store or it isn't. There's no way to say "this product is on the online store but not the POS" or "wholesalers see these 500 SKUs, retail sees 2000."
+
+2. **No order attribution.** `Order.channel` exists as a free-text varchar but isn't connected to any model. You can't query "all POS orders this month" reliably or configure channel-specific behavior.
+
+3. **No B2B company hierarchy.** `CustomerGroup` exists for user segmentation and pricing, but there's no way to model "Acme Corp has 3 offices, each with its own buyers, shipping addresses, and catalog assignments." B2B merchants need Company → Location → Contact.
+
+4. **PriceList lacks a visibility counterpart.** PriceList controls pricing, but there's no matching concept for product visibility. A wholesaler needs both different prices AND a different product assortment.
+
+## Current State
+
+| What exists | What it does | Gap |
+|---|---|---|
+| `Store` | Config boundary — currency, tax, payments, fulfillment | Heavy, covers too much. No sub-store scoping. |
+| `Market` | Geographic/currency region within a store | Read-only regions, no product visibility control |
+| `StoreProduct` | Product ↔ Store join (binary visibility) | No channel/catalog dimension |
+| `CustomerGroup` | User segmentation within a store | No company hierarchy |
+| `PriceList` + `PriceRules` | Conditional pricing (customer group, market, zone, volume, user) | No visibility counterpart |
+| `Order.channel` | Free-text varchar | Not an FK, not a model |
+
+## Architecture
+
+Four concerns, four models:
+
+```
+Store (who you are — legal entity, config boundary)
+ → Channels (where you sell — online, POS, Meta, wholesale)
+ → ProductListings (which products are listed on this channel)
+ → Catalogs (what you sell at what price — assortment + optional PriceList)
+ → CatalogProducts (which products are in this catalog)
+ → PriceList (optional pricing override — existing model)
+ → Markets (where your customers are — geography, currency — existing)
+ → Companies (B2B — who your business customers are)
+ → CompanyLocations (offices/branches with addresses)
+ → CompanyContacts (buyers — linked to user accounts)
+```
+
+**How they compose:**
+
+- A **Channel** has a default Catalog (all listed products, base prices)
+- A **Channel** can have additional Catalogs assigned to CustomerGroups or CompanyLocations
+- A **Market** can have a default Catalog (regional assortment)
+- A **CompanyLocation** can have assigned Catalogs (B2B per-location assortment + pricing)
+
+**Product visibility resolution:**
+
+```
+1. Request arrives with: store, channel, user (optional)
+2. Base set: ProductListings for this channel
+3. If user belongs to a CompanyLocation with Catalogs:
+ → Intersect with CatalogProducts from those Catalogs
+4. Else if user belongs to a CustomerGroup with a Catalog:
+ → Intersect with CatalogProducts from that Catalog
+5. Else: show all channel listings (default catalog)
+```
+
+**Price resolution (extends existing Pricing::Resolver):**
+
+```
+1. Check Catalog's PriceList (if Catalog has one)
+2. Check other applicable PriceLists (existing PriceRule system)
+3. Fall back to base price
+```
+
+## Key Decisions (do not deviate without discussion)
+
+### Channel
+
+- **Lightweight model** — not a config container. Store owns heavyweight config (currency, tax, payment methods, delivery methods). Channel is just a distribution surface.
+- **Belongs to Store** (SingleStoreResource). One store can have many channels.
+- **`Order.channel` becomes a FK** replacing the free-text varchar.
+- **Each Channel can have its own PublishableApiKey** — so a storefront app, a POS app, and a Meta integration each get their own key scoped to their channel.
+- **Default channel created per store** — "Online Store" is always present.
+
+### ProductListing (replaces StoreProduct)
+
+- **Replaces `StoreProduct`** — the table is renamed, the join now connects Product to Channel instead of Product to Store.
+- **Carries listing-specific data** — `listed_at`, `unlisted_at` (scheduled publishing), `position` (sort order per channel).
+- **Store-level scoping derived from Channel** — `store.products` goes through `store.channels → product_listings → products`. No direct Store → Product join needed.
+
+### Catalog
+
+- **Belongs to Store.** A catalog can be shared across channels within the same store.
+- **Has many CatalogProducts** (visibility) + optional **belongs_to PriceList** (pricing).
+- **Catalog without PriceList** = assortment-only (use base prices). Catalog with PriceList = assortment + pricing.
+- **Multiple Catalogs can apply** — when a CompanyLocation has 2 Catalogs, product visibility is the UNION of both. Pricing uses the first matching Catalog's PriceList (priority by position).
+- **Default Catalog per Channel** — optional. If set, only products in the default catalog are visible on that channel. If not set, all ProductListings are visible.
+
+### Company (B2B)
+
+- **Company → CompanyLocation → CompanyContact** hierarchy.
+- **Company** belongs to Store. Represents a business customer (Acme Corp).
+- **CompanyLocation** belongs to Company. Represents an office/branch. Has billing address, shipping address, tax exemption settings. Can have assigned Catalogs.
+- **CompanyContact** belongs to CompanyLocation. Links to a User (Spree.user_class). A user can be a contact at multiple locations.
+- **CustomerGroup is NOT replaced.** Companies and CustomerGroups serve different purposes: CustomerGroup is a flat segmentation tag (VIP, Wholesale). Company is a hierarchical B2B entity. A Company can be IN a CustomerGroup.
+
+## Design Details
+
+### Channel
+
+```ruby
+class Spree::Channel < Spree.base_class
+ has_prefix_id :ch
+
+ include Spree::SingleStoreResource
+ include Spree::Metafields
+ include Spree::Metadata
+
+ belongs_to :store, class_name: 'Spree::Store'
+ belongs_to :default_catalog, class_name: 'Spree::Catalog', optional: true
+
+ has_many :product_listings, class_name: 'Spree::ProductListing', dependent: :destroy
+ has_many :products, through: :product_listings
+ has_many :orders, class_name: 'Spree::Order', inverse_of: :channel
+ has_many :api_keys, class_name: 'Spree::ApiKey', as: :owner
+
+ validates :name, presence: true
+ validates :code, presence: true, uniqueness: { scope: :store_id }
+
+ scope :active, -> { where(active: true) }
+
+ attribute :active, :boolean, default: true
+end
+```
+
+### ProductListing (replaces StoreProduct)
+
+```ruby
+class Spree::ProductListing < Spree.base_class
+ has_prefix_id :pl
+
+ belongs_to :product, class_name: 'Spree::Product', touch: true
+ belongs_to :channel, class_name: 'Spree::Channel'
+
+ validates :product, :channel, presence: true
+ validates :product_id, uniqueness: { scope: :channel_id }
+
+ attribute :listed_at, :datetime
+ attribute :unlisted_at, :datetime
+
+ scope :active, -> {
+ where('listed_at IS NULL OR listed_at <= ?', Time.current)
+ .where('unlisted_at IS NULL OR unlisted_at > ?', Time.current)
+ }
+
+ # Carry over from StoreProduct
+ attribute :units_sold_count, :integer, default: 0
+ attribute :revenue, :decimal, default: 0
+
+ def active?
+ (listed_at.nil? || listed_at <= Time.current) &&
+ (unlisted_at.nil? || unlisted_at > Time.current)
+ end
+end
+```
+
+### Catalog
+
+```ruby
+class Spree::Catalog < Spree.base_class
+ has_prefix_id :cat
+
+ include Spree::SingleStoreResource
+ include Spree::Metafields
+ include Spree::Metadata
+
+ belongs_to :store, class_name: 'Spree::Store'
+ belongs_to :price_list, class_name: 'Spree::PriceList', optional: true
+
+ has_many :catalog_products, class_name: 'Spree::CatalogProduct', dependent: :destroy
+ has_many :products, through: :catalog_products
+
+ # Who sees this catalog
+ has_many :catalog_assignments, class_name: 'Spree::CatalogAssignment', dependent: :destroy
+
+ validates :name, presence: true
+
+ acts_as_list scope: :store_id
+
+ scope :active, -> { where(active: true) }
+
+ attribute :active, :boolean, default: true
+end
+```
+
+### CatalogProduct
+
+```ruby
+class Spree::CatalogProduct < Spree.base_class
+ belongs_to :catalog, class_name: 'Spree::Catalog', touch: true
+ belongs_to :product, class_name: 'Spree::Product'
+
+ validates :catalog, :product, presence: true
+ validates :product_id, uniqueness: { scope: :catalog_id }
+
+ acts_as_list scope: :catalog_id
+end
+```
+
+### CatalogAssignment (who sees this catalog)
+
+```ruby
+class Spree::CatalogAssignment < Spree.base_class
+ belongs_to :catalog, class_name: 'Spree::Catalog'
+
+ # Assignable: Channel, CustomerGroup, CompanyLocation, Market
+ belongs_to :assignable, polymorphic: true
+
+ validates :catalog, :assignable, presence: true
+ validates :catalog_id, uniqueness: { scope: [:assignable_type, :assignable_id] }
+end
+```
+
+Note: this is polymorphic, but the assignable set is small (4 types) and CatalogAssignment is never queried in hot paths — it's loaded once at session start and cached. The assignment direction is "who gets this catalog" not "what catalogs does this entity have" — so we query by catalog, not by assignable.
+
+### Company
+
+```ruby
+class Spree::Company < Spree.base_class
+ has_prefix_id :comp
+
+ include Spree::SingleStoreResource
+ include Spree::Metafields
+ include Spree::Metadata
+
+ belongs_to :store, class_name: 'Spree::Store'
+ belongs_to :customer_group, class_name: 'Spree::CustomerGroup', optional: true
+
+ has_many :company_locations, class_name: 'Spree::CompanyLocation', dependent: :destroy
+ has_many :company_contacts, through: :company_locations
+
+ validates :name, presence: true
+
+ attribute :external_id, :string # ERP/CRM reference
+ attribute :tax_exempt, :boolean, default: false
+end
+```
+
+### CompanyLocation
+
+```ruby
+class Spree::CompanyLocation < Spree.base_class
+ has_prefix_id :cloc
+
+ belongs_to :company, class_name: 'Spree::Company', inverse_of: :company_locations
+ belongs_to :billing_address, class_name: 'Spree::Address', optional: true
+ belongs_to :shipping_address, class_name: 'Spree::Address', optional: true
+
+ has_many :company_contacts, class_name: 'Spree::CompanyContact', dependent: :destroy
+ has_many :users, through: :company_contacts
+
+ # Catalog assignments for this location
+ has_many :catalog_assignments, as: :assignable, class_name: 'Spree::CatalogAssignment'
+ has_many :catalogs, through: :catalog_assignments
+
+ has_many :orders, class_name: 'Spree::Order', inverse_of: :company_location
+
+ validates :name, presence: true
+
+ attribute :tax_exempt, :boolean, default: false # overrides company-level
+ attribute :external_id, :string
+end
+```
+
+### CompanyContact
+
+```ruby
+class Spree::CompanyContact < Spree.base_class
+ has_prefix_id :cc
+
+ belongs_to :company_location, class_name: 'Spree::CompanyLocation', inverse_of: :company_contacts
+ belongs_to :user, class_name: Spree.user_class.to_s
+
+ has_one :company, through: :company_location
+
+ validates :user, :company_location, presence: true
+ validates :user_id, uniqueness: { scope: :company_location_id }
+
+ attribute :role, :string, default: 'buyer' # buyer, admin, viewer
+end
+```
+
+### Order gains Channel and CompanyLocation
+
+```ruby
+class Spree::Order < Spree.base_class
+ belongs_to :channel, class_name: 'Spree::Channel', optional: true
+ belongs_to :company_location, class_name: 'Spree::CompanyLocation', optional: true
+
+ # Remove: string :channel column (replaced by FK)
+
+ def b2b?
+ company_location.present?
+ end
+
+ def company
+ company_location&.company
+ end
+end
+```
+
+### Store gains Channels
+
+```ruby
+class Spree::Store < Spree.base_class
+ has_many :channels, class_name: 'Spree::Channel', dependent: :destroy
+ has_many :catalogs, class_name: 'Spree::Catalog', dependent: :destroy
+ has_many :companies, class_name: 'Spree::Company', dependent: :destroy
+
+ # Product access now goes through channels
+ has_many :product_listings, through: :channels
+ has_many :products, through: :product_listings
+
+ # Remove: has_many :store_products (replaced by channels → product_listings)
+
+ def default_channel
+ channels.find_by(code: 'online') || channels.first
+ end
+end
+```
+
+### Product visibility query
+
+```ruby
+class Spree::Products::ForContext
+ # Returns products visible to the current context
+ def call(store:, channel:, user: nil)
+ # Base: all active listings on this channel
+ products = channel.products.active
+
+ # If user has a company location with catalogs, filter to those
+ if (location = user_company_location(user, store))
+ catalog_ids = location.catalog_assignments.pluck(:catalog_id)
+ if catalog_ids.any?
+ catalog_product_ids = Spree::CatalogProduct.where(catalog_id: catalog_ids).select(:product_id)
+ products = products.where(id: catalog_product_ids)
+ end
+ # If user belongs to a customer group with a catalog
+ elsif (group_catalog_ids = user_group_catalog_ids(user, store)).any?
+ catalog_product_ids = Spree::CatalogProduct.where(catalog_id: group_catalog_ids).select(:product_id)
+ products = products.where(id: catalog_product_ids)
+ end
+ # Else: all channel listings (no catalog filtering)
+
+ products
+ end
+end
+```
+
+### Pricing integration
+
+Existing `Pricing::Context` gains catalog awareness:
+
+```ruby
+# In Spree::Pricing::Resolver
+def resolve(variant, context)
+ # 1. Check catalog's PriceList (if context has a catalog with a PriceList)
+ if context.catalog&.price_list
+ price = find_price(variant, context.catalog.price_list, context.currency)
+ return price if price&.amount
+ end
+
+ # 2. Check other applicable PriceLists (existing logic)
+ # ... existing PriceRule matching ...
+
+ # 3. Fall back to base price
+ variant.price_in(context.currency)
+end
+```
+
+## Migration Path
+
+### Phase 1: Create new tables
+
+```ruby
+class CreateChannelsCatalogsCompanies < ActiveRecord::Migration[7.2]
+ def change
+ # Channels
+ create_table :spree_channels do |t|
+ t.references :store, null: false
+ t.references :default_catalog
+ t.string :name, null: false
+ t.string :code, null: false
+ t.boolean :active, null: false, default: true
+ t.jsonb :metadata
+ t.timestamps
+ end
+ add_index :spree_channels, [:store_id, :code], unique: true
+
+ # ProductListings (replaces StoreProducts)
+ create_table :spree_product_listings do |t|
+ t.references :product, null: false
+ t.references :channel, null: false
+ t.datetime :listed_at
+ t.datetime :unlisted_at
+ t.integer :position
+ t.integer :units_sold_count, null: false, default: 0
+ t.decimal :revenue, precision: 10, scale: 2, null: false, default: 0
+ t.timestamps
+ end
+ add_index :spree_product_listings, [:channel_id, :product_id], unique: true
+
+ # Catalogs
+ create_table :spree_catalogs do |t|
+ t.references :store, null: false
+ t.references :price_list
+ t.string :name, null: false
+ t.boolean :active, null: false, default: true
+ t.integer :position
+ t.jsonb :metadata
+ t.timestamps
+ end
+
+ create_table :spree_catalog_products do |t|
+ t.references :catalog, null: false
+ t.references :product, null: false
+ t.integer :position
+ t.timestamps
+ end
+ add_index :spree_catalog_products, [:catalog_id, :product_id], unique: true
+
+ # CatalogAssignments (who sees which catalog)
+ create_table :spree_catalog_assignments do |t|
+ t.references :catalog, null: false
+ t.string :assignable_type, null: false
+ t.bigint :assignable_id, null: false
+ t.timestamps
+ end
+ add_index :spree_catalog_assignments, [:catalog_id, :assignable_type, :assignable_id],
+ unique: true, name: 'idx_catalog_assignments_unique'
+
+ # Companies
+ create_table :spree_companies do |t|
+ t.references :store, null: false
+ t.references :customer_group
+ t.string :name, null: false
+ t.string :external_id
+ t.boolean :tax_exempt, null: false, default: false
+ t.jsonb :metadata
+ t.timestamps
+ end
+ add_index :spree_companies, [:store_id, :external_id], unique: true,
+ where: 'external_id IS NOT NULL', name: 'idx_companies_external_id'
+
+ create_table :spree_company_locations do |t|
+ t.references :company, null: false
+ t.references :billing_address
+ t.references :shipping_address
+ t.string :name, null: false
+ t.string :external_id
+ t.boolean :tax_exempt, null: false, default: false
+ t.jsonb :metadata
+ t.timestamps
+ end
+
+ create_table :spree_company_contacts do |t|
+ t.references :company_location, null: false
+ t.references :user, null: false
+ t.string :role, null: false, default: 'buyer'
+ t.timestamps
+ end
+ add_index :spree_company_contacts, [:company_location_id, :user_id], unique: true
+
+ # Order: add channel_id and company_location_id
+ add_reference :spree_orders, :channel
+ add_reference :spree_orders, :company_location
+ end
+end
+```
+
+### Phase 2: Data migration (rake task)
+
+```ruby
+# rake spree:migrate_store_products_to_listings
+#
+# 1. For each Store, create a default Channel (code: 'online', name: 'Online Store')
+#
+# 2. For each StoreProduct:
+# → Create ProductListing (product_id, channel_id = store's default channel)
+# → Copy units_sold_count and revenue
+#
+# 3. For each Order with a string channel value:
+# → Find or create Channel with matching code
+# → Set order.channel_id
+#
+# 4. Rename spree_store_products → spree_store_products_legacy
+```
+
+### Phase 3: Model migration
+
+- Create Channel, ProductListing, Catalog, CatalogProduct, CatalogAssignment
+- Create Company, CompanyLocation, CompanyContact
+- Update Store associations (channels, catalogs, companies)
+- Update Order (channel FK, company_location FK)
+- Update Product scoping (through channels → product_listings)
+- Update Pricing::Context and Pricing::Resolver for catalog awareness
+- Wire into API key system (channel-scoped publishable keys)
+
+### Phase 4: API
+
+```
+# Channels (Admin)
+GET /api/v3/admin/channels
+POST /api/v3/admin/channels
+PATCH /api/v3/admin/channels/:id
+DELETE /api/v3/admin/channels/:id
+
+# Product Listings (Admin)
+POST /api/v3/admin/channels/:channel_id/product_listings
+DELETE /api/v3/admin/channels/:channel_id/product_listings/:id
+POST /api/v3/admin/channels/:channel_id/product_listings/bulk # list/unlist many products
+
+# Catalogs (Admin)
+GET /api/v3/admin/catalogs
+POST /api/v3/admin/catalogs
+PATCH /api/v3/admin/catalogs/:id
+DELETE /api/v3/admin/catalogs/:id
+POST /api/v3/admin/catalogs/:id/products # add products to catalog
+DELETE /api/v3/admin/catalogs/:id/products/:product_id
+POST /api/v3/admin/catalogs/:id/assign # assign to channel/group/location
+
+# Companies (Admin)
+GET /api/v3/admin/companies
+POST /api/v3/admin/companies
+PATCH /api/v3/admin/companies/:id
+DELETE /api/v3/admin/companies/:id
+
+# Company Locations (Admin)
+POST /api/v3/admin/companies/:company_id/locations
+PATCH /api/v3/admin/company_locations/:id
+DELETE /api/v3/admin/company_locations/:id
+
+# Company Contacts (Admin)
+POST /api/v3/admin/company_locations/:location_id/contacts
+DELETE /api/v3/admin/company_contacts/:id
+
+# Store API: context-aware product listing
+GET /api/v3/store/products # automatically filtered by channel + catalog context
+```
+
+### Phase 5: Cleanup (6.1)
+
+- Drop `spree_store_products_legacy` table
+- Remove `Order.channel` string column (replaced by FK)
+- Remove `StoreProduct` model
+
+## Constraints on Current Work
+
+- **Don't add new features to StoreProduct.** It's being replaced by ProductListing.
+- **Don't use `Order.channel` as a free-text field.** It will become a FK.
+- **New store-scoped product queries should use `store.products`** (which will be rerouted through channels).
+- **PriceList stays as-is.** Catalog optionally references a PriceList — don't duplicate pricing logic.
+
+## Resolved Questions
+
+1. **API key scoping.** Add optional `channel_id` to existing ApiKey model. One key can serve multiple channels (channel_id nil = all channels) or be scoped to one. No automatic key creation per channel.
+
+2. **Default channel behavior.** Falls back to store's default channel when no channel context provided. Channel resolution via `X-Spree-Channel` request header (accepts channel `code` string, e.g., `X-Spree-Channel: online` or `X-Spree-Channel: pos`). If header is absent, use ApiKey's channel (if scoped) or store's default channel.
+
+3. **Catalog auto-sync.** Manual assignment only for 6.0, with bulk product assignment via Admin API (`POST /catalogs/:id/products/bulk`). Auto-sync using CollectionRule-style patterns is a future enhancement.
+
+4. **CompanyContact roles and B2B approval workflows.** Out of scope for this plan. The 6.0 deliverable is the data model: Company, CompanyLocation, CompanyContact with a simple `role` string column. Role-based permissions, approval workflows, purchase limits, and invoice management are deferred to a dedicated B2B plan post-6.0.
+
+## Open Questions
+
+None at this time.
+
+## References
+
+- Current Store model: `spree/core/app/models/spree/store.rb`
+- Current Market model: `spree/core/app/models/spree/market.rb`
+- Current CustomerGroup: `spree/core/app/models/spree/customer_group.rb`
+- Current PriceList + PriceRules: `spree/core/app/models/spree/price_list.rb`, `spree/core/app/models/spree/price_rule.rb`
+- Current StoreProduct: `spree/core/app/models/spree/store_product.rb`
+- Related plan: `6.0-product-types.md` (ProductType defines product schema)
+- Related plan: `6.0-replace-taxons-with-categories.md` (Collections for merchandising)
diff --git a/docs/plans/6.0-fulfillment-and-delivery.md b/docs/plans/6.0-fulfillment-and-delivery.md
new file mode 100644
index 0000000000..2dd8b4e0a6
--- /dev/null
+++ b/docs/plans/6.0-fulfillment-and-delivery.md
@@ -0,0 +1,542 @@
+# Fulfillment & Delivery Rework
+
+**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)
+**Author:** Damian + Claude
+**Last updated:** 2026-03-16
+
+## 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).
+
+This is 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
+
+## Problem
+
+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.
+
+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.
+
+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.
+
+4. **InventoryUnit is a misleading name.** It represents "items in a fulfillment" — every competitor calls this FulfillmentItem or FulfillmentLine.
+
+## Entity Rename Map
+
+| Current (5.x) | 6.0 | Prefix ID | Table |
+|---|---|---|---|
+| `Spree::Shipment` | `Spree::Fulfillment` | `ful_` | `spree_fulfillments` |
+| `Spree::ShippingMethod` | `Spree::DeliveryMethod` | `dm_` | `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 |
+| — (new) | `Spree::DeliveryMethodStockLocation` | — | `spree_delivery_method_stock_locations` |
+
+## 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', 'local_delivery']
+ attribute :fulfillment_types, default: ['shipping']
+
+ validates :fulfillment_types, presence: true
+end
+```
+
+Products without a ProductType default to `['shipping']` (backward compatible).
+
+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
+
+# Find delivery methods matching those types
+DeliveryMethod.where(fulfillment_type: required_types).eligible_for(order)
+```
+
+For mixed carts (physical + digital), separate fulfillments are created automatically — one per fulfillment type.
+
+**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.
+
+### Fulfillment types are open strings
+
+```ruby
+class Spree::DeliveryMethod < Spree.base_class
+ # Built-in types
+ FULFILLMENT_TYPES = %w[shipping pickup 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
+```
+
+### FulfillmentProvider is a strategy (not a DB model)
+
+```ruby
+class 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 location
+
+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
+```
+
+## Design Details
+
+### DeliveryMethod model
+
+```ruby
+class Spree::DeliveryMethod < Spree.base_class
+ has_prefix_id :dm
+
+ acts_as_paranoid
+ include Spree::SingleStoreResource
+ include Spree::CalculatedAdjustments # pricing calculator (unchanged)
+ include Spree::Metafields
+ include Spree::Metadata
+ include Spree::DisplayOn
+
+ has_many :delivery_rates, class_name: 'Spree::DeliveryRate', inverse_of: :delivery_method
+ has_many :fulfillments, through: :delivery_rates
+
+ 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
+
+ # Fulfillment type: open string
+ attribute :fulfillment_type, :string, default: 'shipping'
+ attribute :fulfillment_provider, :string, default: 'Spree::FulfillmentProvider::Manual'
+
+ scope :by_fulfillment_type, ->(type) { where(fulfillment_type: type) }
+ scope :shipping, -> { by_fulfillment_type('shipping') }
+ scope :pickup, -> { by_fulfillment_type('pickup') }
+ 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 pickup?
+ fulfillment_type == 'pickup'
+ end
+
+ def requires_address?
+ !digital? && !pickup?
+ end
+
+ def provider
+ @provider ||= fulfillment_provider.constantize.new
+ end
+end
+```
+
+### Fulfillment model (renamed from Shipment)
+
+```ruby
+class Spree::Fulfillment < Spree.base_class
+ has_prefix_id :ful
+
+ belongs_to :order, class_name: 'Spree::Order', touch: true
+ belongs_to :address, class_name: 'Spree::Address', optional: true # nil for pickup/digital
+ belongs_to :stock_location, -> { with_deleted }, class_name: 'Spree::StockLocation'
+
+ has_many :fulfillment_items, class_name: 'Spree::FulfillmentItem', dependent: :delete_all
+ has_many :variants, through: :fulfillment_items
+ has_many :delivery_rates, -> { order(:cost) }, class_name: 'Spree::DeliveryRate', dependent: :delete_all
+ has_many :delivery_methods, through: :delivery_rates
+ has_one :selected_delivery_rate, -> { where(selected: true) }, class_name: 'Spree::DeliveryRate'
+
+ # 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"
+ 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 :shipping, -> { by_fulfillment_type('shipping') }
+
+ def digital?
+ fulfillment_type == 'digital'
+ end
+
+ def pickup?
+ fulfillment_type == 'pickup'
+ 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
+ end
+
+ def requires_delivery?
+ line_items.any? { |li| li.product.product_type&.fulfillment_types&.include?('shipping') }
+ end
+end
+```
+
+### 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
+end
+```
+
+Product convenience (replaces `shipping_category` checks):
+```ruby
+class Spree::Product < Spree.base_class
+ # Remove: belongs_to :shipping_category
+ # ProductType handles delivery eligibility
+
+ def digital?
+ product_type&.digital? || false
+ end
+
+ 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
+```
+
+## Migration Path
+
+### Phase 1: Table renames
+
+```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
+
+ # Add fulfillment_type to fulfillments (copied from selected delivery method)
+ add_column :spree_fulfillments, :fulfillment_type, :string
+
+ # 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'
+
+ # 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 2: Data migration (rake task)
+
+```ruby
+# rake spree:migrate_shipping_to_delivery
+#
+# 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)
+#
+# 2. Copy fulfillment_type to existing fulfillments from their selected delivery method
+#
+# 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
+#
+# 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
+#
+# 5. Drop spree_shipping_categories and spree_shipping_method_categories tables
+```
+
+### Phase 3: Model renames + deprecation aliases
+
+- 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
+
+### Phase 4: FulfillmentProvider interface
+
+- Create `Spree::FulfillmentProvider::Base`, `::Manual`, `::Digital`, `::Pickup`
+- Wire providers into Fulfillment state machine transitions
+- Update `Spree.fulfillment_providers` registry
+
+### Phase 5: API + serializer updates
+
+- All API endpoints renamed: `/shipments` → `/fulfillments`, `/shipping_methods` → `/delivery_methods`, `/shipping_rates` → `/delivery_rates`
+- New fields: `fulfillment_type`, `pickup_locations` on delivery methods
+- New endpoint: `GET /delivery_methods/:id/pickup_locations`
+- Run typelizer pipeline
+
+### 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
+
+## 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.
+
+## 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']`.
+
+## Open Questions
+
+None at this time.
+
+## 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)
diff --git a/docs/plans/6.0-normalize-state-to-status.md b/docs/plans/6.0-normalize-state-to-status.md
new file mode 100644
index 0000000000..57b36c46e5
--- /dev/null
+++ b/docs/plans/6.0-normalize-state-to-status.md
@@ -0,0 +1,117 @@
+# Normalize state → status
+
+**Status:** Design finalized, implementation not started
+**Target:** Spree 6.0
+**Depends on:** Cart/Order split (6.0-cart-order-split.md), Split Adjustments (6.0-split-adjustments.md)
+**Author:** Damian + Claude
+**Last updated:** 2026-03-16
+
+## Summary
+
+Rename the `state` column to `status` on the five remaining models that still use it. Newer models already use `status`. Order and Adjustment `state` columns are removed entirely by other 6.0 plans. This finishes the normalization so every state machine in Spree uses `status`.
+
+## Problem
+
+Spree has two conventions for the state machine column name:
+
+- **Legacy models** use `state`: Payment, Shipment, InventoryUnit, ReturnAuthorization, GiftCard
+- **Newer models** use `status`: Product, PriceList, PaymentSession, PaymentSetupSession, Import, ImportRow, Invitation
+
+This inconsistency means developers must remember which column each model uses. API responses mix `state` and `status` fields. Ransack filters differ per model. The CLAUDE.md rule says "default column should be `status`, legacy models use `state`" — 6.0 is the window to eliminate the exception.
+
+## Current State
+
+| Model | Current column | 6.0 action |
+|-------|---------------|------------|
+| Order | `state` | Removed (cart-order-split — no state machine on Order) |
+| Adjustment | `state` | Removed (split-adjustments — no state machine) |
+| **Payment** | `state` | Rename → `status` |
+| **Shipment** | `state` | Rename → `status` |
+| **InventoryUnit** | `state` | Rename → `status` |
+| **ReturnAuthorization** | `state` | Rename → `status` |
+| **GiftCard** | `state` | Rename → `status` |
+| Product | `status` | Already correct |
+| PriceList | `status` | Already correct |
+| PaymentSession | `status` | Already correct |
+| PaymentSetupSession | `status` | Already correct |
+| Import | `status` | Already correct |
+| ImportRow | `status` | Already correct |
+| Invitation | `status` | Already correct |
+| ReturnItem | `reception_status`, `acceptance_status` | Already correct |
+| Reimbursement | `reimbursement_status` | Already correct |
+
+## Key Decisions (do not deviate without discussion)
+
+- **`status` is the standard.** All state machines use `status` as the column name.
+- **Single migration** renames all five columns at once.
+- **Deprecation aliases** (`alias_attribute :state, :status`) for one release to avoid breaking custom code that reads `.state`.
+- **API responses use `status`** everywhere. No more `state` field in serializers.
+- **Order `payment_state` and `shipment_state` stay as-is.** These are derived summary fields on Order, not state machine columns. Renaming them to `payment_status`/`shipment_status` is optional and lower priority.
+
+## Migration Path
+
+### Phase 1: Column renames
+
+```ruby
+class RenameStateToStatus < ActiveRecord::Migration[7.2]
+ def change
+ rename_column :spree_payments, :state, :status
+ rename_column :spree_shipments, :state, :status
+ rename_column :spree_inventory_units, :state, :status
+ rename_column :spree_return_authorizations, :state, :status
+ rename_column :spree_gift_cards, :state, :status
+ end
+end
+```
+
+### Phase 2: Model updates
+
+For each of the five models:
+
+1. Update `state_machine` declaration:
+```ruby
+# Before
+state_machine initial: :pending do
+
+# After
+state_machine :status, initial: :pending do
+```
+
+2. Add deprecation alias:
+```ruby
+# Temporary — remove in 6.1
+alias_attribute :state, :status
+```
+
+3. Update any scopes or methods that reference the `state` column directly (e.g., `where(state: 'shipped')` → `where(status: 'shipped')`).
+
+### Phase 3: Serializer + API updates
+
+- All serializers return `status` instead of `state`
+- Ransack filters updated: `filter[status_eq]=shipped` instead of `filter[state_eq]=shipped`
+
+### Phase 4: StateChange model update
+
+`Spree::StateChange` records state transitions with `name` field (e.g., `"payment"`, `"shipment"`). The `previous_state` and `next_state` columns stay as-is — they store values like `"pending"`, `"shipped"`, not column names.
+
+### Phase 5: Cleanup (6.1)
+
+- Remove `alias_attribute :state, :status` from all five models
+- Remove any remaining `state` references in specs and factories
+
+## Constraints on Current Work
+
+- **Use `status` in all new code.** Don't add new `state` references.
+- **New state machines must use `status` column.** This is already the rule in CLAUDE.md.
+- **Ransack filters on new endpoints should use `status`.** Existing v3 endpoints will be updated in this plan.
+
+## Open Questions
+
+None.
+
+## References
+
+- CLAUDE.md rule: "State machines: default column `status` (legacy uses `state`)"
+- Related plan: `6.0-cart-order-split.md` (removes Order.state entirely)
+- Related plan: `6.0-split-adjustments.md` (removes Adjustment.state entirely)
+- Decision log: `docs/plans/decisions.md` (2026-03-16 entry)
diff --git a/docs/plans/6.0-product-types.md b/docs/plans/6.0-product-types.md
new file mode 100644
index 0000000000..775873608b
--- /dev/null
+++ b/docs/plans/6.0-product-types.md
@@ -0,0 +1,296 @@
+# ProductType (Prototype → ProductType)
+
+**Status:** Draft
+**Target:** Spree 6.0
+**Depends on:** Metafields system (shipped in 5.4), Taxon → Category rename (6.0)
+**Author:** Damian + Claude
+**Last updated:** 2026-03-16
+
+## Summary
+
+Rename and extend the existing `Spree::Prototype` model into `Spree::ProductType` — a persistent, schema-defining association on Product. Today Prototype is a fire-and-forget creation template (copies option types and taxons, then has no ongoing relationship with the product). ProductType becomes the long-lived type that defines what option types, categories, and metafield definitions a product has, driving admin UI form generation and enabling type-aware filtering.
+
+This closes Spree's biggest functional gap in catalog modeling, while building on existing infrastructure rather than starting from scratch.
+
+## Problem
+
+1. **No product schema enforcement.** All Spree products share the same shape. A merchant selling T-shirts and laptops has no way to say "T-shirts must have Size and Color; laptops must have RAM and Storage" without custom code.
+
+2. **No admin form generation from type.** The admin UI shows the same fields for every product. Modern platforms auto-generate product editing forms based on ProductType — adding an attribute to a type instantly updates the form for all products of that type.
+
+3. **Prototype is wasted infrastructure.** The model, join tables (`spree_option_type_prototypes`, `spree_prototype_taxons`), and creation-time callback already exist but serve only as a copy template with no ongoing relationship.
+
+4. **Metafields are unstructured per product.** Any MetafieldDefinition can be attached to any product. There's no way to declare "products of this type should have these metafields."
+
+## Key Decisions (do not deviate without discussion)
+
+- **Rename only, no new table.** `Spree::Prototype` → `Spree::ProductType`, `spree_prototypes` → `spree_product_types`. Existing join tables renamed accordingly. No data loss.
+- **Persistent `belongs_to`.** Product gets `product_type_id` FK (nullable — existing products don't require a type). The current `attr_accessor :prototype_id` + fire-and-forget callback is replaced by a real association.
+- **ProductType defines OptionTypes, Categories, and MetafieldDefinitions.** Three M2M associations on ProductType, all carried over or added via join tables.
+- **MetafieldDefinition association carries `required` and `sort_order`.** The join table `spree_product_type_metafield_definitions` determines which metafield definitions a product type uses, whether they're required, and their display order. This is the schema enforcement layer.
+- **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.
+
+## Design Details
+
+### Models
+
+```ruby
+# Renamed from Spree::Prototype
+class Spree::ProductType < Spree.base_class
+ has_prefix_id :pt
+
+ include Spree::Metadata
+ include Spree::Metafields
+ include Spree::TranslatableResource # translatable name
+
+ # Existing (renamed join tables)
+ has_many :option_type_product_types, class_name: 'Spree::OptionTypeProductType', dependent: :destroy
+ has_many :option_types, through: :option_type_product_types
+
+ has_many :product_type_categories, class_name: 'Spree::ProductTypeCategory', dependent: :destroy
+ has_many :categories, through: :product_type_categories # taxons until 6.0 rename
+
+ # New
+ has_many :product_type_metafield_definitions, class_name: 'Spree::ProductTypeMetafieldDefinition',
+ dependent: :destroy
+ has_many :metafield_definitions, through: :product_type_metafield_definitions
+
+ has_many :products, class_name: 'Spree::Product', dependent: :nullify
+
+ validates :name, presence: true
+end
+```
+
+```ruby
+# New join table: which metafield definitions does this type require?
+class Spree::ProductTypeMetafieldDefinition < Spree.base_class
+ belongs_to :product_type, class_name: 'Spree::ProductType'
+ belongs_to :metafield_definition, class_name: 'Spree::MetafieldDefinition'
+
+ validates :product_type, :metafield_definition, presence: true
+ validates :metafield_definition_id, uniqueness: { scope: :product_type_id }
+
+ # Schema enforcement
+ attribute :required, :boolean, default: false
+ attribute :sort_order, :integer, default: 0
+
+ scope :required, -> { where(required: true) }
+ scope :ordered, -> { order(:sort_order) }
+end
+```
+
+```ruby
+# Renamed from Spree::OptionTypePrototype
+class Spree::OptionTypeProductType < Spree.base_class
+ belongs_to :option_type, class_name: 'Spree::OptionType'
+ belongs_to :product_type, class_name: 'Spree::ProductType'
+
+ validates :product_type, :option_type, presence: true
+ validates :product_type_id, uniqueness: { scope: :option_type_id }
+end
+```
+
+```ruby
+# Renamed from Spree::PrototypeTaxon
+class Spree::ProductTypeCategory < Spree.base_class
+ belongs_to :category, class_name: 'Spree::Taxon' # Taxon until 6.0 rename
+ belongs_to :product_type, class_name: 'Spree::ProductType'
+
+ validates :product_type, :category, presence: true
+ validates :product_type_id, uniqueness: { scope: :category_id }
+end
+```
+
+### Product changes
+
+```ruby
+class Spree::Product < Spree.base_class
+ belongs_to :product_type, class_name: 'Spree::ProductType', optional: true
+
+ # Remove: attr_accessor :prototype_id
+ # Keep creation-time behavior: copy option_types + categories from type
+ after_create :add_associations_from_product_type
+
+ # New: validate required metafields on completion/activation
+ validate :required_metafields_present, if: :active?
+
+ private
+
+ def add_associations_from_product_type
+ return unless product_type
+
+ self.option_types = product_type.option_types if option_types.empty?
+ self.taxons = product_type.categories if taxons.empty?
+ end
+
+ def required_metafields_present
+ return unless product_type
+
+ product_type.product_type_metafield_definitions.required.each do |ptmd|
+ unless has_metafield?(ptmd.metafield_definition)
+ errors.add(:base, "Missing required metafield: #{ptmd.metafield_definition.name}")
+ end
+ end
+ end
+end
+```
+
+### Admin API
+
+```
+GET /api/v3/admin/product_types
+POST /api/v3/admin/product_types
+GET /api/v3/admin/product_types/:id
+PATCH /api/v3/admin/product_types/:id
+DELETE /api/v3/admin/product_types/:id
+```
+
+Response shape (flat, prefixed IDs):
+```json
+{
+ "id": "pt_k5nR8xLq",
+ "name": "T-Shirt",
+ "option_type_ids": ["ot_abc", "ot_def"],
+ "category_ids": ["ctg_xyz"],
+ "metafield_definitions": [
+ { "id": "mfdef_123", "key": "material", "namespace": "product", "required": true, "sort_order": 0 },
+ { "id": "mfdef_456", "key": "care_instructions", "namespace": "product", "required": false, "sort_order": 1 }
+ ],
+ "products_count": 142
+}
+```
+
+### Store API
+
+ProductType exposed as read-only `product_type` expand on products:
+```
+GET /api/v3/store/products/:id?expand=product_type
+```
+
+```json
+{
+ "id": "prod_86Rf07xd4z",
+ "name": "Classic Tee",
+ "product_type": {
+ "id": "pt_k5nR8xLq",
+ "name": "T-Shirt"
+ }
+}
+```
+
+### Admin UI (React SPA)
+
+When editing a product with a ProductType:
+1. Query ProductType's `metafield_definitions` (with `required` and `sort_order`)
+2. Render metafield form fields in `sort_order`, grouped by namespace
+3. Show required indicators on required fields
+4. Validate required metafields before allowing product activation
+
+When creating a product:
+1. Optional ProductType selector
+2. Selecting a type pre-fills option types and categories
+3. Shows the metafield form immediately
+
+## Migration Path
+
+### Phase 1: Rename (non-breaking)
+
+Single migration:
+```ruby
+class RenamePrototypesToProductTypes < ActiveRecord::Migration[7.2]
+ def change
+ rename_table :spree_prototypes, :spree_product_types
+ rename_table :spree_option_type_prototypes, :spree_option_type_product_types
+ rename_table :spree_prototype_taxons, :spree_product_type_categories
+
+ # Rename FK columns in join tables
+ rename_column :spree_option_type_product_types, :prototype_id, :product_type_id
+ rename_column :spree_product_type_categories, :prototype_id, :product_type_id
+ rename_column :spree_product_type_categories, :taxon_id, :category_id
+
+ # Add persistent FK on products
+ add_column :spree_products, :product_type_id, :bigint
+ add_index :spree_products, :product_type_id
+ end
+end
+```
+
+Model files:
+- Rename `prototype.rb` → `product_type.rb`
+- Rename `option_type_prototype.rb` → `option_type_product_type.rb`
+- Rename `prototype_taxon.rb` → `product_type_category.rb`
+- Add `Spree::Prototype = Spree::ProductType` alias in deprecation shim (remove in 6.1)
+- Update Product: replace `attr_accessor :prototype_id` with `belongs_to :product_type`
+
+### Phase 2: MetafieldDefinition association
+
+```ruby
+class CreateSpreeProductTypeMetafieldDefinitions < ActiveRecord::Migration[7.2]
+ def change
+ create_table :spree_product_type_metafield_definitions do |t|
+ t.references :product_type, null: false
+ t.references :metafield_definition, null: false
+ t.boolean :required, null: false, default: false
+ t.integer :sort_order, null: false, default: 0
+ t.timestamps
+ end
+
+ add_index :spree_product_type_metafield_definitions,
+ [:product_type_id, :metafield_definition_id],
+ unique: true,
+ name: 'idx_product_type_metafield_defs_unique'
+ end
+end
+```
+
+### Phase 3: Admin API + serializers + typelizer
+
+- Add `ProductTypeSerializer` (Store + Admin)
+- Add `ProductTypeMetafieldDefinitionSerializer`
+- Add `product_type` expand to `ProductSerializer`
+- Admin CRUD controller
+- Run typelizer pipeline
+
+### Phase 4: Admin UI integration
+
+- ProductType management CRUD pages
+- Product form: type selector, dynamic metafield form from type definition
+- Required metafield validation on product activation
+
+### Rake task: backfill product_type_id
+
+For merchants who used Prototype at creation time and want to recover the association:
+```ruby
+# rake spree:backfill_product_types
+# Looks at products sharing the same set of option_types and suggests type assignments
+```
+
+This is advisory, not automatic — product_type_id stays nullable.
+
+## Constraints on Current Work
+
+- **Do not remove Prototype model yet.** It will be renamed, not deleted. Don't add new features to it either.
+- **Do not add `prototype_id` as a persisted column.** The rename migration will add `product_type_id` instead.
+- **New MetafieldDefinitions should be resource_type-aware.** When creating definitions intended for products, use `resource_type: 'Spree::Product'` — this will matter when ProductType filters which definitions are available.
+- **Don't create a separate Attribute/Property system.** Everything builds on existing Metafields. No new EAV tables.
+
+## Open Questions
+
+1. **Shared value pools for faceted filtering.** Currently metafield values are per-resource strings. For efficient faceted navigation (count products by "Color = Red"), we'd need shared value rows for choice-type metafields (e.g., dropdown/select types). This is a significant addition — should it be a future phase of this plan or a separate plan?
+
+2. **Variant-level metafield definitions on ProductType.** Some platforms distinguish product-level vs variant-level attributes on the ProductType join. Should `ProductTypeMetafieldDefinition` carry a `level` column (`:product` or `:variant`)? OptionTypes already handle the variant dimension identity, so variant-level metafields would be descriptive metadata per variant (e.g., "variant weight note"). Defer or include?
+
+3. **ProductType immutability enforcement.** Should changing `product_type_id` on a product be blocked at the model level, or just warned in the admin UI? We could allow it if no type-specific metafields have been set yet.
+
+4. **Store API filtering by ProductType.** Should `GET /api/v3/store/products?filter[product_type_id]=pt_xxx` be a first-class filter? Useful for storefronts that want to show type-specific browse pages.
+
+## References
+
+- Current Prototype model: `spree/core/app/models/spree/prototype.rb`
+- Current Metafield system: `spree/core/app/models/spree/metafield.rb`, `spree/core/app/models/spree/metafield_definition.rb`
+- Legacy Product Properties (extracted): [github.com/spree/spree_legacy_product_properties](https://github.com/spree/spree_legacy_product_properties)
+- Architecture review: Spree core model analysis (2026-03-16)
+- Related plan: `6.0-cart-order-split.md`
diff --git a/docs/plans/6.0-remove-master-variant.md b/docs/plans/6.0-remove-master-variant.md
new file mode 100644
index 0000000000..ce8e520ed2
--- /dev/null
+++ b/docs/plans/6.0-remove-master-variant.md
@@ -0,0 +1,346 @@
+# Remove Master Variant
+
+**Status:** Design finalized, implementation not started
+**Target:** Spree 6.0
+**Depends on:** None (standalone, but coordinate with Cart/Order split)
+**Author:** Damian + Claude
+**Last updated:** 2026-03-16
+
+## Summary
+
+Eliminate the hidden "master" variant pattern. Every product will have at least one regular variant. Simple products (no options) have exactly one variant. Products with options have N variants. A `default_variant_id` FK on Product replaces the `is_master` flag as the way to identify the "face" of the product.
+
+This removes the single most confusing Spree-specific pattern for new developers and eliminates an entire class of bugs caused by master/non-master branching.
+
+## Problem
+
+Every Spree product has a hidden variant with `is_master: true`. This master variant:
+
+1. **Stores price, SKU, weight for simple products** — then gets **stripped of prices and stock** when real variants are created (via `remove_prices_from_master_variant`, `remove_stock_items_from_master_variant` callbacks). It becomes a ghost row.
+
+2. **Forces two scopes everywhere.** `variants` (excludes master, 99% of use cases) vs `variants_including_master` (includes master, needed for through-associations like prices, stock_items, line_items). Pick the wrong one and you either miss data or double-count.
+
+3. **Creates `has_variants?` branching throughout the codebase.** Every piece of code that touches pricing, stock, availability, or display must check `if has_variants? ... else ... master ...`. This is the hallmark of a leaky abstraction.
+
+4. **Confuses the delegation chain.** `product.price` → `default_variant` → either master (no variants) or first purchasable variant (has variants). `product.sku` → `master` (always). Two different delegation targets on the same model.
+
+5. **Breaks stock state.** Master gets stock items on creation, they're deleted when real variants appear. Delete all variants → master has no stock items → broken state.
+
+No other modern commerce platform uses this pattern. The industry standard is: every product has at least one regular variant, one of which is designated the default.
+
+### Blast radius
+
+| Pattern | Occurrences | Files |
+|---------|------------|-------|
+| `is_master` references | 32 | 13 |
+| `variants_including_master` | 35 | 13 |
+| `.master` on product (app + specs) | 255 | 50 |
+
+## Key Decisions (do not deviate without discussion)
+
+- **Remove `is_master` column from `spree_variants`.** All variants are peers.
+- **Add `default_variant_id` FK on `spree_products`.** Points to the variant used for price display, default add-to-cart, and property delegation. Required (not nullable) — every product must have a default variant.
+- **Every product has at least one variant.** Creating a product auto-creates one variant (like today's master, but without the special flag). Simple products have one variant with no option values. Products with options have N variants.
+- **Option values on variants become truly optional.** Today `validates :option_value_variants, presence: true, unless: :is_master?`. After: option values are optional on all variants. A simple product's sole variant just has no option values.
+- **`product.variants` returns ALL variants** (no `is_master` filter). Drop the `variants_including_master` scope entirely.
+- **Delegation simplification.** All product-level convenience methods (price, sku, weight, cost_price, etc.) delegate to `default_variant`. One delegation target, no branching.
+- **API: `master_variant` expand renamed to `default_variant`.** Deprecation alias for one release.
+- **LineItem stays `belongs_to :variant`.** This is correct. No change.
+- **StockItem stays `belongs_to :variant`.** This is correct. No change.
+- **Add-to-cart stays variant-centric.** `POST /carts/:id/items { variant_id: "variant_xxx" }`. No change.
+- **Remove all ghost callbacks.** `remove_prices_from_master_variant`, `remove_stock_items_from_master_variant`, `set_master_out_of_stock` — all deleted.
+
+## Design Details
+
+### Product model (after)
+
+```ruby
+class Spree::Product < Spree.base_class
+ # Single variants association — no is_master filter
+ has_many :variants,
+ -> { order(:position) },
+ inverse_of: :product,
+ class_name: 'Spree::Variant',
+ dependent: :destroy
+
+ # Default variant — the "face" of the product
+ belongs_to :default_variant,
+ class_name: 'Spree::Variant',
+ optional: true # nullable during creation, set in after_create
+
+ has_many :prices, -> { order('spree_variants.position, spree_variants.id, currency') },
+ through: :variants, source: :prices
+ has_many :stock_items, through: :variants
+ has_many :line_items, through: :variants
+ has_many :orders, through: :line_items
+
+ # All delegations go to default_variant — one target, no branching
+ [
+ :sku, :barcode, :weight, :height, :width, :depth, :dimensions_unit, :weight_unit,
+ :price, :price_in, :amount_in, :compare_at_price, :compare_at_amount_in,
+ :currency, :cost_currency, :cost_price, :track_inventory
+ ].each do |method_name|
+ delegate method_name, :"#{method_name}=", to: :default_variant
+ end
+
+ delegate :display_amount, :display_price, :has_default_price?, :track_inventory?,
+ :display_compare_at_price, :images, to: :default_variant
+
+ after_create :ensure_default_variant
+ after_create :set_default_variant
+
+ validates :default_variant, presence: true, on: :update
+
+ # Renamed from has_variants? — "does this product have options to choose from?"
+ def has_multiple_variants?
+ return variants.size > 1 if variants.loaded?
+
+ variant_count > 1
+ end
+
+ # Simple — always at least one variant
+ def purchasable?
+ variants.any?(&:purchasable?)
+ end
+
+ def in_stock?
+ variants.any?(&:in_stock?)
+ end
+
+ def on_sale?(currency)
+ prices.where(currency: currency).any?(&:discounted?)
+ end
+
+ # Auto-promote next variant when default is deleted/discontinued
+ after_save :auto_promote_default_variant
+
+ private
+
+ def ensure_default_variant
+ return if variants.any?
+
+ variants.create!
+ end
+
+ def set_default_variant
+ update_column(:default_variant_id, variants.first.id) if default_variant_id.nil?
+ end
+
+ def auto_promote_default_variant
+ return if default_variant&.available?
+
+ next_variant = variants.active.order(:position).first
+ update_column(:default_variant_id, next_variant.id) if next_variant
+ end
+end
+```
+
+### Variant model (after)
+
+```ruby
+class Spree::Variant < Spree.base_class
+ belongs_to :product, class_name: 'Spree::Product', touch: true
+
+ # Option values are optional on ALL variants
+ # Simple product's variant: no option values
+ # Multi-variant product: each variant has option values
+ has_many :option_value_variants, class_name: 'Spree::OptionValueVariant'
+ has_many :option_values, through: :option_value_variants
+
+ # No more is_master guards
+ after_create :create_stock_items
+
+ # Removed:
+ # - validates :option_value_variants, presence: true, unless: :is_master?
+ # - after_create :set_master_out_of_stock, unless: :is_master?
+ # - after_commit :remove_prices_from_master_variant, unless: :is_master?
+ # - after_commit :remove_stock_items_from_master_variant, unless: :is_master?
+ # - is_master column and all references
+
+ scope :eligible, -> { all } # All variants are eligible (no master filtering needed)
+
+ def exchange_name
+ option_values.any? ? options_text : name
+ end
+
+ def descriptive_name
+ option_values.any? ? "#{name} - #{options_text}" : name
+ end
+end
+```
+
+### API changes
+
+```ruby
+# Product serializer
+# Before:
+one :master, key: :master_variant, ...
+# After:
+one :default_variant, resource: Spree.api.variant_serializer,
+ if: proc { expand?('default_variant') }
+
+# Deprecation alias: expand=master_variant still works for one release
+```
+
+Store API response — `default_variant_id` replaces `master_variant`:
+```json
+{
+ "id": "prod_86Rf07xd4z",
+ "name": "Classic Tee",
+ "default_variant_id": "variant_k5nR8xLq",
+ "price": 29.99,
+ "sku": "TSHIRT-001",
+ "variants": [...]
+}
+```
+
+### What stays the same
+
+- **LineItem `belongs_to :variant`** — unchanged
+- **StockItem `belongs_to :variant`** — unchanged
+- **Add-to-cart takes `variant_id`** — unchanged
+- **Prices belong to variants** — unchanged
+- **Nested attributes for variants on Product** — unchanged (just remove the separate `master` nested attributes)
+
+## Migration Path
+
+### Phase 1: Add `default_variant_id` column
+
+```ruby
+class AddDefaultVariantIdToProducts < ActiveRecord::Migration[7.2]
+ def change
+ add_column :spree_products, :default_variant_id, :bigint
+ add_index :spree_products, :default_variant_id
+ end
+end
+```
+
+### Phase 2: Data migration (rake task)
+
+```ruby
+# rake spree:remove_master_variant
+#
+# For each product:
+#
+# Case 1: Product has real variants (variant_count > 0)
+# - Master variant has been stripped of prices/stock (ghost)
+# - Set default_variant_id to first non-master variant (by position)
+# - Delete the master variant (it has no prices, no stock, no line items)
+# - If master HAS line items (old completed orders), keep it but set is_master=false
+#
+# Case 2: Product has NO real variants (simple product)
+# - Master is the only variant, holds all data
+# - Set is_master = false (convert to regular variant)
+# - Set default_variant_id to this variant
+#
+# For all products:
+# - Update variant_count to reflect actual count (all variants, no master exclusion)
+```
+
+This task must be **idempotent** and **reversible** (soft — we can't re-create deleted masters, but we can log what was deleted).
+
+### Phase 3: Model changes
+
+1. Remove `is_master` column from `spree_variants`
+2. Remove `has_one :master` from Product
+3. Remove `has_many :variants_including_master` from Product
+4. Change `has_many :variants` to remove `where(is_master: false)` filter
+5. Add `belongs_to :default_variant` on Product
+6. Update all delegations to use `default_variant`
+7. Remove ghost callbacks from Variant
+8. Remove `option_value_variants` presence validation
+9. Update `eligible` scope (no `is_master` filter needed)
+10. Update factories: product factory creates one variant instead of master
+
+### Phase 4: API + serializer updates
+
+- Rename `master_variant` expand to `default_variant` (alias old name)
+- Update admin serializer (`cost_price`, `cost_currency` from `default_variant` instead of `master`)
+- Update SDK types via typelizer pipeline
+
+### Phase 5: Cleanup (6.1)
+
+- Remove `is_master` column migration
+- Remove deprecation aliases (`master_variant` expand, `variants_including_master`)
+- Remove `master` method from Product
+
+## Edge Cases
+
+### Completed orders referencing master variant
+
+LineItems in completed orders may reference the old master variant. Two options:
+
+- **(a) Keep master variants that have line items** — set `is_master = false`, they become regular variants. Old orders still work. This is the safe path.
+- **(b) Migrate line items** to point to the default variant. Risky — changes historical data.
+
+**Decision: (a).** Former masters with line items survive as regular variants. They just lose the `is_master` flag. The `default_variant_id` points to the first real variant (or to this converted master for simple products).
+
+### Product creation flow
+
+Today: create product → `ensure_master` auto-builds a master variant with product-level price.
+
+After: create product with `variants` nested attributes → first variant becomes `default_variant`. If no variants provided, one empty variant is auto-created (simple product). Price is set per-variant, not on the product.
+
+### Nested attributes
+
+Today: `accepts_nested_attributes_for :master` allows setting master's properties inline.
+
+After: `accepts_nested_attributes_for :variants` handles everything. No separate `master` nested attributes. Admin API accepts `variants: [{ sku: ..., prices: [...] }]`.
+
+### Price delegation
+
+Today: `product.price` → `default_variant` (which may be master or first purchasable variant, with branching).
+
+After: `product.price` → `default_variant.price` (always the same record, no branching). Product has no `price` column — it's purely a delegation convenience. If the merchant wants to change which variant is "default", they update `default_variant_id`.
+
+## Constraints on Current Work
+
+- **Stop adding `is_master?` guards.** New code should not branch on master/non-master.
+- **Use `variants_including_master` for through-associations** (prices, stock_items, line_items) — these will become just `variants` after migration.
+- **Don't add new delegations to `master`.** New delegations should go through `default_variant`.
+- **New variant callbacks should not use `unless: :is_master?`.** They should apply to all variants equally.
+
+## Resolved Questions
+
+1. **`default_variant_id` management.** Auto-promote the next variant (by position) when the current default is deleted or discontinued. No admin action required.
+
+2. **Variant count semantics.** Rename `has_variants?` to `has_multiple_variants?` — returns `variant_count > 1`. Clearer intent: "does this product have more than one variant (i.e., options to choose from)?"
+
+3. **Product creation API.** No product-level `price` param. Price lives on variants. The Admin API accepts variants as nested attributes:
+
+```ruby
+# POST /api/v3/admin/products
+{
+ name: "T-Shirt",
+ shipping_category_id: "sc_abc",
+ status: "draft",
+ variants: [
+ {
+ sku: "TSHIRT-S",
+ options: [{ name: "size", value: "Small" }],
+ prices: [
+ { currency: "USD", amount: 29.99 },
+ { currency: "EUR", amount: 27.99 }
+ ],
+ stock_items: [
+ { location_id: "loc_abc", quantity: 10, backorderable: true }
+ ]
+ }
+ ]
+}
+```
+
+If no `variants` are provided, one default variant is auto-created (simple product). Price must then be set on that variant via a follow-up call or via a top-level `price` convenience param that forwards to the auto-created variant.
+
+4. **Weight/dimensions stay on Variant.** The variant is the purchasable/shippable unit. A Small and XL t-shirt weigh differently. `product.weight` delegates to `default_variant.weight` as a convenience — no product-level columns.
+
+## Open Questions
+
+None at this time.
+
+## References
+
+- Industry standard: every product has at least one regular variant, no hidden "master". The variant is the purchasable unit.
+- Current master variant implementation: `spree/core/app/models/spree/product.rb` (lines 93-107, 232-248, 305-331, 692-696)
+- Current ghost callbacks: `spree/core/app/models/spree/variant.rb` (lines 618-678)
+- Related plan: `6.0-cart-order-split.md` (LineItem still points to variant)
diff --git a/docs/plans/6.0-replace-taxons-with-categories.md b/docs/plans/6.0-replace-taxons-with-categories.md
new file mode 100644
index 0000000000..c78ef30c9e
--- /dev/null
+++ b/docs/plans/6.0-replace-taxons-with-categories.md
@@ -0,0 +1,449 @@
+# Replace Taxons with Categories & Add Collections
+
+**Status:** Design finalized, implementation not started
+**Target:** Spree 6.0
+**Depends on:** API v3 conventions, ProductType plan (6.0-product-types.md)
+**Author:** Damian + Claude
+**Last updated:** 2026-03-16
+
+## Summary
+
+Split the overloaded `Taxon` model into two distinct concepts that every modern commerce platform separates:
+
+- **Category** — hierarchical product classification (Men > Clothing > T-Shirts). A product's primary organizational home. Manual membership only.
+- **Collection** — flat, curated or rule-based product groupings ("Summer Sale", "New Arrivals", "Best Sellers"). Supports both manual curation and automatic rules.
+
+Drop the `Taxonomy` model entirely — it's a grouping layer that adds indirection without value. Categories become a single tree per store (rooted, nested set). Collections are flat, store-scoped, and own the current automatic/rule-based functionality.
+
+This also renames `Classification` to `ProductCategory` and `TaxonRule` to `CollectionRule`.
+
+## Problem
+
+1. **"Taxon" and "Taxonomy" are jargon.** No other commerce platform uses these terms. Every new developer has to learn what they mean. The industry-standard separation is Category (hierarchical) + Collection (flat/curated).
+
+2. **Taxon is overloaded.** The same model serves as both hierarchical categories AND flat collections (via the "Collections" taxonomy with automatic rules). These have fundamentally different semantics:
+ - Categories are **hierarchical**, **manual**, and define a product's **primary classification**
+ - Collections are **flat**, often **automatic** (rule-based), and used for **merchandising** (seasonal campaigns, "on sale", "new arrivals")
+
+3. **Taxonomy adds indirection without value.** `Taxonomy` is essentially a named container for a tree of Taxons, scoped to a Store. The root Taxon mirrors the Taxonomy name (kept in sync via callbacks). In practice, merchants have 2-3 taxonomies ("Categories", "Brands", "Collections"). This grouping can be replaced by a `kind` column on the category tree root or by separating Collections entirely.
+
+4. **`Classification` tells you nothing.** The Product↔Taxon join model name gives no hint about what it joins.
+
+## Current State
+
+| Current | API name | Prefix | Notes |
+|---------|----------|--------|-------|
+| `Spree::Taxonomy` | n/a (internal) | `txnmy_` | Container for taxon trees, scoped to store |
+| `Spree::Taxon` | `categories` | `ctg_` | Nested set tree, has `automatic` flag + `TaxonRule` |
+| `Spree::Classification` | n/a | n/a | Product↔Taxon join (table: `spree_products_taxons`) |
+| `Spree::TaxonRule` | n/a | `txrule_` | STI: AvailableOn, Sale, Tag |
+| `Spree::Category` | `categories` | `ctg_` | Already exists as `< Taxon` alias |
+
+The API v3 already exposes taxons as `categories` via the `CategorySerializer`. The `Spree::Category` class already exists as a subclass alias. The prefix `ctg_` is already in use.
+
+Default taxonomies created per store: "Categories", "Brands", "Collections". Automatic taxons ("On Sale", "New Arrivals") live under the "Collections" taxonomy.
+
+## Key Decisions (do not deviate without discussion)
+
+### Category
+
+- **`Spree::Taxon` renamed to `Spree::Category`**, `spree_taxons` renamed to `spree_categories`
+- **`Spree::Taxonomy` dropped.** Categories are a single nested set per store. The `taxonomy_id` column becomes `store_id` directly on the category.
+- **`Spree::Classification` renamed to `Spree::ProductCategory`**, table `spree_products_taxons` renamed to `spree_product_categories`, columns `taxon_id` → `category_id`
+- **Categories are manual only.** The `automatic` flag, `rules_match_policy`, `sort_order`, and `taxon_rules` association move to Collection.
+- **Prefix stays `ctg_`** (already in use)
+- **Nested set stays.** `awesome_nested_set` with `parent_id`, `lft`, `rgt`, `depth`, `children_count`. Proven, no reason to change.
+- **`pretty_name` and hierarchical `permalink` stay.** These are valuable for breadcrumbs and SEO.
+- **`hide_from_nav` stays** on Category — useful for categories that exist for organization but shouldn't appear in navigation.
+
+### Collection
+
+- **New model `Spree::Collection`** — flat (no tree), store-scoped
+- **New join table `Spree::ProductCollection`** (replaces the automatic taxon's use of Classification)
+- **Owns automatic/rule-based membership** — the `automatic` flag, `rules_match_policy`, and rules association move here from Taxon
+- **`Spree::TaxonRule` renamed to `Spree::CollectionRule`** — STI subtypes: `AvailableOn`, `Sale`, `Tag` (plus future rules)
+- **Prefix: `coll_`**
+- **Both manual and automatic collections.** Manual collections have `ProductCollection` records managed by admins. Automatic collections have `CollectionRule` records that regenerate membership.
+- **Sort order on Collection**, not Category. The `SORT_ORDERS` constant (`manual`, `best_selling`, `price asc`, etc.) moves to Collection.
+
+### Taxonomy → dropped
+
+- **No replacement model.** The "kind" of category tree (Categories vs Brands) is handled by the root category's name, or by a simple `kind` string column on Category if explicit grouping is needed.
+- **Store scoping moves to Category directly.** Every category has `store_id` (required). Children auto-copy from parent on create. Simple `where(store_id:)` scoping, no joins needed.
+
+## Design Details
+
+### Category model
+
+```ruby
+class Spree::Category < Spree.base_class
+ has_prefix_id :ctg
+
+ include Spree::TranslatableResource
+ include Spree::TranslatableResourceSlug
+ include Spree::Metafields
+ include Spree::Metadata
+ include Spree::MemoizedData
+
+ acts_as_nested_set dependent: :destroy, counter_cache: :children_count
+
+ # Every category has store_id — children copy from parent on create
+ belongs_to :store, class_name: 'Spree::Store'
+ validates :store, presence: true
+ before_validation :copy_store_from_parent, if: -> { store_id.blank? && parent.present? }
+
+ # Products
+ has_many :product_categories, class_name: 'Spree::ProductCategory', dependent: :destroy_async
+ has_many :products, through: :product_categories
+
+ # ProductType integration (from 6.0-product-types.md)
+ has_many :product_type_categories, class_name: 'Spree::ProductTypeCategory', dependent: :destroy
+ has_many :product_types, through: :product_type_categories
+
+ # Promotions
+ has_many :promotion_rule_categories, class_name: 'Spree::PromotionRuleCategory', dependent: :destroy
+ has_many :promotion_rules, through: :promotion_rule_categories
+
+ # Attachments
+ has_one_attached :image
+ has_one_attached :square_image
+
+ # Validations
+ validates :name, presence: true, uniqueness: { scope: %i[parent_id store_id], case_sensitive: false }
+ validates :hide_from_nav, inclusion: { in: [true, false] }
+
+ # Translations
+ TRANSLATABLE_FIELDS = %i[name pretty_name description permalink].freeze
+ translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)
+ translates :description, backend: :action_text
+
+ # Scopes
+ scope :for_store, ->(store) { where(store_id: store.id) }
+
+ # No automatic/rules — that's Collection's job
+end
+```
+
+### Collection model
+
+```ruby
+class Spree::Collection < Spree.base_class
+ has_prefix_id :coll
+
+ include Spree::SingleStoreResource
+ include Spree::TranslatableResource
+ include Spree::TranslatableResourceSlug
+ include Spree::Metafields
+ include Spree::Metadata
+
+ RULES_MATCH_POLICIES = %w[all any].freeze
+ SORT_ORDERS = %w[
+ manual best_selling
+ price_asc price_desc
+ available_on_desc available_on_asc
+ name_asc name_desc
+ ].freeze
+
+ acts_as_list scope: :store_id
+
+ belongs_to :store, class_name: 'Spree::Store'
+
+ # Products
+ has_many :product_collections, class_name: 'Spree::ProductCollection', dependent: :destroy_async
+ has_many :products, through: :product_collections
+
+ # Automatic rules
+ has_many :collection_rules, class_name: 'Spree::CollectionRule', dependent: :destroy
+ accepts_nested_attributes_for :collection_rules, allow_destroy: true,
+ reject_if: proc { |attrs| attrs['value'].blank? }
+
+ # Attachments
+ has_one_attached :image
+ has_one_attached :square_image
+
+ # Validations
+ validates :name, presence: true
+ validates :store, presence: true
+ validates :rules_match_policy, inclusion: { in: RULES_MATCH_POLICIES }, presence: true
+ validates :sort_order, inclusion: { in: SORT_ORDERS }, presence: true
+
+ # Translations
+ TRANSLATABLE_FIELDS = %i[name description permalink].freeze
+ translates(*TRANSLATABLE_FIELDS, column_fallback: !Spree.always_use_translations?)
+
+ scope :manual, -> { where.not(automatic: true) }
+ scope :automatic, -> { where(automatic: true) }
+
+ # Regenerate product membership from rules (moved from Taxon)
+ def regenerate_products
+ return unless automatic?
+ Spree::Collections::RegenerateProducts.call(collection: self)
+ end
+
+ def products_matching_rules(opts = {})
+ return Spree::Product.none unless automatic? && collection_rules.any?
+ # Same logic as current Taxon#products_matching_rules
+ end
+end
+```
+
+### Join tables
+
+```ruby
+# Renamed from Spree::Classification
+class Spree::ProductCategory < Spree.base_class
+ self.table_name = 'spree_product_categories'
+ acts_as_list scope: :category
+
+ belongs_to :product, class_name: 'Spree::Product', counter_cache: :category_count, touch: true
+ belongs_to :category, class_name: 'Spree::Category', counter_cache: :product_count, touch: true
+
+ validates :category, :product, presence: true
+ validates :category_id, uniqueness: { scope: :product_id }
+end
+
+# New
+class Spree::ProductCollection < Spree.base_class
+ self.table_name = 'spree_product_collections'
+ acts_as_list scope: :collection
+
+ belongs_to :product, class_name: 'Spree::Product', touch: true
+ belongs_to :collection, class_name: 'Spree::Collection', touch: true
+
+ validates :collection, :product, presence: true
+ validates :collection_id, uniqueness: { scope: :product_id }
+end
+```
+
+### CollectionRule (renamed from TaxonRule)
+
+```ruby
+class Spree::CollectionRule < Spree.base_class
+ has_prefix_id :crule
+
+ MATCH_POLICIES = %w[is_equal_to is_not_equal_to contains does_not_contain].freeze
+
+ belongs_to :collection, class_name: 'Spree::Collection', inverse_of: :collection_rules, touch: true
+
+ validates :collection, :type, :value, presence: true
+ validates :match_policy, inclusion: { in: MATCH_POLICIES }, presence: true
+
+ after_commit :regenerate_collection_products,
+ if: -> { saved_change_to_value? || destroyed? || saved_change_to_match_policy? }
+end
+
+# STI subtypes:
+# Spree::CollectionRules::AvailableOn — products created/available within N days
+# Spree::CollectionRules::Sale — products currently on sale
+# Spree::CollectionRules::Tag — products with matching tags
+```
+
+### Product changes
+
+```ruby
+class Spree::Product < Spree.base_class
+ # Categories (renamed from taxons/classifications)
+ has_many :product_categories, dependent: :delete_all, inverse_of: :product
+ has_many :categories, through: :product_categories
+ # Backward compat alias (deprecation period)
+ alias_method :taxons, :categories
+ alias_method :classifications, :product_categories
+
+ # Collections (new)
+ has_many :product_collections, dependent: :delete_all, inverse_of: :product
+ has_many :collections, through: :product_collections
+
+ # main_taxon → primary_category
+ def primary_category
+ @primary_category ||= categories.first
+ end
+
+ # brand_taxon → brand (lookup by taxonomy name replaced by category kind or brand association)
+ # See Open Questions for brand handling
+end
+```
+
+### Store changes
+
+```ruby
+class Spree::Store < Spree.base_class
+ # Drop: has_many :taxonomies
+ # Drop: has_many :taxons, through: :taxonomies
+
+ has_many :categories, class_name: 'Spree::Category'
+ has_many :root_categories, -> { roots }, class_name: 'Spree::Category'
+ has_many :collections, class_name: 'Spree::Collection'
+end
+```
+
+### API
+
+Store API already uses `categories` naming. Changes:
+
+```
+# Categories (existing endpoints, just renamed internally)
+GET /api/v3/store/categories # was taxons
+GET /api/v3/store/categories/:id
+GET /api/v3/store/products/:id?expand=categories
+
+# Collections (new)
+GET /api/v3/store/collections
+GET /api/v3/store/collections/:id
+GET /api/v3/store/collections/:id/products
+
+# Admin API
+GET /api/v3/admin/categories
+POST /api/v3/admin/categories
+PATCH /api/v3/admin/categories/:id
+DELETE /api/v3/admin/categories/:id
+
+GET /api/v3/admin/collections
+POST /api/v3/admin/collections
+PATCH /api/v3/admin/collections/:id
+DELETE /api/v3/admin/collections/:id
+```
+
+Collection response:
+```json
+{
+ "id": "coll_k5nR8xLq",
+ "name": "Summer Sale",
+ "automatic": true,
+ "sort_order": "best_selling",
+ "rules_match_policy": "all",
+ "rules": [
+ { "id": "crule_abc", "type": "Spree::CollectionRules::Tag", "value": "summer", "match_policy": "contains" }
+ ],
+ "image_url": "https://...",
+ "products_count": 42,
+ "slug": "summer-sale"
+}
+```
+
+## Migration Path
+
+### Phase 1: Table renames + new Collection table
+
+Single migration:
+
+```ruby
+class RenameTaxonsToCategories < ActiveRecord::Migration[7.2]
+ def change
+ # Rename core tables
+ rename_table :spree_taxons, :spree_categories
+ rename_table :spree_products_taxons, :spree_product_categories
+ rename_table :spree_taxon_rules, :spree_collection_rules
+
+ # Rename FK columns
+ rename_column :spree_product_categories, :taxon_id, :category_id
+ rename_column :spree_collection_rules, :taxon_id, :collection_id
+
+ # Add store_id to categories (replacing taxonomy_id)
+ add_column :spree_categories, :store_id, :bigint
+ add_index :spree_categories, :store_id
+
+ # Rename counter caches
+ rename_column :spree_categories, :classification_count, :product_count
+ rename_column :spree_products, :classification_count, :category_count
+
+ # Create collections table
+ create_table :spree_collections do |t|
+ t.string :name, null: false
+ t.text :description
+ t.string :permalink
+ t.boolean :automatic, null: false, default: false
+ t.string :rules_match_policy, null: false, default: 'all'
+ t.string :sort_order, null: false, default: 'manual'
+ t.boolean :hide_from_nav, null: false, default: false
+ t.integer :position
+ t.integer :products_count, null: false, default: 0
+ t.references :store, null: false
+ t.string :meta_title
+ t.string :meta_description
+ t.string :meta_keywords
+ t.jsonb :public_metadata
+ t.jsonb :private_metadata
+ t.timestamps
+ end
+
+ add_index :spree_collections, [:store_id, :permalink], unique: true
+
+ # Create product_collections join table
+ create_table :spree_product_collections do |t|
+ t.references :product, null: false
+ t.references :collection, null: false
+ t.integer :position
+ t.timestamps
+ end
+
+ add_index :spree_product_collections, [:collection_id, :product_id], unique: true
+ end
+end
+```
+
+### Phase 2: Data migration (rake task)
+
+```ruby
+# rake spree:migrate_taxons_to_categories_and_collections
+#
+# For each Taxonomy:
+# 1. Set store_id on all its root + descendant taxons (now categories)
+# 2. If taxonomy is "Collections" (by name):
+# - Move its automatic child taxons to spree_collections
+# - Move their TaxonRules to CollectionRules
+# - Move their Classifications to ProductCollections
+# - Move manual child taxons to ProductCollections
+# - Delete the taxonomy root category
+# 3. For other taxonomies ("Categories", "Brands"):
+# - Root category keeps the taxonomy name
+# - Remove taxonomy_id column references
+# 4. Drop taxonomy_id from categories
+```
+
+### Phase 3: Model renames + deprecation aliases
+
+- `Spree::Taxon` → `Spree::Category` (alias `Spree::Taxon = Spree::Category` for one release)
+- `Spree::Taxonomy` → deprecated, no replacement
+- `Spree::Classification` → `Spree::ProductCategory` (alias for one release)
+- `Spree::TaxonRule` → `Spree::CollectionRule`
+- `Spree::TaxonRules::*` → `Spree::CollectionRules::*`
+- Update all serializers, controllers, services, factories, specs
+
+### Phase 4: Cleanup (6.1)
+
+- Remove all aliases and deprecation shims
+- Remove `taxonomy_id` column from categories
+- Remove `spree_taxonomies` table
+- Remove `automatic`, `rules_match_policy`, `sort_order` columns from categories (moved to collections)
+
+## Constraints on Current Work
+
+- **Use `categories` in all new API code.** The Store API already does this. Don't introduce new `taxon` references in API v3.
+- **Use `Spree::Category` alias in new code where possible.** It exists today as `< Taxon`.
+- **Don't add new TaxonRule subtypes.** New rule types should be designed for the Collection model.
+- **Don't add new Taxonomy-dependent features.** Taxonomy is going away.
+- **Keep the `ctg_` prefix.** Already in use, will carry over.
+- **New "collection-like" features go on Taxon's automatic path for now** — they'll migrate cleanly to Collection.
+- **`ProductTypeCategory` join table** (from 6.0-product-types.md) should be named anticipating the Category rename — use `category_id` column, not `taxon_id`.
+
+## Open Questions
+
+1. **Brand handling.** Currently `brand_taxon` looks up a taxon under the "Brands" taxonomy. Options:
+ - (a) Keep brands as a category tree root named "Brands" — simplest, brands are just categories
+ - (b) Add a dedicated `Spree::Brand` model — cleaner but more migration work
+ - (c) Brand as a metafield — too unstructured
+ - Leaning toward (a): brands are categories under a "Brands" root. `product.brand` resolves to the first category under the Brands root.
+
+2. **Category kind/type column.** Should root categories have a `kind` column (e.g., `categories`, `brands`) to replace the Taxonomy name as a semantic grouping? This would make "find the brands root" a query on `kind` rather than a string match on `name`. Low cost, high value.
+
+3. **Collection pagination of products.** Should `GET /collections/:id/products` support full Ransack filtering and Pagy pagination, or should it return the collection's pre-sorted product list? Probably both — Ransack filters scoped to the collection's product set.
+
+4. **Automatic collection scheduling.** Current `AvailableOn` rule regenerates on product changes. Should collections support scheduled regeneration (e.g., daily cron) for time-based rules? The current `after_commit` approach may miss edge cases.
+
+5. **Collection nesting.** The plan says collections are flat. Should we support one level of nesting (parent collection)? Some platforms support hierarchical collections with filter inheritance. Could be a future enhancement.
+
+## References
+
+- Industry pattern: hierarchical Category + flat Collection (manual and/or rule-based) is the standard across modern headless commerce platforms
+- Current Spree API: already uses `categories` naming in Store API v3
+- Related plan: `6.0-product-types.md` (ProductTypeCategory join table)
diff --git a/docs/plans/6.0-returns-exchanges-claims.md b/docs/plans/6.0-returns-exchanges-claims.md
new file mode 100644
index 0000000000..dbb9a919e6
--- /dev/null
+++ b/docs/plans/6.0-returns-exchanges-claims.md
@@ -0,0 +1,619 @@
+# Returns, Exchanges & Claims as First-Class Entities
+
+**Status:** Draft
+**Target:** Spree 6.0
+**Depends on:** Fulfillment & Delivery rework (6.0-fulfillment-and-delivery.md), Split Adjustments (6.0-split-adjustments.md)
+**Author:** Damian + Claude
+**Last updated:** 2026-03-16
+
+## Summary
+
+Replace the deeply nested return/reimbursement chain (ReturnAuthorization → ReturnItem → CustomerReturn → Reimbursement → ReimbursementType → Refund/Exchange) with three first-class entities that directly model the business operations:
+
+- **Return** — customer sends items back, gets a refund
+- **Exchange** — customer sends items back, gets different items
+- **Claim** — customer reports a problem (damaged, missing, wrong item), may keep the original
+
+Each is a top-level model on Order with its own line items, status, and resolution. No more 6-model-deep nesting. No more exchanges-as-a-reimbursement-type hack.
+
+## Problem
+
+### 1. Six models for a simple return
+
+Today's flow: `ReturnAuthorization` → `ReturnItem` → `CustomerReturn` → `Reimbursement` → `ReimbursementType` → `Refund`. A merchant processing a return touches 6 interconnected models. Each has its own state machine. The mental model is impossible for new developers.
+
+### 2. Exchanges are not a first-class concept
+
+An exchange is modeled as a `ReturnItem` with an `exchange_variant_id`, processed through `ReimbursementType::Exchange`. There's no `Exchange` model — you can't query "all exchanges this month" or "exchanges pending fulfillment" without digging through ReturnItems that happen to have an exchange_variant set.
+
+### 3. Claims don't exist
+
+If a customer receives a damaged item, there's no way to model "we're sending a replacement without requiring the original back." Today merchants either create a manual order or hack it through the return flow (create a return authorization, immediately mark as received, create an exchange). There's no `Claim` entity.
+
+### 4. CustomerReturn is confusing
+
+`CustomerReturn` represents "physical receipt of returned items at the warehouse." It's the bridge between ReturnAuthorization (permission) and Reimbursement (money). But it duplicates validation logic from ReturnItem, has no state machine, and its `order` method derives the order from return_items → inventory_units — not a direct association.
+
+### 5. ReimbursementType STI is over-engineered
+
+Four STI subtypes (Credit, Exchange, OriginalPayment, StoreCredit) that each implement `self.reimburse`. The Exchange subtype delegates to `Spree::Exchange`. The OriginalPayment subtype delegates to `Refund`. The indirection adds complexity without flexibility — the actual reimbursement logic lives in `Refund` and `Exchange`, not in the type classes.
+
+## Current State
+
+| Model | Purpose | State machine? | Lines |
+|---|---|---|---|
+| ReturnAuthorization | Permission to return | Yes (authorized → canceled) | ~110 |
+| ReturnItem | Individual item in a return | Yes (reception_status + acceptance_status) | ~290 |
+| CustomerReturn | Physical receipt at warehouse | No | ~95 |
+| Reimbursement | Money-back execution | Yes (pending → reimbursed/errored) | ~170 |
+| ReimbursementType | STI: how to reimburse | No (strategy class) | ~20 + 4 subtypes |
+| Refund | Actual payment reversal | No (after_create: perform!) | ~140 |
+
+Total: ~825 lines across 6+ models for return handling.
+
+## Key Decisions (do not deviate without discussion)
+
+- **Three first-class models:** `Return`, `Exchange`, `Claim`. Each belongs directly to Order.
+- **Each has its own line items:** `ReturnItem`, `ExchangeItem`, `ClaimItem`. No shared polymorphic item model — each type has different fields.
+- **Simple status flow on each.** One state machine per entity, not layered state machines across multiple models.
+- **Refund stays.** `Spree::Refund` is the payment-level reversal — it stays as-is. Returns and Claims link to Refunds when money needs to go back.
+- **Drop:** `CustomerReturn`, `Reimbursement`, `ReimbursementType` (all four subtypes), `ReturnAuthorization`. Their functionality is absorbed into the three new models.
+- **ReturnItem is reused** (renamed from the current model, simplified). ExchangeItem and ClaimItem are new.
+
+## Design Details
+
+### Return
+
+A customer returns items and gets a refund (to original payment, store credit, or gift card).
+
+```ruby
+class Spree::Return < Spree.base_class
+ has_prefix_id :ret
+
+ include Spree::Core::NumberGenerator.new(prefix: 'RET', length: 9)
+ include Spree::NumberIdentifier
+ include Spree::Metafields
+ include Spree::Metadata
+
+ publishes_lifecycle_events
+
+ belongs_to :order, class_name: 'Spree::Order', inverse_of: :returns
+ belongs_to :stock_location, class_name: 'Spree::StockLocation'
+ belongs_to :reason, class_name: 'Spree::ReturnReason', optional: true
+ belongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: true
+
+ has_many :return_items, class_name: 'Spree::ReturnItem', dependent: :destroy, inverse_of: :return
+ has_many :refunds, class_name: 'Spree::Refund', as: :originator
+
+ validates :order, :stock_location, presence: true
+ validates :return_items, presence: true
+
+ accepts_nested_attributes_for :return_items, allow_destroy: true
+
+ state_machine :status, initial: :requested do
+ event :approve do
+ transition from: :requested, to: :approved
+ end
+ event :receive do
+ transition from: :approved, to: :received
+ end
+ event :refund do
+ transition from: :received, to: :refunded
+ end
+ event :cancel do
+ transition from: [:requested, :approved], to: :canceled
+ end
+
+ after_transition to: :received, do: :restock_items
+ after_transition to: :refunded, do: :process_refund
+ end
+
+ # Total refund amount
+ def refund_total
+ return_items.sum(:pre_tax_amount)
+ end
+
+ private
+
+ def restock_items
+ return_items.each do |item|
+ next unless item.resellable?
+
+ stock_location.restock(item.variant, item.quantity)
+ end
+ end
+
+ def process_refund
+ # Create Refund against the order's payment
+ payment = order.payments.completed.last
+ return unless payment
+
+ Spree::Refund.create!(
+ payment: payment,
+ amount: refund_total,
+ reason: Spree::RefundReason.return_processing,
+ originator: self
+ )
+ end
+end
+```
+
+### ReturnItem (simplified)
+
+```ruby
+class Spree::ReturnItem < Spree.base_class
+ has_prefix_id :ri
+
+ belongs_to :return, class_name: 'Spree::Return', inverse_of: :return_items
+ belongs_to :fulfillment_item, class_name: 'Spree::FulfillmentItem' # renamed from InventoryUnit
+ belongs_to :line_item, class_name: 'Spree::LineItem'
+ belongs_to :variant, class_name: 'Spree::Variant'
+
+ validates :fulfillment_item, :quantity, presence: true
+ validates :quantity, numericality: { greater_than: 0 }
+
+ attribute :pre_tax_amount, :decimal, default: 0
+ attribute :resellable, :boolean, default: true
+ attribute :quantity, :integer, default: 1
+
+ before_create :set_default_pre_tax_amount
+
+ delegate :order, to: :return
+
+ private
+
+ def set_default_pre_tax_amount
+ self.pre_tax_amount ||= line_item.pre_tax_amount / line_item.quantity * quantity
+ end
+end
+```
+
+### Exchange
+
+A customer returns items and gets different items in return (different size, different product).
+
+```ruby
+class Spree::Exchange < Spree.base_class
+ has_prefix_id :exch
+
+ include Spree::Core::NumberGenerator.new(prefix: 'EX', length: 9)
+ include Spree::NumberIdentifier
+ include Spree::Metafields
+ include Spree::Metadata
+
+ publishes_lifecycle_events
+
+ belongs_to :order, class_name: 'Spree::Order', inverse_of: :exchanges
+ belongs_to :stock_location, class_name: 'Spree::StockLocation'
+ belongs_to :reason, class_name: 'Spree::ReturnReason', optional: true
+ belongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: true
+
+ has_many :exchange_items, class_name: 'Spree::ExchangeItem', dependent: :destroy, inverse_of: :exchange
+ has_one :exchange_fulfillment, class_name: 'Spree::Fulfillment', as: :originator # the new shipment
+
+ # If there's a price difference, link to a refund or additional payment
+ has_many :refunds, class_name: 'Spree::Refund', as: :originator
+
+ validates :order, :stock_location, presence: true
+ validates :exchange_items, presence: true
+
+ accepts_nested_attributes_for :exchange_items, allow_destroy: true
+
+ state_machine :status, initial: :requested do
+ event :approve do
+ transition from: :requested, to: :approved
+ end
+ event :receive do
+ transition from: :approved, to: :received
+ end
+ event :fulfill do
+ transition from: :received, to: :fulfilled
+ end
+ event :cancel do
+ transition from: [:requested, :approved], to: :canceled
+ end
+
+ after_transition to: :received, do: :restock_returned_items
+ after_transition to: :fulfilled, do: :create_exchange_fulfillment
+ end
+
+ # Price difference: positive = customer owes more, negative = refund due
+ def price_difference
+ exchange_items.sum { |ei| ei.new_variant_price - ei.original_price }
+ end
+
+ private
+
+ def restock_returned_items
+ exchange_items.each do |item|
+ next unless item.resellable?
+
+ stock_location.restock(item.original_variant, item.quantity)
+ end
+ end
+
+ def create_exchange_fulfillment
+ # Create a new fulfillment with the exchange variants
+ fulfillment = order.fulfillments.create!(
+ stock_location: stock_location,
+ fulfillment_type: 'shipping',
+ address: order.ship_address
+ )
+
+ exchange_items.each do |item|
+ fulfillment.fulfillment_items.create!(
+ variant: item.new_variant,
+ quantity: item.quantity,
+ order: order,
+ line_item: item.line_item
+ )
+ end
+ end
+end
+```
+
+### ExchangeItem
+
+```ruby
+class Spree::ExchangeItem < Spree.base_class
+ has_prefix_id :ei
+
+ belongs_to :exchange, class_name: 'Spree::Exchange', inverse_of: :exchange_items
+ belongs_to :fulfillment_item, class_name: 'Spree::FulfillmentItem' # the original item being returned
+ belongs_to :line_item, class_name: 'Spree::LineItem' # original line item
+ belongs_to :original_variant, class_name: 'Spree::Variant'
+ belongs_to :new_variant, class_name: 'Spree::Variant'
+
+ validates :fulfillment_item, :original_variant, :new_variant, :quantity, presence: true
+ validates :quantity, numericality: { greater_than: 0 }
+
+ attribute :quantity, :integer, default: 1
+ attribute :resellable, :boolean, default: true
+
+ def original_price
+ line_item.price * quantity
+ end
+
+ def new_variant_price
+ new_variant.price_in(exchange.order.currency)&.amount.to_d * quantity
+ end
+end
+```
+
+### Claim
+
+A customer reports a problem — damaged, missing, or wrong item. The merchant may send a replacement, issue a refund, or both — without requiring the original item back.
+
+```ruby
+class Spree::Claim < Spree.base_class
+ has_prefix_id :claim
+
+ include Spree::Core::NumberGenerator.new(prefix: 'CLM', length: 9)
+ include Spree::NumberIdentifier
+ include Spree::Metafields
+ include Spree::Metadata
+
+ publishes_lifecycle_events
+
+ CLAIM_TYPES = %w[damaged missing wrong_item other].freeze
+
+ belongs_to :order, class_name: 'Spree::Order', inverse_of: :claims
+ belongs_to :reason, class_name: 'Spree::ClaimReason', optional: true
+ belongs_to :created_by, class_name: Spree.admin_user_class.to_s, optional: true
+
+ has_many :claim_items, class_name: 'Spree::ClaimItem', dependent: :destroy, inverse_of: :claim
+ has_many :refunds, class_name: 'Spree::Refund', as: :originator
+ has_one :replacement_fulfillment, class_name: 'Spree::Fulfillment', as: :originator
+
+ validates :order, :claim_type, presence: true
+ validates :claim_items, presence: true
+ validates :claim_type, inclusion: { in: CLAIM_TYPES }
+
+ accepts_nested_attributes_for :claim_items, allow_destroy: true
+
+ state_machine :status, initial: :open do
+ event :approve do
+ transition from: :open, to: :approved
+ end
+ event :resolve do
+ transition from: :approved, to: :resolved
+ end
+ event :deny do
+ transition from: :open, to: :denied
+ end
+ event :cancel do
+ transition from: [:open, :approved], to: :canceled
+ end
+
+ after_transition to: :resolved, do: :execute_resolution
+ end
+
+ # Resolution type: how the claim is being resolved
+ # 'refund', 'replacement', 'refund_and_replacement'
+ attribute :resolution, :string
+
+ private
+
+ def execute_resolution
+ process_refund if resolution&.include?('refund')
+ create_replacement if resolution&.include?('replacement')
+ end
+
+ def process_refund
+ payment = order.payments.completed.last
+ return unless payment
+
+ amount = claim_items.sum(:refund_amount)
+ return if amount.zero?
+
+ Spree::Refund.create!(
+ payment: payment,
+ amount: amount,
+ reason: Spree::RefundReason.claim_processing,
+ originator: self
+ )
+ end
+
+ def create_replacement
+ stock_location = Spree::StockLocation.default
+ fulfillment = order.fulfillments.create!(
+ stock_location: stock_location,
+ fulfillment_type: 'shipping',
+ address: order.ship_address
+ )
+
+ claim_items.where(send_replacement: true).each do |item|
+ fulfillment.fulfillment_items.create!(
+ variant: item.replacement_variant || item.variant,
+ quantity: item.quantity,
+ order: order,
+ line_item: item.line_item
+ )
+ end
+ end
+end
+```
+
+### ClaimItem
+
+```ruby
+class Spree::ClaimItem < Spree.base_class
+ has_prefix_id :ci
+
+ belongs_to :claim, class_name: 'Spree::Claim', inverse_of: :claim_items
+ belongs_to :line_item, class_name: 'Spree::LineItem'
+ belongs_to :variant, class_name: 'Spree::Variant'
+ belongs_to :replacement_variant, class_name: 'Spree::Variant', optional: true
+
+ # Optional images of damage
+ has_many_attached :images
+
+ validates :line_item, :variant, :quantity, presence: true
+ validates :quantity, numericality: { greater_than: 0 }
+
+ attribute :quantity, :integer, default: 1
+ attribute :send_replacement, :boolean, default: false
+ attribute :refund_amount, :decimal, default: 0
+ attribute :description, :text # customer's description of the problem
+end
+```
+
+### Order associations
+
+```ruby
+class Spree::Order < Spree.base_class
+ has_many :returns, class_name: 'Spree::Return', dependent: :destroy
+ has_many :exchanges, class_name: 'Spree::Exchange', dependent: :destroy
+ has_many :claims, class_name: 'Spree::Claim', dependent: :destroy
+
+ # Remove:
+ # has_many :return_authorizations
+ # has_many :reimbursements
+end
+```
+
+### Refund gains polymorphic originator
+
+```ruby
+class Spree::Refund < Spree.base_class
+ # Existing: belongs_to :payment
+ # Add: polymorphic originator — who triggered this refund?
+ belongs_to :originator, polymorphic: true, optional: true
+ # originator can be: Spree::Return, Spree::Exchange, Spree::Claim, or nil (manual refund)
+end
+```
+
+Note: this is the one intentional polymorphic association — Refund needs to know what triggered it, and the originator set is small and closed (3 types + nil). The performance concern from Adjustments doesn't apply here because refunds are infrequent and never bulk-queried in hot paths.
+
+## Migration Path
+
+### Phase 1: Create new tables
+
+```ruby
+class CreateReturnsExchangesClaims < ActiveRecord::Migration[7.2]
+ def change
+ create_table :spree_returns do |t|
+ t.string :number, null: false
+ t.references :order, null: false
+ t.references :stock_location, null: false
+ t.references :reason
+ t.references :created_by
+ t.string :status, null: false, default: 'requested'
+ t.text :memo
+ t.jsonb :public_metadata
+ t.jsonb :private_metadata
+ t.timestamps
+ end
+ add_index :spree_returns, :number, unique: true
+
+ create_table :spree_exchanges do |t|
+ t.string :number, null: false
+ t.references :order, null: false
+ t.references :stock_location, null: false
+ t.references :reason
+ t.references :created_by
+ t.string :status, null: false, default: 'requested'
+ t.text :memo
+ t.jsonb :public_metadata
+ t.jsonb :private_metadata
+ t.timestamps
+ end
+ add_index :spree_exchanges, :number, unique: true
+
+ create_table :spree_claims do |t|
+ t.string :number, null: false
+ t.references :order, null: false
+ t.references :reason
+ t.references :created_by
+ t.string :status, null: false, default: 'open'
+ t.string :claim_type, null: false
+ t.string :resolution
+ t.text :memo
+ t.jsonb :public_metadata
+ t.jsonb :private_metadata
+ t.timestamps
+ end
+ add_index :spree_claims, :number, unique: true
+
+ # Rename old return_items to legacy, create new simplified table
+ rename_table :spree_return_items, :spree_return_items_legacy
+
+ create_table :spree_return_items do |t|
+ t.references :return, null: false
+ t.references :fulfillment_item, null: false
+ t.references :line_item, null: false
+ t.references :variant, null: false
+ t.integer :quantity, null: false, default: 1
+ t.decimal :pre_tax_amount, precision: 10, scale: 2, null: false, default: 0
+ t.boolean :resellable, null: false, default: true
+ t.timestamps
+ end
+
+ create_table :spree_exchange_items do |t|
+ t.references :exchange, null: false
+ t.references :fulfillment_item, null: false
+ t.references :line_item, null: false
+ t.references :original_variant, null: false
+ t.references :new_variant, null: false
+ t.integer :quantity, null: false, default: 1
+ t.boolean :resellable, null: false, default: true
+ t.timestamps
+ end
+
+ create_table :spree_claim_items do |t|
+ t.references :claim, null: false
+ t.references :line_item, null: false
+ t.references :variant, null: false
+ t.references :replacement_variant
+ t.integer :quantity, null: false, default: 1
+ t.boolean :send_replacement, null: false, default: false
+ t.decimal :refund_amount, precision: 10, scale: 2, null: false, default: 0
+ t.text :description
+ t.timestamps
+ end
+
+ # Refund: add polymorphic originator
+ add_column :spree_refunds, :originator_type, :string
+ add_column :spree_refunds, :originator_id, :bigint
+ add_index :spree_refunds, [:originator_type, :originator_id]
+ end
+end
+```
+
+### Phase 2: Data migration (rake task)
+
+```ruby
+# rake spree:migrate_returns
+#
+# For each ReturnAuthorization + its ReturnItems:
+# If any ReturnItem has exchange_variant_id:
+# → Create Exchange with ExchangeItems
+# Else:
+# → Create Return with ReturnItems (new table)
+#
+# For each Reimbursement:
+# Link its Refunds to the new Return/Exchange via originator
+#
+# Claims: no migration needed (didn't exist before)
+#
+# ReturnAuthorizationReason → ReturnReason (rename or alias)
+# RefundReason stays as-is
+# New: ClaimReason
+```
+
+### Phase 3: Model migration
+
+- Create Return, Exchange, Claim models + line items
+- Update Order associations
+- Update Refund with originator
+- Create ReturnReason, ClaimReason models (or reuse existing reason tables)
+- Update FulfillmentItem (was InventoryUnit) to remove return-specific methods
+- Wire into events system (lifecycle events for each entity)
+
+### Phase 4: Drop legacy models
+
+- Drop: ReturnAuthorization, CustomerReturn, Reimbursement, ReimbursementType (all subtypes)
+- Drop: `spree_return_authorizations`, `spree_customer_returns`, `spree_reimbursements`, `spree_reimbursement_types`
+- Keep: `spree_return_items_legacy` (renamed in Phase 1) for historical reference, drop in 6.1
+- Drop: `Spree::Exchange` service class (replaced by model)
+
+### Phase 5: API
+
+```
+# Returns
+POST /api/v3/admin/orders/:order_id/returns
+GET /api/v3/admin/orders/:order_id/returns
+PATCH /api/v3/admin/returns/:id
+DELETE /api/v3/admin/returns/:id
+POST /api/v3/admin/returns/:id/approve
+POST /api/v3/admin/returns/:id/receive
+POST /api/v3/admin/returns/:id/refund
+
+# Exchanges
+POST /api/v3/admin/orders/:order_id/exchanges
+GET /api/v3/admin/orders/:order_id/exchanges
+PATCH /api/v3/admin/exchanges/:id
+POST /api/v3/admin/exchanges/:id/approve
+POST /api/v3/admin/exchanges/:id/receive
+POST /api/v3/admin/exchanges/:id/fulfill
+
+# Claims
+POST /api/v3/admin/orders/:order_id/claims
+GET /api/v3/admin/orders/:order_id/claims
+PATCH /api/v3/admin/claims/:id
+POST /api/v3/admin/claims/:id/approve
+POST /api/v3/admin/claims/:id/resolve
+
+# Store API: customers can initiate returns/claims
+POST /api/v3/store/orders/:order_id/returns
+POST /api/v3/store/orders/:order_id/claims
+GET /api/v3/store/orders/:order_id/returns
+GET /api/v3/store/orders/:order_id/claims
+```
+
+## Constraints on Current Work
+
+- **Don't add new features to ReturnAuthorization, CustomerReturn, or Reimbursement.** They're being replaced.
+- **Don't add new ReimbursementType subtypes.** The STI hierarchy is being dropped.
+- **New return/exchange logic should be designed for the three-model pattern.** Think "Return with ReturnItems" not "ReturnAuthorization with ReturnItems through CustomerReturn."
+- **Refund stays as-is.** It's the payment-level primitive. Returns, Exchanges, and Claims create Refunds when money needs to go back.
+
+## Resolved Questions
+
+1. **Store API return initiation.** Both Store API (self-service) and Admin API. Customers can initiate returns and claims; exchanges may require admin approval depending on store config. Self-service returns are the modern standard — backoffice-only is legacy.
+
+2. **Return shipping labels.** Yes. Return gains `generate_label` which delegates to the FulfillmentProvider interface (from 6.0-fulfillment-and-delivery.md). E.g., `return.generate_label` calls EasyPost to create a prepaid return label. The label URL is stored on the Return record. Add `return_label_url` column.
+
+3. **Partial returns/exchanges.** No separate "case" or "ticket" model. All three entities belong to Order — `order.returns`, `order.exchanges`, `order.claims` gives the full picture. The admin UI shows a unified "Post-sale" tab on the order page listing all three chronologically. If correlation is needed (e.g., "this claim was filed because the exchange arrived damaged"), use the `metadata` JSON column.
+
+## Open Questions
+
+None at this time.
+
+## References
+
+- Current return models: `spree/core/app/models/spree/return_authorization.rb`, `return_item.rb`, `customer_return.rb`, `reimbursement.rb`
+- Current ReimbursementType hierarchy: `spree/core/app/models/spree/reimbursement_type/`
+- Related plan: `6.0-fulfillment-and-delivery.md` (FulfillmentItem replaces InventoryUnit, Fulfillment replaces Shipment)
+- Related plan: `6.0-split-adjustments.md` (return credits removed from adjustment system)
+- Related plan: `6.0-typed-stock-movements.md` (restock on return creates `received` movement)
diff --git a/docs/plans/6.0-split-adjustments.md b/docs/plans/6.0-split-adjustments.md
new file mode 100644
index 0000000000..27cb6cb8b1
--- /dev/null
+++ b/docs/plans/6.0-split-adjustments.md
@@ -0,0 +1,496 @@
+# Split Adjustments into Typed Tables
+
+**Status:** Draft
+**Target:** Spree 6.0
+**Depends on:** None (standalone)
+**Author:** Damian + Claude
+**Last updated:** 2026-03-16
+
+## 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.
+
+The `Spree.adjusters` extensibility pattern is preserved — developers register custom adjusters that write to the appropriate typed table.
+
+## Problem
+
+### 1. Polymorphic source prevents eager loading
+
+`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.
+
+### 2. Polymorphic adjustable adds complexity
+
+`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.
+
+### 3. One table does too many jobs
+
+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)
+
+Scopes like `tax`, `promotion`, `shipping`, `price` all filter by string-matching `source_type` or `adjustable_type` — unindexed class name comparisons.
+
+### 4. Recalculation is N+1 heavy
+
+`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.
+
+### 5. State machine is unnecessary
+
+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.
+
+### Current blast radius
+
+| 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 |
+
+## 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
+
+- **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.
+
+- **All three models belong to `order`** directly — for order-level queries (`order.tax_lines`, `order.discounts`).
+
+- **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 `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.
+
+- **Keep `Spree.adjusters` registry** for extensibility. Custom adjusters write to `Fee` (or `Discount` for custom discount types). Registration pattern unchanged.
+
+- **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.
+
+## Design Details
+
+### TaxLine
+
+```ruby
+class Spree::TaxLine < Spree.base_class
+ has_prefix_id :tl
+
+ belongs_to :order, class_name: 'Spree::Order', inverse_of: :tax_lines
+ belongs_to :tax_rate, class_name: 'Spree::TaxRate'
+
+ # Concrete adjustable — one of these is set, not both
+ belongs_to :line_item, class_name: 'Spree::LineItem', optional: true
+ belongs_to :shipment, class_name: 'Spree::Shipment', optional: true
+
+ validates :amount, numericality: true
+ validates :label, presence: true
+ validate :exactly_one_adjustable
+
+ # Replaces adjustment.included? — tax can be included in price or additional
+ attribute :included, :boolean, default: false
+
+ scope :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
+end
+```
+
+### Discount
+
+```ruby
+class Spree::Discount < Spree.base_class
+ has_prefix_id :disc
+
+ belongs_to :order, class_name: 'Spree::Order', inverse_of: :discounts
+ belongs_to :promotion_action, class_name: 'Spree::PromotionAction', optional: true
+ belongs_to :promotion, class_name: 'Spree::Promotion', optional: true
+
+ # Concrete adjustable — always one of these (order-level discounts distributed to line items)
+ belongs_to :line_item, class_name: 'Spree::LineItem', optional: true
+ belongs_to :shipment, class_name: 'Spree::Shipment', optional: true
+
+ validates :amount, numericality: true # always negative (credit)
+ validates :label, presence: true
+ validate :exactly_one_adjustable
+
+ scope :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 :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?
+ end
+end
+```
+
+### Fee (extensible)
+
+```ruby
+class Spree::Fee < Spree.base_class
+ has_prefix_id :fee
+
+ belongs_to :order, class_name: 'Spree::Order', inverse_of: :fees
+
+ # Concrete adjustable
+ belongs_to :line_item, class_name: 'Spree::LineItem', optional: true
+ belongs_to :shipment, class_name: 'Spree::Shipment', optional: true
+
+ validates :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
+end
+```
+
+### Order associations
+
+```ruby
+class Spree::Order < 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
+
+ # Convenience through-associations
+ has_many :line_item_tax_lines, through: :line_items, source: :tax_lines
+ has_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
+end
+```
+
+### LineItem / Shipment associations
+
+```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
+
+ # Denormalized totals stay — recomputed from typed tables
+ # included_tax_total, additional_tax_total, promo_total, adjustment_total
+end
+
+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
+end
+```
+
+### Recalculation (new)
+
+The `AdjustmentsUpdater` is replaced by typed updaters that can eager-load their sources:
+
+```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
+
+ private
+
+ 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)
+
+ 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
+
+ def update_discount_totals
+ # Single query
+ order.promo_total = order.discounts.sum(:amount) # always negative
+ end
+
+ def update_fee_totals
+ order.fee_total = order.fees.sum(:amount)
+ end
+end
+```
+
+### TaxRate (source side changes)
+
+```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
+```
+
+### PromotionAction (source side changes)
+
+```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
+ end
+end
+```
+
+### Best-promo selection (simplified)
+
+Instead of writing all competing promo adjustments and then marking losers as `eligible: false`, we compute all candidates and only persist the winner:
+
+```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: ... }, ...]
+
+ best = candidates.min_by { |c| c[:amount] } # most negative = biggest discount
+ return unless best
+
+ # Delete any existing non-winning discounts for this adjustable
+ adjustable.discounts.where.not(promotion_action_id: best[:promotion_action].id).destroy_all
+
+ # 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
+```
+
+No `eligible` flag, no write-then-update-all. Only the winner is stored.
+
+### Extensibility
+
+Custom adjustment types register as adjusters and write to `Fee`:
+
+```ruby
+# config/initializers/spree.rb
+Spree.adjusters << MyApp::Adjustable::Adjuster::GiftWrap
+
+# 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?
+
+ 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
+
+ @totals[:non_taxable_adjustment_total] += 5.99
+ end
+end
+```
+
+For custom discount types, same pattern with `Discount`:
+
+```ruby
+class MyApp::Adjustable::Adjuster::LoyaltyDiscount < Spree::Adjustable::Adjuster::Base
+ def update
+ points = adjustable.order.user&.loyalty_points || 0
+ return if points.zero?
+
+ discount_amount = [points * 0.01, adjustable.amount * 0.1].min
+
+ 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
+```
+
+## Migration Path
+
+### Phase 1: Create new tables
+
+```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
+```
+
+### Phase 2: Data migration (rake task)
+
+```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)
+```
+
+### 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
+
+### Phase 4: API + serializer updates
+
+- `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`
+
+### Phase 5: Cleanup (6.1)
+
+- Drop `spree_adjustments` table
+- Remove `Spree::Adjustment` model
+- Remove all legacy scopes and methods
+
+## 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.
+
+## 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.
+
+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`.
+
+## Open Questions
+
+None at this time.
+
+## References
+
+- 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`
diff --git a/docs/plans/6.0-stock-reservations.md b/docs/plans/6.0-stock-reservations.md
new file mode 100644
index 0000000000..ca896c52d5
--- /dev/null
+++ b/docs/plans/6.0-stock-reservations.md
@@ -0,0 +1,400 @@
+# Stock Reservations
+
+**Status:** Design finalized, implementation not started
+**Target:** Spree 6.0
+**Depends on:** Cart/Order split (6.0-cart-order-split.md)
+**Author:** Damian + Claude
+**Last updated:** 2026-03-16
+
+## Summary
+
+Add time-limited stock reservations during checkout to prevent overselling. When a customer enters checkout, their line item quantities are soft-held against `StockItem.count_on_hand` with a configurable TTL. Other customers see reduced availability. If the reservation expires (abandoned checkout), stock is automatically released. On order completion, the reservation converts to a permanent decrement of `count_on_hand`.
+
+This is purely additive — the existing `StockItem`, `StockMovement`, and `InventoryUnit` models are unchanged. Reservations are a new layer on top.
+
+## Problem
+
+Today, stock is only checked at the moment of order completion (`ensure_line_items_are_in_stock`). No stock is held during checkout. This means:
+
+1. **Two customers can checkout the same last unit simultaneously.** Both see it as available, both enter payment details, one fails at completion.
+2. **Failure happens at the worst moment** — after address, shipping, and payment entry. Maximum friction, maximum abandonment.
+3. **Flash sales and limited drops are unusable** — high-demand items oversell because there's no reservation window.
+4. **No visibility into pending demand** — merchants can't see how much stock is "in checkout" vs truly available.
+
+Every modern commerce platform solves this with time-limited reservations.
+
+## Key Decisions (do not deviate without discussion)
+
+- **New model `Spree::StockReservation`** — concrete FKs to `stock_item`, `line_item`, `order`. No polymorphism.
+- **`StockItem.count_on_hand` is never modified by reservations.** It only changes on order completion (decrement) or stock adjustment. Reservations are a soft hold computed at query time.
+- **Available quantity = `count_on_hand - active_reservations`** — the `Quantifier` is updated to subtract active reservations from physical stock.
+- **Configurable trigger** — `Spree::Config[:reserve_stock_on]` controls when reservations are created: `:checkout` (when entering checkout, default) or `:cart` (when adding to cart). Cart-level is more aggressive, checkout-level is the standard.
+- **Configurable TTL per store** — `store.preferred_stock_reservation_ttl` (default: 10 minutes). Merchants can tune this based on their checkout complexity.
+- **Reservations extend on activity** — each checkout interaction (address update, shipping selection, payment) resets `expires_at` to prevent expiry during active checkout.
+- **Background job expires reservations** — `Spree::StockReservations::ExpireJob` runs periodically, deletes expired records. Simple `DELETE WHERE expires_at < NOW()`.
+- **On order completion: reservation deleted, `count_on_hand` decremented** — the existing stock decrement logic stays, reservation is just cleaned up.
+- **Backorderable items skip reservation** — if `StockItem.backorderable?`, no reservation needed (unlimited supply).
+- **Reservation is optional** — stores can disable it entirely via `Spree::Config[:stock_reservations_enabled] = false` (default: `true`). When disabled, behavior is identical to today.
+
+## Design Details
+
+### StockReservation model
+
+```ruby
+class Spree::StockReservation < Spree.base_class
+ has_prefix_id :res
+
+ belongs_to :stock_item, class_name: 'Spree::StockItem'
+ belongs_to :line_item, class_name: 'Spree::LineItem'
+ belongs_to :order, class_name: 'Spree::Order'
+
+ validates :stock_item, :line_item, :order, :quantity, :expires_at, presence: true
+ validates :quantity, numericality: { greater_than: 0, only_integer: true }
+ validates :line_item_id, uniqueness: { scope: :stock_item_id }
+
+ scope :active, -> { where('expires_at > ?', Time.current) }
+ scope :expired, -> { where('expires_at <= ?', Time.current) }
+ scope :for_variant, ->(variant) { joins(:stock_item).where(spree_stock_items: { variant_id: variant.id }) }
+ scope :for_order, ->(order) { where(order: order) }
+
+ def active?
+ expires_at > Time.current
+ end
+
+ def expired?
+ !active?
+ end
+
+ def extend!(duration = nil)
+ duration ||= order.store.preferred_stock_reservation_ttl.minutes
+ update!(expires_at: Time.current + duration)
+ end
+
+ def release!
+ destroy!
+ end
+end
+```
+
+### Quantifier changes
+
+```ruby
+class Spree::Stock::Quantifier
+ def total_on_hand
+ @total_on_hand ||= if variant.should_track_inventory?
+ raw_count_on_hand - reserved_quantity
+ else
+ BigDecimal::INFINITY
+ end
+ end
+
+ def reserved_quantity
+ return 0 unless Spree::Config[:stock_reservations_enabled]
+
+ @reserved_quantity ||= Spree::StockReservation
+ .active
+ .where(stock_item: stock_items)
+ .sum(:quantity)
+ end
+
+ # Existing: physical count without reservations (for admin/reporting)
+ def raw_count_on_hand
+ if association_loaded?
+ stock_items.sum(&:count_on_hand)
+ else
+ stock_items.sum(:count_on_hand)
+ end
+ end
+end
+```
+
+### Reservation service
+
+```ruby
+module Spree
+ module StockReservations
+ class Reserve
+ prepend Spree::ServiceModule::Base
+
+ def call(order:)
+ return success(order) unless Spree::Config[:stock_reservations_enabled]
+
+ ttl = order.store.preferred_stock_reservation_ttl.minutes
+ expires_at = Time.current + ttl
+
+ ApplicationRecord.transaction do
+ order.line_items.includes(variant: :stock_items).each do |line_item|
+ next unless line_item.variant.should_track_inventory?
+
+ stock_item = select_stock_item(line_item.variant)
+ next if stock_item.nil? || stock_item.backorderable?
+
+ # Check availability (count_on_hand minus other reservations)
+ available = stock_item.count_on_hand - other_reservations(stock_item, order)
+ if available < line_item.quantity
+ return failure(line_item, Spree.t(:insufficient_stock_for_reservation,
+ item: line_item.variant.name, available: [available, 0].max))
+ end
+
+ # Upsert reservation
+ reservation = Spree::StockReservation.find_or_initialize_by(
+ stock_item: stock_item,
+ line_item: line_item,
+ order: order
+ )
+ reservation.quantity = line_item.quantity
+ reservation.expires_at = expires_at
+ reservation.save!
+ end
+ end
+
+ success(order)
+ end
+
+ private
+
+ def select_stock_item(variant)
+ variant.stock_items.detect { |si| si.stock_location.active? && si.available? }
+ end
+
+ def other_reservations(stock_item, exclude_order)
+ Spree::StockReservation
+ .active
+ .where(stock_item: stock_item)
+ .where.not(order: exclude_order)
+ .sum(:quantity)
+ end
+ end
+ end
+end
+```
+
+### Release service
+
+```ruby
+module Spree
+ module StockReservations
+ class Release
+ prepend Spree::ServiceModule::Base
+
+ def call(order:)
+ Spree::StockReservation.where(order: order).delete_all
+ success(order)
+ end
+ end
+ end
+end
+```
+
+### Extend service (on checkout activity)
+
+```ruby
+module Spree
+ module StockReservations
+ class Extend
+ prepend Spree::ServiceModule::Base
+
+ def call(order:)
+ return success(order) unless Spree::Config[:stock_reservations_enabled]
+
+ ttl = order.store.preferred_stock_reservation_ttl.minutes
+ expires_at = Time.current + ttl
+
+ Spree::StockReservation
+ .where(order: order)
+ .update_all(expires_at: expires_at, updated_at: Time.current)
+
+ success(order)
+ end
+ end
+ end
+end
+```
+
+### Expire job
+
+```ruby
+module Spree
+ module StockReservations
+ class ExpireJob < ApplicationJob
+ def perform
+ Spree::StockReservation.expired.delete_all
+ end
+ end
+ end
+end
+```
+
+Scheduled via `cron` or `solid_queue` recurring task — runs every 1 minute.
+
+### Integration points
+
+#### Checkout service (reserve on entering checkout)
+
+```ruby
+# In Spree::Checkout::Next or Spree::Checkout::Update
+# When order transitions from 'cart' to 'address' (first checkout step):
+
+after_transition from: :cart do |order|
+ Spree::StockReservations::Reserve.call(order: order)
+end
+```
+
+With the Cart/Order split (6.0-cart-order-split.md), this happens in `Spree::Carts::Complete` when the cart converts to an order.
+
+#### Checkout activity (extend on each step)
+
+```ruby
+# In Spree::Checkout::Update, after any successful step update:
+Spree::StockReservations::Extend.call(order: order)
+```
+
+#### Order completion (release reservation, decrement stock)
+
+```ruby
+# In Spree::Checkout::Complete, after order is finalized:
+# Existing stock decrement logic runs (InventoryUnit creation, count_on_hand decrement)
+# Then clean up the reservation:
+Spree::StockReservations::Release.call(order: order)
+```
+
+#### Cart emptied / order canceled
+
+```ruby
+# In Spree::Cart::Empty and order cancellation:
+Spree::StockReservations::Release.call(order: order)
+```
+
+#### Line item quantity changed
+
+```ruby
+# In Spree::Cart::SetQuantity, after quantity update:
+# Re-run reservation to adjust quantities
+Spree::StockReservations::Reserve.call(order: order)
+```
+
+#### Line item removed
+
+```ruby
+# In Spree::Cart::RemoveLineItem:
+# Reservation for that line item auto-deleted via dependent: :destroy on LineItem
+# Or explicit release:
+Spree::StockReservation.where(line_item: line_item).delete_all
+```
+
+### Store API
+
+New read-only field on variants:
+
+```json
+{
+ "id": "variant_k5nR8xLq",
+ "in_stock": true,
+ "total_on_hand": 5,
+ "reserved_quantity": 2,
+ "available_quantity": 3
+}
+```
+
+`available_quantity` = `total_on_hand` (already reflects reservations via Quantifier).
+
+Admin API gets reservation visibility:
+
+```
+GET /api/v3/admin/stock_reservations?filter[variant_id]=variant_xxx
+```
+
+```json
+{
+ "id": "res_abc",
+ "stock_item_id": "si_xyz",
+ "line_item_id": "li_123",
+ "order_id": "or_456",
+ "quantity": 2,
+ "expires_at": "2026-03-16T14:35:00Z",
+ "active": true
+}
+```
+
+### Configuration
+
+```ruby
+Spree::Config[:stock_reservations_enabled] = true # default: true
+Spree::Config[:reserve_stock_on] = :checkout # :checkout or :cart
+
+# Per-store TTL (minutes)
+store.preferred_stock_reservation_ttl = 10 # default: 10
+```
+
+### Database schema
+
+```ruby
+class CreateSpreeStockReservations < ActiveRecord::Migration[7.2]
+ def change
+ create_table :spree_stock_reservations do |t|
+ t.references :stock_item, null: false
+ t.references :line_item, null: false
+ t.references :order, null: false
+ t.integer :quantity, null: false
+ t.datetime :expires_at, null: false
+ t.timestamps
+ end
+
+ add_index :spree_stock_reservations, [:stock_item_id, :line_item_id], unique: true,
+ name: 'idx_stock_reservations_item_line_item'
+ add_index :spree_stock_reservations, :expires_at,
+ name: 'idx_stock_reservations_expires_at'
+ add_index :spree_stock_reservations, :order_id
+ end
+end
+```
+
+## Migration Path
+
+This is purely additive — no existing tables or models are modified (beyond Quantifier logic).
+
+### Phase 1: Model + migration + services
+
+- Create `StockReservation` model and table
+- Create `Reserve`, `Release`, `Extend`, `ExpireJob` services
+- Update `Quantifier` to subtract reservations
+- Add configuration options
+
+### Phase 2: Checkout integration
+
+- Wire `Reserve` into checkout entry
+- Wire `Extend` into checkout step updates
+- Wire `Release` into order completion and cancellation
+- Add `ExpireJob` to recurring job schedule
+
+### Phase 3: API + admin visibility
+
+- Add `reserved_quantity` / `available_quantity` to variant serializer
+- Add admin API for stock reservations
+- Admin dashboard: show reservations on stock management page
+
+### Phase 4: Cart-level reservation (optional)
+
+- If `reserve_stock_on: :cart`, wire `Reserve` into `Cart::AddItem` and `Cart::SetQuantity`
+- More aggressive but prevents add-to-cart for truly out-of-stock items
+
+## Constraints on Current Work
+
+- **Don't modify `StockItem.count_on_hand` for reservations.** Reservations are a separate layer. `count_on_hand` only changes on order completion, stock adjustments, and shipment.
+- **Use `Quantifier#total_on_hand` for availability checks.** Don't query `count_on_hand` directly — the quantifier will handle the reservation subtraction.
+- **New checkout services should call `StockReservations::Extend`** after any successful step to keep reservations alive.
+
+## Open Questions
+
+1. **Multi-location reservation.** When a store has multiple stock locations, should the reservation lock stock at a specific location (determined at reservation time) or float until fulfillment? Locking early is simpler but may lead to suboptimal warehouse selection. Floating requires re-checking at completion.
+
+2. **Reservation failure UX.** When stock runs out during reservation (another customer completed first), should the checkout: (a) block the transition with an error, (b) auto-adjust the quantity down and notify, or (c) allow proceeding with a backorder warning? Probably (a) by default with (b) as an option.
+
+3. **Reservation visibility in Store API.** Should the Store API expose that an item has "only 3 left" (accounting for reservations) to create urgency? Or only expose boolean `in_stock`? This is a merchandising decision that could be store-configurable.
+
+## References
+
+- Current stock system: `spree/core/app/models/spree/stock_item.rb`, `spree/core/app/models/spree/stock/quantifier.rb`
+- Current stock check at completion: `spree/core/app/models/spree/order.rb:600` (`ensure_line_items_are_in_stock`)
+- Industry pattern: time-limited reservations with TTL expiry
+- Related plan: `6.0-cart-order-split.md` (reservation created when Cart converts to Order)
diff --git a/docs/plans/6.0-typed-stock-movements.md b/docs/plans/6.0-typed-stock-movements.md
new file mode 100644
index 0000000000..d1fea89834
--- /dev/null
+++ b/docs/plans/6.0-typed-stock-movements.md
@@ -0,0 +1,420 @@
+# Typed Stock Movements
+
+**Status:** Draft
+**Target:** Spree 6.0
+**Depends on:** Stock Reservations (6.0-stock-reservations.md), Remove Master Variant (6.0-remove-master-variant.md)
+**Author:** Damian + Claude
+**Last updated:** 2026-03-16
+
+## Summary
+
+Replace the generic `Spree::StockMovement` (quantity + polymorphic originator) with typed movement records that explicitly describe what happened to stock and why. Each type has concrete FKs to its cause — no polymorphic `originator`.
+
+This gives merchants a full audit trail ("10 units allocated to order or_abc, 3 units shipped in ship_xyz, 2 units returned via RA ra_456") instead of today's opaque list of positive/negative numbers.
+
+## Problem
+
+### 1. No semantic meaning
+
+Today's `StockMovement` is just `{ quantity: -3, originator_type: 'Spree::Shipment', originator_id: 42 }`. You can't answer "how many units are allocated to pending orders?" or "how many units were returned this month?" without parsing originator types and guessing the business meaning of positive vs negative quantities.
+
+### 2. Polymorphic originator
+
+`belongs_to :originator, polymorphic: true` — same problem as polymorphic Adjustment. Can't eager load, can't JOIN cleanly. Originator can be `Shipment`, `ReturnAuthorization`, `StockTransfer`, or `nil` (manual adjustment).
+
+### 3. No allocation tracking
+
+When an order is placed, stock should be **allocated** (reserved for fulfillment) before it's **shipped** (physically removed). Today there's no allocation concept — stock decrements happen at various points (shipment creation, shipment shipping) depending on configuration, with no clear audit of the transition.
+
+### 4. No movement lifecycle
+
+There's no way to trace the lifecycle of a unit: received → allocated → shipped. Or: received → allocated → released (order canceled). Each step is just an anonymous +/- on count_on_hand.
+
+## Current State
+
+| What | How it works |
+|------|-------------|
+| `StockMovement` | `quantity` (int) + `originator` (polymorphic) + `stock_item_id` |
+| Shipment ships | `stock_location.unstock(variant, qty, shipment)` → creates movement with negative qty |
+| Return received | `StockMovement.create!(stock_item_id:, quantity: +qty, originator: return_authorization)` |
+| Stock transfer | `source.unstock(...)` + `destination.restock(...)` → two movements, linked by StockTransfer originator |
+| Manual adjustment | `stock_item.adjust_count_on_hand(value)` → no movement record (!) |
+| Fulfillment change | `current_location.restock(...)` + `desired_location.unstock(...)` |
+| After create | `update_stock_item_quantity` → calls `stock_item.adjust_count_on_hand` |
+| Immutable | `readonly?` returns true after persist — movements can't be edited |
+
+Originator types in practice: `Spree::Shipment`, `Spree::ReturnAuthorization`, `Spree::StockTransfer`, `nil`.
+
+## Key Decisions (do not deviate without discussion)
+
+- **Single table with `kind` column** (not separate tables per type). Stock movements are all the same shape (stock_item, quantity, timestamp, reason) — splitting into 5 tables would add complexity without benefit. The `kind` column is an indexed string, not a polymorphic type.
+- **Concrete FKs replace polymorphic originator.** Separate nullable FKs: `shipment_id`, `order_id`, `return_authorization_id`, `stock_transfer_id`. Each movement has at most one set.
+- **Five defined kinds:**
+ - `received` — stock added (purchase order, manual receipt, return restock)
+ - `allocated` — stock earmarked for an order (on order completion or payment authorization)
+ - `shipped` — allocated stock physically sent (on shipment ship)
+ - `released` — allocated stock returned to available (order canceled, fulfillment changed)
+ - `adjusted` — manual correction (admin inventory count, shrinkage, damage)
+- **Movements are immutable.** Existing `readonly?` pattern stays. To reverse a movement, create a counterpart (e.g., `released` reverses `allocated`).
+- **`count_on_hand` semantics change.** Today it's the only number. After:
+ - `count_on_hand` = physical stock at location (unchanged by allocation, only by receipt/ship/adjust)
+ - `allocated_quantity` = derived from movements (`SUM of allocated - shipped - released`)
+ - `available_quantity` = `count_on_hand - allocated_quantity - reserved_quantity` (from StockReservations plan)
+- **`StockItem` gets `allocated_count` denormalized column** — updated on allocation/release/ship movements. Avoids SUM query on every availability check.
+- **Keep `StockLocation.restock/unstock` methods** but they create typed movements instead of generic ones.
+
+## Design Details
+
+### StockMovement model (rewritten)
+
+```ruby
+class Spree::StockMovement < Spree.base_class
+ has_prefix_id :sm
+
+ KINDS = %w[received allocated shipped released adjusted].freeze
+
+ include Spree::StockMovement::Webhooks
+ include Spree::StockMovement::CustomEvents
+
+ publishes_lifecycle_events
+
+ belongs_to :stock_item, class_name: 'Spree::StockItem', inverse_of: :stock_movements
+
+ # Concrete FKs — at most one is set per movement
+ belongs_to :order, class_name: 'Spree::Order', optional: true
+ belongs_to :shipment, class_name: 'Spree::Shipment', optional: true
+ belongs_to :return_authorization, class_name: 'Spree::ReturnAuthorization', optional: true
+ belongs_to :stock_transfer, class_name: 'Spree::StockTransfer', optional: true
+
+ validates :stock_item, :quantity, :kind, presence: true
+ validates :kind, inclusion: { in: KINDS }
+ validates :quantity, numericality: { other_than: 0, only_integer: true }
+ validates :reason, presence: true, if: -> { kind == 'adjusted' }
+
+ after_create :update_stock_item_quantities
+
+ scope :recent, -> { order(created_at: :desc) }
+ scope :by_kind, ->(kind) { where(kind: kind) }
+ scope :received, -> { by_kind('received') }
+ scope :allocated, -> { by_kind('allocated') }
+ scope :shipped, -> { by_kind('shipped') }
+ scope :released, -> { by_kind('released') }
+ scope :adjusted, -> { by_kind('adjusted') }
+ scope :for_order, ->(order) { where(order: order) }
+ scope :for_shipment, ->(shipment) { where(shipment: shipment) }
+
+ delegate :variant, :variant_id, to: :stock_item, allow_nil: true
+
+ def readonly?
+ persisted?
+ end
+
+ private
+
+ def update_stock_item_quantities
+ return unless stock_item.should_track_inventory?
+
+ case kind
+ when 'received', 'adjusted'
+ # Changes physical count
+ stock_item.adjust_count_on_hand(quantity)
+ when 'allocated'
+ # Earmarks stock — no count_on_hand change, increment allocated_count
+ stock_item.increment!(:allocated_count, quantity.abs)
+ when 'shipped'
+ # Physically removed — decrement count_on_hand, decrement allocated_count
+ stock_item.adjust_count_on_hand(-quantity.abs)
+ stock_item.decrement!(:allocated_count, quantity.abs)
+ when 'released'
+ # Returns to available — decrement allocated_count only
+ stock_item.decrement!(:allocated_count, quantity.abs)
+ end
+ end
+end
+```
+
+### StockItem changes
+
+```ruby
+class Spree::StockItem < Spree.base_class
+ # Existing
+ # count_on_hand — physical stock at location
+
+ # New denormalized column
+ # allocated_count — units earmarked for pending orders
+
+ def available_count
+ count_on_hand - allocated_count
+ end
+
+ # Used by Quantifier (replaces raw count_on_hand)
+ def available?
+ available_count > 0 || backorderable?
+ end
+end
+```
+
+### Quantifier changes
+
+```ruby
+class Spree::Stock::Quantifier
+ def total_on_hand
+ @total_on_hand ||= if variant.should_track_inventory?
+ available_stock - reserved_quantity
+ else
+ BigDecimal::INFINITY
+ end
+ end
+
+ # Physical stock minus allocated (pending fulfillment)
+ def available_stock
+ if association_loaded?
+ stock_items.sum(&:available_count)
+ else
+ stock_items.sum('count_on_hand - allocated_count')
+ end
+ end
+
+ # From StockReservations plan
+ def reserved_quantity
+ return 0 unless Spree::Config[:stock_reservations_enabled]
+
+ Spree::StockReservation.active.where(stock_item: stock_items).sum(:quantity)
+ end
+end
+```
+
+**Full availability formula:**
+```
+available = count_on_hand - allocated_count - reserved_quantity
+```
+
+Where:
+- `count_on_hand` = physical units at location
+- `allocated_count` = units earmarked for orders awaiting shipment
+- `reserved_quantity` = units held during checkout (from StockReservations plan)
+
+### StockLocation changes
+
+```ruby
+class Spree::StockLocation < Spree.base_class
+ # Restock: units received at location
+ def restock(variant, quantity, originator = nil)
+ stock_item = stock_item_or_create(variant)
+ stock_item.stock_movements.create!(
+ quantity: quantity,
+ kind: 'received',
+ stock_transfer: originator.is_a?(Spree::StockTransfer) ? originator : nil,
+ return_authorization: originator.is_a?(Spree::ReturnAuthorization) ? originator : nil
+ )
+ end
+
+ # Unstock: units physically leaving location (shipped)
+ def unstock(variant, quantity, shipment)
+ stock_item = stock_item_or_create(variant)
+ stock_item.stock_movements.create!(
+ quantity: quantity,
+ kind: 'shipped',
+ shipment: shipment,
+ order: shipment.order
+ )
+ end
+
+ # Allocate: earmark units for an order
+ def allocate(variant, quantity, order)
+ stock_item = stock_item_or_create(variant)
+ stock_item.stock_movements.create!(
+ quantity: quantity,
+ kind: 'allocated',
+ order: order
+ )
+ end
+
+ # Release: return allocated units to available
+ def release(variant, quantity, order)
+ stock_item = stock_item_or_create(variant)
+ stock_item.stock_movements.create!(
+ quantity: quantity,
+ kind: 'released',
+ order: order
+ )
+ end
+
+ # Adjust: manual inventory correction
+ def adjust(variant, quantity, reason:)
+ stock_item = stock_item_or_create(variant)
+ stock_item.stock_movements.create!(
+ quantity: quantity,
+ kind: 'adjusted',
+ reason: reason
+ )
+ end
+end
+```
+
+### Order lifecycle integration
+
+With the Cart/Order split (6.0-cart-order-split.md), the order state machine is gone. `cart.complete!` calls `Spree::Carts::Complete` which creates a new Order. Stock allocation happens at this point — when the cart converts to an order.
+
+```ruby
+# On cart completion (Spree::Carts::Complete):
+# Reservation (from StockReservations plan) is released, allocation created
+order.line_items.each do |li|
+ stock_location = select_stock_location(li.variant)
+ stock_location.allocate(li.variant, li.quantity, order)
+end
+# Release checkout reservation (reservation plan handles this)
+
+# On shipment ship:
+# Convert allocation to shipped (count_on_hand decremented, allocated_count decremented)
+shipment.inventory_units.each do |iu|
+ shipment.stock_location.unstock(iu.variant, iu.quantity, shipment)
+end
+
+# On order cancellation:
+# Release allocated stock
+order.line_items.each do |li|
+ stock_location.release(li.variant, li.quantity, order)
+end
+
+# On return received:
+# Restock units
+stock_location.restock(variant, quantity, return_authorization)
+```
+
+### Admin API
+
+```
+GET /api/v3/admin/stock_movements?filter[stock_item_id]=si_xxx
+GET /api/v3/admin/stock_movements?filter[kind]=allocated&filter[order_id]=or_abc
+```
+
+Response:
+```json
+{
+ "id": "sm_k5nR8xLq",
+ "kind": "allocated",
+ "quantity": 3,
+ "stock_item_id": "si_xyz",
+ "order_id": "or_abc",
+ "shipment_id": null,
+ "return_authorization_id": null,
+ "stock_transfer_id": null,
+ "reason": null,
+ "created_at": "2026-03-16T14:30:00Z"
+}
+```
+
+StockItem response gains `allocated_count` and `available_count`:
+```json
+{
+ "id": "si_xyz",
+ "count_on_hand": 50,
+ "allocated_count": 8,
+ "available_count": 42,
+ "backorderable": false
+}
+```
+
+## Migration Path
+
+### Phase 1: Schema changes
+
+```ruby
+class AddTypedStockMovements < ActiveRecord::Migration[7.2]
+ def change
+ # Add kind and concrete FKs to existing table
+ add_column :spree_stock_movements, :kind, :string
+ add_column :spree_stock_movements, :order_id, :bigint
+ add_column :spree_stock_movements, :shipment_id, :bigint
+ add_column :spree_stock_movements, :return_authorization_id, :bigint
+ add_column :spree_stock_movements, :stock_transfer_id, :bigint
+ add_column :spree_stock_movements, :reason, :string
+
+ add_index :spree_stock_movements, :kind
+ add_index :spree_stock_movements, :order_id
+ add_index :spree_stock_movements, :shipment_id
+
+ # Add allocated_count to stock_items
+ add_column :spree_stock_items, :allocated_count, :integer, null: false, default: 0
+ end
+end
+```
+
+### Phase 2: Data migration (rake task)
+
+```ruby
+# rake spree:type_stock_movements
+#
+# For each existing StockMovement:
+# originator_type == 'Spree::Shipment' && quantity < 0
+# → kind: 'shipped', shipment_id: originator_id, order_id: shipment.order_id
+# originator_type == 'Spree::Shipment' && quantity > 0
+# → kind: 'released', shipment_id: originator_id (fulfillment change restock)
+# originator_type == 'Spree::ReturnAuthorization'
+# → kind: 'received', return_authorization_id: originator_id
+# originator_type == 'Spree::StockTransfer' && quantity > 0
+# → kind: 'received', stock_transfer_id: originator_id
+# originator_type == 'Spree::StockTransfer' && quantity < 0
+# → kind: 'shipped', stock_transfer_id: originator_id
+# originator_type == nil
+# → kind: 'adjusted', reason: 'Legacy manual adjustment'
+#
+# Note: No historical 'allocated' movements exist (allocation didn't exist before).
+# allocated_count on StockItems starts at 0 — only new orders create allocations.
+```
+
+### Phase 3: Model update
+
+- Add `kind` validation, concrete FK associations
+- Update `update_stock_item_quantities` callback with kind-based logic
+- Update `StockLocation.restock/unstock` to create typed movements
+- Add `StockLocation.allocate/release/adjust` methods
+- Update `Quantifier` to use `available_count`
+- Wire allocation into order completion flow
+- Wire release into order cancellation flow
+
+### Phase 4: Remove polymorphic originator
+
+```ruby
+class RemoveOriginatorFromStockMovements < ActiveRecord::Migration[7.2]
+ def change
+ remove_column :spree_stock_movements, :originator_type
+ remove_column :spree_stock_movements, :originator_id
+
+ # kind is now required
+ change_column_null :spree_stock_movements, :kind, false
+ end
+end
+```
+
+### Phase 5: API + serializer updates
+
+- Add `kind`, concrete FK IDs to StockMovement serializer
+- Add `allocated_count`, `available_count` to StockItem serializer
+- Admin dashboard: stock movement history with kind filters
+
+## Constraints on Current Work
+
+- **Don't create StockMovements directly.** Use `StockLocation.restock/unstock/allocate/release/adjust` methods which will create properly typed movements.
+- **Don't rely on `originator_type` for business logic.** Use the `kind` column / scopes instead.
+- **Use `Quantifier#total_on_hand` for availability.** Don't query `count_on_hand` directly — the quantifier accounts for allocations and reservations.
+
+## Resolved Questions
+
+1. **Allocation timing.** Stock is allocated on **cart completion** — when `cart.complete!` creates the Order (see 6.0-cart-order-split.md). The checkout reservation (from 6.0-stock-reservations.md) is released at the same time. Flow: customer in checkout → reservation holds stock → cart completes → reservation released, allocation created → shipment ships → allocation converted to shipped.
+
+2. **Stock transfer movements.** Reuse `shipped`/`received` with a `stock_transfer_id` FK. A transfer is just shipping from one location and receiving at another. No new kinds needed.
+
+## Open Questions
+
+None at this time.
+
+## References
+
+- Current stock movement: `spree/core/app/models/spree/stock_movement.rb`
+- Current stock location restock/unstock: `spree/core/app/models/spree/stock_location.rb:96-114`
+- Current shipment unstock: `spree/core/app/models/spree/shipment.rb:491`
+- Current return restock: `spree/core/app/models/spree/return_item.rb:201`
+- Related plan: `6.0-stock-reservations.md` (reservations layer on top of availability)
+- Related plan: `6.0-split-adjustments.md` (same pattern: replace polymorphic with concrete FKs)
diff --git a/docs/plans/_template.md b/docs/plans/_template.md
new file mode 100644
index 0000000000..c6dec09a78
--- /dev/null
+++ b/docs/plans/_template.md
@@ -0,0 +1,32 @@
+# [Feature Name]
+
+**Status:** Draft | Design Finalized | In Progress | Complete
+**Target:** Spree X.Y
+**Depends on:** (other plans or features)
+**Author:** (who drove the design)
+**Last updated:** YYYY-MM-DD
+
+## Summary
+One paragraph explaining what this is and why.
+
+## Key Decisions (do not deviate without discussion)
+- Decision 1
+- Decision 2
+
+## Design Details
+The actual technical design. Models, APIs, flows, etc.
+
+## Migration Path
+How we get from current state to target state.
+Step-by-step if applicable.
+
+## Constraints on Current Work
+What developers/agents should do NOW even before
+this plan is implemented:
+- ...
+
+## Open Questions
+Things still unresolved.
+
+## References
+Links to related plans, PRs, discussions.
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
new file mode 100644
index 0000000000..ec528c4ece
--- /dev/null
+++ b/docs/plans/decisions.md
@@ -0,0 +1,82 @@
+## 2026-03-16: PaymentMethod and DeliveryMethod become SingleStoreResource
+Both PaymentMethod and DeliveryMethod (renamed from ShippingMethod) switch from
+multi-store join tables (`StorePaymentMethod`, `StoreShippingMethod`) to
+`SingleStoreResource` with direct `belongs_to :store`.
+
+In practice, different stores have different currencies, zones, and provider
+accounts — 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
+
+## 2026-03-16: Fix promotion rule/action STI namespacing
+Rename `Spree::Promotion::Rules::*` → `Spree::PromotionRules::*` and
+`Spree::Promotion::Actions::*` → `Spree::PromotionActions::*`.
+
+The convention for STI subtypes is `Spree::{BaseClass}s::{Subtype}` — pluralized
+base class as the namespace. Every other hierarchy follows this already:
+
+- `Spree::PriceRules::VolumeRule`
+- `Spree::Metafields::ShortText`
+- `Spree::CollectionRules::Tag` (from categories plan)
+- `Spree::ReimbursementType::Credit`
+
+Promotion was the only one nesting under the parent model (`Spree::Promotion::Rules`)
+instead of the base class (`Spree::PromotionRules`).
+
+Changes:
+- Move files from `app/models/spree/promotion/rules/` → `app/models/spree/promotion_rules/`
+- Move files from `app/models/spree/promotion/actions/` → `app/models/spree/promotion_actions/`
+- Data migration: update `type` column in `spree_promotion_rules` and `spree_promotion_actions`
+ (e.g., `Spree::Promotion::Rules::Product` → `Spree::PromotionRules::Product`)
+- Deprecation aliases for one release
+
+## 2026-03-16: Normalize state → status across all models
+Settle on `status` as the standard column name for state machines. Newer models
+(Product, PriceList, PaymentSession, Import, Invitation) already use `status`.
+
+Order.state and Adjustment.state are removed entirely by other 6.0 plans
+(cart-order-split, split-adjustments). Five remaining models need a column
+rename from `state` → `status` in 6.0:
+
+- **Payment** — `state` → `status`
+- **Shipment** — `state` → `status`
+- **InventoryUnit** — `state` → `status`
+- **ReturnAuthorization** — `state` → `status`
+- **GiftCard** — `state` → `status`
+
+Single migration renaming all five columns. State machine declarations updated
+to `state_machine :status, initial: ...`. Deprecation aliases
+(`alias_attribute :state, :status`) for one release.
+
+Models already correct (no change): Product, PriceList, PaymentSession,
+PaymentSetupSession, Import, ImportRow, Invitation, ReturnItem
+(`reception_status`/`acceptance_status`), Reimbursement (`reimbursement_status`).
+
+## 2026-03-16: Consolidate metadata — drop public_metadata, keep metadata JSON column
+Drop `public_metadata` column (never exposed in Store API, unused). Rename
+`private_metadata` → `metadata` in the database. Simplify the `Spree::Metadata`
+concern to a single `metadata` JSON column with no alias indirection.
+
+**Metadata** (JSON column) stays as a schemaless developer escape hatch —
+integration IDs, sync state, ad-hoc flags. No definition required, one-step API:
+`PATCH /product { metadata: { erp_id: "123" } }`. Never exposed in Store API
+(Stripe convention: write-only).
+
+**Metafields** stay as merchant-defined structured data — typed values
+(short_text, number, boolean, json, rich_text, long_text), require a
+`MetafieldDefinition`, have visibility control (front_end/back_end),
+searchable, CSV importable. With the ProductType plan (6.0-product-types.md),
+metafields become schema-enforced custom attributes driven by ProductType.
+
+Two systems, two purposes, no overlap. No consolidation into one.
+
+## 2026-03-10: Product descriptions stay as plain column
+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.