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.

Update plans

Damian Legawiec57c04ff64312
diff --git a/CLAUDE.md b/CLAUDE.md
index 0173cf6aef..a8c511717a 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -104,7 +104,7 @@ One-time machine setup: Homebrew `postgresql@18` running on :5432 (with a `postg
- All code namespaced under `Spree::` module
- Follow Rails conventions and the Rails Security Guide
-- RESTful routes and action names
+- RESTful routes and action names, AVID adding custom non CRUD/RESTful actions, promote them to sub-controllers
- 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`). This applies to **every** lookup in a controller, including the incidental ones — resolving a `reason_id` or `stock_location_id` from a create param through the model constant accepts an id belonging to another store. Reading it through `current_store.<association>` turns that into a 404, which is the cheapest defence against IDOR. `accessible_by(current_ability, ...)` is not a substitute: it filters by role, not by tenant.
- Ransack for filtering/searching, Pagy for pagination
@@ -134,9 +134,10 @@ Per-request context available in models, controllers, jobs, and services:
### Models
- ALWAYS Inherit from `Spree.base_class`
+- We're on Rails 8.1 so use all the new and available methods from this release
- New models carrying store-specific data (configuration, catalog, commerce records) ALWAYS `belongs_to :store` via `Spree::SingleStoreResource` — only genuinely global reference data (countries, states, roles) goes unscoped. Cross-store sharing is gone (`spree_multi_store` is legacy and unsupported)
- ALWAYS pass `class_name` and `dependent` on associations; use `dependent: :destroy_async` for high-fanout associations to offload deletion to a background job
-- Include `Spree::Metafields` for custom fields support (see docs/plans/5.4-6.0-custom-fields-rename.md)
+- Include `Spree::CustomFields` for custom fields support
- Include `Spree::Metadata` for JSON metadata support
- ALWAYS Use string columns instead of enums
- NEVER use `Struct` for domain value objects — use a plain Ruby class with `ActiveModel::Model` + `ActiveModel::Attributes` (typed attributes, validations) so it behaves like an ActiveRecord object (e.g. `Spree::PickupPointOption`)
@@ -151,6 +152,7 @@ Per-request context available in models, controllers, jobs, and services:
- ALWAYS use insert_all/upsert_all when creating records in bulk, this relies on proper database uniqueness indexes. Special treatment for MySQL is needed though
- ALWAYS put callbacks in private group
- ALWAYS use existing vocabulary and naming patterns, avoid slang terms
+- DO NOT override Rails core API methods, eg. `update```
```ruby
class Spree::Product < Spree.base_class
diff --git a/docs/plans/6.0-6.1-b2b-payment-terms.md b/docs/plans/6.0-6.1-b2b-payment-terms.md
index c448002810..b17341f9c4 100644
--- a/docs/plans/6.0-6.1-b2b-payment-terms.md
+++ b/docs/plans/6.0-6.1-b2b-payment-terms.md
@@ -140,7 +140,7 @@ credit is the commercial instrument (decided 2026-08-30).
multiple payments; payment due status; net terms; PO separation).
- `docs/plans/6.0-b2b-wholesale-shipping.md` — deposit collection
(amended: method deposit is now a source).
-- `spree-enterprise-v2/docs/plans/b2b-companies.md` — terms/invoicing
+- `ee/docs/plans/b2b-companies.md` — terms/invoicing
roadmap (the `net` kind's home); `b2b-quotes.md` — terms on quotations.
- Payments machinery: `spree/core/app/models/spree/payment.rb`
(`max_amount`), `app/services/spree/orders/update_statuses.rb`
diff --git a/docs/plans/6.0-b2b-companies-and-catalogs.md b/docs/plans/6.0-b2b-companies-and-catalogs.md
index 54eb0c0890..4d9bb2b383 100644
--- a/docs/plans/6.0-b2b-companies-and-catalogs.md
+++ b/docs/plans/6.0-b2b-companies-and-catalogs.md
@@ -76,7 +76,7 @@ Company → Employee; depth exists only in paid tiers elsewhere. Spree 6.0
ships it free, with the directory + hierarchy + catalogs in OSS and
governance (roles, approvals, spend limits, terms) layered on top by
Enterprise through hooks and policies — those plans live in the
-`spree-enterprise-v2` repository, never here.
+`ee` repository, never here.
## Why the shipped model is being replaced
@@ -173,7 +173,7 @@ existed as far as any upgrade path is concerned.
CRUD. Certificate verify/revoke keeps its existing workflow.
- **Enterprise governance layers on, never in.** Spending limits, approvals,
company roles, payment terms, quotes: their plans live in
- `spree-enterprise-v2/docs/plans/`, and they consume OSS hooks
+ `ee/docs/plans/`, and they consume OSS hooks
(`carts.complete.validate`), the storefront access policy class, dashboard
slots, and events. Any mechanism they need that does not exist is an OSS
contribution first.
@@ -286,7 +286,7 @@ class Spree::CompanyMembership < Spree.base_class
# role: cosmetic label only ('buyer' by convention). OSS has no company
# permission model — every member can do everything within their standing;
# the capability model is Enterprise
- # (spree-enterprise-v2/docs/plans/b2b-companies.md).
+ # (ee/docs/plans/b2b-companies.md).
end
```
@@ -568,7 +568,7 @@ Phases (each lands green on its own):
`Customers::Create`), writable cart `company_id`, catalog-aware product
listing/pricing through the existing gate.
5. **Dashboard** — companies tree UI, node page, catalogs pages, slot
- renames; Enterprise plan (`spree-enterprise-v2`) updated to the new slot
+ renames; Enterprise plan (`ee`) updated to the new slot
contracts.
6. **Docs + sample data** — wholesale channel demo gains a two-level company
with a division and per-tree catalog; `docs/use-case/b2b/*` reconciled.
@@ -592,7 +592,7 @@ Phases (each lands green on its own):
validation accepts.
- **No governance fields on OSS models.** Spending limits, approval settings,
role capabilities, payment terms do not get columns here — their plans live
- in `spree-enterprise-v2/docs/plans/` and consume hooks/slots/policies (the
+ in `ee/docs/plans/` and consume hooks/slots/policies (the
model-not-the-feature rule, decisions.md 2026-08-07).
- **Catalog and company lookups are store-scoped** like every controller
lookup (`current_store.companies`, `current_store.catalogs`) including
@@ -626,7 +626,7 @@ deferred:
- `6.0-tax-provider.md` Phase 7 — the shipped Company tree this replaces;
its exemption/identifier contracts are unchanged, only the anchor moves.
- `6.0-admin-rbac.md` — company capability vocabulary stays Enterprise-owned.
-- `spree-enterprise-v2/docs/plans/b2b-companies.md` — governance layer,
+- `ee/docs/plans/b2b-companies.md` — governance layer,
OSS/Enterprise boundary, slot contracts (updated with this plan).
- `5.5-6.0-order-cancellation-and-approval.md` — superseded 2026-09-02;
the Enterprise approval flow keeps its own record (OSS ships no
diff --git a/docs/plans/6.0-b2b-company-self-registration.md b/docs/plans/6.0-b2b-company-self-registration.md
index 1efa54782e..7ce9007768 100644
--- a/docs/plans/6.0-b2b-company-self-registration.md
+++ b/docs/plans/6.0-b2b-company-self-registration.md
@@ -21,7 +21,7 @@ posture means "company members only" — a useful trade-store feature on its
own. The merchant-approval *flow* (pending applications, verification
requirements, review queue, request-more-information) is the Enterprise
onboarding product built on these mechanisms (tier split decided 2026-08-30
-— see `spree-enterprise-v2/docs/plans/b2b-company-onboarding.md`; no
+— see `ee/docs/plans/b2b-company-onboarding.md`; no
competitor ships approval in open source, and everyone who has it charges
for it).
@@ -167,7 +167,7 @@ queue) belong to the Enterprise plan.
- Merchant feedback, 2026-08 (register → browse "awaiting approval" →
verify → assign the agreement → ordering enabled).
- Tier split + rationale: `docs/plans/decisions.md` 2026-08-30;
- `spree-enterprise-v2/docs/plans/b2b-company-onboarding.md` (the flow).
+ `ee/docs/plans/b2b-company-onboarding.md` (the flow).
- `docs/plans/6.0-b2b-companies-and-catalogs.md` — tree, memberships,
self-service, `Catalog.for_context`.
- Gating: `spree/core/app/models/spree/channel/gating.rb`,
diff --git a/docs/plans/6.0-b2b-customer-po-numbers.md b/docs/plans/6.0-b2b-customer-po-numbers.md
index 0eeb65741e..cc381010a0 100644
--- a/docs/plans/6.0-b2b-customer-po-numbers.md
+++ b/docs/plans/6.0-b2b-customer-po-numbers.md
@@ -172,7 +172,7 @@ built.)
the payment-method anti-pattern, the upload gap) — private, not in this
repo.
- `docs/plans/6.0-inventory-operations.md` — the *other* purchase order.
-- `spree-enterprise-v2/docs/plans/b2b-quotes.md` — amended to consume this
+- `ee/docs/plans/b2b-quotes.md` — amended to consume this
field.
- Attachment precedents: seller requirement submissions (spoofing
protection), media library (blob sharing).
diff --git a/docs/plans/6.0-draft-order-negotiation-mechanics.md b/docs/plans/6.0-draft-order-negotiation-mechanics.md
index f8c934f937..934771a2a0 100644
--- a/docs/plans/6.0-draft-order-negotiation-mechanics.md
+++ b/docs/plans/6.0-draft-order-negotiation-mechanics.md
@@ -17,7 +17,7 @@ units @ $7.20 for this order only, without touching the customer's price
list") — plus the machinery to start a negotiation from a customer's cart
without consuming it. This plan ships those **open-source mechanics**; the
customer-facing quotation product (lifecycle, send/accept, expiry, portal)
-is Enterprise (`spree-enterprise-v2/docs/plans/b2b-quotes.md`; tier split
+is Enterprise (`ee/docs/plans/b2b-quotes.md`; tier split
decided 2026-08-30 — same shape as company registration: OSS mechanisms,
Enterprise flow). Manual pricing is deliberately 6.0: it polishes the
brand-new draft-order surface (phone orders need it too) and rides with two
@@ -181,7 +181,7 @@ payment-status value is owned by the wholesale-deposit rollup work.)
- Merchant feedback, 2026-08 (extend draft orders into quotations;
negotiated line-item pricing that must not touch the price list).
- Tier split: `docs/plans/decisions.md` 2026-08-30;
- `spree-enterprise-v2/docs/plans/b2b-quotes.md` (the flow).
+ `ee/docs/plans/b2b-quotes.md` (the flow).
- Repricing contract: `spree/core/app/services/spree/carts/price_items.rb`,
`spree/core/app/models/spree/line_item.rb` (`should_update_price?`,
`update_adjustments`).
diff --git a/docs/plans/6.0-inventory-operations.md b/docs/plans/6.0-inventory-operations.md
index c271707f6e..665f09ef6f 100644
--- a/docs/plans/6.0-inventory-operations.md
+++ b/docs/plans/6.0-inventory-operations.md
@@ -1,7 +1,7 @@
# Inventory Operations (Transfers + Purchase Orders + Lots + Variant History)
**Status:** Draft
-**Target:** Spree 6.0 (transfers, purchase orders, history) / 6.1 (lot tracking — deferred 2026-08-30 scope review: purely additive, opt-in, nothing in 6.0 or Enterprise depends on it)
+**Target:** Spree 6.0 (transfers, purchase orders, history) / 6.1 (simple lot capture). **Tier split 2026-09-07:** the lot LIBRARY — received-lot inventory, quantities, expiry, FIFO/FEFO auto-allocation — moved to Enterprise (`ee/docs/plans/inventory-lots.md`); OSS keeps the traceability capture below.
**Depends on:** Typed Stock Movements (6.0-typed-stock-movements.md), Fulfillment & Delivery (6.0-fulfillment-and-delivery.md), Stock Reservations (6.0-stock-reservations.md)
**Author:** Damian + Claude
**Last updated:** 2026-08-30
@@ -15,7 +15,7 @@ Lift inventory operations from "atomic decrement + log" to a first-class workflo
1. **`Spree::StockTransfer` gains a lifecycle.** Today a transfer is one-shot — source decrements and destination increments in the same transaction. After this plan: `draft → ready_to_ship → in_transit → received` (with `cancelled` as a terminal escape hatch), plus line items, partial receive support, and a discrepancy column. Source units leave on `mark_in_transit`, destination units land on `receive` — not at the same instant.
2. **New `Spree::PurchaseOrder` model** for supplier receives. Today's "external receive" hack (a `StockTransfer` with `source_location_id: nil`) is replaced by a proper `PurchaseOrder` with `supplier`, `expected_at`, `line_items[]` with `unit_cost`, and the same receive flow as transfers.
3. **Variant + Location stock history.** Surfaces the audit feed introduced by `6.0-typed-stock-movements.md` as inline timelines in the admin SPA — answering "why is on-hand 47?" in the place users always ask: on a SKU or a warehouse.
-4. **Lot-level inventory** (added 2026-08-30, interactive review — full lot tracking chosen over provenance-only; **6.1** per the same-day scope trim). New `Spree::StockLot` decomposes a lot-tracked variant's on-hand quantity per location into lots (`lot_number`, optional `expires_at`); receives assign lots, dispatch picks them FEFO, and every stock movement on a lot-tracked variant names its lot — so a merchant can answer "which LOT/pallet went into this shipment" and "what expires next", the two questions wholesale and regulated-goods merchants actually ask.
+4. **Simple lot capture** (reshaped 2026-09-07 — the tier split): OSS records **which lot/batch a fulfillment actually shipped** — entered at fulfillment time, split across batches when needed — and makes the lot number searchable in both directions (customer → order → lot; lot → every order/customer that received it — the recall question). The full lot **library** (received-lot inventory with quantities, expiry, FIFO/FEFO auto-allocation) is the Enterprise layer that fills these same capture rows automatically.
This plan is the **UX surface** for inventory ops. The data primitives (typed `StockMovement`, `kind`, concrete FKs to Order/Fulfillment/Return/Exchange/StockTransfer/PurchaseOrder) come from `6.0-typed-stock-movements.md` and the Fulfillment rename. Those two plans must land first.
@@ -74,40 +74,29 @@ Once `6.0-typed-stock-movements.md` lands, every change to `count_on_hand` carri
- **`PurchaseOrderItem` has `unit_cost` (Money) and `quantity_ordered` / `quantity_received`.** Currency comes from the PO's `currency` column (defaults to the store's). Receiving units writes typed `received` stock movements with `purchase_order_id`.
- **PO does not affect `count_on_hand` until receive.** Ordered units are visible to the merchant as "on order" (computed: `SUM(quantity_ordered - quantity_received)` per variant), but never count toward availability.
-### Lot tracking (added 2026-08-30 · targeted 6.1)
-
-- **Lots are opt-in per variant** (`lot_tracked` boolean). Untracked variants — the vast majority — see zero behavior change; no lot rows, no lot columns on their movements.
-- **A lot is a per-location quantity bucket, not a global batch record.** `Spree::StockLot` belongs to a variant + stock location and carries `lot_number`, `quantity`, `expires_at` (nullable), `received_at`, and optional provenance FKs (`purchase_order_id` / `stock_transfer_id`). Uniqueness on `(stock_location_id, variant_id, lot_number)`. The same physical batch split across two warehouses is two rows sharing a `lot_number` — receiving reconciles by number.
-- **Lot quantities are a decomposition of `count_on_hand`, kept in sync transactionally.** For a lot-tracked variant, `SUM(stock_lots.quantity)` must equal the stock level's `count_on_hand` at that location — the same invariant discipline as the license-pool count sync in `6.0-digital-assets.md`. Every movement that changes `count_on_hand` on a lot-tracked variant adjusts a lot in the same transaction; drift is a bug, never reconciled lazily.
-- **Movements name their lot.** `spree_stock_movements` gains a nullable `stock_lot_id`; a physical quantity change spanning several lots is several movement rows, one per lot. This keeps the typed-movements doctrine intact — `count_on_hand` still only ever changes through movements; lots add *which shelf section*, not a second write path.
-- **Receiving assigns lots.** PO and transfer receive payloads accept per-item lot allocations (`[{ lot_number, expires_at, quantity }]`); receiving finds-or-creates the destination lot and writes the `received` movements against it. A lot-tracked item received without lot data is refused — the receive screen is the one moment the information exists.
-- **Allocation stays lot-agnostic; dispatch picks lots.** Per `6.0-typed-stock-movements.md`, stock leaves the shelf at fulfillment: `allocated` movements (order placement) carry no lot — an allocation is a promise, not a physical pick. The `shipped` movements written at dispatch pick lots **FEFO** (earliest `expires_at`, then oldest `received_at`), with a per-fulfillment override so the warehouse can record what was actually grabbed. The fulfillment's movements are the record of which lots shipped, surfaced on the fulfillment page and in the variant history (`+200 received · PO-42 · LOT 2026-113`).
-- **Returns and adjustments are lot-aware** for tracked variants: a return receive lands in the lot it shipped from when known (else a merchant-chosen lot), and manual adjustments name the lot they correct.
-- **No storefront exposure in 6.0.** Lots are back-office data; nothing in the Store API reads them.
-
-```ruby
-class Spree::StockLot < Spree.base_class
- has_prefix_id :lot
-
- belongs_to :variant, class_name: 'Spree::Variant'
- belongs_to :stock_location, class_name: 'Spree::StockLocation'
- belongs_to :purchase_order, class_name: 'Spree::PurchaseOrder', optional: true
- belongs_to :stock_transfer, class_name: 'Spree::StockTransfer', optional: true
-
- has_many :stock_movements, class_name: 'Spree::StockMovement', inverse_of: :stock_lot
-
- validates :lot_number, presence: true,
- uniqueness: { scope: [:stock_location_id, :variant_id, *spree_base_uniqueness_scope] }
- validates :quantity, numericality: { greater_than_or_equal_to: 0, only_integer: true }
-
- scope :available, -> { where('quantity > 0') }
- scope :fefo, -> { order(Arel.sql('expires_at IS NULL, expires_at ASC, received_at ASC')) }
-end
-```
-
-Admin surface: lots listed on the variant Inventory tab and the stock-location Activity view (with expiry badges); lot filter on the movement history; per-lot adjustment from the lot row. API: `GET /api/v3/admin/stock_lots` (Ransack-filterable by variant/location/expiry) + lot allocations embedded in the existing receive/adjustment payloads — no standalone lot mutation endpoints beyond adjustment, since lots change through receives and picks.
-
-### Typed Stock Movements wiring
+### Simple lot capture (reshaped 2026-09-07 · 6.1)
+
+- **`Spree::FulfillmentLot`** — the capture row: `fulfillment_item_id`,
+ `lot_number` (string, required), `quantity` (nullable — nil = the whole
+ line; multiple rows express a split batch, e.g. 80 × LOT-001 + 20 ×
+ LOT-002). Entered in the fulfill dialog or added/corrected afterwards on
+ the fulfillment card; `lot_number` is ransackable, and the dashboard's
+ order search gains a lot-number mode so an accountant or QA manager can
+ paste a batch number and see every affected fulfillment, order and
+ customer.
+- **`lot_tracked` boolean on the variant** is an advisory prompt: the
+ fulfill dialog requires lot entry for flagged variants (dashboard-level,
+ the advisory-required precedent from product types); the server accepts
+ lot rows on any item, flagged or not.
+- **No quantities, no expiry, no allocation in OSS** — the capture answers
+ traceability, not inventory. The Enterprise lot library (received-lot
+ rows per variant + location, `expires_at`/`manufactured_on`/supplier
+ reference, `manual | fifo | fefo` allocation) **writes these same
+ capture rows automatically at dispatch**, so the recall search reads one
+ surface regardless of tier.
+- Store API: nothing — lots are back-office data.
+
+### Typed Stock Movements wiring### Typed Stock Movements wiring
These additions live in `6.0-typed-stock-movements.md`; this plan only consumes them.
@@ -534,27 +523,16 @@ class AddInventoryOperations < ActiveRecord::Migration[7.2]
add_column :spree_stock_movements, :purchase_order_id, :bigint
add_index :spree_stock_movements, :purchase_order_id
- # Lot tracking
+ # Simple lot capture (6.1)
add_column :spree_variants, :lot_tracked, :boolean, default: false, null: false
- create_table :spree_stock_lots do |t|
- t.references :variant, null: false
- t.references :stock_location, null: false
- t.references :purchase_order
- t.references :stock_transfer
- t.string :lot_number, null: false
- t.integer :quantity, null: false, default: 0
- t.date :expires_at
- t.datetime :received_at
+ create_table :spree_fulfillment_lots do |t|
+ t.references :fulfillment_item, null: false
+ t.string :lot_number, null: false
+ t.integer :quantity
t.timestamps
end
- add_index :spree_stock_lots,
- [:stock_location_id, :variant_id, :lot_number],
- unique: true,
- name: 'idx_stock_lots_unique'
-
- add_column :spree_stock_movements, :stock_lot_id, :bigint
- add_index :spree_stock_movements, :stock_lot_id
+ add_index :spree_fulfillment_lots, :lot_number
end
end
```
@@ -613,7 +591,7 @@ All other existing transfers (with a real source location) become `status: 'rece
- **Don't add receive flows to `StockTransfer` without `source_location_id`.** Supplier receives move to `PurchaseOrder`. If a 5.5 feature needs to record a supplier receive, scope it minimally and flag it for migration.
- **Don't create a separate "Stock Movements" admin SPA page.** Movement history is always inline on variant + stock location.
- **Don't fold cost data onto `StockTransfer`.** Transfers don't have a unit cost — they move existing inventory between owned locations. Cost lives on `PurchaseOrderItem.unit_cost`.
-- **Don't put lot numbers anywhere but `Spree::StockLot`.** No `lot_number` strings on line items, fulfillments, or movements-as-text — a movement references its lot by FK, and everything else reads through the movement. A lot quantity never changes outside the transaction that writes its movement.
+- **Lot capture lives only on `Spree::FulfillmentLot` rows** — no `lot_number` strings on line items, orders, or movements. The Enterprise library layers on these rows (its allocation fills them); OSS never grows lot quantities, expiry, or allocation of its own.
## Open Questions
@@ -621,8 +599,7 @@ All other existing transfers (with a real source location) become `status: 'rece
2. **Suppliers shared across stores?** Today the plan scopes them per-store. Some merchants run multiple storefronts off one supplier base. Could promote to a `Spree::Supplier` with a M2M to stores in a follow-up. Defer.
3. **Average / weighted-average cost on Variant?** A PO's `unit_cost` enables margin reporting. The natural extension is `Variant.average_cost` (rolling avg of received unit costs) for COGS. Likely worth a separate plan — call it out, don't scope it here.
4. **Pickup transfers (ship-to-store).** `6.0-fulfillment-and-delivery.md` mentions `pickup_stock_policy: 'any'` as enabling ship-to-store. The natural implementation is auto-creating a `StockTransfer` when a pickup order's items aren't local at the chosen pickup location. Mechanism is straightforward; UX (does the customer see "ready in 3 days" instead of "ready in 2 hours"?) needs a separate decision. Defer.
-5. **Expired lots and sellability.** Should a lot past `expires_at` be excluded from FEFO picking (forcing a manual override), and should expiring stock reduce the availability `Stock::Quantifier` reports? Leaning: warn-and-skip in FEFO, no availability change in 6.0 — availability semantics touch checkout and deserve their own decision. Unblocked by: implementing the receive/pick flows and seeing what merchants on lot-tracked catalogs report.
-6. **Turning `lot_tracked` on for a variant with existing stock.** The existing `count_on_hand` has no lot decomposition; the flag flip likely requires an opening "untracked" lot holding the current quantity (adjusted into real lots by the merchant). Decide during implementation.
+5. **Server-side enforcement of `lot_tracked`** — should the fulfill workflow refuse (not just prompt) when a flagged variant ships without lot rows? Advisory in v1 (dashboard requires, server accepts); revisit if merchants report gaps. The library-tier questions (expired lots, flag flips over existing stock) moved to the Enterprise plan.
## References
diff --git a/docs/plans/6.0-volume-pricing.md b/docs/plans/6.0-volume-pricing.md
new file mode 100644
index 0000000000..46ef47cb58
--- /dev/null
+++ b/docs/plans/6.0-volume-pricing.md
@@ -0,0 +1,163 @@
+# Volume Pricing (Quantity Breaks + Banded Adjustments)
+
+**Status:** Draft — design finalized 2026-09-07, nothing built
+**Target:** Spree 6.0 — fully (2026-09-07: first the schema/resolver phases were pulled into the major because `min_quantity` changes the row identity of the released `spree_prices` table; then the whole plan followed — shipping the feature in one release is faster than splitting the UI off by a release boundary)
+**Depends on:** Catalog Agreement Rework (6.0-catalog-agreement-rework.md — implemented; owned lists + contextual rules), Price List Automatic Pricing (6.0-price-list-automatic-pricing.md — implemented; the ±% machinery this extends), B2B Quantity Rules (6.0-b2b-quantity-rules.md — the separate ordering axis)
+**Author:** Damian + Claude
+**Last updated:** 2026-09-07
+
+## Summary
+
+B2B unit prices change with quantity. Today Spree covers the single
+threshold elegantly (a price list with a `VolumeRule` — standalone or
+catalog-owned — optionally with the ±% adjustment) and stops exactly where
+a real ladder begins: a catalog owns one list, so 24/48/96/200 tiers
+cannot exist on it, and per-variant breaks cannot exist at all. This plan
+closes the gap with two symmetric extensions of the pricing machinery
+itself (2026-09-07 review — the earlier promotions-based percent design
+was superseded the same day): **fixed contracted ladders become a
+dimension of the price row** (`min_quantity` — the shape every platform
+with real volume pricing converged on; nobody models tiers as
+list-matching rules), and **percentage ladders become quantity bands on
+the list's ±% adjustment** — the implemented automatic-pricing machinery
+already treats a percentage as *pricing* (computed on read, clean unit
+price, never touching explicit rows), so bands are consistent extension
+with an already-answered "percent off what": the base price. Both halves
+live on the price list and edit on the catalog's Pricing card. Marketing-
+visible volume discounts (strikethrough, D2C "buy more save more") remain
+promotion territory and are deliberately deferred.
+
+## Key Decisions (do not deviate without discussion)
+
+- **The tier doctrine, one sentence (2026-09-07): promotions = DTC
+ consumers, price lists = B2B.** Agreement pricing — fixed or percent —
+ lives on price lists and renders as unit prices; consumer-facing
+ marketing discounts live on promotions and render as discounts. Every
+ volume-pricing question resolves by asking which side of that line it
+ sits on.
+- **Fixed breaks are price rows, never rules or discounts** (2026-09-07,
+ interactive review): `spree_prices.min_quantity` (integer, default 1,
+ null: false — integer defaults are house-legal, so every existing row is
+ a quantity-1 price with zero backfill); row identity becomes
+ `(variant, currency, price_list, min_quantity)` with the unique indexes
+ extended accordingly. The resolver picks, within the winning list, the
+ row with the **highest `min_quantity` ≤ the line quantity**. Contracted
+ unit prices must appear as unit prices on every B2B document — a $9.00
+ agreement rendered as "$10.00 minus discount" is unacceptable paperwork.
+- **A break ladder beats the list's ±% adjustment for that variant**
+ (the market leader's exact precedence, stated in their docs as "volume
+ pricing fixes the price"): our resolver already gives
+ explicit-row-beats-adjustment; the dashboard marks such variants
+ ("fixed tiers — the list's % adjustment doesn't apply here").
+- **Breaks live on price lists only in v1** (`min_quantity > 1` requires
+ `price_list_id`): base-price tiers would make every D2C PDP
+ quantity-dependent — a storefront surface no platform ships natively.
+ Lifting it later is deleting one validation; the column is the same.
+ **≤10 breaks per variant** (the leader's cap — a UI sanity bound, model-
+ validated).
+- **Percentage ladders are quantity bands on the adjustment**
+ (2026-09-07, superseding the same-day promotions design): the list keeps
+ `price_adjustment_percentage` as its quantity-1 value; a new
+ `spree_price_adjustment_tiers` table (`price_list_id, min_quantity,
+ percentage`, unique per `(list, min_quantity)`) holds the higher bands,
+ and the resolver picks the band with the highest `min_quantity ≤ the
+ line quantity`, falling back to the column. Computed on read off the
+ base price exactly like the implemented adjustment — clean unit prices,
+ no discount rows, no promotion machinery — and **never applied to
+ explicit rows** (the implemented precedence): a buyer whose price is the
+ adjusted base gets "percent off their current price" by construction; a
+ buyer with negotiated explicit rows uses fixed breaks. A ladder shared
+ across many agreements verbatim is repeated per list — accepted: terms
+ differ per agreement, and the genuinely shared case is marketing.
+- **Volume pricing stays separate from quantity rules** (MOQ/multiples —
+ `6.0-b2b-quantity-rules.md`): ordering constraints and price tiers are
+ sibling axes everywhere in the market and in the merchant's own framing
+ ("how many they may buy" vs "what they pay"). No coupling, ever.
+- **`VolumeRule` on price lists is kept** for list-level eligibility (a
+ wholesale list that only exists at 48+) — it swaps whole lists, breaks
+ and bands price within one; different jobs, documented as such.
+- **Marketing volume discounts stay promotions, later**: a visible
+ strikethrough "buy more save more" (D2C) would be a line-quantity
+ promotion rule + a quantity-tiered percent calculator (sibling of the
+ existing `TieredPercent`) — recorded as the deferred design, not built
+ here. Contracted terms never render as discounts; marketing never hides
+ as pricing.
+- **Quotes/draft orders**: the volume price computes on quantity change
+ through the existing repricing path (`quantity` is already in
+ `Pricing::Context`); a `price_source: 'manual'` override still beats it
+ — the negotiation ordering already recorded.
+
+## Design Details
+
+- Resolution: `find_price_for_list` becomes "rows for (variant, currency)
+ on this list, `min_quantity <= context.quantity` (quantity nil → 1),
+ pick max `min_quantity`"; nil-amount placeholder rows keep falling
+ through per row. Cache keys gain the quantity bucket only where the
+ resolution cache is quantity-sensitive (the line-item pricing path
+ already carries quantity per call).
+- Dashboard: the price-list editor's variant×currency cell shows the
+ quantity-1 price with a "+N tiers" badge; clicking opens the inline tier
+ editor (`[Min qty | Unit price]` rows, first row locked to 1, add/delete,
+ strictly-increasing validation) — one component, reused on the catalog
+ page's products-with-prices view. CSV import/export of a list gains a
+ `min_quantity` column (one line per tier); the admin price endpoints +
+ bulk upsert accept it.
+- Storefront: no ladder display in v1 (the merchant's own preference) —
+ the line's unit price re-resolves as quantity crosses thresholds. A
+ PDP "buy more, save more" widget is a later opt-in read of the same
+ rows.
+- Banded adjustment: the Pricing card (standalone list page + catalog
+ page) gains "Add quantity tier" rows under the existing
+ magnitude/direction controls — same tier-editor component as the fixed
+ breaks; the resolution cache keys gain the quantity band the same way
+ the fixed-break path does.
+
+## Migration Path
+
+1. **Schema** — `min_quantity` on `spree_prices` (default 1) + the
+ unique-index reshape; model validations (list-only, cap, increasing
+ ladder via uniqueness). In the major so SDK types, CSV shapes, bulk
+ upsert and integrations never harden against the old row identity.
+2. **Resolver** — quantity-aware row pick + specs (ladder pick,
+ placeholder fallthrough, adjustment precedence, owned + standalone
+ lists, quantity nil → identical behavior to today until tiers exist).
+3. **Banded adjustment** — `spree_price_adjustment_tiers` + resolver band
+ pick + specs (band pick, column fallback, explicit-row precedence,
+ owned + standalone).
+4. **Admin API + dashboard** — tier editor for breaks and bands (both
+ homes), CSV, bulk upsert.
+
+No data migration: the integer default makes every existing price a
+quantity-1 row.
+
+## Constraints on Current Work
+
+- **Never model a contracted tier — fixed or percent — as a
+ discount/promotion**, and never build marketing volume discounts into
+ pricing: agreement terms are price rows/bands, marketing is promotions.
+- **Price-reading code must pass the line quantity** through
+ `Pricing::Context` — a caller that omits it silently gets quantity-1
+ prices.
+- No coupling between quantity rules (MOQ/multiple) and price tiers.
+- Exports/feeds reading list prices must account for tier rows (a
+ quantity-1-only export silently drops the ladder).
+
+## Open Questions
+
+None for this scope. Deferred, recorded: base-price (D2C) tiers = one
+validation to lift; PDP ladder widget; the marketing volume-discount
+promotion pair (`LineQuantity` rule + quantity-tiered percent calculator);
+per-tier `kind: percent` on price rows (rejected — bands on the adjustment
+cover it with the implemented semantics).
+
+## References
+
+- Merchant feedback, 2026-09 (fixed + percentage tiers; catalog
+ compatibility; storefront shows the applied price; MOQ separation;
+ quotes override).
+- Platform research 2026-09-07 (break-on-the-price-record as the universal
+ shape; fixed-only tiers; the leader's %-adjustment precedence; quantity
+ rules as a sibling axis) — private, not in this repo.
+- `spree/core/app/models/spree/price_rules/volume_rule.rb` (kept,
+ list-level), `.../calculator/tiered_percent.rb` (the sibling),
+ `.../adjusters/promotion.rb` (winner-only).
diff --git a/docs/plans/6.1-b2b-order-documents.md b/docs/plans/6.1-b2b-order-documents.md
index c76bcc11da..6f34f52b46 100644
--- a/docs/plans/6.1-b2b-order-documents.md
+++ b/docs/plans/6.1-b2b-order-documents.md
@@ -104,5 +104,5 @@ artifact is an invoicing feature.)
- Print precedent: `packages/dashboard/src/lib/packing-slip.ts`.
- Attachment precedents: `Spree::TaxExemptionCertificate#document`,
`Spree::SellerRequirementSubmission#file`.
-- Enterprise invoicing: `spree-enterprise-v2/docs/plans/b2b-companies.md`
+- Enterprise invoicing: `ee/docs/plans/b2b-companies.md`
roadmap item 1.
diff --git a/docs/plans/6.1-order-change-substrate.md b/docs/plans/6.1-order-change-substrate.md
index 529e296a40..be075b6258 100644
--- a/docs/plans/6.1-order-change-substrate.md
+++ b/docs/plans/6.1-order-change-substrate.md
@@ -359,7 +359,7 @@ directly mutable, carries no payments and therefore no balance to settle —
the confirm spine (settle at the gateway, re-derive statuses) is meaningless
for it, and forcing drafts through preview-then-apply is pure ceremony. This
is also what keeps B2B quotations thin
-(`spree-enterprise-v2/docs/plans/b2b-quotes.md`): pre-acceptance negotiation
+(`ee/docs/plans/b2b-quotes.md`): pre-acceptance negotiation
edits the mutable draft directly and needs no change-set; only
post-conversion amendments ride OrderChange. The admin edit screen may share
components across drafts and placed orders, but only placed orders create
diff --git a/docs/plans/6.1-product-market-availability.md b/docs/plans/6.1-product-market-availability.md
new file mode 100644
index 0000000000..edb7a5d14c
--- /dev/null
+++ b/docs/plans/6.1-product-market-availability.md
@@ -0,0 +1,150 @@
+# Product Market Availability (Territory Exclusions)
+
+**Status:** Draft — design finalized 2026-09-07, nothing built
+**Target:** Spree 6.1 (purely additive — nullable column + exception rows; pulls forward if a 6.0 slot opens)
+**Depends on:** Markets (shipped), Channels/ProductPublication (shipped), Products::ForContext (shipped), Channel-Markets allowlist (6.0-channel-markets.md — adjacent axis, in progress)
+**Author:** Damian + Claude
+**Last updated:** 2026-09-07
+
+## Summary
+
+A store selling one range into many markets sometimes may not sell a
+handful of products in particular territories — exclusive distribution
+agreements, licensing, regulation. Today the only expression is a channel
+per territory, which duplicates surfaces to hide two products. This plan
+adds a **product-level market availability axis**: a nullable
+`market_availability` mode (`NULL`=all markets | `all_except` | `only`)
+plus exception rows naming markets, composed with publications as an
+intersection on the read path — **published on the channel ∧ available in
+the market** — with full hiding in excluded markets (listings, search,
+collections, feeds, direct URL) and a completion validation covering the
+mid-cart market change. The design copies the behavior of the only
+platform that runs channel and market as two axes on one product (full
+hide, everything-by-default, one publishing surface) while avoiding its
+storage tax (per-market membership materialization) and keeping the
+doctrine intact: **Channel answers surface, Market answers territory,
+Catalog answers buyer** — this is the territory answer, deliberately not a
+market catalog (the door 2026-08-28 closed stays closed).
+
+## Key Decisions (do not deviate without discussion)
+
+- **Exceptions-only storage, zero backfill** (2026-09-07, interactive
+ review): `spree_products.market_availability` is nullable with **NULL
+ meaning "all markets"** — every existing product is correct at migration
+ time with nothing written; a restricted product flips the mode and gains
+ join rows *only for the named markets* (the 100-products × 20-markets ×
+ 2-exceptions case is 3 rows). New markets need nothing: `all_except`
+ includes them, `only` excludes them, correct by construction. (The
+ no-defaults-on-string-columns rule is about workflow-set statuses;
+ NULL-as-all is the deliberate fallthrough here, read as
+ `market_availability || 'all'`.)
+- **Full hide, not a purchase-block warning** (2026-09-07): an excluded
+ market never sees the product — a "not available in your market" PDP
+ advertises exactly the product the distributor holds rights to. The
+ market-competent platform made the same call (redirect/null; no
+ visible-but-unsellable state per market). A visible-but-blocked display
+ mode is a recorded possible later addition, not v1.
+- **Composition, not a second visibility mechanism**: availability =
+ `published(channel) AND available(market)`, both evaluated per request
+ (`Spree::Current.channel` / `Spree::Current.market`), nothing derived or
+ stored — nothing to de-sync. Merchant comprehension is handled the way
+ the two-axis platform does it: **one Availability card** on the product
+ page showing publications and market availability together, both
+ defaulting to "everywhere" so neither axis exists until deliberately
+ narrowed.
+- **Checkout re-validates on market change.** No platform enforces
+ territory at checkout (their restriction resolves at browse context) —
+ but Spree's market can shift mid-cart via the address, so
+ `Carts::Complete` (and the address-driven market change path) validates
+ line items against the new market with a clear removal/error code. A
+ correctness improvement over every precedent.
+- **Deny-list first-class**: `all_except` is the primary mode (sell
+ globally, subtract territories — the exclusive-distribution shape, which
+ only one platform's UX offers and none model natively); `only` covers
+ licensing ("approved for AU+NZ only") with the same rows.
+
+## Design Details
+
+```ruby
+# spree_products.market_availability string, nullable (NULL = all)
+# spree_product_market_availabilities:
+# product_id bigint, null: false
+# market_id bigint, null: false
+# unique index (product_id, market_id); partial index on
+# spree_products.market_availability WHERE NOT NULL (restricted set is tiny)
+
+class Spree::Product
+ MARKET_AVAILABILITY_MODES = %w[all_except only].freeze # nil = all
+
+ has_many :market_availability_entries,
+ class_name: 'Spree::ProductMarketAvailability', dependent: :destroy
+ has_many :restricted_markets, through: :market_availability_entries, source: :market
+
+ def available_in_market?(market)
+ case market_availability
+ when nil then true
+ when 'all_except' then !restricted_market_ids.include?(market&.id)
+ when 'only' then restricted_market_ids.include?(market&.id)
+ end
+ end
+end
+```
+
+- **Read path**: one scope (`Product.available_in_market(market)`) applied
+ in the same base the channel publication filter runs in — store products
+ listing, `Products::ForContext`, search indexing/filtering (the search
+ provider indexes the exception data so the database and Meilisearch
+ providers filter alike), collections, sitemap/feeds. Product show in an
+ excluded market → not found (the storefront decides redirect vs 404,
+ matching its own conventions; the API answer is 404 in that market
+ context). SQL stays cheap: the `IS NULL` short-circuit covers virtually
+ every row; `EXISTS` touches only flagged products.
+- **Cart/checkout**: `Carts::AddItem`/`UpsertItems` validate the variant's
+ product against the cart's market; `Carts::Complete` re-validates
+ (market may have changed via address) with `code:
+ 'not_available_in_market'`; completed orders untouched (history is
+ history).
+- **Admin**: the product page's Availability card gains a Markets section
+ (mode select + market multi-select via the standard combobox), beside
+ the existing channel publishing; the three new attributes ride the
+ product write paths; bulk via the spreadsheet editor later if asked.
+- **Serializers**: admin product exposes mode + markets; store API simply
+ never returns the product in an excluded market — no flag to leak.
+
+## Migration Path
+
+1. Schema + model + scope + spec battery (mode semantics, new-market
+ behavior, guest/no-market context = available).
+2. Read-path wiring (listing, ForContext, search providers, show,
+ feeds) + cart/completion validations.
+3. Admin API + dashboard Availability card + SDK types.
+
+Nothing to migrate.
+
+## Constraints on Current Work
+
+- **Availability = publication ∧ market availability, evaluated on read** —
+ never denormalize an "effective visibility" flag anywhere.
+- **Never model territory availability as a catalog** (assignment or
+ otherwise) — catalogs answer buyers; the 2026-08-28 market-catalog
+ closure stands.
+- New market-context read surfaces (feeds, recommendations, APIs) must
+ apply the scope — a surface that skips it leaks restricted products.
+
+## Open Questions
+
+1. **Visible-but-unpurchasable display mode** (per-product opt-in) —
+ deferred; no territory precedent exists and full hide is the safe
+ default. Unblocked by: a merchant needing the softer mode.
+
+## References
+
+- Merchant feedback, 2026-09 (exclusive distribution; three modes; full
+ hiding incl. direct URL; territory ≠ buyer).
+- Platform research 2026-09-07 (two-axis precedent, full-hide choice,
+ deny-list UX, storage tax) — private, not in this repo.
+- decisions.md 2026-08-28 (market-catalog closure), 2026-08-30 (one
+ question per entity), 2026-09-07 (this decision).
+- `docs/plans/6.0-channel-markets.md` — the adjacent channel↔market
+ allowlist (which surface serves which territories; orthogonal to which
+ products a territory may buy).
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 27a7c2938b..d0af3e154b 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -4049,7 +4049,7 @@ group); group-style targeting of companies arrives, if ever, as explicit
rule kinds on the promotion/price-rule STI families.
**OSS trusts every member; governance is Enterprise, and its plans live in
-`spree-enterprise-v2/docs/plans/`.** The Store API ships full directory
+`ee/docs/plans/`.** The Store API ships full directory
self-service — node detail, addresses, members, subtree order history,
writable cart `company_id` (sole standing as the default; explicit node for
multi-node buyers, finally settling the "provisional — revisit" resolution
@@ -4314,7 +4314,7 @@ Deliberately 6.1: every piece is additive, nothing needs the 6.0 breaking
window, and 6.0 work must not build interim approval primitives in the
meantime.
-**Enterprise** (`spree-enterprise-v2/docs/plans/b2b-company-onboarding.md`)
+**Enterprise** (`ee/docs/plans/b2b-company-onboarding.md`)
registers the policy and owns the flow: an application record (FK → the
OSS company; `spree_companies` stays status-free — this supersedes the
same-day draft that put five statuses on Company), the seller-onboarding
@@ -4366,7 +4366,7 @@ wholesale-deposit rollup work, decided once). In 6.1:
leaving the cart untouched (deliberately not the completion copier, which
re-points money records and is one-shot).
-**Enterprise (`spree-enterprise-v2/docs/plans/b2b-quotes.md`)** owns the
+**Enterprise (`ee/docs/plans/b2b-quotes.md`)** owns the
quote product: a thin `Quote` row over the draft order (own model → clean
`Q` numbers from the per-resource sequence; one quote per draft), statuses
`draft → sent → accepted → converted` (+ `changes_requested`, `expired`
@@ -4853,3 +4853,68 @@ keys in every dashboard locale, not a `Spree.t` label; new validation errors in
core use a symbol and parameters, never a preformatted string; nothing in the
dashboard prints an API `label`/`name`/`description` directly; shared admin copy
goes in `dashboard-core` locales, never in `packages/seller-dashboard`.
+
+## 2026-09-07 — Three merchant asks resolved: market availability, the lot tier split, and the volume-pricing doctrine
+
+The next feedback batch (market exclusions, lot detail + tier question,
+volume pricing) resolved after three research passes (per-market
+availability, lot landscape, volume-pricing implementations).
+
+**Product market availability is a product-level territory axis**
+(`6.1-product-market-availability.md`): nullable
+`spree_products.market_availability` (NULL = all markets — zero backfill,
+exceptions-only join rows, new markets correct by construction) composed
+with publications as an intersection evaluated per request — **published
+on the channel ∧ available in the market** — with full hiding (the
+market-competent platform's choice; a "not available here" PDP advertises
+the product the distributor holds rights to) and a completion validation
+for the mid-cart market change no platform handles. One Availability card
+shows both axes (their de-confusion recipe). Deliberately NOT a market
+catalog — the 2026-08-28 closure stands; catalogs answer buyers, this
+answers territory. Channels were considered and rejected as the wrong
+axis (a channel per territory to hide two products is the duplication the
+merchant rejects). Constraints: availability is never denormalized; every
+market-context read surface applies the scope.
+
+**Lots split on the depth line** (maintainer's call, 2026-09-07 —
+supersedes the 2026-08-30 all-OSS decision and its 6.1 scope-trim note):
+OSS 6.1 keeps **simple lot capture** — `Spree::FulfillmentLot` rows
+(fulfillment item × lot number × optional quantity for split batches),
+advisory `lot_tracked` prompt, ransackable recall search both directions;
+the **lot library** (received-lot `StockLot` inventory, quantities,
+expiry/manufactured dates, supplier references, manual/FIFO/FEFO
+auto-allocation, the transactional `count_on_hand` decomposition) moves to
+**Enterprise** (`ee/docs/plans/inventory-lots.md`), whose
+allocation **writes the same OSS capture rows** so recall reads one
+surface on either tier. Landscape recorded with the trade-off: no platform
+ships lots natively at any tier, the app market monetizes exactly this
+depth ladder ($10 record-and-alert vs $24–199 library+FEFO), the one full
+open implementation (the ERP benchmark) is free in its community edition,
+and the traceability-lot-code compliance wave (July 2028) is why level-1
+capture stays OSS. Constraint: lot capture lives only on `FulfillmentLot`
+rows — no lot strings anywhere else, and OSS never grows quantities,
+expiry, or allocation.
+
+**Volume pricing: promotions = DTC consumers, price lists = B2B** — the
+one-sentence tier doctrine (`6.0-volume-pricing.md`). Fixed contracted
+ladders become a **price-row dimension**: `spree_prices.min_quantity`
+(integer default 1 — every existing row is a quantity-1 price, zero
+backfill; row identity gains the column; resolver picks the highest break
+≤ line quantity; ≤10 breaks; breaks require a price list in v1; a break
+ladder beats the list's ±% per variant — the market leader's stated
+precedence). Percentage ladders become **quantity bands on the list's ±%
+adjustment** (`spree_price_adjustment_tiers`: list × min_quantity ×
+percentage, falling back to the column) — this superseded, same day, a
+briefly-drafted promotions-based percent design: the implemented
+adjustment already treats percentage as *pricing* (computed on read, unit
+prices, never touching explicit rows), so bands answer "percent off what"
+with the implemented semantics, while marketing-visible volume discounts
+(strikethrough, D2C) remain promotion territory as a recorded deferred
+design (line-quantity rule + quantity-tiered percent calculator).
+Research verdict behind it: every platform with real volume pricing
+attaches tiers to the price record; nobody models them as list-matching
+rules; quantity RULES (MOQ/multiples) stay a sibling non-pricing axis
+everywhere — validating the existing quantity-rules split. Constraints:
+contracted tiers are never discounts, marketing discounts are never
+prices; price-reading callers must pass line quantity through
+`Pricing::Context`; exports must carry tier rows.