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.

Replace per-product delivery exclusions with a delivery method rule (#14399)

Damian Legawiec8321b0a17e9a
diff --git a/CLAUDE.md b/CLAUDE.md
index 3205958b0a..3775964f61 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -29,7 +29,7 @@ Active plans (6.0 target, work pending):
- `6.0-rich-text-descriptions.md` — Drop ActionText **entirely** at 6.0 (incl. CustomFields::RichText values + Order/User internal notes; gem dependency removed), store sanitized HTML in text columns, serve `field` + `field_html`, **write via `field_html`** (read/write symmetry). description_html serializer shipped 5.4; sanitizer shipped in **5.6.2** with a permissive-but-safe configurable allowlist + `sanitize_rich_text` step in the 5.5→5.6 upgrade manifest (decisions.md 2026-07-27/28), tightened to the Tiptap set at 6.0
- `6.0-inventory-operations.md` — StockTransfer lifecycle (draft → ready_to_ship → in_transit → received with partial receive), new `Spree::PurchaseOrder` + `Spree::Supplier` (renamed from Vendor — `Spree::Vendor` is the marketplace seller, see decisions.md 2026-07-14) replacing today's "external receive" hack, variant + stock-location stock history panels. Consumes the typed-movement primitives from `6.0-typed-stock-movements.md`.
- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). **Shipped to 6-0-dev (PR #14302):** the Category surface (5.5–5.6) plus the 6.0 core — `spree_taxons`→`spree_categories` table rename + inheritance flip (`Spree::Category < Spree.base_class`, `Spree::Taxon` alias kept), the full `Collection` stack (model + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data migration, and de-ruling Category. Pending (all 6.1): channel-aware `CollectionRules::AvailableOn` (ships interim now, rides with channels) + dropping `spree_taxon_rules`/`Taxonomy`. No brand feature in 6.0 — brands are modeled as a Category/Collection; `brand_taxon`/`brand_name` removed with `Taxonomy`.
-- `6.0-delivery-method-rules.md` — `Spree::DeliveryMethodRule` STI on DeliveryMethod (design finalized 2026-07-29): ItemTotal/Weight rules first (Channel/Market/CustomerGroup later in lockstep with payment-method-rules), enforced solely in `Stock::Estimator`'s method filter so calculator- AND provider-priced methods obey eligibility; replaces the FlatRate-only bound preferences (one-release bridge + data task). Phase 1 rides the 6.0 core-rewrite finishing work.
+- `6.0-delivery-method-rules.md` — `Spree::DeliveryMethodRule` STI on DeliveryMethod (design finalized 2026-07-29): ItemTotal/Weight rules first (Channel/Market/CustomerGroup later in lockstep with payment-method-rules), enforced solely in `Stock::Estimator`'s method filter so calculator- AND provider-priced methods obey eligibility; replaces the FlatRate-only bound preferences (one-release bridge + data task). **Phase 1 shipped** (rules + Estimator seam + admin nested CRUD/types discovery + dashboard Conditions card). **2026-08-06:** `ExcludedProductsRule` (products via `spree_delivery_method_rule_products` join, Saleor-style method-side exclusion) replaces the dropped `spree_products.excluded_delivery_method_ids` JSON column; rule-reference storage picks by cardinality — small reference sets stay `normalize_id_preference` arrays, catalog-scale (products) gets a join table.
- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` — named steps inside a plain `def perform(order:, ...)` (the ActiveJob::Continuable shape; bare `super` turns parameters into readers). Vocabulary: `step`/`external_step` (+ `with:`, `on_flow_failure:`), `run_hooks` + class-level `hooks`, `failure`/`halt!`; plain `ApplicationRecord.transaction`/`with_lock`/`rescue`/`publish_event`; every step instrumented as `step.spree_workflow`. Money lives in `Carts::RecalculateTotals` (single totals seam; the completed-order branch is the post-placement resum — rows re-summed, never regenerated), statuses in `Orders::UpdateStatuses` (refreshes each fulfillment's state, then rolls up); Order/CartUpdater are 6.1-removed warning shells. Shared Cart/Order surface lives in `Spree::Purchase::*` concerns; completion side effects (newsletter, account creation, risk) run in the sync `OrderPlacedSubscriber` on order.placed. Reserved for flows needing hooks, compensation/external I/O, or replay — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively — but hooks on flows already in the tier ship deliberately on the 6.0 boundary (2026-08-02), since hook keys are public API and moving one later is breaking. **New models get no state machine** — plain `status` string + inclusion validation, transitions through workflows; gateway I/O never in a save callback. Three hook families, contracts settled 2026-08-02: **lifecycle** (past tense, read-only), **validate** (handler calls `workflow.reject!(message)` to veto), **context** (`set_*_context`/`get_provider_data` — handler returns a hash, `run_hooks` deep-merges all handlers and returns it; last writer wins on collision). Phase 3 **shipped (2026-08-02)**: `run_hooks` returns the merged hash and `Workflow#reject!` is public API; `validate`/context/lifecycle hooks live on AddItem, Complete, Recalculate, RecalculateTotals, Cancel and Resume; `Fulfillments::Create`, `Payments::Capture`/`Refund`, `Payments::HandleWebhook` and `Carts::Merge` moved to `app/workflows/` (seams `fulfillment_create_workflow`, `payment_capture_workflow`, `payment_refund_workflow`, `payments_handle_webhook_workflow`, `cart_merge_workflow`; legacy names readable one release). **Customer registration (2026-08-05):** `Customers::Create` (seam `customer_create_workflow`, hooks `customers.create.validate`/`after_create`) is the single storefront customer-creation flow — self-registration + checkout account box (optional `order:` adopts addresses and links the order); absorbs `Orders::CreateUserAccount` (deprecated shell); admin create stays plain CRUD; token issuance stays in controllers; core sends NO welcome email — signup email is host-app code on `user.created` or the `after_create` hook. Payment workflows own the transaction boundary and guards — money movement stays in the model, called from an `external_step`. No workflows for plain CRUD. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `Carts::Complete` battery must pass unmodified. **Durability = plain Rails:** long-running background work uses `ActiveJob::Continuable` directly (reference: `Spree::Imports::ProcessJob` — CSV spine with a row-number cursor; `CreateRowsJob`/`ProcessRowsJob` deprecated shells); workflows are synchronous request-cycle flows and are NOT jobs — Workflow-level durable execution ships only if the payout run proves the need.
- `6.0-store-scoped-configuration.md` — Move nine commerce-behavior globals (`auto_capture`, `auto_capture_on_dispatch`, `allow_checkout_on_gateway_error`, `track_inventory_levels`, `stock_reservations_enabled`, `track_price_history`, `show_products_without_price`, `address_requires_phone`, `disable_sku_validation`) from `Spree::Config` to `Spree::Store` preferences. Store preference is **authoritative — no runtime fallback** (a fallback chain is what made `default_stock_reservation_ttl_minutes` silently unreachable); upgrade carries values over via `spree:store_settings:backfill_from_config`; globals are deprecated shells until 6.1. Storeless readers (`Address`, the product availability scope) use `Spree::Current.store` with a default fallback. Seven dead settings (`products_per_page`, `storefront_*_path`, …) get shells then deletion. **Constraints now:** no new `Spree::Config` reads of the movers; new behavior flags are born on Store, never global; jobs that validate addresses or query the catalog must set `Spree::Current.store`.
- `6.0-store-scoped-custom-field-definitions.md` — Add `store_id` + persisted `filter_key` to `Spree::MetafieldDefinition` (today global and computed), making uniqueness `(store_id, resource_type, filter_key)` with a DB index. Deferred from the 5.6 custom-field search/sort/filter work (schema change, not patch-safe). **Until then:** `filter_key` is a computed method — no Ransack predicates or `where`/`order` against it; definitions are global; uniqueness rests on a `CONCAT` validation with no index behind it.
diff --git a/docs/plans/5.7-payment-method-rules.md b/docs/plans/5.7-payment-method-rules.md
index 848cc3899c..83bbcb4a78 100644
--- a/docs/plans/5.7-payment-method-rules.md
+++ b/docs/plans/5.7-payment-method-rules.md
@@ -74,9 +74,12 @@ module Spree
Spree.t("payment_method_rule_types.#{api_type}.description", default: '')
end
- def self.registered_subclasses
- Array(Spree.payment_method_rules)
- end
+ # Declares where PreferenceSchema finds the registered rule kinds
+ # (drives `find_by_api_type` + the admin type picker). Superseded the
+ # per-class `registered_subclasses` override on 2026-08-06 — a class
+ # that declares no registry now raises instead of silently reporting
+ # zero subclasses.
+ registers_subclasses_via { Array(Spree.payment_method_rules) }
end
end
```
diff --git a/docs/plans/6.0-core-rewrite-tasks.md b/docs/plans/6.0-core-rewrite-tasks.md
index 8dee69bf8d..62df3540db 100644
--- a/docs/plans/6.0-core-rewrite-tasks.md
+++ b/docs/plans/6.0-core-rewrite-tasks.md
@@ -102,7 +102,7 @@ The big mechanical wave. Whole-suite blast radius via factories; one-release con
- [x] `spree_delivery_methods`: `fulfillment_type` (nullable, indexed; model-level default `'shipping'`), `fulfillment_provider` (nullable; model-level default Manual + blank-fallback in `#provider`), `pickup_point_provider`. DB defaults deliberately avoided (house rule); existing rows ride the T7.1 backfill.
- [x] `spree_fulfillments`: `fulfillment_type`, `pickup_point_data` (json/jsonb-guarded), `cart_id` (nullable — owner pattern).
- [x] `spree_delivery_method_stock_locations` join (unique on the pair) + model with vendor-consistency validation stubbed for the marketplace wave.
-- [x] `spree_products.excluded_delivery_method_ids` (json/jsonb-guarded).
+- [x] `spree_products.excluded_delivery_method_ids` (json/jsonb-guarded). **Superseded 2026-08-06:** column dropped (was never writable); replaced by `ExcludedProductsRule` + `spree_delivery_method_rule_products` (`6.0-delivery-method-rules.md`, `feat/product-exlcluded-delivery-methods`).
- [x] Settled (Decision 4): no owner columns on `spree_delivery_rates` — owner derives through `fulfillment.owner`.
- [x] **Not here** (shipped or other plans): StockLocation pickup columns, `store_id` (delivery-rate plan), `vendor_id` (marketplace wave).
@@ -115,7 +115,7 @@ The big mechanical wave. Whole-suite blast radius via factories; one-release con
- [x] CanCanCan grants, PermittedAttributes, seeds (incl. `Seeds::DigitalDelivery` + the hardcoded `'Digital'`/`'Default'` category readers), factories (`shipment_factory`→`fulfillment_factory` etc. with aliases; `product_factory` stops assigning shipping categories — whole-suite impact).
### T2.4 Eligibility rework — ShippingCategory retired from behavior (needs T0.1) — ✅ done 2026-07-29
-- [x] `Package#eligible_delivery_methods` replaces `Package#shipping_methods`: intersect package items' `fulfillment_types` (via ProductType, `['shipping']` fallback when typeless) with `DeliveryMethod#fulfillment_type`, minus per-product `excluded_delivery_method_ids`. Seam stays **inside `Stock::Estimator#shipping_methods`**.
+- [x] `Package#eligible_delivery_methods` replaces `Package#shipping_methods`: intersect package items' `fulfillment_types` (via ProductType, `['shipping']` fallback when typeless) with `DeliveryMethod#fulfillment_type`. Seam stays **inside `Stock::Estimator#shipping_methods`**. (The "minus per-product `excluded_delivery_method_ids`" subtraction was removed 2026-08-06 — that constraint now lives in `ExcludedProductsRule` at the rule seam.)
- [x] `Stock::Splitter::ShippingCategory` → `Splitter::FulfillmentType` (homogeneous packages by fulfillment type); `Splitter::Digital` folds in.
- [x] Digital discriminator to columns: `DeliveryMethod#digital?/pickup?/pickup_point?/requires_address?`; `.digital` scope; `Product#digital?` + net-new `Product#fulfillment_types` via ProductType; `DigitalDelivery` calculator demoted to plain zero-cost (calculators stay — decisions.md 2026-07-27).
- [x] Remove ShippingCategory presence-validation/auto-assign from Product **now** (tables/columns drop in 6.1; products must stay saveable in between).
diff --git a/docs/plans/6.0-delivery-method-rules.md b/docs/plans/6.0-delivery-method-rules.md
index cc39efdced..ba79be9698 100644
--- a/docs/plans/6.0-delivery-method-rules.md
+++ b/docs/plans/6.0-delivery-method-rules.md
@@ -1,10 +1,10 @@
# Delivery Method Rules
-**Status:** Design Finalized
+**Status:** Phase 1 shipped (ItemTotal/Weight + Estimator seam + admin CRUD + Conditions card); ExcludedProductsRule (decision 2026-08-06) in review as PR #14399
**Target:** Spree 6.0
**Depends on:** `6.0-fulfillment-and-delivery.md` (DeliveryMethod), `6.0-delivery-rate-provider.md` (shared Estimator seam), `5.7-payment-method-rules.md` (pattern sibling — expected to retarget 6.0 per 2026-07-29 direction to skip 5.7 for a faster 6.0 launch)
**Author:** Damian + Claude (design review 2026-07-29)
-**Last updated:** 2026-07-29
+**Last updated:** 2026-08-06
## Summary
@@ -12,7 +12,9 @@ Move delivery-method *eligibility* out of pricing calculators and into first-cla
`Spree::DeliveryMethodRule` STI records on `Spree::DeliveryMethod` — the fifth
instance of the house rule pattern (PromotionRule, PriceRule, OrderRoutingRule,
PaymentMethodRule). Phase 1 ships `ItemTotalRule` and `WeightRule` (the two
-constraints that exist today); the shape leaves room for `ChannelRule` /
+constraints that exist today) plus `ExcludedProductsRule` (added 2026-08-06 —
+absorbs the product-side `excluded_delivery_method_ids` column, which is
+dropped); the shape leaves room for `ChannelRule` /
`MarketRule` / `CustomerGroupRule` to land later in lockstep with the
payment-method-rules set. Rules are enforced at the single point every rate
consumer already flows through — `Stock::Estimator`'s method filtering — so
@@ -74,9 +76,50 @@ buries eligibility in the pricing object.
`package.item_total`, `package.owner.channel_id` when the later rule set
lands) — never `Spree::Current`.
- **Initial rule set:** `ItemTotalRule` (min/max, currency-aware via the
- owner's currency), `WeightRule` (min/max, store weight unit). Channel /
+ owner's currency), `WeightRule` (min/max, store weight unit),
+ `ExcludedProductsRule` (added 2026-08-06, below). Channel /
Market / CustomerGroup ride the payment-rules wave so both sets appear in
the dashboard together.
+- **ExcludedProductsRule replaces the product-side JSON column** (2026-08-06).
+ `spree_products.excluded_delivery_method_ids` (added by the fulfillment
+ rework's Phase 1b; console-only — no API or UI ever exposed it) is dropped.
+ The "fragile item can't ship express" case becomes a rule on the delivery
+ method holding products through a `spree_delivery_method_rule_products`
+ join table — concrete FKs, because an ID list in JSON cannot be indexed or
+ queried portably across the three supported databases, leaves stale IDs
+ behind when a delivery method is deleted, and forces a raw-ID/prefixed-ID
+ mapping shim at the API boundary. Method-side exclusion is Saleor's exact
+ model (`ShippingMethodType.excludedProducts` +
+ `shippingPriceExcludeProducts`); it also keeps eligibility at this plan's
+ single Estimator seam instead of a second, plan-violating seam inside
+ `Stock::Package#eligible_delivery_methods` (where the column was consumed).
+ A package is ineligible when it contains **any** excluded product; a rule
+ with no products passes (fail-open, matching the empty-preference
+ convention). No data migration: the column was never writable through the
+ supported API or dashboard, so there is no merchant-created data to carry.
+ Anyone who populated it directly from the Rails console during the 6.0
+ pre-release loses those values and must recreate them as an
+ `excluded_products_rule` on each delivery method.
+- **Association-backed rules are legitimate; pick storage by cardinality**
+ (2026-08-06). Small reference-data sets (channels, markets, customer
+ groups — dozens of rows) stay as `:array` preferences via
+ `normalize_id_preference`, matching the promotion-rule and price-rule
+ precedent. Catalog-scale references (products) get a concrete join table,
+ matching `Promotion::Rules::Product` / `ProductPromotionRule` — a
+ thousand-product list does not belong in a JSON preference. The nested
+ rules API carries association writes as prefixed-ID params
+ (`product_ids`), resolved through the store scope **and** the caller's
+ ability (`accessible_by(current_ability, :show)`, matching how
+ DeliveryMethodsController resolves its tax category / zones / pickup
+ locations) — an unreachable ID is dropped from the selection rather than
+ linked or 404ing the save, since it cannot become an exclusion either way
+ and failing would strand a merchant whose sheet was open when a product
+ was deleted (matching how price lists filter membership); the
+ serializer exposes them back under the same name (read/write symmetry).
+ The dashboard
+ Conditions card renders a product picker instead of a `PreferencesForm` for
+ any rule the discovery endpoint reports as taking `product_ids` — see the
+ `association_fields` decision below.
- **WeightRule compares raw numbers in the store's implicit weight unit**
(2026-07-29) — exactly how the legacy FlatRate bounds behave; the
dashboard label surfaces the store's unit_system. Unit-aware weight
@@ -95,6 +138,36 @@ buries eligibility in the pricing object.
- **Management is dashboard-only** — Admin API v3 nested CRUD + a dedicated
"Conditions" card on the delivery-method sheet (separate from the
calculator's pricing preferences, which caused this review).
+- **Rules save with the method, not on their own** (2026-08-06, supersedes
+ the live-mutating Conditions card). `DeliveryMethod#rules=` is a
+ flat-payload writer over `Spree::TypedAssociations` — the same mechanism
+ behind `Promotion#rules=` and `PriceList#rules=` — so one POST/PATCH
+ carrying `rules: [...]` reconciles the desired set (rows update by `id`,
+ new rows build via `find_by_api_type`, omitted rows are destroyed) and the
+ dashboard saves the whole sheet in one round-trip. The first cut shipped a
+ per-rule Save button that wrote immediately, which put two Save buttons on
+ one sheet and diverged from every sibling editor. The nested
+ `/delivery_methods/:id/rules` endpoints stay for programmatic use.
+- **Association-backed rule config declares itself on the rule class**
+ (2026-08-06). `DeliveryMethodRule.additional_permitted_attributes` mirrors
+ `PromotionRule`'s, so `ExcludedProductsRule` contributes `product_ids: []`
+ and the controller's permitted params stay generic — a plugin shipping an
+ association-backed rule needs no API change. `DeliveryMethodRule` also
+ overrides `registered_subclasses` so PreferenceSchema's `find_by_api_type`
+ resolves against `Spree.delivery_method_rules`. The controller still
+ resolves `product_ids` through the store scope and the caller's ability,
+ because the model writers apply neither.
+- **`/delivery_method_rules/types` reports `association_fields`**
+ (2026-08-06) — derived from each rule's `additional_permitted_attributes`,
+ so the dashboard picks picker-vs-preferences from the registry instead of
+ matching a hardcoded rule type. Without it the backend was registry-driven
+ while the client was not: a plugin's association-backed rule would be
+ accepted by the API but rendered as an empty preferences form with its ids
+ dropped at submit. A dashboard **slot registry** (the promotion-editor
+ pattern) is the fuller answer and is deliberately deferred — ~150 lines of
+ new structure to serve one editor whose body is a single autocomplete. Its
+ trigger is the second rule needing non-preferences config, or the first
+ plugin-supplied one.
## Design Details
@@ -138,6 +211,32 @@ class Spree::DeliveryMethodRules::ItemTotalRule < Spree::DeliveryMethodRule
end
# app/models/spree/delivery_method_rules/weight_rule.rb — same shape over package.weight
+
+# app/models/spree/delivery_method_rules/excluded_products_rule.rb (2026-08-06)
+class Spree::DeliveryMethodRules::ExcludedProductsRule < Spree::DeliveryMethodRule
+ has_many :delivery_method_rule_products, class_name: 'Spree::DeliveryMethodRuleProduct',
+ foreign_key: :delivery_method_rule_id, dependent: :destroy
+ has_many :products, class_name: 'Spree::Product', through: :delivery_method_rule_products
+
+ # Ineligible when the package contains any excluded product; no products = pass.
+ # Asks the join table about the package's products rather than loading the
+ # whole exclusion list — the composite index answers it without transferring
+ # rows. Reading `target` covers links assigned but not yet saved (the admin
+ # controller assigns products before save) without triggering a load.
+ def eligible?(package)
+ product_ids = package.contents.map { |item| item.variant.product_id }.uniq
+ return true if product_ids.empty?
+
+ return false if delivery_method_rule_products.target.any? { |link|
+ link.new_record? && product_ids.include?(link.product_id)
+ }
+ return true if new_record?
+
+ !delivery_method_rule_products.exists?(product_id: product_ids)
+ end
+end
+# Join model Spree::DeliveryMethodRuleProduct mirrors Spree::ProductPromotionRule
+# (unique on [delivery_method_rule_id, product_id]).
```
Boundary semantics: rules use inclusive minimum / inclusive maximum
@@ -191,7 +290,14 @@ plugin-extensible) + `type_must_be_registered` — same shape as
rule rows on its delivery method, clear the preferences. Idempotent
(skips methods that already have the rule type). Rides the 5.6→6.0
upgrade manifest after `migrate_shipping_to_delivery`.
-6. 6.1: delete the four preferences + FlatRate nil-guards.
+6. `ExcludedProductsRule` (2026-08-06): `spree_delivery_method_rule_products`
+ join table, drop `spree_products.excluded_delivery_method_ids` (no data
+ task — the column was never writable through the API or dashboard;
+ console-set pre-release values must be recreated as rules), remove the
+ exclusion subtraction
+ from `Stock::Package#eligible_delivery_methods`, register the rule,
+ `product_ids` on the rules API + dashboard product picker.
+7. 6.1: delete the four preferences + FlatRate nil-guards.
## Constraints on Current Work
@@ -221,5 +327,10 @@ None currently.
- `5.7-payment-method-rules.md` — authoritative pattern wording
- `6.0-delivery-rate-provider.md` — the provider bypass this plan closes
-- decisions.md 2026-07-29 (geo modeling; regional method rows)
+- decisions.md 2026-07-29 (geo modeling; regional method rows), 2026-08-06
+ (ExcludedProductsRule replaces the product-side column)
- `flat_rate.rb:9-24`, `estimator.rb:61-71`, `shipping_calculator.rb:11`
+- Saleor `excludedProducts` / `shippingPriceExcludeProducts` — the
+ method-side exclusion precedent (competitor survey 2026-08-05: Shopify and
+ Medusa model the inverse via shipping profiles ≈ the retired
+ ShippingCategory; Vendure has code-only eligibility checkers)
diff --git a/docs/plans/6.0-fulfillment-and-delivery.md b/docs/plans/6.0-fulfillment-and-delivery.md
index 4bce776d65..c5b9476b62 100644
--- a/docs/plans/6.0-fulfillment-and-delivery.md
+++ b/docs/plans/6.0-fulfillment-and-delivery.md
@@ -86,7 +86,7 @@ Replacement semantics:
- `ProductType#fulfillment_types` (JSON array, default `['shipping']`; see the 2026-07-27 addendum in `6.0-product-types.md`). Products without a ProductType default to `['shipping']` — the reconciliation between optional ProductType and today's effectively-mandatory ShippingCategory (`Product` presence-validates + auto-assigns one today, `product.rb:133, 153, 945-951`).
- `DeliveryMethod#fulfillment_type` (single string) must be **included in every package item's** `fulfillment_types` for the method to be eligible.
-- `Package#eligible_delivery_methods` replaces `Package#shipping_methods`: intersect items' fulfillment types, then subtract per-product exclusions. `Product.excluded_delivery_method_ids` (JSON array column, jsonb-guarded) covers the rare restriction case ("fragile item can't ship express") without a dedicated model.
+- `Package#eligible_delivery_methods` replaces `Package#shipping_methods`: intersect items' fulfillment types. ~~Then subtract per-product exclusions via `Product.excluded_delivery_method_ids` (JSON array column)~~ — **superseded 2026-08-06**: the column is dropped; the restriction case ("fragile item can't ship express") is `Spree::DeliveryMethodRules::ExcludedProductsRule`, enforced at the Estimator's rule seam like every other eligibility constraint. See `6.0-delivery-method-rules.md`.
- `Stock::Splitter::ShippingCategory` → `Stock::Splitter::FulfillmentType` — packages stay homogeneous by fulfillment type, so mixed carts (physical + digital) still split automatically. `Splitter::Digital` folds into it.
- The eligibility seam stays **inside `Stock::Estimator#shipping_methods`** (per the delivery-rate-provider plan, which owns filtering — including the marketplace vendor gate). This plan changes the *inputs* to that filter, not its location. No separate `DeliveryMethods::Available` service.
@@ -98,7 +98,7 @@ Replacement semantics:
`shipping`, `pickup` (merchant location), `pickup_point` (third-party point — InPost locker, DHL ServicePoint), `digital`, `local_delivery` built in; extensible via `Spree.fulfillment_types << 'same_day_courier'` in an initializer. NOT a model — a type is a behavior discriminator only meaningful to code (splitter, estimator, provider); AR-record reference data was the countries/states mistake. But not open strings either: an unregistered/typo'd type silently produces empty intersections (no error, just missing rates), so `DeliveryMethod#fulfillment_type` and each element of `ProductType#fulfillment_types` validate inclusion against the registry — **on attribute change only**, so rows carrying tokens not yet registered (e.g. freshly migrated) stay loadable and savable. The registry is exposed to admin UIs via `GET /admin/delivery_methods/fulfillment_providers` (`fulfillment_types` key) — the dashboard renders type selects/checkboxes from it, so extension-registered types appear without dashboard changes (the JS `FULFILLMENT_TYPES` const is pre-fetch fallback + labels only).
-**Modality vs segment.** New fulfillment types are for genuinely new delivery *modalities* (need provider code anyway — the initializer is the smallest part of the work). Product *segments* ("oversized", "fragile") should NOT become custom types: model them with `DeliveryMethodRule` (weight/item-total — merchant-manageable in the dashboard, registry `Spree.delivery_method_rules` for custom rules) plus `Product#excluded_delivery_method_ids` for one-off subtractions. The Wave 7 shipping→delivery data migration MAY mint custom tokens for 5.x shipping categories whose method bindings actually narrow (a category not served by all methods) — flattening those to `'shipping'` would silently widen eligibility — but that token-minting is a compatibility measure, not recommended modeling; the migration task must print the `Spree.fulfillment_types += [...]` initializer line for every token it mints.
+**Modality vs segment.** New fulfillment types are for genuinely new delivery *modalities* (need provider code anyway — the initializer is the smallest part of the work). Product *segments* ("oversized", "fragile") should NOT become custom types: model them with `DeliveryMethodRule` (weight/item-total/excluded-products — merchant-manageable in the dashboard, registry `Spree.delivery_method_rules` for custom rules; the former `Product#excluded_delivery_method_ids` column is gone per the 2026-08-06 decision — one-off subtractions are `ExcludedProductsRule`). The Wave 7 shipping→delivery data migration MAY mint custom tokens for 5.x shipping categories whose method bindings actually narrow (a category not served by all methods) — flattening those to `'shipping'` would silently widen eligibility — but that token-minting is a compatibility measure, not recommended modeling; the migration task must print the `Spree.fulfillment_types += [...]` initializer line for every token it mints.
### FulfillmentProvider is a strategy (not a DB model)
@@ -287,7 +287,7 @@ Phase 1 as previously drafted was one ~20-operation migration; per CLAUDE.md (da
- `delivery_methods`: `fulfillment_type` (nullable, indexed — default `'shipping'` lives on the model per house rule; existing rows backfilled by the Phase 2 data task), `fulfillment_provider` (nullable — model default Manual, `#provider` falls back on blank), `pickup_point_provider`.
- `fulfillments`: `fulfillment_type`, `pickup_point_data` (JSON, jsonb-guarded), `cart_id` (per owner decision).
- `spree_delivery_method_stock_locations` join (unique on the pair).
-- `products.excluded_delivery_method_ids` (JSON, jsonb-guarded).
+- `products.excluded_delivery_method_ids` (JSON, jsonb-guarded). **Dropped 2026-08-06** (never writable through any API/UI) — replaced by `ExcludedProductsRule` + `spree_delivery_method_rule_products`; see `6.0-delivery-method-rules.md`.
- NOT here: StockLocation pickup columns (shipped), `store_id` (delivery-rate plan), `vendor_id` (marketplace wave).
### Phase 2 — data rake tasks (`spree:migrate_shipping_to_delivery`) ✅ shipped
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index ed9da40d72..d4b24108ed 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1344,3 +1344,66 @@ idempotency, sweeper resume) and its spec battery must pass unmodified
after the retrofit. Durable flows compile onto ActiveJob Continuations
in Phase 2 (imports, upgrade migrations, payout runs) and may land
post-GA without blocking the DSL.
+
+
+## 2026-08-06 — Per-product delivery exclusions are a delivery-method rule, not a product column
+
+`spree_products.excluded_delivery_method_ids` (JSON array, shipped with
+the fulfillment rework but never writable through any API or UI) is
+dropped in favor of `Spree::DeliveryMethodRules::ExcludedProductsRule` —
+products attached through the concrete
+`spree_delivery_method_rule_products` join table. Rationale: an ID list
+in JSON is unqueryable and unindexable portably across the three
+supported databases, rots when delivery methods are deleted, and would
+have needed its own bespoke API/serializer/UI surface; the rules
+framework already ships the registry, nested admin CRUD, discovery
+endpoint and dashboard Conditions card. It also removes the second
+eligibility seam inside `Stock::Package#eligible_delivery_methods` —
+the rules plan mandates the Estimator's rule filter as the only one.
+Method-side exclusion matches Saleor (`excludedProducts`); Shopify and
+Medusa model the inverse via shipping profiles (≈ the retired
+ShippingCategory), Vendure is code-only. Companion convention — storage
+by cardinality: small reference sets (channels/markets/customer groups)
+stay `:array` preferences via `normalize_id_preference`; catalog-scale
+references (products) get a join table, per the
+`Promotion::Rules::Product`/`ProductPromotionRule` precedent. On the
+wire both travel as prefixed-ID params resolved through the store scope
+and `accessible_by(current_ability, :show)`. Plans updated:
+`6.0-delivery-method-rules.md` (owner),
+`6.0-fulfillment-and-delivery.md`, `6.0-core-rewrite-tasks.md`.
+
+
+## 2026-08-06 — STI rule families declare their subclass registry
+
+`Spree::PreferenceSchema.registered_subclasses` resolved a class's
+registered subclasses by matching two hardcoded class names
+(`Spree::PromotionAction`, `Spree::PromotionRule`) and otherwise
+returning `[]`. Four families had each worked around that with a private
+per-class override in three different idioms (`PriceRule`,
+`OrderRoutingRule`, `CollectionRule`, `DeliveryMethodRule`), and
+`5.7-payment-method-rules.md` specced a fifth. The empty-list fallback
+failed **silently**: `find_by_api_type` returned nil, so
+`TypedAssociations` dropped typed rows from a payload with no error and
+`subclasses_with_preference_schema` rendered empty admin pickers — the
+bug that broke `DeliveryMethod#rules=` on first attempt.
+
+Replaced with a declarative hook: each STI parent calls
+`registers_subclasses_via { <registry> }` (one line), stored in a
+`class_attribute` so STI subclasses inherit the parent's declaration —
+resolving on a subclass works, which it did not before under either
+scheme. A class that declares none raises
+`Spree::PreferenceSchema::UndeclaredRegistryError` (a **StandardError**,
+so host apps' `rescue => e` catches it — `NotImplementedError` descends
+from `ScriptError` and would slip past). Migrated in place:
+PromotionRule, PromotionAction, PriceRule, OrderRoutingRule,
+CollectionRule, DeliveryMethodRule, and **PaymentMethod** — gateways
+declare `registers_subclasses_via { providers }` rather than being a
+special case in the resolver, so there is exactly one resolution rule.
+`5.7-payment-method-rules.md` updated to the new form.
+
+Known debt: the registry is a lodger inside `PreferenceSchema` (which
+`Spree::Base` includes, so ~200 models carry class methods only six use),
+and `Spree::CalculatedAdjustments` resolves an equivalent registry
+separately. Extract a `Spree::RegisteredSubclasses` concern when a family
+needs the registry without preferences — that second consumer is the
+trigger, and it would absorb CalculatedAdjustments too.
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index b19815102b..b2eb11adfe 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -1607,7 +1607,13 @@ export class AdminClient {
create: (
deliveryMethodId: string,
- params: { type: string; active?: boolean; preferences?: Record<string, unknown> },
+ params: {
+ type: string
+ active?: boolean
+ preferences?: Record<string, unknown>
+ /** Prefixed product IDs — association-backed rules (excluded_products_rule). */
+ product_ids?: string[]
+ },
options?: RequestOptions,
): Promise<DeliveryMethodRule> =>
this.request<DeliveryMethodRule>('POST', `/delivery_methods/${deliveryMethodId}/rules`, {
@@ -1618,7 +1624,12 @@ export class AdminClient {
update: (
deliveryMethodId: string,
id: string,
- params: { active?: boolean; preferences?: Record<string, unknown> },
+ params: {
+ active?: boolean
+ preferences?: Record<string, unknown>
+ /** Prefixed product IDs — association-backed rules (excluded_products_rule). */
+ product_ids?: string[]
+ },
options?: RequestOptions,
): Promise<DeliveryMethodRule> =>
this.request<DeliveryMethodRule>(
@@ -1640,6 +1651,8 @@ export class AdminClient {
name: string
description: string
preference_schema: PreferenceField[]
+ /** Association-backed config the rule accepts, e.g. `['product_ids']`. */
+ association_fields: string[]
}>
}> =>
this.request<{
@@ -1648,6 +1661,7 @@ export class AdminClient {
name: string
description: string
preference_schema: PreferenceField[]
+ association_fields: string[]
}>
}>('GET', '/delivery_method_rules/types', options),
}
diff --git a/packages/admin-sdk/src/types/generated/DeliveryMethodRule.ts b/packages/admin-sdk/src/types/generated/DeliveryMethodRule.ts
index e041367a8d..02ca146852 100644
--- a/packages/admin-sdk/src/types/generated/DeliveryMethodRule.ts
+++ b/packages/admin-sdk/src/types/generated/DeliveryMethodRule.ts
@@ -1,4 +1,4 @@
-// Typelizer digest aa3f7271558adddfc56659d58e2cf620
+// Typelizer digest 1a2fbc5517ea0d5a54e09c26c3922855
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -12,6 +12,7 @@ interface DeliveryMethodRule {
description: string;
preferences: Record<string, unknown>;
preference_schema: Array<{ key: string; type: string; default: unknown }>;
+ product_ids: Array<string>;
}
export default DeliveryMethodRule;
diff --git a/packages/dashboard/src/hooks/use-products.ts b/packages/dashboard/src/hooks/use-products.ts
index 426d2330a5..6447908bee 100644
--- a/packages/dashboard/src/hooks/use-products.ts
+++ b/packages/dashboard/src/hooks/use-products.ts
@@ -1,3 +1,4 @@
+import type { Product } from '@spree/admin-sdk'
import type { FilterRule } from '@spree/dashboard-core'
import {
adminClient,
@@ -17,6 +18,21 @@ interface UseProductsParams {
filters?: FilterRule[]
}
+/**
+ * Shared config for any `<ResourceMultiAutocomplete>` over products.
+ * Pass a unique `queryKey` per instance.
+ */
+export function productAutocompleteProps(queryKey: string) {
+ return {
+ queryKey,
+ search: (q: string) => adminClient.products.list({ name_cont: q, limit: 10, sort: 'name' }),
+ hydrate: (ids: string[]) => adminClient.products.list({ id_in: ids, limit: ids.length }),
+ getOptionLabel: (product: Product) => product.name ?? product.id,
+ placeholder: i18n.t('admin.products.autocomplete.placeholder'),
+ emptyText: i18n.t('admin.products.autocomplete.empty'),
+ }
+}
+
export function useProducts({
page = 1,
limit = 25,
diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.json
index 9feb1f0fc8..0b06f7aa65 100644
--- a/packages/dashboard/src/locales/ar.json
+++ b/packages/dashboard/src/locales/ar.json
@@ -2573,6 +2573,10 @@
"search_placeholder": "ابحث في أنواع المنتجات"
},
"products": {
+ "autocomplete": {
+ "empty": "لا توجد منتجات متطابقة",
+ "placeholder": "البحث عن المنتجات بالاسم…"
+ },
"category_search_placeholder": "فئات البحث…",
"collection_search_placeholder": "ابحث عن مجموعات…",
"columns": {
diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.json
index 12af525ceb..fd9099095b 100644
--- a/packages/dashboard/src/locales/de.json
+++ b/packages/dashboard/src/locales/de.json
@@ -2573,6 +2573,10 @@
"search_placeholder": "Produkttypen durchsuchen"
},
"products": {
+ "autocomplete": {
+ "empty": "Keine passenden Produkte",
+ "placeholder": "Produkte nach Namen suchen…"
+ },
"category_search_placeholder": "Kategorien suchen…",
"collection_search_placeholder": "Kollektionen suchen…",
"columns": {
diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.json
index caa4134b9f..9fccf9f1a3 100644
--- a/packages/dashboard/src/locales/en.json
+++ b/packages/dashboard/src/locales/en.json
@@ -2573,6 +2573,10 @@
"search_placeholder": "Search product types"
},
"products": {
+ "autocomplete": {
+ "empty": "No products match",
+ "placeholder": "Search products by name…"
+ },
"category_search_placeholder": "Search categories…",
"collection_search_placeholder": "Search collections…",
"columns": {
diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.json
index 07f9b61fdf..1c9d84c2f4 100644
--- a/packages/dashboard/src/locales/fr.json
+++ b/packages/dashboard/src/locales/fr.json
@@ -2573,6 +2573,10 @@
"search_placeholder": "Rechercher des types de produit"
},
"products": {
+ "autocomplete": {
+ "empty": "Aucun produit ne correspond",
+ "placeholder": "Rechercher des produits par nom…"
+ },
"category_search_placeholder": "Rechercher des catégories…",
"collection_search_placeholder": "Rechercher des collections…",
"columns": {
diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.json
index 2cadce990d..574f05a4ee 100644
--- a/packages/dashboard/src/locales/pl.json
+++ b/packages/dashboard/src/locales/pl.json
@@ -2605,6 +2605,10 @@
"search_placeholder": "Szukaj typów produktów"
},
"products": {
+ "autocomplete": {
+ "empty": "Brak pasujących produktów",
+ "placeholder": "Szukaj produktów po nazwie…"
+ },
"category_search_placeholder": "Szukaj kategorii…",
"collection_search_placeholder": "Szukaj kolekcji…",
"columns": {
diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.json
index 9378d2497d..bb82ed114f 100644
--- a/packages/dashboard/src/locales/zh-CN.json
+++ b/packages/dashboard/src/locales/zh-CN.json
@@ -2573,6 +2573,10 @@
"search_placeholder": "搜索商品类型"
},
"products": {
+ "autocomplete": {
+ "empty": "没有匹配的商品",
+ "placeholder": "按名称搜索商品…"
+ },
"category_search_placeholder": "搜索分类…",
"collection_search_placeholder": "搜索系列…",
"columns": {
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-methods.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-methods.tsx
index 14ea8db8b8..073c27df7b 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-methods.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-methods.tsx
@@ -1,15 +1,15 @@
import { zodResolver } from '@hookform/resolvers/zod'
-import type { DeliveryMethod, DeliveryMethodRule, PreferenceField } from '@spree/admin-sdk'
+import type { DeliveryMethod, PreferenceField, Product } from '@spree/admin-sdk'
import {
adminClient,
Can,
mapSpreeErrorsToForm,
PreferencesForm,
+ ResourceMultiAutocomplete,
ResourceTable,
resourceSearchSchema,
Subject,
usePermissions,
- useResourceKeyBuilder,
} from '@spree/dashboard-core'
import {
Button,
@@ -39,11 +39,10 @@ import {
useConfirm,
useRowClickBridge,
} from '@spree/dashboard-ui'
-import { useMutation, useQueryClient } from '@tanstack/react-query'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { PlusIcon, Trash2Icon } from 'lucide-react'
-import { useEffect, useMemo, useState } from 'react'
-import { Controller, type UseFormReturn, useForm } from 'react-hook-form'
+import { useEffect, useMemo } from 'react'
+import { Controller, type UseFormReturn, useFieldArray, useForm } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { z } from 'zod/v4'
import {
@@ -57,6 +56,7 @@ import {
useUpdateDeliveryMethod,
} from '../../../../hooks/use-delivery-methods'
import { useDeliveryZones } from '../../../../hooks/use-delivery-zones'
+import { productAutocompleteProps } from '../../../../hooks/use-products'
import { useStockLocations } from '../../../../hooks/use-stock-locations'
import { useTaxCategories } from '../../../../hooks/use-tax-categories'
import {
@@ -68,6 +68,18 @@ import {
} from '../../../../schemas/delivery-method'
import '../../../../tables/delivery-methods'
+/** One entry from the delivery-method-rule discovery endpoint. */
+type DeliveryMethodRuleType = Awaited<
+ ReturnType<typeof adminClient.deliveryMethods.ruleTypes>
+>['data'][number]
+
+/** Whether a rule kind is configured with a product list rather than preferences. */
+function takesProducts(ruleTypes: DeliveryMethodRuleType[] | undefined, type: string) {
+ return (
+ ruleTypes?.find((candidate) => candidate.type === type)?.association_fields ?? []
+ ).includes('product_ids')
+}
+
const deliveryMethodsSearchSchema = resourceSearchSchema.extend({
edit: z.string().optional(),
new: z.coerce.boolean().optional(),
@@ -196,8 +208,11 @@ function CreateDeliveryMethodSheet({
<SheetDescription>{t('admin.delivery_methods.create_description')}</SheetDescription>
</SheetHeader>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
- <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
- <DeliveryMethodFormFields form={form} />
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">
+ <div className="flex flex-col gap-4 p-4">
+ <DeliveryMethodFormFields form={form} />
+ </div>
+ <ConditionsSection form={form} />
</div>
<SheetFooter>
<Button
@@ -231,8 +246,15 @@ function EditDeliveryMethodSheet({
onOpenChange: (open: boolean) => void
}) {
const { t } = useTranslation()
- const { data: deliveryMethod, isLoading } = useDeliveryMethod(id)
+ const { data: deliveryMethod, isLoading: methodLoading } = useDeliveryMethod(id)
+ const { data: rules, isLoading: rulesLoading } = useDeliveryMethodRules(id)
+ const { data: ruleTypes, isLoading: ruleTypesLoading } = useDeliveryMethodRuleTypes()
const updateMutation = useUpdateDeliveryMethod(id)
+ // Saving sends the full rule set for reconciliation, so the form must not be
+ // reachable until the existing rules have loaded — otherwise a quick save
+ // would submit an empty set and delete them all. Rule types are needed too,
+ // since they decide which rules carry a product list.
+ const isLoading = methodLoading || rulesLoading || ruleTypesLoading
const form = useForm<DeliveryMethodFormValues>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -241,7 +263,9 @@ function EditDeliveryMethodSheet({
})
useEffect(() => {
- if (deliveryMethod) {
+ // Wait for rules too — seeding the form before they arrive would reset
+ // again once they land, discarding anything already edited.
+ if (deliveryMethod && rules && ruleTypes) {
form.reset({
name: deliveryMethod.name,
admin_name: deliveryMethod.admin_name ?? '',
@@ -263,9 +287,16 @@ function EditDeliveryMethodSheet({
(deliveryMethod.calculator_preferences as Record<string, unknown>) ?? {},
delivery_zone_ids: deliveryMethod.delivery_zone_ids ?? [],
stock_location_ids: deliveryMethod.stock_location_ids ?? [],
+ rules: (rules?.data ?? []).map((rule) => ({
+ id: rule.id,
+ type: rule.type,
+ preferences: rule.preferences as Record<string, unknown>,
+ product_ids: rule.product_ids,
+ takes_products: takesProducts(ruleTypes?.data, rule.type),
+ })),
})
}
- }, [deliveryMethod, form])
+ }, [deliveryMethod, rules, ruleTypes, form])
async function onSubmit(values: DeliveryMethodFormValues) {
try {
@@ -290,10 +321,12 @@ function EditDeliveryMethodSheet({
<div className="p-4 text-sm text-muted-foreground">{t('admin.common.loading')}</div>
) : (
<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
- <div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
- <DeliveryMethodFormFields form={form} />
+ <div className="flex min-h-0 flex-1 flex-col overflow-y-auto">
+ <div className="flex flex-col gap-4 p-4">
+ <DeliveryMethodFormFields form={form} />
+ </div>
+ <ConditionsSection form={form} />
</div>
- <ConditionsSection deliveryMethodId={id} />
<SheetFooter>
<Button
type="button"
@@ -320,37 +353,15 @@ function EditDeliveryMethodSheet({
}
// ---------------------------------------------------------------------------
-// Conditions (eligibility rules) — live-mutating, separate from the form
+// Conditions (eligibility rules) — held in form state, saved with the sheet
// ---------------------------------------------------------------------------
-function ConditionsSection({ deliveryMethodId }: { deliveryMethodId: string }) {
+function ConditionsSection({ form }: { form: UseFormReturn<DeliveryMethodFormValues> }) {
const { t } = useTranslation()
- const queryClient = useQueryClient()
- const buildKey = useResourceKeyBuilder()
- const { data: rules } = useDeliveryMethodRules(deliveryMethodId)
const { data: ruleTypes } = useDeliveryMethodRuleTypes()
+ const rulesArray = useFieldArray({ control: form.control, name: 'rules', keyName: '_key' })
- const invalidate = () =>
- queryClient.invalidateQueries({
- queryKey: buildKey('delivery-methods', deliveryMethodId, 'rules'),
- })
-
- const addMutation = useMutation({
- mutationFn: (type: string) =>
- adminClient.deliveryMethods.rules.create(deliveryMethodId, { type }),
- onSuccess: invalidate,
- })
- const updateMutation = useMutation({
- mutationFn: ({ id, preferences }: { id: string; preferences: Record<string, unknown> }) =>
- adminClient.deliveryMethods.rules.update(deliveryMethodId, id, { preferences }),
- onSuccess: invalidate,
- })
- const removeMutation = useMutation({
- mutationFn: (id: string) => adminClient.deliveryMethods.rules.delete(deliveryMethodId, id),
- onSuccess: invalidate,
- })
-
- const existingTypes = new Set((rules?.data ?? []).map((rule) => rule.type))
+ const existingTypes = new Set(rulesArray.fields.map((rule) => rule.type))
const availableTypes = (ruleTypes?.data ?? []).filter((type) => !existingTypes.has(type.type))
return (
@@ -361,7 +372,7 @@ function ConditionsSection({ deliveryMethodId }: { deliveryMethodId: string }) {
<DropdownMenu>
<DropdownMenuTrigger
render={
- <Button type="button" variant="outline" size="sm" disabled={addMutation.isPending}>
+ <Button type="button" variant="outline" size="sm">
<PlusIcon className="size-4" />
{t('admin.delivery_methods.conditions.add')}
</Button>
@@ -369,7 +380,17 @@ function ConditionsSection({ deliveryMethodId }: { deliveryMethodId: string }) {
/>
<DropdownMenuContent align="end">
{availableTypes.map((type) => (
- <DropdownMenuItem key={type.type} onClick={() => addMutation.mutate(type.type)}>
+ <DropdownMenuItem
+ key={type.type}
+ onClick={() =>
+ rulesArray.append({
+ type: type.type,
+ preferences: {},
+ product_ids: [],
+ takes_products: type.association_fields.includes('product_ids'),
+ })
+ }
+ >
{type.name}
</DropdownMenuItem>
))}
@@ -378,19 +399,20 @@ function ConditionsSection({ deliveryMethodId }: { deliveryMethodId: string }) {
)}
</div>
- {(rules?.data ?? []).length === 0 && (
+ {rulesArray.fields.length === 0 && (
<p className="text-muted-foreground text-sm">
{t('admin.delivery_methods.conditions.empty')}
</p>
)}
- {(rules?.data ?? []).map((rule) => (
+ {rulesArray.fields.map((field, index) => (
<ConditionRuleRow
- key={rule.id}
- rule={rule}
- onSave={(preferences) => updateMutation.mutate({ id: rule.id, preferences })}
- onRemove={() => removeMutation.mutate(rule.id)}
- saving={updateMutation.isPending}
+ key={field._key}
+ form={form}
+ index={index}
+ ruleType={(ruleTypes?.data ?? []).find((candidate) => candidate.type === field.type)}
+ fallbackLabel={field.type}
+ onRemove={() => rulesArray.remove(index)}
/>
))}
</div>
@@ -398,26 +420,30 @@ function ConditionsSection({ deliveryMethodId }: { deliveryMethodId: string }) {
}
function ConditionRuleRow({
- rule,
- onSave,
+ form,
+ index,
+ ruleType,
+ fallbackLabel,
onRemove,
- saving,
}: {
- rule: DeliveryMethodRule
- onSave: (preferences: Record<string, unknown>) => void
+ form: UseFormReturn<DeliveryMethodFormValues>
+ index: number
+ ruleType?: DeliveryMethodRuleType
+ fallbackLabel: string
onRemove: () => void
- saving: boolean
}) {
const { t } = useTranslation()
- const [values, setValues] = useState<Record<string, unknown>>(
- rule.preferences as Record<string, unknown>,
- )
- const dirty = JSON.stringify(values) !== JSON.stringify(rule.preferences)
+ // Rules that take a product list get a picker; every other kind renders its
+ // preference schema. Driven by the discovery endpoint, so a plugin rule with
+ // the same shape works without a change here.
+ const productBacked = ruleType?.association_fields?.includes('product_ids') ?? false
+ const label = ruleType?.name ?? fallbackLabel
+ const schema = ruleType?.preference_schema ?? []
return (
<div className="flex flex-col gap-2 rounded-md border p-3">
<div className="flex items-center justify-between">
- <span className="text-sm">{rule.name}</span>
+ <span className="text-sm">{label}</span>
<Button
type="button"
variant="ghost"
@@ -428,11 +454,26 @@ function ConditionRuleRow({
<Trash2Icon className="size-4" />
</Button>
</div>
- <PreferencesForm schema={rule.preference_schema} values={values} onChange={setValues} />
- {dirty && (
- <Button type="button" size="sm" onClick={() => onSave(values)} disabled={saving}>
- {saving ? t('admin.actions.saving') : t('admin.actions.save')}
- </Button>
+ {productBacked ? (
+ <Controller
+ control={form.control}
+ name={`rules.${index}.product_ids`}
+ render={({ field }) => (
+ <ResourceMultiAutocomplete<Product>
+ {...productAutocompleteProps('delivery-method-rule-products')}
+ value={field.value}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ ) : (
+ <Controller
+ control={form.control}
+ name={`rules.${index}.preferences`}
+ render={({ field }) => (
+ <PreferencesForm schema={schema} values={field.value} onChange={field.onChange} />
+ )}
+ />
)}
</div>
)
diff --git a/packages/dashboard/src/schemas/delivery-method.ts b/packages/dashboard/src/schemas/delivery-method.ts
index 03a8ed11bb..128c8d321d 100644
--- a/packages/dashboard/src/schemas/delivery-method.ts
+++ b/packages/dashboard/src/schemas/delivery-method.ts
@@ -2,6 +2,22 @@ import { z } from 'zod/v4'
export const FULFILLMENT_TYPES = ['shipping', 'digital', 'pickup', 'pickup_point'] as const
+/**
+ * One eligibility rule as held in form state. `id` is absent for rules added
+ * in this editing session. `takes_products` comes from the rule-type discovery
+ * endpoint and decides whether `product_ids` is part of this rule's payload —
+ * it is display-only state, stripped before send.
+ */
+export const deliveryMethodRuleSchema = z.object({
+ id: z.string().optional(),
+ type: z.string(),
+ preferences: z.record(z.string(), z.unknown()),
+ product_ids: z.array(z.string()),
+ takes_products: z.boolean(),
+})
+
+export type DeliveryMethodRuleDraft = z.infer<typeof deliveryMethodRuleSchema>
+
export const deliveryMethodFormSchema = z.object({
name: z.string().min(1),
admin_name: z.string().optional(),
@@ -17,6 +33,7 @@ export const deliveryMethodFormSchema = z.object({
calculator_preferences: z.record(z.string(), z.unknown()).optional(),
delivery_zone_ids: z.array(z.string()),
stock_location_ids: z.array(z.string()),
+ rules: z.array(deliveryMethodRuleSchema),
})
export type DeliveryMethodFormValues = z.infer<typeof deliveryMethodFormSchema>
@@ -36,6 +53,7 @@ export const DELIVERY_METHOD_DEFAULTS: DeliveryMethodFormValues = {
calculator_preferences: {},
delivery_zone_ids: [],
stock_location_ids: [],
+ rules: [],
}
export function deliveryMethodValuesToParams(values: DeliveryMethodFormValues) {
@@ -60,5 +78,16 @@ export function deliveryMethodValuesToParams(values: DeliveryMethodFormValues) {
: {}),
delivery_zone_ids: values.delivery_zone_ids,
stock_location_ids: values.stock_location_ids,
+ // Rules ride along with the method so one request saves the whole sheet.
+ // Omitting `id` marks a rule as new; dropping one from the array deletes
+ // it. `product_ids` is always sent for association-backed rules — omitting
+ // an emptied array would read as "leave unchanged" and silently keep the
+ // exclusions the merchant just removed.
+ rules: values.rules.map((rule) => ({
+ ...(rule.id ? { id: rule.id } : {}),
+ type: rule.type,
+ preferences: rule.preferences,
+ ...(rule.takes_products ? { product_ids: rule.product_ids } : {}),
+ })),
}
}
diff --git a/spree/api/app/controllers/spree/api/v3/admin/delivery_method_rules_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/delivery_method_rules_controller.rb
index c4e34209aa..6375edf9c1 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/delivery_method_rules_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/delivery_method_rules_controller.rb
@@ -15,7 +15,11 @@ module Spree
type: klass.api_type,
name: klass.human_name,
description: klass.human_description,
- preference_schema: klass.serialized_preference_schema
+ preference_schema: klass.serialized_preference_schema,
+ # Association-backed config (e.g. `product_ids`) a rule accepts
+ # beyond its preferences, so admin UIs can render the right
+ # editor without hardcoding rule types.
+ association_fields: association_fields_for(klass)
}
end
@@ -31,6 +35,18 @@ module Spree
def serializer_class
Spree.api.admin_delivery_method_rule_serializer
end
+
+ private
+
+ # `additional_permitted_attributes` entries are either bare symbols
+ # or `{ product_ids: [] }`-style hashes; both reduce to field names.
+ def association_fields_for(klass)
+ return [] unless klass.respond_to?(:additional_permitted_attributes)
+
+ klass.additional_permitted_attributes.flat_map do |attribute|
+ attribute.is_a?(Hash) ? attribute.keys : attribute
+ end.map(&:to_s)
+ end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/delivery_methods/rules_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/delivery_methods/rules_controller.rb
index b123d8256a..9692e9c67a 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/delivery_methods/rules_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/delivery_methods/rules_controller.rb
@@ -23,6 +23,7 @@ module Spree
@resource = rule_class.new(delivery_method: parent, active: active_param)
assign_rule_preferences(@resource)
+ assign_rule_products(@resource)
authorize_resource!(@resource, :create)
if @resource.save
@@ -35,6 +36,7 @@ module Spree
def update
@resource.active = active_param unless params[:active].nil?
assign_rule_preferences(@resource)
+ assign_rule_products(@resource)
if @resource.save
render json: serialize_resource(@resource)
@@ -58,7 +60,7 @@ module Spree
end
def permitted_params
- params.permit(:type, :active, preferences: {})
+ params.permit(:type, :active, preferences: {}, product_ids: [])
end
private
@@ -78,6 +80,20 @@ module Spree
rule.set_preference(key, value)
end
end
+
+ # Association-backed rule config (ExcludedProductsRule). Products are
+ # looked up within the rule's store and through the caller's ability;
+ # ids that resolve to nothing are dropped rather than failing the
+ # save, since an unreachable product cannot become an exclusion. A
+ # nil param leaves the selection untouched; an empty array clears it.
+ def assign_rule_products(rule)
+ ids = permitted_params[:product_ids]
+ return if ids.nil? || !rule.respond_to?(:products)
+
+ rule.products = rule.store.products.
+ accessible_by(current_ability, :show).
+ where(id: decode_prefixed_ids(ids))
+ end
end
end
end
diff --git a/spree/api/app/controllers/spree/api/v3/admin/delivery_methods_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/delivery_methods_controller.rb
index 410f2f0b48..9b1a8c8efa 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/delivery_methods_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/delivery_methods_controller.rb
@@ -75,16 +75,33 @@ module Spree
Spree.api.admin_delivery_method_serializer
end
+ # A single POST/PATCH can ship eligibility rules alongside the
+ # basics; `DeliveryMethod#rules=` reconciles to the desired set, so
+ # the dashboard saves the whole sheet in one round-trip.
def permitted_params
params.permit(
:name, :admin_name, :code, :fulfillment_type, :fulfillment_provider,
:pickup_point_provider, :storefront_visible, :tracking_url,
:estimated_transit_business_days_min, :estimated_transit_business_days_max,
:tax_category_id, :calculator_type,
- delivery_zone_ids: [], stock_location_ids: [], calculator_preferences: {}
+ delivery_zone_ids: [], stock_location_ids: [], calculator_preferences: {},
+ rules: rule_attributes
)
end
+ def rule_attributes
+ [:id, :type, :active, { preferences: {} }, *subclassed_rule_attributes]
+ end
+
+ # Association-backed rule config declares itself on the rule class
+ # (e.g. `[product_ids: []]`), so plugin-defined rules need no change
+ # here.
+ def subclassed_rule_attributes
+ Spree.delivery_method_rules.flat_map do |klass|
+ klass.respond_to?(:additional_permitted_attributes) ? klass.additional_permitted_attributes : []
+ end.uniq
+ end
+
def collection_includes
[:calculator, :tax_category, :delivery_zones]
end
@@ -103,9 +120,33 @@ module Spree
if params.key?(:stock_location_ids)
attributes[:pickup_locations] = Array(params[:stock_location_ids]).map { |id| current_store.stock_locations.accessible_by(current_ability, :show).find_by_prefix_id!(id) }
end
+ attributes[:rules] = resolved_rule_rows if params.key?(:rules)
attributes
end
+ # `DeliveryMethod#rules=` decodes prefixed ids but applies no store
+ # or ability scoping, so resolve association-backed config here — a
+ # product the caller cannot reach 404s rather than silently linking.
+ def resolved_rule_rows
+ Array(permitted_params[:rules]).map do |row|
+ row = row.to_h
+ row['product_ids'].blank? ? row : row.merge('product_ids' => accessible_product_ids(row['product_ids']))
+ end
+ end
+
+ # Keeps only the products this caller can reach in this store, and
+ # plucks ids rather than hydrating rows to read them back. Ids that
+ # resolve to nothing — another store's, or a product deleted while
+ # the sheet was open — are dropped: they cannot become an exclusion,
+ # and failing the whole save over one would leave the merchant stuck
+ # with no way to clear it. Mirrors how price lists filter membership.
+ def accessible_product_ids(ids)
+ current_store.products.
+ accessible_by(current_ability, :show).
+ where(id: decode_prefixed_ids(ids)).
+ pluck(:id)
+ end
+
def assign_calculator(delivery_method)
calculator_type = permitted_params[:calculator_type]
preferences = permitted_params[:calculator_preferences]
diff --git a/spree/api/app/serializers/spree/api/v3/admin/delivery_method_rule_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/delivery_method_rule_serializer.rb
index a3c241f6f5..3d5138a461 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/delivery_method_rule_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/delivery_method_rule_serializer.rb
@@ -6,7 +6,8 @@ module Spree
typelize type: :string, active: :boolean,
preferences: 'Record<string, unknown>',
preference_schema: "Array<{ key: string; type: string; default: unknown }>",
- name: :string, description: :string
+ name: :string, description: :string,
+ product_ids: [:string, multi: true]
attributes :active, created_at: :iso8601, updated_at: :iso8601
@@ -26,6 +27,12 @@ module Spree
attribute :preferences, &:serialized_preferences
attribute :preference_schema, &:serialized_preference_schema
+
+ # Association-backed config (ExcludedProductsRule); empty for
+ # preference-only rules. Same name read and written.
+ attribute :product_ids do |rule|
+ rule.respond_to?(:product_prefixed_ids) ? rule.product_prefixed_ids : []
+ end
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/delivery_method_rules_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/delivery_method_rules_controller_spec.rb
index a1b58584c6..d7dabde006 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/delivery_method_rules_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/delivery_method_rules_controller_spec.rb
@@ -12,9 +12,12 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodRulesController, type: :cont
get :types, params: {}, as: :json
expect(response).to have_http_status(:ok)
- expect(json_response['data'].map { |row| row['type'] }).to contain_exactly('item_total_rule', 'weight_rule')
+ expect(json_response['data'].map { |row| row['type'] }).to contain_exactly('item_total_rule', 'weight_rule', 'excluded_products_rule')
item_total = json_response['data'].find { |row| row['type'] == 'item_total_rule' }
expect(item_total['preference_schema'].map { |field| field['key'] }).to contain_exactly('minimum_amount', 'maximum_amount')
+
+ excluded = json_response['data'].find { |row| row['type'] == 'excluded_products_rule' }
+ expect(excluded['association_fields']).to eq(['product_ids'])
end
end
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods/rules_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods/rules_controller_spec.rb
index 02e281c9e9..74a37ba725 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods/rules_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods/rules_controller_spec.rb
@@ -5,7 +5,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethods::RulesController, type: :c
include_context 'API v3 Admin authenticated'
- let!(:delivery_method) { create(:shipping_method, name: 'Standard') }
+ let!(:delivery_method) { create(:delivery_method, name: 'Standard') }
before { request.headers.merge!(headers) }
@@ -54,6 +54,36 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethods::RulesController, type: :c
expect(response).to have_http_status(:unprocessable_content)
end
+
+ it 'creates an excluded-products rule from prefixed product ids' do
+ product = create(:product)
+
+ post :create, params: {
+ delivery_method_id: delivery_method.prefixed_id,
+ type: 'excluded_products_rule',
+ product_ids: [product.prefixed_id]
+ }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(json_response['type']).to eq('excluded_products_rule')
+ expect(json_response['product_ids']).to eq([product.prefixed_id])
+ expect(delivery_method.delivery_method_rules.sole.products).to eq([product])
+ end
+
+ # Unreachable ids are dropped rather than failing the save — they cannot
+ # become an exclusion either way.
+ it 'drops products belonging to another store' do
+ other_store_product = create(:product, store: create(:store))
+
+ post :create, params: {
+ delivery_method_id: delivery_method.prefixed_id,
+ type: 'excluded_products_rule',
+ product_ids: [other_store_product.prefixed_id]
+ }, as: :json
+
+ expect(response).to have_http_status(:created)
+ expect(delivery_method.delivery_method_rules.sole.products).to be_empty
+ end
end
describe 'PATCH #update' do
@@ -72,6 +102,24 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethods::RulesController, type: :c
expect(rule.active).to be(false)
expect(rule.preferred_minimum_amount).to eq(50)
end
+
+ it 'replaces the excluded products' do
+ kept = create(:product)
+ dropped = create(:product)
+ excluded_rule = Spree::DeliveryMethodRules::ExcludedProductsRule.create!(
+ delivery_method: delivery_method, products: [dropped]
+ )
+
+ patch :update, params: {
+ delivery_method_id: delivery_method.prefixed_id,
+ id: excluded_rule.prefixed_id,
+ product_ids: [kept.prefixed_id]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(json_response['product_ids']).to eq([kept.prefixed_id])
+ expect(excluded_rule.reload.products).to eq([kept])
+ end
end
describe 'DELETE #destroy' do
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb
index 10dd3ee298..873e1c9a6d 100644
--- a/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb
+++ b/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods_controller_spec.rb
@@ -8,7 +8,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
before { request.headers.merge!(headers) }
describe 'GET #index' do
- let!(:delivery_method) { create(:shipping_method, name: 'UPS Ground') }
+ let!(:delivery_method) { create(:delivery_method, name: 'UPS Ground') }
it 'lists delivery methods with admin fields' do
get :index, params: {}, as: :json
@@ -126,7 +126,7 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
end
describe 'PATCH #update' do
- let!(:delivery_method) { create(:shipping_method, name: 'UPS Ground') }
+ let!(:delivery_method) { create(:delivery_method, name: 'UPS Ground') }
it 'updates attributes and calculator preferences' do
patch :update, params: {
@@ -139,10 +139,68 @@ RSpec.describe Spree::Api::V3::Admin::DeliveryMethodsController, type: :controll
expect(delivery_method.reload.name).to eq('UPS Ground v2')
expect(delivery_method.calculator.preferred_amount).to eq(99)
end
+
+ # The dashboard sheet saves basics and conditions together.
+ it 'saves nested eligibility rules alongside the method' do
+ product = create(:product)
+
+ patch :update, params: {
+ id: delivery_method.prefixed_id,
+ name: 'Express',
+ rules: [
+ { type: 'item_total_rule', preferences: { minimum_amount: 25 } },
+ { type: 'excluded_products_rule', product_ids: [product.prefixed_id] }
+ ]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ delivery_method.reload
+ expect(delivery_method.name).to eq('Express')
+ expect(delivery_method.delivery_method_rules.count).to eq(2)
+
+ excluded = delivery_method.delivery_method_rules.detect do |rule|
+ rule.is_a?(Spree::DeliveryMethodRules::ExcludedProductsRule)
+ end
+ expect(excluded.products).to eq([product])
+ end
+
+ it 'clears excluded products when an empty array is sent' do
+ product = create(:product)
+ rule = Spree::DeliveryMethodRules::ExcludedProductsRule.create!(
+ delivery_method: delivery_method, products: [product]
+ )
+
+ patch :update, params: {
+ id: delivery_method.prefixed_id,
+ rules: [{ id: rule.prefixed_id, type: 'excluded_products_rule', product_ids: [] }]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(rule.reload.products).to be_empty
+ expect(delivery_method.delivery_method_rules.reload.size).to eq(1)
+ end
+
+ # An unreachable product cannot become an exclusion, but it must not fail
+ # the whole save either — the merchant would have no way to clear it.
+ it 'drops nested rule products from another store' do
+ foreign_product = create(:product, store: create(:store))
+ own_product = create(:product)
+
+ patch :update, params: {
+ id: delivery_method.prefixed_id,
+ rules: [{
+ type: 'excluded_products_rule',
+ product_ids: [foreign_product.prefixed_id, own_product.prefixed_id]
+ }]
+ }, as: :json
+
+ expect(response).to have_http_status(:ok)
+ expect(delivery_method.delivery_method_rules.sole.products).to eq([own_product])
+ end
end
describe 'DELETE #destroy' do
- let!(:delivery_method) { create(:shipping_method) }
+ let!(:delivery_method) { create(:delivery_method) }
it 'soft deletes the delivery method' do
delete :destroy, params: { id: delivery_method.prefixed_id }, as: :json
diff --git a/spree/core/app/models/concerns/spree/preference_schema.rb b/spree/core/app/models/concerns/spree/preference_schema.rb
index cc20def28b..02d10f148e 100644
--- a/spree/core/app/models/concerns/spree/preference_schema.rb
+++ b/spree/core/app/models/concerns/spree/preference_schema.rb
@@ -5,9 +5,28 @@ module Spree
# Used by the admin API (`/payment_methods/types`, `/promotion_actions/types`,
# `/promotion_rules/types`) so that admin UIs can render configuration forms
# for any provider/action/rule subclass without hard-coding field lists.
+ #
+ # Also hosts the subclass registry (`registers_subclasses_via`) that
+ # `find_by_api_type` and `subclasses_with_preference_schema` resolve against.
+ # That is a lodger rather than a natural fit — the registry is its own
+ # concept, and `Spree::CalculatedAdjustments` resolves an equivalent one
+ # separately. Extract a `Spree::RegisteredSubclasses` concern when a family
+ # needs the registry without preferences.
module PreferenceSchema
extend ActiveSupport::Concern
+ # Raised when a class reaches registry resolution without declaring one.
+ # A StandardError so host apps' normal rescues catch it — NotImplementedError
+ # descends from ScriptError and slips past `rescue => e`.
+ class UndeclaredRegistryError < StandardError; end
+
+ included do
+ # Where this class's registered subclasses live, as a block evaluated on
+ # the class. `class_attribute` so STI subclasses inherit their parent's
+ # declaration.
+ class_attribute :subclass_registry, instance_accessor: false, default: nil
+ end
+
delegate :preference_schema, :serialized_preference_schema, :password_preference_keys, to: :class
# Wire-safe view of `preferences` with `:password`-typed values
@@ -166,17 +185,30 @@ module Spree
outer.delete_prefix('Spree').presence&.titleize || leaf.titleize
end
+ # Declares where this STI parent's subclass registry lives, powering
+ # `find_by_api_type` and `subclasses_with_preference_schema`. The block
+ # is evaluated on the class, so it can read config that changes at boot:
+ #
+ # registers_subclasses_via { Spree.delivery_method_rules }
+ #
+ # @return [void]
+ def registers_subclasses_via(&block)
+ self.subclass_registry = block
+ end
+
private
- # Each STI parent (PaymentMethod, PromotionAction, PromotionRule)
- # already exposes its registry — we just route to the right one.
- # Override in the including class to add support for custom parents.
+ # Resolves the declared registry.
+ #
+ # Raises rather than returning an empty list: a missing declaration used
+ # to mean `find_by_api_type` silently returned nil, so typed rows were
+ # dropped from a payload with no error and admin pickers rendered empty.
def registered_subclasses
- return providers if respond_to?(:providers)
- return Spree.promotions.actions if name == 'Spree::PromotionAction'
- return Spree.promotions.rules if name == 'Spree::PromotionRule'
+ raise UndeclaredRegistryError,
+ "#{name} has no subclass registry. Declare one with " \
+ '`registers_subclasses_via { ... }` returning the registered subclasses.' if subclass_registry.nil?
- []
+ instance_exec(&subclass_registry)
end
# Defaults can be Procs that hit the database (e.g. `Spree::Store.default`);
diff --git a/spree/core/app/models/spree/collection_rule.rb b/spree/core/app/models/spree/collection_rule.rb
index e17000fe84..a6528ef7fe 100644
--- a/spree/core/app/models/spree/collection_rule.rb
+++ b/spree/core/app/models/spree/collection_rule.rb
@@ -37,18 +37,7 @@ module Spree
def human_name = self.class.human_name
def human_description = self.class.human_description
- # Routes Spree::PreferenceSchema's subclass discovery
- # (`subclasses_with_preference_schema`, `find_by_api_type`) to the
- # collection-rule registry, so a plugin-registered rule is discoverable
- # by the dashboard without a core change.
- module ClassMethods
- private
-
- def registered_subclasses
- Rails.application.config.spree.collection_rules
- end
- end
- extend ClassMethods
+ registers_subclasses_via { Rails.application.config.spree.collection_rules }
private
diff --git a/spree/core/app/models/spree/delivery_method.rb b/spree/core/app/models/spree/delivery_method.rb
index eafc3c2dfa..86a958c7d4 100644
--- a/spree/core/app/models/spree/delivery_method.rb
+++ b/spree/core/app/models/spree/delivery_method.rb
@@ -11,6 +11,7 @@ module Spree
include Spree::VendorConcern
end
include Spree::MemoizedData
+ include Spree::TypedAssociations
extend Spree::DisplayMoney
@@ -49,6 +50,7 @@ module Spree
# Every method rates through a calculator; pickup/digital methods default
# to free so API/dashboard creation doesn't have to send one.
before_validation :ensure_calculator, on: :create
+ after_save :apply_pending_rules, if: :pending_rules?
attribute :fulfillment_provider, :string, default: 'Spree::FulfillmentProvider::Manual'
scope :by_fulfillment_type, ->(type) { where(fulfillment_type: type) }
@@ -158,6 +160,17 @@ module Spree
@provider ||= (fulfillment_provider.presence || 'Spree::FulfillmentProvider::Manual').constantize.new
end
+ # Flat-payload writer for `rules`, so one PATCH saves the method and its
+ # conditions together. See
+ # {Spree::TypedAssociations#assign_typed_association}.
+ def rules=(rows)
+ assign_typed_association(:delivery_method_rules, rows)
+ end
+
+ def pending_rules?
+ @pending_delivery_method_rules.present?
+ end
+
# AND over the method's active rules; no rules = eligible everywhere.
# Evaluated in the Estimator's method filter — the single seam every rate
# consumer (checkout, routing, cart estimates) flows through.
@@ -280,5 +293,11 @@ module Spree
Spree::Deprecation.warn('Spree::DeliveryMethod#display_on= is deprecated and will be removed in Spree 6.1. Use #storefront_visible= instead.')
self.storefront_visible = value.to_s != 'back_end'
end
+
+ private
+
+ def apply_pending_rules
+ flush_pending_typed_association(:delivery_method_rules)
+ end
end
end
diff --git a/spree/core/app/models/spree/delivery_method_rule.rb b/spree/core/app/models/spree/delivery_method_rule.rb
index fb3ff79a9d..10e310f850 100644
--- a/spree/core/app/models/spree/delivery_method_rule.rb
+++ b/spree/core/app/models/spree/delivery_method_rule.rb
@@ -25,6 +25,17 @@ module Spree
scope :active, -> { where(active: true) }
+ # Extra params a subclass accepts beyond `type`/`active`/`preferences` —
+ # association-backed config declares itself here so the nested rules API
+ # stays generic (mirrors {Spree::PromotionRule.additional_permitted_attributes}).
+ #
+ # @return [Array]
+ def self.additional_permitted_attributes
+ []
+ end
+
+ registers_subclasses_via { Spree.delivery_method_rules }
+
# @return [String] localized display name for the rule kind, used by admin pickers
def self.human_name
Spree.t("delivery_method_rule_types.#{api_type}.name", default: api_type.titleize)
diff --git a/spree/core/app/models/spree/delivery_method_rule_product.rb b/spree/core/app/models/spree/delivery_method_rule_product.rb
new file mode 100644
index 0000000000..f7313a1c27
--- /dev/null
+++ b/spree/core/app/models/spree/delivery_method_rule_product.rb
@@ -0,0 +1,9 @@
+module Spree
+ class DeliveryMethodRuleProduct < Spree.base_class
+ belongs_to :delivery_method_rule, class_name: 'Spree::DeliveryMethodRule'
+ belongs_to :product, class_name: 'Spree::Product'
+
+ validates :delivery_method_rule, :product, presence: true
+ validates :product_id, uniqueness: { scope: :delivery_method_rule_id }, allow_nil: true
+ end
+end
diff --git a/spree/core/app/models/spree/delivery_method_rules/excluded_products_rule.rb b/spree/core/app/models/spree/delivery_method_rules/excluded_products_rule.rb
new file mode 100644
index 0000000000..1591b9f0fe
--- /dev/null
+++ b/spree/core/app/models/spree/delivery_method_rules/excluded_products_rule.rb
@@ -0,0 +1,50 @@
+module Spree
+ module DeliveryMethodRules
+ # Blocks the method for packages containing any of the attached products
+ # ("fragile item can't ship express"). Products hang off the concrete
+ # spree_delivery_method_rule_products join table — catalog-scale
+ # references never live in preferences. A rule with no products passes,
+ # matching the empty-preference fail-open convention.
+ class ExcludedProductsRule < Spree::DeliveryMethodRule
+ has_many :delivery_method_rule_products, class_name: 'Spree::DeliveryMethodRuleProduct',
+ foreign_key: :delivery_method_rule_id, dependent: :destroy,
+ inverse_of: :delivery_method_rule
+ has_many :products, class_name: 'Spree::Product', through: :delivery_method_rule_products
+
+ def self.additional_permitted_attributes
+ [product_ids: []]
+ end
+
+ # Excluded product ids in prefixed form. Plucked rather than hydrating N
+ # Product rows just to re-encode their ids, but read through the products
+ # association so soft-deleted products drop out — a client resubmitting
+ # this list must not be told a product it never chose is unreachable.
+ # Sorted so clients can compare a response against what they sent.
+ #
+ # @return [Array<String>]
+ def product_prefixed_ids
+ products.pluck(:id).sort.map { |id| Spree::Product.prefixed_id_for(id) }
+ end
+
+ # Asks whether any of the package's products is excluded, rather than
+ # loading the whole exclusion list — the join table's composite index
+ # answers it without transferring rows.
+ def eligible?(package)
+ product_ids = package.contents.map { |item| item.variant.product_id }.uniq
+ return true if product_ids.empty?
+
+ # `target` is whatever is already in memory, so reading it never
+ # triggers a load. It covers links assigned but not yet saved — the
+ # admin controller assigns products before saving the rule.
+ return false if delivery_method_rule_products.target.any? { |link|
+ link.new_record? && product_ids.include?(link.product_id)
+ }
+ # An unsaved rule has no rows to query, and asking would still cost a
+ # round trip.
+ return true if new_record?
+
+ !delivery_method_rule_products.exists?(product_id: product_ids)
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/order_routing_rule.rb b/spree/core/app/models/spree/order_routing_rule.rb
index e6066dd26a..4830846b7e 100644
--- a/spree/core/app/models/spree/order_routing_rule.rb
+++ b/spree/core/app/models/spree/order_routing_rule.rb
@@ -80,17 +80,7 @@ module Spree
raise NotImplementedError, "#{self.class} must implement #rank(order, locations)"
end
- # Routes Spree::PreferenceSchema's subclass discovery
- # (`subclasses_with_preference_schema`, `find_by_api_type`) to the
- # order-routing rule registry.
- module ClassMethods
- private
-
- def registered_subclasses
- Spree.order_routing.rules
- end
- end
- extend ClassMethods
+ registers_subclasses_via { Spree.order_routing.rules }
private
diff --git a/spree/core/app/models/spree/payment_method.rb b/spree/core/app/models/spree/payment_method.rb
index 7d80067e3c..d564b7b7b6 100644
--- a/spree/core/app/models/spree/payment_method.rb
+++ b/spree/core/app/models/spree/payment_method.rb
@@ -36,6 +36,10 @@ module Spree
Spree.payment_methods
end
+ # Gateways predate `registers_subclasses_via` and expose their registry as
+ # `providers`; declaring it keeps subclass resolution to a single rule.
+ registers_subclasses_via { providers }
+
def provider_class
raise ::NotImplementedError, 'You must implement provider_class method for this gateway.'
end
diff --git a/spree/core/app/models/spree/price_rule.rb b/spree/core/app/models/spree/price_rule.rb
index 12f0d535b4..8b97769da9 100644
--- a/spree/core/app/models/spree/price_rule.rb
+++ b/spree/core/app/models/spree/price_rule.rb
@@ -28,11 +28,6 @@ module Spree
''
end
- # Pull the rule registry off the global pricing config so
- # PreferenceSchema's `.subclasses_with_preference_schema` can power
- # the admin's "Add rule" picker.
- def self.registered_subclasses
- Array(Spree.pricing&.rules)
- end
+ registers_subclasses_via { Array(Spree.pricing&.rules) }
end
end
diff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rb
index 310dadb212..0c0ff28012 100644
--- a/spree/core/app/models/spree/product.rb
+++ b/spree/core/app/models/spree/product.rb
@@ -111,6 +111,13 @@ module Spree
has_many :product_collections, class_name: 'Spree::ProductCollection', dependent: :destroy_async, inverse_of: :product
has_many :collections, through: :product_collections
+ # Dropped with the product so a deleted product stops excluding itself from
+ # delivery methods. Destroyed inline rather than async — a product sits in
+ # at most a handful of exclusion rules, and deferring it would leave the
+ # rule reporting an id the API can no longer resolve.
+ has_many :delivery_method_rule_products, class_name: 'Spree::DeliveryMethodRuleProduct',
+ dependent: :destroy, inverse_of: :product
+
has_many :product_promotion_rules, class_name: 'Spree::ProductPromotionRule'
has_many :promotion_rules, through: :product_promotion_rules, class_name: 'Spree::PromotionRule'
diff --git a/spree/core/app/models/spree/promotion_action.rb b/spree/core/app/models/spree/promotion_action.rb
index f7007fb4b3..8bd26444c0 100644
--- a/spree/core/app/models/spree/promotion_action.rb
+++ b/spree/core/app/models/spree/promotion_action.rb
@@ -4,6 +4,8 @@ module Spree
class PromotionAction < Spree.base_class
has_prefix_id :pact
+ registers_subclasses_via { Spree.promotions.actions }
+
acts_as_paranoid
belongs_to :promotion, class_name: 'Spree::Promotion', touch: true
diff --git a/spree/core/app/models/spree/promotion_rule.rb b/spree/core/app/models/spree/promotion_rule.rb
index e061f414bd..b61bf7daa8 100644
--- a/spree/core/app/models/spree/promotion_rule.rb
+++ b/spree/core/app/models/spree/promotion_rule.rb
@@ -3,6 +3,8 @@ module Spree
class PromotionRule < Spree.base_class
has_prefix_id :prorule
+ registers_subclasses_via { Spree.promotions.rules }
+
belongs_to :promotion, class_name: 'Spree::Promotion', inverse_of: :promotion_rules, touch: true
delegate :stores, to: :promotion
diff --git a/spree/core/app/models/spree/stock/package.rb b/spree/core/app/models/spree/stock/package.rb
index ab3cd855c7..cdd0f95214 100644
--- a/spree/core/app/models/spree/stock/package.rb
+++ b/spree/core/app/models/spree/stock/package.rb
@@ -92,18 +92,17 @@ module Spree
end
# Delivery methods eligible to serve this package: the method's
- # fulfillment_type must be supported by every item, minus any
- # per-product exclusions. Replaces the ShippingCategory-based
- # Package#shipping_methods.
+ # fulfillment_type must be supported by every item. Replaces the
+ # ShippingCategory-based Package#shipping_methods. Per-product
+ # exclusions are DeliveryMethodRules::ExcludedProductsRule, enforced
+ # with the other rules in the Estimator's method filter.
#
# @return [ActiveRecord::Relation<Spree::DeliveryMethod>]
def eligible_delivery_methods
types = fulfillment_types
return Spree::DeliveryMethod.none if types.empty?
- methods = Spree::DeliveryMethod.by_fulfillment_type(types)
- excluded_ids = contents.flat_map { |item| item.variant.product.excluded_delivery_method_ids || [] }.uniq
- excluded_ids.any? ? methods.where.not(id: excluded_ids) : methods
+ Spree::DeliveryMethod.by_fulfillment_type(types)
end
# @deprecated Use {#eligible_delivery_methods}; removed in 6.1.
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index c018a3d2ec..543884a502 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -813,6 +813,9 @@ en:
deleted: Deleted
delivery: Delivery
delivery_method_rule_types:
+ excluded_products_rule:
+ description: Blocks the delivery method for packages containing the selected products
+ name: Excluded products
item_total_rule:
description: Limits the delivery method to carts within an item total range
name: Item total
diff --git a/spree/core/db/migrate/20260806000001_create_spree_delivery_method_rule_products.rb b/spree/core/db/migrate/20260806000001_create_spree_delivery_method_rule_products.rb
new file mode 100644
index 0000000000..3352216621
--- /dev/null
+++ b/spree/core/db/migrate/20260806000001_create_spree_delivery_method_rule_products.rb
@@ -0,0 +1,22 @@
+class CreateSpreeDeliveryMethodRuleProducts < ActiveRecord::Migration[7.2]
+ def change
+ create_table :spree_delivery_method_rule_products do |t|
+ t.references :delivery_method_rule, null: false, index: false
+ t.references :product, null: false
+
+ t.timestamps
+ end
+
+ add_index :spree_delivery_method_rule_products, [:delivery_method_rule_id, :product_id],
+ unique: true, name: 'idx_delivery_method_rule_products_uniqueness'
+
+ # Never writable through any API or UI, so there is no data to carry over —
+ # per-product exclusions live on ExcludedProductsRule now
+ # (docs/plans/6.0-delivery-method-rules.md, decision 2026-08-06).
+ if connection.adapter_name.downcase.include?('postgresql')
+ remove_column :spree_products, :excluded_delivery_method_ids, :jsonb
+ else
+ remove_column :spree_products, :excluded_delivery_method_ids, :json
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index 22e6a03e0d..234a6695ad 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -209,7 +209,8 @@ module Spree
# Delivery-method eligibility rule kinds (docs/plans/6.0-delivery-method-rules.md).
Rails.application.config.spree.delivery_method_rules.concat [
Spree::DeliveryMethodRules::ItemTotalRule,
- Spree::DeliveryMethodRules::WeightRule
+ Spree::DeliveryMethodRules::WeightRule,
+ Spree::DeliveryMethodRules::ExcludedProductsRule
]
Rails.application.config.spree.calculators.promotion_actions_create_adjustments = [
diff --git a/spree/core/spec/models/spree/delivery_method_rule_spec.rb b/spree/core/spec/models/spree/delivery_method_rule_spec.rb
index 48e0f7beb8..1670a8d9f8 100644
--- a/spree/core/spec/models/spree/delivery_method_rule_spec.rb
+++ b/spree/core/spec/models/spree/delivery_method_rule_spec.rb
@@ -2,7 +2,7 @@ require 'spec_helper'
describe Spree::DeliveryMethodRule, type: :model do
let(:store) { @default_store }
- let(:delivery_method) { create(:shipping_method) }
+ let(:delivery_method) { create(:delivery_method) }
let(:package) do
order = create(:order_with_line_items, store: store, line_items_price: 20)
Spree::Stock::Coordinator.new(order).packages.first
@@ -54,6 +54,63 @@ describe Spree::DeliveryMethodRule, type: :model do
end
end
+ describe Spree::DeliveryMethodRules::ExcludedProductsRule do
+ it 'blocks packages containing an excluded product and fails open without products' do
+ rule = described_class.create!(delivery_method: delivery_method)
+ expect(rule.eligible?(package)).to be(true)
+
+ rule.products << package.contents.first.variant.product
+ expect(rule.eligible?(package)).to be(false)
+ end
+
+ it 'passes packages containing none of the excluded products' do
+ rule = described_class.create!(delivery_method: delivery_method, products: [create(:product)])
+
+ expect(rule.eligible?(package)).to be(true)
+ end
+ end
+
+ # One PATCH saves the method and its conditions together, mirroring
+ # Promotion#rules= / PriceList#rules=.
+ describe 'Spree::DeliveryMethod#rules=' do
+ it 'creates rules alongside a new method in one save' do
+ method = Spree::DeliveryMethod.new(name: 'Express', store: store, fulfillment_type: 'shipping')
+ method.rules = [{ type: 'item_total_rule', preferences: { minimum_amount: 50 } }]
+ method.save!
+
+ expect(method.delivery_method_rules.reload.sole.preferred_minimum_amount).to eq(50)
+ end
+
+ it 'updates, adds and removes rules to match the payload' do
+ existing = Spree::DeliveryMethodRules::ItemTotalRule.create!(
+ delivery_method: delivery_method, preferences: { minimum_amount: 10 }
+ )
+
+ delivery_method.rules = [
+ { id: existing.prefixed_id, type: 'item_total_rule', preferences: { minimum_amount: 99 } },
+ { type: 'weight_rule', preferences: { maximum_weight: 5 } }
+ ]
+ delivery_method.save!
+
+ expect(delivery_method.delivery_method_rules.reload.size).to eq(2)
+ expect(existing.reload.preferred_minimum_amount).to eq(99)
+
+ delivery_method.rules = []
+ delivery_method.save!
+
+ expect(delivery_method.delivery_method_rules.reload).to be_empty
+ end
+
+ it 'assigns products on a brand-new association-backed rule' do
+ product = create(:product)
+ method = Spree::DeliveryMethod.new(name: 'Express', store: store, fulfillment_type: 'shipping')
+ method.rules = [{ type: 'excluded_products_rule', product_ids: [product.id] }]
+ method.save!
+
+ expect(method.delivery_method_rules.reload.sole.products).to eq([product])
+ end
+ end
+
describe 'Estimator enforcement' do
let(:order) { create(:order_with_line_items, store: store, ship_address: create(:address)) }
diff --git a/spree/core/spec/models/spree/stock/package_spec.rb b/spree/core/spec/models/spree/stock/package_spec.rb
index 2dde784c51..b41a99cefa 100644
--- a/spree/core/spec/models/spree/stock/package_spec.rb
+++ b/spree/core/spec/models/spree/stock/package_spec.rb
@@ -60,8 +60,8 @@ module Spree
# Replaces the ShippingCategory intersection (#2804) with the 6.0
# fulfillment-type eligibility semantics.
describe '#eligible_delivery_methods' do
- let!(:shipping_dm) { create(:shipping_method) }
- let!(:digital_dm) { create(:digital_shipping_method) }
+ let!(:shipping_dm) { create(:delivery_method) }
+ let!(:digital_dm) { create(:digital_delivery_method) }
it 'returns methods whose fulfillment type every item supports' do
variant1 = create(:product).default_variant
@@ -83,14 +83,8 @@ module Spree
expect(package.eligible_delivery_methods).to be_empty
end
- it 'subtracts per-product exclusions' do
- excluded = create(:shipping_method)
- variant = create(:product, excluded_delivery_method_ids: [excluded.id]).default_variant
- contents = [ContentItem.new(build(:inventory_unit, variant_id: variant.id))]
-
- package = Package.new(stock_location, contents)
- expect(package.eligible_delivery_methods).to eq([shipping_dm])
- end
+ # Per-product exclusions moved to DeliveryMethodRules::ExcludedProductsRule,
+ # covered in delivery_method_rule_spec.rb.
end
it 'can convert to a fulfillment' do