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.

Invert the catalog price list binding and close the deactivation leak (#14525)

Damian Legawiec34ab139e365a
diff --git a/CLAUDE.md b/CLAUDE.md
index cfa26dce5f..efcbf34f19 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -13,7 +13,7 @@ Use `/project:create-plan` and `/project:update-plan` for plan management.
Active plans (6.0 target, work pending):
- `6.0-b2b-storefront-purchasing.md` — Storefront company self-service (account section: members, invitations, address book, company orders; the invitation acceptance page the mailer already links) + company-aware checkout (buying-for picker on cart **and** checkout, company address book replacing the personal one at the address step). **Implemented, in review 2026-08-27** (spree/spree#14498 + spree/storefront#214). **No polymorphic owner on Cart/Order** — a purchase keeps two buyer-side parties (`customer_id` + `company_id`), the industry dual axis; OSS ships plain machinery, the polished buyer portal is Enterprise. Backend grew past the planned one-guard widening: `Spree::HasAddressBook` lets an owner declare where its default slots live (a customer's `bill_address_id` vs a company's `default_bill_address_id`) so `Addresses::Create`/`Update` work for any owner — they silently dropped a company's default flag before; default flags are three-state (claim / give up / say nothing) and released by conditional UPDATE, never read-then-write; `Company#address_book` is the inherited reading list, and reads inherit while writes stay with the owning node. **Constraints now:** never branch on an address owner's class — ask the owner (`has_address_book`); a new owner declares its slots or its defaults silently no-op; nothing storefront-side may branch on a member's "role" (OSS has none — gate on standing).
-- `6.0-catalog-agreement-rework.md` — Implementation of the one-question-per-entity catalog consequences (design finalized 2026-08-30; extracted from the `6.0-b2b-companies-and-catalogs.md` amendment block so its Implemented status stops hiding unbuilt work; **sequence Wave 1 — everything catalog-shaped builds on it**): the binding inversion (`spree_price_lists.catalog_id` replaces `spree_catalogs.price_list_id`; catalogs migration rewritten in place — unreleased edge; generic rule matching skips owned lists by FK, closing the deactivated-catalog leak in `bound_price_list_ids`, which is deleted along with its `Spree::Current` memoization); `PriceRules::CustomerGroupRule`/`UserRule` deprecated (bridge + `spree:upgrade:migrate_audience_price_rules_to_catalogs`; mixed-rule lists are REPORTED for manual review, never auto-converted — a wrong conversion is a silent price change), `ChannelRule` grandfathered; catalog-first dashboard (agreement editor, inline `price_list` payload on catalog create/update, products-with-prices view, detach warning, one-go wizard). **Constraints now:** no new reads of `spree_catalogs.price_list_id` or `bound_price_list_ids`; no new features on the deprecated/grandfathered price rules; catalog-page features (terms, pricing card) mount on the agreement editor, never parallel surfaces.
+- `6.0-catalog-agreement-rework.md` — Implementation of the one-question-per-entity catalog consequences (design finalized 2026-08-30; extracted from the `6.0-b2b-companies-and-catalogs.md` amendment block so its Implemented status stops hiding unbuilt work; **sequence Wave 1 — everything catalog-shaped builds on it**; **phases 1–3 implemented 2026-08-30** — schema inversion, resolver leak fix, rule supersession; phase 4 — inline `price_list` payload, agreement editor, products-with-prices view, wizard, detach warning — pending, Wave 2): the binding inversion (`spree_price_lists.catalog_id` replaces `spree_catalogs.price_list_id`; catalogs migration rewritten in place — unreleased edge; generic rule matching skips owned lists by FK in `PriceList.for_context`, closing the deactivated-catalog leak in `bound_price_list_ids`, which is deleted along with its `Spree::Current` memoization; the catalog↔list binding is applied in an `after_save`, never on assignment — a rejected save must not silently release a list store-wide); `PriceRules::CustomerGroupRule`/`UserRule` **grandfathered like `ChannelRule`** (revised 2026-08-30: kept working indefinitely, `superseded?` hides them from the rule picker — NO deprecation warning, NO removal date, NO data task; migrating who-gets-which-price automatically is a silent-price-change risk merchants gain nothing from). **Constraints now:** no new reads of `spree_catalogs.price_list_id` or `bound_price_list_ids`; no new features on the grandfathered price rules (audience targeting is catalog assignment, channel pricing is the default catalog); catalog-page features (terms, pricing card) mount on the agreement editor, never parallel surfaces.
- `6.0-b2b-wholesale-shipping.md` — Wholesale/freight shipping (design finalized 2026-08-30, nothing built): **`Spree::PackageType`** — store-scoped packaging vocabulary (`box|envelope|carton|pallet|container`, one default per store Channel-style) absorbing the four `default_package_*` store preferences (one-release bridges; deliberately NOT `Spree::Package` — `Stock::Package` is the in-memory packer); variant packing chain `carton_package_type_id` + `units_per_carton` + `carton_weight` + `cartons_per_pallet` (geometry on the shared carton row, packing facts on the variant; Unit → Carton → Pallet → CBM/weight); unit-aware `Spree::FreightSummary` (units/cartons/pallets/CBM/gross weight, `complete?` flag) built on the currently-unused `Stock::Package#volume` chain via a new `Spree::Measurement` conversion helper; shipment tiers = `DeliveryMethodRules::VolumeRule` (CBM min/max) + `CompanyRule` (`company_presence`) — **no new delivery profile kind** (the same product ships parcel retail and carton wholesale, and a product has one profile); **unpriced rates are first-class** (`unpriced` on Estimate + `spree_delivery_rates`, estimator skips markup, UIs render "quoted after review" — never a $0 rate that displays as Free) returned by `DeliveryRateProvider::Freight`, whose rate `metadata` snapshots the summary + deposit terms (frozen at completion — duties doctrine, never re-derived); **deposits are collected, not displayed**: deposit terms → `Cart#amount_due_at_checkout`, `Carts::Complete` validates payments against the deposit (base = order total at placement), order completes `partially_paid` with the existing `outstanding_balance` (2026-08-30 amendment: the method-level `deposit_percentage` is a *default source* feeding the order's `payment_terms` snapshot — see `6.0-6.1-b2b-payment-terms.md`); the forwarder's quote lands later as `Fee(kind: 'freight')` through `/admin/orders/:id/fees`. **Constraints now:** all volume/CBM math goes through the unit-aware helper (raw dimension-column multiplication is forbidden — the `WeightRule` raw-number shortcut does not extend to volume); no new readers of the `default_package_*` preferences; never model quote-later as a zero-cost priced rate; carton geometry never becomes variant columns; nothing may assume a completed order is paid in full (check `payment_status`/`outstanding_balance`); post-placement freight charges are Fees, never delivery-rate edits.
- `6.0-b2b-quantity-rules.md` — B2B MOQ + order multiples + purchase unit (design finalized 2026-08-30 under the one-question-per-entity doctrine — decisions.md): variant base columns `minimum_order_quantity`/`order_multiple`/`purchase_unit` (`unit|carton`, display-only vocabulary — stored quantities stay units) binding every cart, enforced as named steps in `Carts::AddItem`/`UpsertItems` on the RESULTING line quantity and re-checked at `Carts::Complete` (staff/admin unrestricted; server refuses invalid quantities naming the nearest valid neighbors — **never silently rounds**); storefront steppers step by the multiple / count cartons ("2 CTNS — 48 units"). **Commercial terms are Catalog data:** the catalog-wide default = `minimum_order_quantity` + `order_multiple` **columns on `spree_catalogs`** (same pair at three levels: variant base → catalog default → override), contextual per-SKU tiers = `spree_catalog_quantity_rules` (catalog_id, variant_id both null: false, one plain unique index — strictly overrides), and the cart-level minimum = `spree_catalog_order_minimums` (per-currency rows, never one amount + a currency column) — **deliberately typed tables per grain, never one generic catalog_rules table or an STI rule family** (hot-path indexed lookups + DB uniqueness; rules are matching predicates, terms are values — typed-adjustments doctrine), all resolved **per-field nearest-agreement-wins** through `Catalog.for_context` (override row → catalog columns → variant base; a channel minimum is just its default catalog's terms; a terms-only catalog with empty assortment is legitimate); serializers expose the buyer's *resolved* rules + the minimum/shortfall. The earlier same-day `ChannelRule` STI family is superseded — access gating (`storefront_access`/`guest_checkout`) stays as Channel preferences because gating binds before identity exists. **Constraints now:** nothing below the cart layer may read quantity rules (stock/allocation/fulfillment stay unit-pure); new item mutations keep routing through `AddItem`/`UpsertItems`; commercial terms are catalog rows/columns resolved per-field — no purchase-term settings on Channel, no term columns on variants beyond the base rules; never move gating onto catalogs.
- `6.0-price-list-automatic-pricing.md` — Automatic price adjustments (design finalized 2026-08-30): `spree_price_lists.price_adjustment_percentage` (signed decimal, nil = fixed list; `adjust_compare_at` boolean) — the resolver derives base × factor **on read** for variants without an explicit row (explicit amounts override per variant × currency; nil-amount placeholder rows fall through), currency-rounded, currency-agnostic (applies to every base currency), **never materialized** (no refresh jobs, no drift; resolution cache keys must include the base price's version). Combined with `VolumeRule` this gives automatic % volume discounts with zero rows to maintain. Dashboard Pricing card (magnitude + increase/decrease + compare-at switch) on the standalone list page AND embedded on the catalog page for a catalog-owned list. **Constraints now:** no job/rake/import may write price rows computed from an adjustment; price exports/feeds/reports must resolve through the pricing provider once adjustment lists exist; "how numbers are made" lives on PriceList, never Catalog.
@@ -86,7 +86,7 @@ Pending design work (drafts, no implementation yet):
- `6.1-exchange-rates.md` — `Spree::ExchangeRate` + `ExchangeRateProvider` (ECB feed as the credential-free default, registry copied from `tax_providers`/`delivery_rate_providers`, keyed providers via `Spree::Integration`). **Rates fill fields, they never price anything** — a merchant gets editable suggestions for the other currencies and what persists is a plain number they own; Spree's "one explicit amount per currency, no FX" stance is unchanged. Never at charge time: EU VAT Directive Art. 91 pins the rate to the instant VAT becomes chargeable, so a commission invoice's VAT figure must be frozen with its rate/date/source or the platform cannot reproduce its own filed documents (Shopify converts at capture and is the wrong pattern here; Vendure/Medusa/Saleor never convert in core). Rates are stored historically and looked up **most-recent-on-or-before**, never exact-date (the ECB skips weekends); cross-currency derives through the base per Art. 91, never stored as a third row; rate precision is NOT money's `decimal(_,2)`. **Constraints now:** never set `Money.default_bank` or call `exchange_to` (the empty rate store raising `UnknownRate` is correct); new money configuration is born per currency, never one amount + a currency column; no conversion endpoint on any API. Also records two live promotion bugs found while researching it — `Calculator::FlatRate` silently discounts **zero** on a currency mismatch, and `Promotion::Rules::ItemTotal` stores a bare threshold with no currency — both independent of this feature.
Shipped plans:
-- `6.0-b2b-companies-and-catalogs.md` — B2B companies as a **multi-level organization tree** + Catalogs pulled into 6.0 (**implemented 2026-08-25**; replaced the unreleased Company→CompanyLocation→CompanyContact prototype outright — migrations rewritten in place, no bridges). One `spree_companies` table: self-referential `parent_id`, `kind` = `company` (legal entity) | `division`, depth capped at `MAX_DEPTH` (5), roots must be `company`; **`#legal_entity` (nearest self-or-ancestor company node) is the single tax anchor** — TaxIdentifier/TaxExemptionCertificate refuse division owners, and purchases read `company_legal_entity`, never the node. `CompanyAddress` (owned rows, labeled, one default per kind via Channel-style demotion + partial index), `CompanyMembership` (always customer-backed; standing = node + subtree, checked via `Customer#standing_for?`/`company_standing(store:)` — never node equality), `CompanyInvitation` (plaintext token, 30-day expiry, pending-scoped uniqueness; mail in `spree/emails`, acceptance via `CompanyInvitations::Accept` running `Customers::Create`; both member-adding surfaces converge on `Companies::AddMember` by email). Carts/orders carry `company_id` (any node; cart-side standing validation, sole-membership resolution in `resolved_company`, frozen at completion). **Catalogs:** `Catalog` (assortment + optional PriceList) + `CatalogProduct` (membership only — **no position**: a catalog decides what a buyer sees, never the order they see it in; category/collection membership stays positioned) + polymorphic `CatalogAssignment` (CustomerGroup|Company — buyer audiences only, company assignments cover the subtree; narrowed 2026-08-28 from the original four: Channel/Market were write-only — a channel's catalog is `spree_channels.default_catalog_id`, a market catalog returns only with a designed regional-assortment reader); visibility = `Products::ForContext` (union of effective catalogs, wired into the store products listing), pricing = catalog price lists nearest-node-first in `Pricing::Resolver` (catalog-bound lists excluded from generic rule matching — a rule-less list must not leak to everyone). Store API self-service (`/store/account/companies`, `/store/companies/*`, unauthenticated invitation lookup/accept, writable cart `company_id`) authorizes by **standing + `Storefront::AccessPolicy`** (company branch answers yes for any member — OSS has no company roles; Enterprise narrows via the policy class + checkout hooks). Dashboard: lazy tree list, node page (sub-units/members+invitations/address book; tax cards hidden on divisions), catalogs pages; slots renamed `company_membership.*`, `company.form_*` only. **Constraints:** never reference the deleted location/contact models; no governance fields on OSS models; `kind` stays the fixed two (divergence = STI, never a second table); catalog/company lookups store-scoped including incidental ids. **Amended 2026-08-30 (one-question-per-entity doctrine — decisions.md):** the Catalog is the **commercial agreement** — it grows commercial terms (catalog-level `minimum_order_quantity`/`order_multiple` columns + per-variant override rows + per-currency order minimums, owned by `6.0-b2b-quantity-rules.md`); the list binding **inverts** to `spree_price_lists.catalog_id` (a list is standalone or owned by ONE catalog; generic rule matching skips owned lists by FK — the shipped active-catalogs-only derived set leaked a deactivated catalog's rule-less list to the whole store); `PriceRules::CustomerGroupRule`/`UserRule` deprecated (bridge + data task → assortment-less catalogs), `PriceRules::ChannelRule` grandfathered (kept working, nothing new builds on it — forward path is the channel's default catalog); dashboard goes catalog-first with one-go setup (inline `price_list` payload on catalog create/update, products-with-prices view). Implementation extracted to `6.0-catalog-agreement-rework.md` (Draft).
+- `6.0-b2b-companies-and-catalogs.md` — B2B companies as a **multi-level organization tree** + Catalogs pulled into 6.0 (**implemented 2026-08-25**; replaced the unreleased Company→CompanyLocation→CompanyContact prototype outright — migrations rewritten in place, no bridges). One `spree_companies` table: self-referential `parent_id`, `kind` = `company` (legal entity) | `division`, depth capped at `MAX_DEPTH` (5), roots must be `company`; **`#legal_entity` (nearest self-or-ancestor company node) is the single tax anchor** — TaxIdentifier/TaxExemptionCertificate refuse division owners, and purchases read `company_legal_entity`, never the node. `CompanyAddress` (owned rows, labeled, one default per kind via Channel-style demotion + partial index), `CompanyMembership` (always customer-backed; standing = node + subtree, checked via `Customer#standing_for?`/`company_standing(store:)` — never node equality), `CompanyInvitation` (plaintext token, 30-day expiry, pending-scoped uniqueness; mail in `spree/emails`, acceptance via `CompanyInvitations::Accept` running `Customers::Create`; both member-adding surfaces converge on `Companies::AddMember` by email). Carts/orders carry `company_id` (any node; cart-side standing validation, sole-membership resolution in `resolved_company`, frozen at completion). **Catalogs:** `Catalog` (assortment + optional PriceList) + `CatalogProduct` (membership only — **no position**: a catalog decides what a buyer sees, never the order they see it in; category/collection membership stays positioned) + polymorphic `CatalogAssignment` (CustomerGroup|Company — buyer audiences only, company assignments cover the subtree; narrowed 2026-08-28 from the original four: Channel/Market were write-only — a channel's catalog is `spree_channels.default_catalog_id`, a market catalog returns only with a designed regional-assortment reader); visibility = `Products::ForContext` (union of effective catalogs, wired into the store products listing), pricing = catalog price lists nearest-node-first in `Pricing::Resolver` (catalog-bound lists excluded from generic rule matching — a rule-less list must not leak to everyone). Store API self-service (`/store/account/companies`, `/store/companies/*`, unauthenticated invitation lookup/accept, writable cart `company_id`) authorizes by **standing + `Storefront::AccessPolicy`** (company branch answers yes for any member — OSS has no company roles; Enterprise narrows via the policy class + checkout hooks). Dashboard: lazy tree list, node page (sub-units/members+invitations/address book; tax cards hidden on divisions), catalogs pages; slots renamed `company_membership.*`, `company.form_*` only. **Constraints:** never reference the deleted location/contact models; no governance fields on OSS models; `kind` stays the fixed two (divergence = STI, never a second table); catalog/company lookups store-scoped including incidental ids. **Amended 2026-08-30 (one-question-per-entity doctrine — decisions.md):** the Catalog is the **commercial agreement** — it grows commercial terms (catalog-level `minimum_order_quantity`/`order_multiple` columns + per-variant override rows + per-currency order minimums, owned by `6.0-b2b-quantity-rules.md`); the list binding **inverts** to `spree_price_lists.catalog_id` (a list is standalone or owned by ONE catalog; generic rule matching skips owned lists by FK — the shipped active-catalogs-only derived set leaked a deactivated catalog's rule-less list to the whole store); `PriceRules::CustomerGroupRule`/`UserRule` grandfathered alongside `PriceRules::ChannelRule` (all kept working, hidden from the picker, nothing new builds on them — forward path is catalog assignment, and for a channel its default catalog); dashboard goes catalog-first with one-go setup (inline `price_list` payload on catalog create/update, products-with-prices view). Implementation extracted to `6.0-catalog-agreement-rework.md` (Draft).
- `5.4-store-api-bridges.md` — Bridge 6.0 naming into 5.4 Store API (PR #13782)
- `5.4-spree-starter-and-create-spree-app.md` — Replace monorepo server/ with spree-starter template repo
- `5.4-option-type-enhancements.md` — `kind` (dropdown/color_swatch/buttons) on OptionType + `color_code` on OptionValue
diff --git a/docs/developer/core-concepts/catalogs.mdx b/docs/developer/core-concepts/catalogs.mdx
index 66d223ae01..2849d2afa7 100644
--- a/docs/developer/core-concepts/catalogs.mdx
+++ b/docs/developer/core-concepts/catalogs.mdx
@@ -20,10 +20,8 @@ flowchart LR
erDiagram
Catalog ||--o{ CatalogProduct : "assortment"
Catalog ||--o{ CatalogAssignment : "audiences"
- Catalog }o--o| PriceList : "optional pricing"
- CatalogAssignment }o--|| Channel : "one of"
+ Catalog ||--o| PriceList : "owns (optional)"
CatalogAssignment }o--|| CustomerGroup : "one of"
- CatalogAssignment }o--|| Market : "one of"
CatalogAssignment }o--|| Company : "one of"
Catalog {
@@ -64,6 +62,8 @@ const catalog = await adminClient.catalogs.create({
The price list is optional. A catalog with an assortment and no price list restricts the range at normal prices; a catalog with a price list and no assortment adjusts prices without hiding anything.
+A price list is either **standalone** (matched by its own rules) or **owned by exactly one catalog** — attaching a list a catalog already claims moves it. Detaching (`price_list_id: null`) is an explicit act with a real consequence: a released list starts matching by its own rules again, and a rule-less one matches everyone.
+
### Filling the assortment
```typescript Admin SDK
@@ -75,7 +75,7 @@ const { data: products } = await adminClient.catalogs.products.list(catalog.id)
await adminClient.catalogs.products.delete(catalog.id, 'prod_xxx')
```
-Products are positioned, so a catalog also controls the order they're presented in.
+Membership is all a catalog holds — it decides *what* a buyer sees, never the order they see it in. Presentation order stays with categories and collections.
When a catalog should restrict to exactly what its price list covers, there's a shortcut that copies those products in rather than making someone add them by hand:
@@ -85,15 +85,15 @@ const { added_count } = await adminClient.catalogs.importProducts(catalog.id)
## Choosing the audience
-A catalog is assigned to one of four things:
+A catalog is assigned to a buyer audience:
| Assign to | Meaning |
|---|---|
-| **[Channel](/developer/core-concepts/channels)** | Everyone buying through this channel — an app, a retail till |
| **[Customer group](/developer/core-concepts/customers)** | A segment — wholesale accounts, staff, a loyalty tier |
-| **[Market](/developer/core-concepts/markets)** | Everyone in a region |
| **[Company](/developer/core-concepts/companies)** | One B2B organization |
+A [Channel](/developer/core-concepts/channels) is not assigned — it names its catalog directly via `default_catalog_id`, which applies to everyone buying through it when nothing narrower does.
+
```typescript Admin SDK
await adminClient.catalogs.assign(catalog.id, {
assignable_type: 'customer_group',
@@ -134,9 +134,9 @@ Prices are checked in order, and the first match wins:
Nearest-first is what lets a subsidiary hold a better-negotiated rate than the group's, without disturbing anyone else.
<Warning>
-A price list attached to a catalog applies **because the catalog applies** — its own rules are not consulted, and it's excluded from ordinary rule matching.
+A price list owned by a catalog applies **because the catalog applies** — its own rules are not consulted, and it's excluded from ordinary rule matching.
-That exclusion is load-bearing: a price list with no rules would otherwise match everyone, and one company's negotiated pricing would leak to the entire storefront.
+That exclusion is load-bearing: a price list with no rules would otherwise match everyone, and one company's negotiated pricing would leak to the entire storefront. It also means a deactivated catalog's list goes **dormant** — turning the catalog off never releases its pricing to the whole store. Only explicitly detaching the list puts it back into rule matching.
</Warning>
## Related
diff --git a/docs/developer/core-concepts/pricing.mdx b/docs/developer/core-concepts/pricing.mdx
index b2dfb14116..2a29faa758 100644
--- a/docs/developer/core-concepts/pricing.mdx
+++ b/docs/developer/core-concepts/pricing.mdx
@@ -149,7 +149,7 @@ const priceList = await client.priceLists.create({
name: 'EU wholesale',
match_policy: 'all',
rules: [
- { type: 'customer_group_rule', preferences: { customer_group_ids: ['cg_xxx'] } },
+ { type: 'market_rule', preferences: { market_ids: ['mkt_xxx'] } },
],
prices: [
{ variant_id: 'variant_xxx', currency: 'EUR', amount: '19.99' },
@@ -173,16 +173,20 @@ spree api patch /price_lists/pl_xxx/activate
## Price Rules
-Price Rules define conditions that must be met for a Price List to apply. Spree includes five built-in rule types:
+Price Rules define conditions that must be met for a Price List to apply. Rules describe the *context* of a purchase — where, through what, how much:
| Rule | Description | Use Case |
|------|-------------|----------|
| **Market Rule** | Matches based on the current [Market](/developer/core-concepts/markets) | Regional pricing across markets |
| **Channel Rule** | Matches based on the [Channel](/developer/core-concepts/channels) the customer is buying through | App-only or in-store pricing |
-| **User Rule** | Matches specific customer accounts | VIP customers, wholesale accounts |
-| **Customer Group Rule** | Matches members of customer groups | Loyalty tiers, membership pricing |
| **Volume Rule** | Matches based on quantity purchased | Bulk discounts, tiered pricing |
+*Who* gets a price list is not a rule — it's a [Catalog](/developer/core-concepts/catalogs): attach the list to a catalog assigned to the customer groups or companies it's for.
+
+<Note>
+The **User Rule** and **Customer Group Rule** kinds still work and are not going away, but they're no longer offered when adding a rule — targeting an audience through a catalog is the one way to do it now. Nothing needs migrating; rules you already have keep matching exactly as before.
+</Note>
+
### Market Rule
Regional pricing. Applies the Price List when the customer is in one of the specified markets.
@@ -191,15 +195,7 @@ Regional pricing. Applies the Price List when the customer is in one of the spec
### Channel Rule
-Applies when the customer is buying through a particular sales channel — a discount that exists only in the mobile app, or a price that only applies at a retail till.
-
-### User Rule
-
-Limits the Price List to specific customer accounts. Useful for VIP customers, employee pricing, or wholesale accounts.
-
-### Customer Group Rule
-
-Applies to members of specific customer groups. Useful for wholesale tiers, loyalty programs, or membership-based pricing.
+Applies when the customer is buying through a particular sales channel — a discount that exists only in the mobile app, or a price that only applies at a retail till. For new setups, prefer giving the channel a default [Catalog](/developer/core-concepts/catalogs) that owns the price list — that is where channel-wide commercial terms live going forward.
### Volume Rule
@@ -224,7 +220,7 @@ When resolving prices, Spree considers the full context of the request:
| Currency | Market or request header | The currency to price in |
| Market | Customer's country | The [Market](/developer/core-concepts/markets) for market-based rules |
| Channel | The API credential in use | The [Channel](/developer/core-concepts/channels) for channel-based rules |
-| Customer | Authentication | The signed-in customer for user-based rules |
+| Customer | Authentication | The signed-in customer, for resolving their [Catalogs](/developer/core-concepts/catalogs) |
| Quantity | Cart line item | The quantity for volume-based rules |
| Date | Current time | For time-based Price List scheduling |
diff --git a/docs/plans/6.0-catalog-agreement-rework.md b/docs/plans/6.0-catalog-agreement-rework.md
index 28018b1b7a..2ca73a1477 100644
--- a/docs/plans/6.0-catalog-agreement-rework.md
+++ b/docs/plans/6.0-catalog-agreement-rework.md
@@ -1,6 +1,6 @@
# Catalog Agreement Rework (Binding Inversion + Audience-Rule Retirement)
-**Status:** Draft — design finalized 2026-08-30 (extracted 2026-08-30 from the amendment block in `6.0-b2b-companies-and-catalogs.md`, whose Implemented status was hiding this unbuilt work), nothing built
+**Status:** In progress — phases 1–3 implemented 2026-08-30 (binding inversion, resolver + leak fix, audience-rule supersession); phase 4 (inline `price_list` payload, agreement editor, products-with-prices view, wizard, detach warning) pending — sequenced Wave 2. Design finalized 2026-08-30 (extracted from the amendment block in `6.0-b2b-companies-and-catalogs.md`, whose Implemented status was hiding this unbuilt work)
**Target:** Spree 6.0 — sequence Wave 1: everything catalog-shaped builds on the inverted binding, and the leak fix touches unreleased code
**Depends on:** B2B Companies & Catalogs (6.0-b2b-companies-and-catalogs.md — the shipped catalogs this reworks), PriceList system (released)
**Author:** Damian + Claude
@@ -36,16 +36,20 @@ catalog page this rework establishes.
start matching by its own rules"). Sharing one list across catalogs is
lost — one catalog serving many audiences through assignments is the
replacement.
-- **Audience price rules retire; context rules stay.**
- `PriceRules::CustomerGroupRule` and `PriceRules::UserRule` duplicated
- catalog assignment with different, silent precedence — deprecated in 6.0
- with the standard one-release bridge and a data task converting each such
- list into an assortment-less catalog assigned to the audience and owning
- the list (a `UserRule` list maps to a single-member customer group).
- `PriceRules::ChannelRule` is **grandfathered**: kept working, nothing new
- builds on it, the forward path is the channel's default catalog owning an
- assortment-less list. `MarketRule` (carries VAT restatement) and
- `VolumeRule` are context-shaped and stay first-class.
+- **Audience price rules are grandfathered, not deprecated** (revised
+ 2026-08-30 after review — supersedes the same-day "deprecated + data
+ task" decision). `PriceRules::CustomerGroupRule` and
+ `PriceRules::UserRule` duplicated catalog assignment with different,
+ silent precedence, so they are **hidden from the rule picker** and
+ nothing new builds on them — but they keep matching indefinitely, with
+ no removal date, no creation warning, and **no data task**. Rationale:
+ the conversion only had to exist because the classes were being removed;
+ once they simply keep working, migrating is churn a merchant gains
+ nothing from, and an automatic remap of who-gets-which-price is exactly
+ the class of change that is dangerous to get wrong. This puts them on
+ the same footing as `PriceRules::ChannelRule`, already grandfathered for
+ the same reason. `MarketRule` (carries VAT restatement) and `VolumeRule`
+ are context-shaped and stay first-class and offered.
- **Because catalogs are unreleased (6.0 edge), the catalogs side rewrites
in place** — the create-catalogs migration drops its `price_list_id`
reference, no bridge, per the companies-plan precedent. The
@@ -72,14 +76,14 @@ catalog page this rework establishes.
`catalog_price_lists` reads the association. Only **active** catalogs
still claim their list in the resolution walk (unchanged semantics,
now leak-free on the exclusion side).
-- Deprecation bridges: creating a new `CustomerGroupRule`/`UserRule` warns
- (removed 6.1); existing rows keep matching through the bridge release so
- un-migrated stores don't lose pricing mid-upgrade.
-- Data task (`spree:upgrade:migrate_audience_price_rules_to_catalogs`, in
- the 6.0 manifest): audience-only lists convert cleanly; a list mixing
- audience and context rules (or `match_policy: all` across both) is
- reported for manual review rather than guessed at — a wrong automatic
- conversion here is a silent price change.
+- Supersession is a discovery-level flag, not a bridge: `superseded?` on
+ the rule class surfaces as `superseded: true` in types discovery (present
+ only when true, so rule families without the concept keep their wire
+ shape), and the dashboard picker filters those kinds out. Existing rules
+ render, edit and match unchanged.
+- No upgrade step: nothing in the 6.0 manifest touches price rules. A
+ store upgrades with its audience rules matching exactly as before, and
+ adopts catalogs for new agreements at whatever pace suits it.
- Admin API: catalogs create/update accept `price_list: {...}` (create or
update the owned list inline); the price-lists endpoints keep working for
standalone lists; detach = `price_list: null`-style explicit action.
@@ -91,12 +95,27 @@ catalog page this rework establishes.
1. **Schema** — rewrite the catalogs migration in place (drop
`price_list_id`); additive `catalog_id` on `spree_price_lists`; edge
- worktrees rebuild the template DB.
+ worktrees rebuild the template DB. **Done 2026-08-30** (one live list per
+ catalog is enforced on every adapter — a partial unique index on
+ PostgreSQL/SQLite, a unique index over a stored generated column on
+ MySQL/MariaDB per the `spree_commission_rates` precedent, so the rule
+ never rests on the model validation alone; soft-deleted lists release the
+ slot. The admin API keeps its `price_list_id` read/write shape through
+ model-level accessors over the inverted association until phase 4
+ reshapes the payload).
2. **Model + resolver** — association flip, SQL-level owned-list exclusion,
delete the derived set + memoization; specs pin the leak (a deactivated
- catalog's rule-less list prices nobody).
-3. **Rule retirement** — deprecation warnings + bridge, the data task,
- types-discovery marking.
+ catalog's rule-less list prices nobody). **Done 2026-08-30** (the
+ exclusion lives in `PriceList.for_context` — the one feed for both
+ `Spree::Current.price_lists` and the resolver's direct fetch; detach and
+ catalog destroy release the list to standalone, `dependent: :nullify`).
+3. **Rule supersession** — types-discovery marking only. **Done
+ 2026-08-30** (`superseded: true` in
+ `subclasses_with_preference_schema`, present only when true so other
+ type-discovery endpoints keep their wire shape; the dashboard rule
+ picker filters those kinds while existing rules still render, edit and
+ match). Deliberately no warnings, no bridge and no data task — see the
+ revised Key Decision above.
4. **API + dashboard** — inline `price_list` payload, agreement editor,
products-with-prices view, wizard, detach warning. (The pricing card's
±% controls and the Terms card arrive with their own plans on this
@@ -106,9 +125,10 @@ catalog page this rework establishes.
- **No new code reads `spree_catalogs.price_list_id`** or
`Catalog.bound_price_list_ids` — the FK on the list is the one binding.
-- **No new features build on `PriceRules::CustomerGroupRule`/`UserRule`**
- (deprecated) **or `ChannelRule`** (grandfathered) — audience targeting is
- catalog assignment; channel pricing is the default catalog.
+- **No new features build on `PriceRules::CustomerGroupRule`/`UserRule`
+ or `ChannelRule`** (all grandfathered — kept working, hidden from
+ pickers) — audience targeting is catalog assignment; channel pricing is
+ the default catalog.
- Catalog-page features (terms, pricing card) mount on the agreement
editor this plan establishes — no parallel catalog editing surfaces.
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 42e3264c89..8210d33a93 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -4411,3 +4411,42 @@ standard deprecation bridges; decided when inventory-operations is groomed.
Further optional trims, in order, if 6.0 needs more relief: the one-go
catalog wizard polish, the wholesale storefront surfaces, automatic pricing
(last resort — the catalog wizard's ±% option wants it).
+
+## 2026-08-30 — Audience price rules are grandfathered, not deprecated: no bridge, no data task
+
+Revises, later the same day, the retirement clause of the
+one-question-per-entity entry above. That entry deprecated
+`PriceRules::CustomerGroupRule` and `PriceRules::UserRule` in 6.0 with a
+one-release bridge and a data task
+(`spree:upgrade:migrate_audience_price_rules_to_catalogs`) converting each
+audience-targeted list into an assortment-less catalog assigned to that
+audience. Both were built, then removed on review.
+
+**Decision:** the two audience rules are **grandfathered on exactly the terms
+`PriceRules::ChannelRule` already had** — they keep matching indefinitely,
+carry no removal date and no creation warning, and there is no upgrade step.
+The only change that ships is a discovery-level flag: `superseded?` on the
+rule class surfaces as `superseded: true` in
+`subclasses_with_preference_schema` (present only when true, so rule families
+without the concept keep their wire shape byte-identical), and the dashboard
+rule picker filters those kinds out. Existing rules render, edit and match
+unchanged.
+
+The reasoning is that the data task only ever existed to service the removal.
+Once the classes simply keep working, converting is churn a merchant gains
+nothing from — and an automatic remap of *who gets which price* is exactly the
+class of change that is expensive to get wrong and invisible when it is. The
+doctrine goal was never to delete rows; it was to stop offering two mechanisms
+for one question, which hiding the kinds achieves on its own. It also removes
+the awkward middle state where a store that upgraded but never ran the task was
+one release away from silently losing its audience pricing.
+
+Accepted trade-off: two mechanisms for audience targeting remain in the
+codebase permanently, with the precedence the resolver already defines
+(catalog-owned lists first, then rule-matched lists). New work builds only on
+catalog assignment.
+
+Nothing else in the one-question-per-entity entry changes: the binding
+inversion, the leak fix, and the catalog-first dashboard direction all stand.
+Plans amended: `6.0-catalog-agreement-rework.md` (Key Decisions + phase 3),
+`6.0-b2b-companies-and-catalogs.md` (amendment block).
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index d4839a0242..631b202c89 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -1895,6 +1895,12 @@ export interface ResourceTypeDefinition {
label: string
description: string | null
preference_schema: PreferenceField[]
+ /**
+ * Present (true) only on kinds a better mechanism has replaced: existing
+ * records keep working and rendering, but pickers must stop offering the
+ * kind to new setups.
+ */
+ superseded?: boolean
}
// ---------------------------------------------------------------------------
diff --git a/packages/dashboard/e2e/price-lists.spec.ts b/packages/dashboard/e2e/price-lists.spec.ts
index be0a1bf0a2..492a27325a 100644
--- a/packages/dashboard/e2e/price-lists.spec.ts
+++ b/packages/dashboard/e2e/price-lists.spec.ts
@@ -1,14 +1,5 @@
import { expect, type Page, test } from '@playwright/test'
-import {
- FIXTURE_PROMO_CUSTOMER_EMAIL,
- FIXTURE_PROMO_CUSTOMER_FIRST_NAME,
- FIXTURE_PROMO_CUSTOMER_GROUP,
- FIXTURE_PROMO_PRODUCT,
- gotoIndex,
- login,
- openRowMenu,
- rowButton,
-} from './helpers'
+import { FIXTURE_PROMO_PRODUCT, gotoIndex, login, openRowMenu, rowButton } from './helpers'
const PRICE_LISTS_PATH = (storeId: string) => `/${storeId}/products/price-lists`
const PRODUCTS_PATH = (storeId: string) => `/${storeId}/products`
@@ -168,69 +159,27 @@ test.describe('price lists', () => {
await expect(page.getByText(/volume rule/i).first()).toBeVisible({ timeout: 15_000 })
})
- test('adds a Customer Group Rule with the seeded group', async ({ page }) => {
+ // The audience rules (customer group / customer) are superseded by catalog
+ // assignment (docs/plans/6.0-catalog-agreement-rework.md). Existing rules
+ // keep working and rendering; the picker stops offering them.
+ test('does not offer the superseded audience rules in the picker', async ({ page }) => {
const creds = await login(page)
await gotoIndex(page, PRICE_LISTS_PATH(creds.store_id), CTA)
- const name = `E2E PL CG Rule ${Date.now()}`
+ const name = `E2E PL No Audience Rules ${Date.now()}`
await startNewPriceList(page, creds.store_id, name)
await submitCreate(page, name)
- await pickRule(page, /^customer group rule\b/i)
- await expect(page.getByRole('heading', { name: /^customer group rule$/i })).toBeVisible({
- timeout: 5_000,
- })
-
- await pickAutocompleteOption(page, /search customer groups/i, FIXTURE_PROMO_CUSTOMER_GROUP)
- await saveEditor(page)
-
- // Row summary renders the group name (proves the API embed shipped the
- // resolved `customer_groups` array, which the SPA echoes on the draft).
- await expect(page.getByText(FIXTURE_PROMO_CUSTOMER_GROUP).first()).toBeVisible({
- timeout: 5_000,
- })
-
- await saveForm(page)
-
- // Reload and verify the chip + preview survive (proves the serializer
- // embed round-trips on reload, not just during the in-progress edit).
- await page.reload()
- await expect(page.getByText(FIXTURE_PROMO_CUSTOMER_GROUP).first()).toBeVisible({
- timeout: 15_000,
- })
- })
-
- test('adds a Customer Rule with the seeded customer', async ({ page }) => {
- const creds = await login(page)
- await gotoIndex(page, PRICE_LISTS_PATH(creds.store_id), CTA)
+ await page.getByRole('button', { name: /^add rule$/i }).click()
+ await expect(page.getByRole('heading', { name: /^add rule$/i })).toBeVisible()
- const name = `E2E PL Customer Rule ${Date.now()}`
- await startNewPriceList(page, creds.store_id, name)
- await submitCreate(page, name)
-
- // Wire shorthand is `user_rule`; the SPA labels it "Customer rule"
- // (see `Spree::PriceRules::UserRule.human_name`).
- await pickRule(page, /^customer rule\b/i)
- await expect(page.getByRole('heading', { name: /^customer rule$/i })).toBeVisible({
- timeout: 5_000,
- })
-
- // `Spree.user_class.search` matches first_name (LIKE) and email (exact);
- // we type the first name to drive the search, then assert on the email
- // string the price-list `RuleSummary` renders.
- await pickAutocompleteOption(page, /search customers/i, FIXTURE_PROMO_CUSTOMER_FIRST_NAME)
- await saveEditor(page)
-
- await expect(page.getByText(FIXTURE_PROMO_CUSTOMER_EMAIL).first()).toBeVisible({
- timeout: 5_000,
- })
-
- await saveForm(page)
-
- await page.reload()
- await expect(page.getByText(FIXTURE_PROMO_CUSTOMER_EMAIL).first()).toBeVisible({
- timeout: 15_000,
- })
+ const picker = page.getByRole('dialog')
+ // The context rules stay first-class…
+ await expect(picker.getByRole('button', { name: /^volume rule\b/i })).toBeVisible()
+ await expect(picker.getByRole('button', { name: /^market rule\b/i })).toBeVisible()
+ // …the audience rules are gone.
+ await expect(picker.getByRole('button', { name: /^customer group rule\b/i })).toHaveCount(0)
+ await expect(picker.getByRole('button', { name: /^customer rule\b/i })).toHaveCount(0)
})
test('adds a Market Rule with the seeded default market', async ({ page }) => {
diff --git a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
index 38375baeee..d6434e56b1 100644
--- a/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
+++ b/packages/dashboard/src/components/spree/price-list-editors/price-list-form.tsx
@@ -526,7 +526,12 @@ function RulesCard({
const [pickerOpen, setPickerOpen] = useState(false)
const [editingIndex, setEditingIndex] = useState<number | null>(null)
- const types = typesData?.data ?? []
+ // Superseded kinds (audience rules, replaced by catalog assignment) stay
+ // renderable for existing rows but are never offered for new ones. The
+ // picker's empty state reads the unfiltered count, so a registry holding
+ // only superseded kinds says "all used" rather than "none registered".
+ const registeredTypes = typesData?.data ?? []
+ const types = registeredTypes.filter((tt) => !tt.superseded)
const watchedRules = (form.watch('rules') ?? []) as PriceRuleFormDraft[]
return (
@@ -593,7 +598,7 @@ function RulesCard({
<RulePickerSheet
// One rule type per list (backend uniqueness on `type`).
types={types.filter((tt) => !watchedRules.some((r) => r.type === tt.type))}
- registeredCount={types.length}
+ registeredCount={registeredTypes.length}
open
onOpenChange={(o) => !o && setPickerOpen(false)}
onPicked={(type) => {
diff --git a/spree/core/app/models/concerns/spree/preference_schema.rb b/spree/core/app/models/concerns/spree/preference_schema.rb
index bec9dff250..1653492589 100644
--- a/spree/core/app/models/concerns/spree/preference_schema.rb
+++ b/spree/core/app/models/concerns/spree/preference_schema.rb
@@ -151,12 +151,17 @@ module Spree
# discovery surface and must never leak gateway-shipped defaults.
def subclasses_with_preference_schema
registered_subclasses.map do |klass|
- {
+ entry = {
type: klass.api_type,
label: subclass_label(klass),
description: klass.respond_to?(:description) ? klass.description : nil,
preference_schema: klass.respond_to?(:serialized_preference_schema) ? klass.serialized_preference_schema : []
}
+ # Only present when true, so families without the concept keep
+ # their wire shape byte-identical. Pickers stop offering a
+ # superseded kind; existing rows still render and match.
+ entry[:superseded] = true if klass.respond_to?(:superseded?) && klass.superseded?
+ entry
end.sort_by { |entry| entry[:label] }
end
diff --git a/spree/core/app/models/spree/base.rb b/spree/core/app/models/spree/base.rb
index 04aba81c87..2e8355d623 100644
--- a/spree/core/app/models/spree/base.rb
+++ b/spree/core/app/models/spree/base.rb
@@ -71,8 +71,10 @@ class Spree::Base < ApplicationRecord
true
end
+ # @see Spree.mysql? — the single definition; this reads it so a model can
+ # branch without reaching for the connection itself.
def mysql_adapter?
- ActiveRecord::Base.connection.adapter_name.downcase.include?('mysql')
+ Spree.mysql?
end
def self.json_api_columns
diff --git a/spree/core/app/models/spree/catalog.rb b/spree/core/app/models/spree/catalog.rb
index 90f90f9fdd..316d4aa7e1 100644
--- a/spree/core/app/models/spree/catalog.rb
+++ b/spree/core/app/models/spree/catalog.rb
@@ -21,8 +21,12 @@ module Spree
attribute :active, :boolean, default: true
belongs_to :store, class_name: 'Spree::Store', inverse_of: :catalogs
- # nil = assortment-only; base prices apply.
- belongs_to :price_list, class_name: 'Spree::PriceList', optional: true
+ # The owned list, or nil for an assortment-only catalog priced at base.
+ # The FK lives on the list (a list is standalone or owned by exactly one
+ # catalog); detaching or destroying the catalog releases the list back to
+ # standalone — an explicit act, since a rule-less standalone list starts
+ # matching by its own (absent) rules.
+ has_one :price_list, class_name: 'Spree::PriceList', inverse_of: :catalog, dependent: :nullify
has_many :catalog_products, class_name: 'Spree::CatalogProduct', dependent: :destroy,
inverse_of: :catalog
@@ -33,12 +37,18 @@ module Spree
validates :name, presence: true
validate :price_list_in_same_store
+ # The binding is applied inside the save, never on assignment: writing a
+ # has_one on a persisted record updates the child immediately, so a
+ # rejected save would already have re-homed the list — or, detaching,
+ # released it to store-wide rule matching, which is the leak this design
+ # exists to close. After rather than before, so a newly created catalog
+ # has an id for the child to point at; still inside the save transaction,
+ # so a later failure takes the binding down with it.
+ after_save :apply_pending_price_list
+
# Request-scoped catalog memoization must not keep a set that a write
# in the same request has already superseded.
- after_commit -> {
- Spree::Current.applicable_catalogs = nil
- Spree::Current.catalog_bound_price_list_ids = nil
- }
+ after_commit -> { Spree::Current.applicable_catalogs = nil }
scope :active, -> { where(active: true) }
scope :by_position, -> { order(position: :asc) }
@@ -119,18 +129,44 @@ module Spree
catalogs
end
- # Price-list ids claimed by an active catalog of the store. Only ACTIVE
- # catalogs claim their list: an inactive catalog is off, and blacklisting
- # its list would silently kill a rule-based list that was working before
- # the catalog draft existed.
+ # The owned list's id. Reads like the column the binding replaced, so
+ # serializers and write payloads keep their shape while the FK lives on
+ # the list side. An assigned-but-unsaved binding reads back as itself, so
+ # a rejected form round-trips what the merchant chose.
#
- # @param store [Spree::Store, nil]
- # @return [Set<Integer>]
- def self.bound_price_list_ids(store)
- return Set.new if store.nil?
+ # @return [Integer, String, nil]
+ def price_list_id
+ return @pending_price_list&.id if defined?(@pending_price_list)
+
+ price_list&.id
+ end
+
+ # Attaches the given list as this catalog's owned list (raw id), or
+ # detaches with nil — releasing the list back to standalone matching.
+ # A list already owned elsewhere is re-homed to this catalog.
+ #
+ # Records the intent only; {#apply_pending_price_list} performs the write
+ # inside the save, so a record that fails validation changes nothing.
+ #
+ # @param value [Integer, String, nil] raw price list PK
+ # @return [void]
+ def price_list_id=(value)
+ @pending_price_list = value.presence && Spree::PriceList.find(value)
+ end
+
+ # Assigning the association directly goes through the same deferral, so
+ # every write path — +price_list=+, +price_list_id=+, nested attributes —
+ # lands in the save rather than on assignment.
+ def price_list=(list)
+ @pending_price_list = list
+ end
- active.where(store_id: store.id).where.not(price_list_id: nil).
- distinct.pluck(:price_list_id).to_set
+ # Reads back an assigned-but-unsaved binding, so callers see what they
+ # set rather than what is still on disk.
+ def price_list
+ return @pending_price_list if defined?(@pending_price_list)
+
+ super
end
# Adds products to the assortment, appending to the manual order and
@@ -189,11 +225,60 @@ module Spree
private
+ # Runs before anything is written, so a foreign-store list is a validation
+ # error on the catalog rather than a RecordNotSaved raised out of the
+ # child's own same-store check.
def price_list_in_same_store
return if price_list.nil? || store_id.nil?
return if price_list.store_id == store_id
errors.add(:price_list, :invalid)
end
+
+ # Applies the deferred binding inside the save transaction: the newly
+ # claimed list points here, and a list this catalog is giving up is
+ # released. Written through the child, since the FK lives on the list.
+ def apply_pending_price_list
+ return unless defined?(@pending_price_list)
+
+ pending = @pending_price_list
+ remove_instance_variable(:@pending_price_list)
+
+ # An unsaved list is persisted through its own lifecycle — it has no id
+ # to bind yet, and skipping that would silently drop it.
+ if pending && !pending.persisted?
+ pending.catalog_id = id
+ pending.save!
+ finish_price_list_binding
+ return
+ end
+
+ # Ownership moves under a row lock, so two concurrent saves cannot
+ # interleave the read of the current binding with the writes. Locking in
+ # id order avoids deadlock, and the binding is re-read once held.
+ association(:price_list).reset
+ lock_ids = [association(:price_list).load_target&.id, pending&.id].compact.uniq.sort
+ Spree::PriceList.where(id: lock_ids).order(:id).lock.load if lock_ids.any?
+
+ association(:price_list).reset
+ previous = association(:price_list).load_target
+ return if previous&.id == pending&.id
+
+ # Compare-and-swap on the release: a list another request has already
+ # re-homed must not be sent back to standalone matching, where a
+ # rule-less list prices the whole store.
+ Spree::PriceList.where(id: previous.id, catalog_id: id).update_all(catalog_id: nil) if previous
+ pending&.update_column(:catalog_id, id)
+
+ finish_price_list_binding
+ end
+
+ def finish_price_list_binding
+ association(:price_list).reset
+ # The writes above skip PriceList's own after_commit, so the request's
+ # memoized generic-matching set is cleared here instead — a detach must
+ # be visible to the rest of this request, not the next one.
+ Spree::Current.price_lists = nil
+ end
end
end
diff --git a/spree/core/app/models/spree/current.rb b/spree/core/app/models/spree/current.rb
index cbf67376fb..7d26a7c322 100644
--- a/spree/core/app/models/spree/current.rb
+++ b/spree/core/app/models/spree/current.rb
@@ -4,7 +4,7 @@ module Spree
# All attributes are automatically reset between requests by Rails.
# Fallback chains ensure sensible defaults when attributes are not explicitly set.
class Current < ::ActiveSupport::CurrentAttributes
- attribute :store, :channel, :market, :currency, :locale, :content_locale, :tax_country, :price_lists, :applicable_catalogs, :catalog_bound_price_list_ids, :global_pricing_context, :provider_cache, :integrations
+ attribute :store, :channel, :market, :currency, :locale, :content_locale, :tax_country, :price_lists, :applicable_catalogs, :global_pricing_context, :provider_cache, :integrations
# Scratch space for provider strategies to memoize a call across the
# request — part of the delivery rate provider contract (nothing in core
@@ -81,7 +81,9 @@ module Spree
super || (self.integrations = store ? store.integrations.active.to_a : [])
end
- # Returns the current price lists for the global pricing context.
+ # Returns the standalone (rule-matched) price lists in effect for the
+ # global pricing context. Catalog-owned lists are excluded — pricing
+ # reaches them through {#catalogs_for}.
# @return [ActiveRecord::Relation<Spree::PriceList>]
def price_lists
super || begin
@@ -108,13 +110,6 @@ module Spree
)
end
- # Price-list ids claimed by any active catalog in the current store.
- # One pluck per request — the listing path asked this for every variant.
- # @return [Set<Integer>]
- def catalog_bound_price_list_ids
- super || (self.catalog_bound_price_list_ids = Spree::Catalog.bound_price_list_ids(store))
- end
-
# @return [Hash]
def applicable_catalogs
super || (self.applicable_catalogs = {})
diff --git a/spree/core/app/models/spree/price_list.rb b/spree/core/app/models/spree/price_list.rb
index 0725e0d9bc..d1ca661693 100644
--- a/spree/core/app/models/spree/price_list.rb
+++ b/spree/core/app/models/spree/price_list.rb
@@ -10,19 +10,27 @@ module Spree
MATCH_POLICIES = %w[all any].freeze
belongs_to :store, class_name: 'Spree::Store'
+ # The owning agreement, or nil for a standalone list. An owned list is
+ # reached only through its catalog — generic rule matching skips it in
+ # SQL (see .for_context) — so a deactivated catalog's list goes dormant
+ # instead of leaking back into store-wide matching. `touch` keeps the
+ # catalog's cache key honest when its pricing changes.
+ belongs_to :catalog, class_name: 'Spree::Catalog', optional: true, inverse_of: :price_list, touch: true
has_many :price_rules, class_name: 'Spree::PriceRule', autosave: true, dependent: :destroy
alias rules price_rules
has_many :prices, class_name: 'Spree::Price', dependent: :destroy_async
- # Catalogs that price through this list. Nullify: deleting the list turns
- # them back into assortment-only catalogs.
- has_many :catalogs, class_name: 'Spree::Catalog', dependent: :nullify
has_many :variants, -> { distinct }, through: :prices, source: :variant
has_many :products, -> { distinct }, through: :variants, source: :product
alias price_list_products products
after_save :apply_pending_rules
+ # Request-scoped memoization of the generic matching set must not keep a
+ # set that a write in the same request has already superseded — a status
+ # flip or a catalog attach/detach changes which lists match generically.
+ after_commit -> { Spree::Current.price_lists = nil }
+
# Flat-payload writer for `rules`. See
# {Spree::TypedAssociations#assign_typed_association}.
def rules=(rows)
@@ -31,12 +39,19 @@ module Spree
validates :name, presence: true
validates :match_policy, presence: true, inclusion: { in: MATCH_POLICIES }
+ # One live list per catalog; soft-deleted lists release the slot. Backed
+ # by a unique index on every adapter — partial on PostgreSQL and SQLite,
+ # over a stored generated column on MySQL/MariaDB.
+ validates :catalog_id, uniqueness: { scope: spree_base_uniqueness_scope,
+ conditions: -> { where(deleted_at: nil) } }, allow_nil: true
validate :starts_at_before_ends_at
+ validate :catalog_in_same_store
self.whitelisted_ransackable_attributes = %w[status match_policy starts_at ends_at]
scope :by_position, -> { order(position: :asc) }
scope :for_store, ->(store) { where(store: store) }
+ scope :standalone, -> { where(catalog_id: nil) }
scope :current, lambda { |timezone = nil|
timezone ||= Rails.application.config.time_zone
# Round to beginning of minute to enable Rails query caching
@@ -72,12 +87,18 @@ module Spree
update(status: 'scheduled')
end
- # Returns price lists applicable for a given pricing context
+ # Returns price lists eligible for generic rule matching in a pricing
+ # context:
# - active: always applies (within date range)
# - scheduled: applies only within starts_at/ends_at date range
+ # - standalone only: a catalog-owned list is reached exclusively through
+ # its catalog, so it is excluded here in SQL — which is what keeps a
+ # deactivated catalog's (typically rule-less) list dormant instead of
+ # pricing the whole store.
def self.for_context(context)
timezone = context.store&.preferred_timezone || 'UTC'
for_store(context.store)
+ .standalone
.with_status(:active, :scheduled)
.current(timezone)
.by_position
@@ -259,6 +280,13 @@ module Spree
Spree::Variants::TouchJob.perform_later(variant_ids)
end
+ def catalog_in_same_store
+ return if catalog.nil? || store_id.nil?
+ return if catalog.store_id == store_id
+
+ errors.add(:catalog, :invalid)
+ end
+
def starts_at_before_ends_at
return if starts_at.blank? || ends_at.blank?
diff --git a/spree/core/app/models/spree/price_rule.rb b/spree/core/app/models/spree/price_rule.rb
index 9cdf7eb7aa..d71d742134 100644
--- a/spree/core/app/models/spree/price_rule.rb
+++ b/spree/core/app/models/spree/price_rule.rb
@@ -28,6 +28,16 @@ module Spree
false
end
+ # Whether a better mechanism has replaced this rule kind. Superseded
+ # kinds are grandfathered — existing rules keep matching indefinitely —
+ # but they are flagged in types discovery so pickers stop offering them
+ # to new setups (docs/plans/6.0-catalog-agreement-rework.md).
+ #
+ # @return [Boolean]
+ def self.superseded?
+ false
+ end
+
# Returns the human name of the price rule
# @return [String]
def self.human_name
diff --git a/spree/core/app/models/spree/price_rules/channel_rule.rb b/spree/core/app/models/spree/price_rules/channel_rule.rb
index f9a5a9030e..9782da4a98 100644
--- a/spree/core/app/models/spree/price_rules/channel_rule.rb
+++ b/spree/core/app/models/spree/price_rules/channel_rule.rb
@@ -1,5 +1,8 @@
module Spree
module PriceRules
+ # Grandfathered (2026-08-30, one-question-per-entity doctrine): kept
+ # working, but nothing new builds on it — the forward path for channel
+ # pricing is the channel's default catalog owning a price list.
class ChannelRule < Spree::PriceRule
# Stored as raw IDs. Accepts prefixed IDs (`ch_…`) from API
# callers and decodes them on write so eligibility checks compare
diff --git a/spree/core/app/models/spree/price_rules/customer_group_rule.rb b/spree/core/app/models/spree/price_rules/customer_group_rule.rb
index 269629f163..ba3ee9b8db 100644
--- a/spree/core/app/models/spree/price_rules/customer_group_rule.rb
+++ b/spree/core/app/models/spree/price_rules/customer_group_rule.rb
@@ -1,5 +1,10 @@
module Spree
module PriceRules
+ # Superseded by catalog assignment, and grandfathered: existing rules
+ # keep matching indefinitely, but new setups target an audience by
+ # assigning it a catalog that owns the price list
+ # (docs/plans/6.0-catalog-agreement-rework.md). Hidden from the rule
+ # picker; nothing new builds on it.
class CustomerGroupRule < Spree::PriceRule
# Stored as raw IDs. Accepts prefixed IDs (`cg_…`) from API
# callers and decodes them on write so eligibility checks compare
@@ -30,6 +35,10 @@ module Spree
def self.description
Spree.t('price_rules.customer_group_rule.description')
end
+
+ def self.superseded?
+ true
+ end
end
end
end
diff --git a/spree/core/app/models/spree/price_rules/user_rule.rb b/spree/core/app/models/spree/price_rules/user_rule.rb
index 26020092cc..2deb0beccf 100644
--- a/spree/core/app/models/spree/price_rules/user_rule.rb
+++ b/spree/core/app/models/spree/price_rules/user_rule.rb
@@ -1,5 +1,10 @@
module Spree
module PriceRules
+ # Superseded by catalog assignment, and grandfathered: existing rules
+ # keep matching indefinitely, but new setups target a buyer by assigning
+ # them a catalog that owns the price list
+ # (docs/plans/6.0-catalog-agreement-rework.md). Hidden from the rule
+ # picker; nothing new builds on it.
class UserRule < Spree::PriceRule
# Stored as raw IDs. Accepts prefixed IDs (the user class's prefix,
# e.g. `usr_…`) from API callers and decodes them on write. Resolves
@@ -33,6 +38,10 @@ module Spree
def self.human_name
'Customer rule'
end
+
+ def self.superseded?
+ true
+ end
end
end
end
diff --git a/spree/core/app/models/spree/pricing_provider/internal.rb b/spree/core/app/models/spree/pricing_provider/internal.rb
index 05377dc1f3..7b2f4f6d34 100644
--- a/spree/core/app/models/spree/pricing_provider/internal.rb
+++ b/spree/core/app/models/spree/pricing_provider/internal.rb
@@ -64,29 +64,17 @@ module Spree
@catalog_price_lists ||= catalogs_for_context.filter_map(&:price_list).uniq.select(&:currently_active?)
end
- # Returns the price lists that are applicable to the context.
- # Catalog-attached lists are excluded here: they are audience-scoped
- # by their catalog, and a rule-less list would otherwise apply to
- # everyone.
+ # Returns the price lists that are applicable to the context by their
+ # own rules. Catalog-owned lists never appear here — the FK filter in
+ # {Spree::PriceList.for_context} keeps them out in SQL, since an
+ # owned list is audience-scoped by its catalog and a rule-less one
+ # would otherwise apply to everyone.
# @return [Array<Spree::PriceList>]
def applicable_price_lists
@applicable_price_lists ||= price_lists_for_context.
- reject { |list| catalog_bound_price_list_ids.include?(list.id) }.
select { |list| list.applicable?(context) }
end
- # Only ACTIVE catalogs claim their list: an inactive catalog is off,
- # and blacklisting its list would silently kill a rule-based list
- # that was working before the catalog draft existed.
- def catalog_bound_price_list_ids
- @catalog_bound_price_list_ids ||=
- if context.store == Spree::Current.store
- Spree::Current.catalog_bound_price_list_ids
- else
- Spree::Catalog.bound_price_list_ids(context.store)
- end
- end
-
# Catalogs that apply to this buyer. Reused from {Spree::Current}
# when the context is the current store, so a product listing does
# not re-resolve the same company / group / channel set per variant.
diff --git a/spree/core/app/services/spree/categories/remove_products.rb b/spree/core/app/services/spree/categories/remove_products.rb
index 02ed6e3639..dd09bf3050 100644
--- a/spree/core/app/services/spree/categories/remove_products.rb
+++ b/spree/core/app/services/spree/categories/remove_products.rb
@@ -65,7 +65,7 @@ module Spree
private
def mysql_adapter?
- ActiveRecord::Base.connection.adapter_name.downcase.include?('mysql')
+ Spree.mysql?
end
end
end
diff --git a/spree/core/app/services/spree/collections/remove_products.rb b/spree/core/app/services/spree/collections/remove_products.rb
index c8b4e6381a..566e8fb71b 100644
--- a/spree/core/app/services/spree/collections/remove_products.rb
+++ b/spree/core/app/services/spree/collections/remove_products.rb
@@ -58,7 +58,7 @@ module Spree
private
def mysql_adapter?
- ActiveRecord::Base.connection.adapter_name.downcase.include?('mysql')
+ Spree.mysql?
end
end
end
diff --git a/spree/core/app/services/spree/prices/bulk_upsert.rb b/spree/core/app/services/spree/prices/bulk_upsert.rb
index 4acbcc6ecd..3a5e3d0b60 100644
--- a/spree/core/app/services/spree/prices/bulk_upsert.rb
+++ b/spree/core/app/services/spree/prices/bulk_upsert.rb
@@ -162,7 +162,7 @@ module Spree
end
def mysql?
- ActiveRecord::Base.connection.adapter_name == 'Mysql2'
+ Spree.mysql?
end
# MySQL-only path: NULLs are distinct in unique indexes, so
diff --git a/spree/core/db/migrate/20260816210001_create_spree_commission_rates.rb b/spree/core/db/migrate/20260816210001_create_spree_commission_rates.rb
index 278e881598..0d1aa27b6d 100644
--- a/spree/core/db/migrate/20260816210001_create_spree_commission_rates.rb
+++ b/spree/core/db/migrate/20260816210001_create_spree_commission_rates.rb
@@ -131,7 +131,7 @@ class CreateSpreeCommissionRates < ActiveRecord::Migration[8.1]
# MySQL-only too. This expression is the one both accept.
# One amount per currency per rate, among live rows.
def add_rate_value_uniqueness_index
- if mysql?
+ if Spree.mysql?
reversible do |dir|
dir.up do
execute <<~SQL.squish
@@ -155,7 +155,7 @@ class CreateSpreeCommissionRates < ActiveRecord::Migration[8.1]
end
def add_rule_product_uniqueness_index
- if mysql?
+ if Spree.mysql?
reversible do |dir|
dir.up do
execute <<~SQL.squish
@@ -181,7 +181,7 @@ class CreateSpreeCommissionRates < ActiveRecord::Migration[8.1]
# Same per-adapter split as the rate's code index below, and for the same
# reason: only PostgreSQL and SQLite have partial indexes.
def add_rule_uniqueness_index
- if mysql?
+ if Spree.mysql?
reversible do |dir|
dir.up do
execute <<~SQL.squish
@@ -205,7 +205,7 @@ class CreateSpreeCommissionRates < ActiveRecord::Migration[8.1]
end
def add_code_uniqueness_index
- if mysql?
+ if Spree.mysql?
reversible do |dir|
dir.up do
execute <<~SQL.squish
@@ -226,8 +226,4 @@ class CreateSpreeCommissionRates < ActiveRecord::Migration[8.1]
unique: true, where: 'deleted_at IS NULL', name: INDEX_NAME
end
end
-
- def mysql?
- ActiveRecord::Base.connection.adapter_name.match?(/mysql|trilogy/i)
- end
end
diff --git a/spree/core/db/migrate/20260825000001_create_spree_catalogs.rb b/spree/core/db/migrate/20260825000001_create_spree_catalogs.rb
index e16c4d12a3..1ad74e869e 100644
--- a/spree/core/db/migrate/20260825000001_create_spree_catalogs.rb
+++ b/spree/core/db/migrate/20260825000001_create_spree_catalogs.rb
@@ -2,7 +2,6 @@ class CreateSpreeCatalogs < ActiveRecord::Migration[8.1]
def change
create_table :spree_catalogs do |t|
t.references :store, null: false
- t.references :price_list # nil = assortment-only, base prices
t.string :name, null: false
t.boolean :active, null: false, default: true
t.integer :position
diff --git a/spree/core/db/migrate/20260830000001_add_catalog_to_spree_price_lists.rb b/spree/core/db/migrate/20260830000001_add_catalog_to_spree_price_lists.rb
new file mode 100644
index 0000000000..7c984c9f3d
--- /dev/null
+++ b/spree/core/db/migrate/20260830000001_add_catalog_to_spree_price_lists.rb
@@ -0,0 +1,47 @@
+class AddCatalogToSpreePriceLists < ActiveRecord::Migration[8.1]
+ INDEX_NAME = 'index_spree_price_lists_one_per_catalog'.freeze
+
+ def change
+ # nil = standalone list, matched by its own rules; set = owned by exactly
+ # one catalog and reached only through it
+ # (docs/plans/6.0-catalog-agreement-rework.md).
+ add_reference :spree_price_lists, :catalog, index: false
+
+ add_catalog_uniqueness_index
+ end
+
+ private
+
+ # One live list per catalog. Soft-deleted lists release the slot, so a
+ # catalog whose list was deleted can be given a replacement.
+ #
+ # Written per adapter because only PostgreSQL and SQLite have partial
+ # indexes. MySQL and MariaDB instead index a stored generated column holding
+ # the catalog only while the row is live, so a deleted list drops out of the
+ # index altogether — NULLs compare distinct there, which is also what lets a
+ # standalone list (catalog_id NULL) sit alongside any number of others.
+ # Expression per the spree_commission_rates precedent: the one form both
+ # MySQL 8 and MariaDB 11 accept.
+ def add_catalog_uniqueness_index
+ if Spree.mysql?
+ reversible do |dir|
+ dir.up do
+ execute <<~SQL.squish
+ ALTER TABLE spree_price_lists
+ ADD COLUMN catalog_key BIGINT
+ AS (IF(deleted_at IS NULL, catalog_id, NULL)) STORED
+ SQL
+ add_index :spree_price_lists, :catalog_key, unique: true, name: INDEX_NAME
+ end
+
+ dir.down do
+ remove_index :spree_price_lists, name: INDEX_NAME
+ remove_column :spree_price_lists, :catalog_key
+ end
+ end
+ else
+ add_index :spree_price_lists, :catalog_id, unique: true,
+ where: 'catalog_id IS NOT NULL AND deleted_at IS NULL', name: INDEX_NAME
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index 4c0f20fc1e..17228610f8 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -40,6 +40,19 @@ module Spree
:cdn_host, :root_domain, :events_adapter_class, :queues,
:google_places_api_key
+ # Whether the connected database is MySQL or a MySQL-compatible server.
+ # The single definition every adapter branch reads — models, services and
+ # migrations alike — so a new adapter name is added in one place.
+ #
+ # Matches Trilogy and MariaDB as well as Mysql2: they share the behaviors
+ # Spree branches on (no partial indexes, `upsert_all` inferring its own
+ # conflict target, NULLs distinct in unique indexes).
+ #
+ # @return [Boolean]
+ def self.mysql?
+ ActiveRecord::Base.connection.adapter_name.match?(/mysql|trilogy/i)
+ end
+
def self.base_class(constantize: true)
@@base_class ||= 'Spree::Base'
if @@base_class.is_a?(Class)
diff --git a/spree/core/spec/lib/spree/core/pricing/catalog_pricing_spec.rb b/spree/core/spec/lib/spree/core/pricing/catalog_pricing_spec.rb
index be15038213..f05ebb976a 100644
--- a/spree/core/spec/lib/spree/core/pricing/catalog_pricing_spec.rb
+++ b/spree/core/spec/lib/spree/core/pricing/catalog_pricing_spec.rb
@@ -80,21 +80,43 @@ describe 'catalog-aware pricing' do
expect(Spree::Pricing::Resolver.new(context).resolve.amount).to eq(95)
end
- # An inactive catalog is off: it must neither price its audience nor keep
- # claiming its list away from the generic rule matcher — a rule-less list
- # that worked before the catalog draft existed has to keep working.
- it 'releases a price list back to rule matching while its catalog is inactive' do
+ # An inactive catalog is off, and its owned list goes dormant WITH it: the
+ # old derived exclusion set read active catalogs only, so deactivating a
+ # catalog dropped its typically rule-less list into generic matching and
+ # priced the whole store (docs/plans/6.0-catalog-agreement-rework.md).
+ # Releasing the list is an explicit detach, never a side effect.
+ it 'keeps an inactive catalog price list dormant until explicitly detached' do
price_list = price_list_with_price(80)
catalog = create(:catalog, store: store, price_list: price_list, active: false)
create(:catalog_assignment, catalog: catalog, assignable: company)
- expect(resolve(company: company).amount).to eq(80)
+ expect(resolve(company: company).amount).to eq(100)
+ expect(resolve.amount).to eq(100)
+
+ price_list.update!(catalog: nil)
+
+ expect(resolve.amount).to eq(80)
+ end
+
+ # Detaching through the catalog writes the list's FK directly, skipping
+ # PriceList's own callbacks — the request-scoped matching set has to be
+ # cleared anyway, or the released list stays invisible until the next
+ # request.
+ it 'sees a detach made through the catalog within the same request' do
+ price_list = price_list_with_price(80)
+ catalog = create(:catalog, store: store, price_list: price_list)
+
+ Spree::Current.store = store
+ expect(resolve.amount).to eq(100)
+
+ catalog.update!(price_list: nil)
+
expect(resolve.amount).to eq(80)
end
- # Product listings build one Pricing::Context per variant. The bound
- # price-list ids and the catalogs that apply to this buyer are request
- # scoped, so later rows must not query catalogs again.
+ # Product listings build one Pricing::Context per variant. The catalogs
+ # that apply to this buyer are request scoped, so later rows must not
+ # query catalogs again.
it 'loads applicable catalogs once across many variant resolutions' do
catalog = create(:catalog, store: store, price_list: price_list_with_price(80))
create(:catalog_assignment, catalog: catalog, assignable: company)
diff --git a/spree/core/spec/models/spree/catalog_spec.rb b/spree/core/spec/models/spree/catalog_spec.rb
index d1c24eb825..14f8674d3e 100644
--- a/spree/core/spec/models/spree/catalog_spec.rb
+++ b/spree/core/spec/models/spree/catalog_spec.rb
@@ -211,4 +211,126 @@ describe Spree::Catalog, type: :model do
expect(catalog.reload.price_list_id).to be_nil
end
+
+ # The FK lives on the list: a list is standalone or owned by exactly one
+ # catalog (docs/plans/6.0-catalog-agreement-rework.md).
+ describe 'price list ownership' do
+ let(:price_list) { create(:price_list, :active, store: store) }
+
+ it 'claims the list through its foreign key' do
+ catalog = create(:catalog, store: store, price_list: price_list)
+
+ expect(price_list.reload.catalog).to eq(catalog)
+ expect(catalog.price_list_id).to eq(price_list.id)
+ end
+
+ it 'attaches and detaches through the price_list_id writer' do
+ catalog = create(:catalog, store: store)
+
+ catalog.update!(price_list_id: price_list.id)
+ expect(price_list.reload.catalog).to eq(catalog)
+
+ catalog.update!(price_list_id: nil)
+ expect(price_list.reload.catalog).to be_nil
+ end
+
+ it 're-homes a list already owned by another catalog' do
+ create(:catalog, store: store, price_list: price_list)
+ other = create(:catalog, store: store)
+
+ other.update!(price_list: price_list)
+
+ expect(price_list.reload.catalog).to eq(other)
+ end
+
+ it 'releases the list back to standalone when the catalog is destroyed' do
+ catalog = create(:catalog, store: store, price_list: price_list)
+
+ catalog.destroy!
+
+ expect(price_list.reload.catalog_id).to be_nil
+ end
+
+ # The binding is a write on the LIST, so assigning it on a persisted
+ # catalog would hit the database before validation. A rejected save that
+ # had already detached would release a rule-less list to the whole store
+ # — the leak this design closes, arriving through the failure path.
+ describe 'a rejected save' do
+ it 'attaches nothing' do
+ catalog = create(:catalog, store: store)
+
+ catalog.assign_attributes(price_list_id: price_list.id, name: '')
+
+ expect(catalog.save).to be false
+ expect(price_list.reload.catalog_id).to be_nil
+ end
+
+ it 'detaches nothing' do
+ catalog = create(:catalog, store: store, price_list: price_list)
+
+ catalog.assign_attributes(price_list_id: nil, name: '')
+
+ expect(catalog.save).to be false
+ expect(price_list.reload.catalog_id).to eq(catalog.id)
+ end
+
+ it 'reads back the binding the caller asked for, so a form round-trips' do
+ catalog = create(:catalog, store: store)
+
+ catalog.assign_attributes(price_list_id: price_list.id, name: '')
+ catalog.save
+
+ expect(catalog.price_list_id).to eq(price_list.id)
+ end
+ end
+
+ # An unsaved list has no id to bind, so it is saved through its own
+ # lifecycle rather than silently dropped.
+ describe 'an unsaved price list' do
+ it 'is persisted and bound when the catalog is new' do
+ catalog = build(:catalog, store: store)
+ catalog.price_list = build(:price_list, store: store, name: 'Fresh')
+
+ catalog.save!
+
+ expect(catalog.price_list.reload).to be_persisted
+ expect(catalog.price_list.catalog_id).to eq(catalog.id)
+ end
+
+ it 'is persisted and bound on a catalog that already exists' do
+ catalog = create(:catalog, store: store)
+ catalog.price_list = build(:price_list, store: store, name: 'Fresh')
+
+ expect { catalog.save! }.to change { store.price_lists.count }.by(1)
+ expect(catalog.price_list.reload.catalog_id).to eq(catalog.id)
+ end
+ end
+
+ # Releasing is a compare-and-swap: a list another request already re-homed
+ # must not be sent back to standalone matching, where a rule-less list
+ # prices the whole store.
+ it 'does not release a list that another catalog has already claimed' do
+ catalog = create(:catalog, store: store, price_list: price_list)
+ other = create(:catalog, store: store)
+ other.update!(price_list: price_list)
+
+ # `catalog` still believes it owns the list; detaching must be a no-op.
+ catalog.association(:price_list).reset
+ catalog.update!(price_list: nil)
+
+ expect(price_list.reload.catalog_id).to eq(other.id)
+ end
+
+ # Rejecting through the catalog's own validation rather than raising
+ # RecordNotSaved out of the child's same-store check.
+ it 'refuses a foreign-store list as a validation error' do
+ catalog = create(:catalog, store: store)
+ foreign = create(:price_list, store: create(:store))
+
+ catalog.price_list = foreign
+
+ expect(catalog).not_to be_valid
+ expect(catalog.errors[:price_list]).to be_present
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/current_spec.rb b/spree/core/spec/models/spree/current_spec.rb
index 4fa32a83e5..ea761cc948 100644
--- a/spree/core/spec/models/spree/current_spec.rb
+++ b/spree/core/spec/models/spree/current_spec.rb
@@ -232,6 +232,12 @@ RSpec.describe Spree::Current do
expect(described_class.price_lists).not_to include(inactive_price_list)
end
+ it 'excludes catalog-owned price lists — pricing reaches them through the catalog walk' do
+ owned = create(:price_list, :active, store: store, catalog: create(:catalog, store: store))
+
+ expect(described_class.price_lists).not_to include(owned)
+ end
+
it 'returns price lists ordered by position' do
expect(described_class.price_lists.to_a).to eq([active_price_list, scheduled_price_list])
end
@@ -284,25 +290,6 @@ RSpec.describe Spree::Current do
end
end
- describe '#catalog_bound_price_list_ids' do
- let(:store) { @default_store }
- let!(:price_list) { create(:price_list, :active, store: store) }
-
- before { described_class.store = store }
-
- it 'includes price lists claimed by an active catalog' do
- create(:catalog, store: store, price_list: price_list)
-
- expect(described_class.catalog_bound_price_list_ids).to include(price_list.id)
- end
-
- it 'memoizes the id set' do
- first = described_class.catalog_bound_price_list_ids
- second = described_class.catalog_bound_price_list_ids
- expect(first).to be(second)
- end
- end
-
describe '.reset' do
let(:store) { create(:store) }
let(:country) { create(:country) }
@@ -345,14 +332,6 @@ RSpec.describe Spree::Current do
expect(described_class.instance_variable_get(:@applicable_catalogs)).to be_nil
end
- it 'clears memoized catalog_bound_price_list_ids' do
- described_class.catalog_bound_price_list_ids
-
- described_class.reset
-
- expect(described_class.instance_variable_get(:@catalog_bound_price_list_ids)).to be_nil
- end
-
it 'clears memoized global_pricing_context' do
# Access global_pricing_context to memoize
described_class.global_pricing_context
diff --git a/spree/core/spec/models/spree/price_list_spec.rb b/spree/core/spec/models/spree/price_list_spec.rb
index 1c56279376..099b8dae70 100644
--- a/spree/core/spec/models/spree/price_list_spec.rb
+++ b/spree/core/spec/models/spree/price_list_spec.rb
@@ -12,6 +12,47 @@ describe Spree::PriceList, type: :model do
end
end
+ # The catalog binding: nil = standalone (rule-matched), set = owned by
+ # exactly one catalog and reached only through it
+ # (docs/plans/6.0-catalog-agreement-rework.md).
+ describe 'catalog ownership' do
+ let(:store) { @default_store }
+ let(:catalog) { create(:catalog, store: store) }
+
+ it 'allows one live list per catalog, releasing the slot on soft delete' do
+ owned = create(:price_list, store: store, catalog: catalog)
+
+ expect(build(:price_list, store: store, catalog: catalog)).not_to be_valid
+
+ owned.destroy
+ expect(build(:price_list, store: store, catalog: catalog)).to be_valid
+ end
+
+ it 'refuses a catalog from another store' do
+ foreign_catalog = create(:catalog, store: create(:store))
+
+ expect(build(:price_list, store: store, catalog: foreign_catalog)).not_to be_valid
+ end
+
+ it 'scopes standalone lists to the ones without an owner' do
+ standalone = create(:price_list, store: store)
+ owned = create(:price_list, store: store, catalog: catalog)
+
+ expect(described_class.standalone).to include(standalone)
+ expect(described_class.standalone).not_to include(owned)
+ end
+
+ it 'keeps an owned list out of .for_context whatever the owning catalog status' do
+ owned = create(:price_list, :active, store: store, catalog: catalog)
+ context = Spree::Pricing::Context.new(store: store, currency: 'USD')
+
+ expect(described_class.for_context(context)).not_to include(owned)
+
+ catalog.update!(active: false)
+ expect(described_class.for_context(context)).not_to include(owned)
+ end
+ end
+
describe 'status' do
let(:price_list) { create(:price_list) }
diff --git a/spree/core/spec/models/spree/price_rule_spec.rb b/spree/core/spec/models/spree/price_rule_spec.rb
index cf3e7ced99..915091e06e 100644
--- a/spree/core/spec/models/spree/price_rule_spec.rb
+++ b/spree/core/spec/models/spree/price_rule_spec.rb
@@ -24,4 +24,19 @@ describe Spree::PriceRule, type: :model do
expect(other).to be_valid
end
end
+
+ # Catalog assignment supersedes the audience rules, so pickers stop
+ # offering them — but they are grandfathered, not removed. The context
+ # rules stay unmarked.
+ describe '.subclasses_with_preference_schema' do
+ it 'flags only the superseded audience kinds' do
+ entries = described_class.subclasses_with_preference_schema.index_by { |entry| entry[:type] }
+
+ expect(entries['customer_group_rule'][:superseded]).to be true
+ expect(entries['user_rule'][:superseded]).to be true
+ expect(entries['channel_rule']).not_to have_key(:superseded)
+ expect(entries['market_rule']).not_to have_key(:superseded)
+ expect(entries['volume_rule']).not_to have_key(:superseded)
+ end
+ end
end
diff --git a/spree/core/spec/models/spree/price_rules/customer_group_rule_spec.rb b/spree/core/spec/models/spree/price_rules/customer_group_rule_spec.rb
index a7d77a318d..f37a75f976 100644
--- a/spree/core/spec/models/spree/price_rules/customer_group_rule_spec.rb
+++ b/spree/core/spec/models/spree/price_rules/customer_group_rule_spec.rb
@@ -9,6 +9,20 @@ describe Spree::PriceRules::CustomerGroupRule, type: :model do
let(:user) { create(:user) }
let(:variant) { create(:variant) }
+ # Grandfathered: hidden from the picker, but it keeps working for the
+ # stores already using it — no warning, no removal date.
+ describe 'supersession' do
+ it 'is flagged superseded yet still matches its audience' do
+ expect(described_class.superseded?).to be true
+
+ created = create(:customer_group_price_rule, price_list: price_list, customer_group_ids: [customer_group.id])
+ customer_group.add_customers([user.id])
+
+ context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', user: user)
+ expect(created.applicable?(context)).to be true
+ end
+ end
+
describe '#applicable?' do
context 'when customer_group_ids preference is empty' do
before { rule.preferred_customer_group_ids = [] }
diff --git a/spree/core/spec/models/spree/price_rules/user_rule_spec.rb b/spree/core/spec/models/spree/price_rules/user_rule_spec.rb
index b3a9043906..15f6151a09 100644
--- a/spree/core/spec/models/spree/price_rules/user_rule_spec.rb
+++ b/spree/core/spec/models/spree/price_rules/user_rule_spec.rb
@@ -6,6 +6,19 @@ describe Spree::PriceRules::UserRule, type: :model do
let(:user) { create(:user) }
let(:variant) { create(:variant) }
+ # Grandfathered: hidden from the picker, but it keeps working for the
+ # stores already using it — no warning, no removal date.
+ describe 'supersession' do
+ it 'is flagged superseded yet still matches its buyer' do
+ expect(described_class.superseded?).to be true
+
+ created = create(:user_price_rule, price_list: price_list, user_ids: [user.id])
+
+ context = Spree::Pricing::Context.new(variant: variant, currency: 'USD', user: user)
+ expect(created.applicable?(context)).to be true
+ end
+ end
+
describe '#applicable?' do
context 'when user_ids preference is empty' do
before { rule.preferred_user_ids = [] }