Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add delivery method rules (Phase 1)
Damian Legawiecf45134ddde43
diff --git a/docs/plans/6.0-delivery-method-rules.md b/docs/plans/6.0-delivery-method-rules.mdnew file mode 100644index 0000000000..cc39efdced--- /dev/null+++ b/docs/plans/6.0-delivery-method-rules.md@@ -0,0 +1,225 @@+# Delivery Method Rules++**Status:** Design Finalized+**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++## Summary++Move delivery-method *eligibility* out of pricing calculators and into first-class+`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` /+`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+calculator-priced *and* provider-priced methods obey the same eligibility.++## Problem++Eligibility bounds are currently conflated with pricing, twice over:++1. `minimum_item_total` / `maximum_item_total` / `minimum_weight` /+ `maximum_weight` are **preferences on `Calculator::Shipping::FlatRate`+ only** (`flat_rate.rb:9-13`). FlexiRate, PerItem, PriceSack and+ FlatPercentItemTotal offer no bounds at all — eligibility depends on which+ pricing formula you picked.+2. They are enforced by `compute_package` **returning nil**+ (`flat_rate.rb:20-24`) — "not eligible" is encoded as "no price". The+ `ShippingCalculator#available?(package)` hook the Estimator actually+ consults (`estimator.rb:67`) is unused by them.+3. Under `6.0-delivery-rate-provider.md`, provider-backed methods dispatch to+ the provider *instead of* the calculator — **methods rated by+ EasyPost/Shippo silently lose their bounds** because the object carrying+ them is bypassed.+4. In the dashboard the bounds render inside the "Rate calculator" preference+ form, which reads as pricing configuration (screenshot review 2026-07-29).++Every surveyed platform separates the concerns: Shopify puts weight/price+**conditions** directly on the zone rate; Saleor uses **columns on the+method** (+ per-channel price bounds); Medusa v2 attaches typed+**ShippingOptionRule** records; Vendure gives ShippingMethod a dedicated+**ShippingEligibilityChecker** strategy parallel to its calculator. Nobody+buries eligibility in the pricing object.++## Key Decisions (do not deviate without discussion)++- **Mirror `Spree::PaymentMethodRule`, don't invent a framework.** STI base+ `Spree::DeliveryMethodRule` on `spree_delivery_method_rules`, subclasses+ under `app/models/spree/delivery_method_rules/`, preference-schema-driven+ config, registry-validated `type`. Where this plan and+ `5.7-payment-method-rules.md` overlap (base-class shape, AND semantics,+ empty-preference fail-open, registry, dashboard-only management), the+ payment plan's wording is authoritative — keep the two symmetric.+- **Rules over method columns.** Saleor-style columns would cover Phase 1 but+ dead-ends the channel/market/customer-group axis the payment side already+ committed to. One pattern, both methods.+- **No rules = eligible everywhere.** Zero behavior change on upgrade before+ the data task runs.+- **AND semantics; one rule instance per type per method** (uniqueness on+ `[:type, :delivery_method_id]`).+- **One enforcement seam: the Estimator's method filter.** `Stock::Estimator`+ gains `delivery_method.eligible_for_package?(package)` in the same+ filter chain as `calculator.available?` (`estimator.rb:61-71`). All three+ entry points (`Fulfillment#refresh_rates`, `OrderRouting::Strategy::Rules`,+ `Carts::EstimateShippingRates`) get enforcement for free — the same+ argument that shaped the delivery-rate-provider plan. There is no+ admin-bypass concept here (unlike payment rules): the Estimator is the only+ rate source, and weight/total bounds are logistics constraints, not+ storefront gating.+- **Rules evaluate the package + its owner** (`package.weight`,+ `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 /+ Market / CustomerGroup ride the payment-rules wave so both sets appear in+ the dashboard together.+- **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+ values are a separate future project; no per-rule unit preference.+- **Rules are method-scoped only** (2026-07-29) — no zone context, ever.+ Different bounds per region = two methods, per the regional-methods+ decision. The Estimator's zone filter runs independently.+- **Phase 1 ships with the 6.0 core-rewrite finishing work** (2026-07-29) —+ alongside the fulfillment-plan finishing list, before the final gates.+ Closes the provider bypass before any rate-provider implementation+ starts.+- **Calculator bounds become a one-release deprecation bridge.** FlatRate's+ four preferences keep working (its `compute_package` nil-guards stay);+ writing them logs a `Spree::Deprecation` warning. The data task converts+ them to rules; the preferences are deleted in 6.1.+- **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).++## Design Details++### Base class + rules++```ruby+# app/models/spree/delivery_method_rule.rb+module Spree+ class DeliveryMethodRule < Spree.base_class+ has_prefix_id :dmrule++ belongs_to :delivery_method, class_name: 'Spree::DeliveryMethod',+ inverse_of: :delivery_method_rules, touch: true++ delegate :store, to: :delivery_method++ attribute :active, :boolean, default: true++ validates :type, :delivery_method, presence: true+ validates :type, uniqueness: { scope: [:delivery_method_id, *spree_base_uniqueness_scope] }+ validate :type_must_be_registered++ # @param package [Spree::Stock::Package]+ # @return [Boolean]+ def eligible?(_package) = raise NotImplementedError+ end+end++# app/models/spree/delivery_method_rules/item_total_rule.rb+class Spree::DeliveryMethodRules::ItemTotalRule < Spree::DeliveryMethodRule+ preference :minimum_amount, :decimal, default: nil, nullable: true+ preference :maximum_amount, :decimal, default: nil, nullable: true++ def eligible?(package)+ total = package.item_total+ return false if preferred_minimum_amount.present? && total < preferred_minimum_amount+ return false if preferred_maximum_amount.present? && total > preferred_maximum_amount++ true+ end+end++# app/models/spree/delivery_method_rules/weight_rule.rb — same shape over package.weight+```++Boundary semantics: rules use inclusive minimum / inclusive maximum+(`total < min` fails, `total > max` fails). Note the legacy FlatRate guards+are exclusive on the minimum (`>= package.item_total`); the data task keeps+the merchant's stored numbers and accepts the off-by-one-cent boundary+change — it is a bug fix, not a regression.++### DeliveryMethod + Estimator++```ruby+class Spree::DeliveryMethod < Spree.base_class+ has_many :delivery_method_rules, class_name: 'Spree::DeliveryMethodRule',+ dependent: :destroy, inverse_of: :delivery_method++ # AND over active rules; no rules = eligible.+ def eligible_for_package?(package)+ delivery_method_rules.select(&:active).all? { |rule| rule.eligible?(package) }+ end+end+```++`Stock::Estimator#shipping_methods` adds `method.eligible_for_package?(package)`+alongside the existing zone/currency/`calculator.available?` checks. That is+the entire runtime change.++### Registry++`Spree.delivery_method_rules` (engine-defaulted array of class names,+plugin-extensible) + `type_must_be_registered` — same shape as+`Spree.payment_method_rules` / `Spree.order_routing.rules`.++### Admin API v3 + dashboard++- `GET/POST/PATCH/DELETE /api/v3/admin/delivery_methods/:id/rules` (flat+ params: `type` wire shorthand + `preferences`), `GET+ /api/v3/admin/delivery_method_rules/types` discovery with+ `preference_schema` — mirroring the payment plan's endpoints.+- Dashboard: "Conditions" card on the delivery-method sheet listing rules+ with `PreferencesForm`-rendered config; the calculator card stays+ pricing-only. i18n in all six locales.++## Migration Path++1. Table + base class + ItemTotal/Weight rules + registry (additive).+2. Estimator filter line + `eligible_for_package?`.+3. Deprecation warnings on writing the four FlatRate bound preferences.+4. Admin API + dashboard Conditions card + SDK + OpenAPI.+5. Data task `spree:migrate_calculator_bounds_to_delivery_method_rules`:+ for each FlatRate calculator with any bound set, create the matching+ 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.++## Constraints on Current Work++- **Don't add eligibility preferences to any calculator** — new constraints+ wait for rules.+- **Don't build storefront features on the FlatRate bounds** — they are a+ deprecation bridge.+- The Estimator filter chain (`estimator.rb:61-71`) is the only place+ eligibility may hook — no per-call-site checks in controllers/services.++## Resolved Questions (interactive review, 2026-07-29)++1. **Weight unit** → implicit store unit, raw-number comparison (legacy+ parity); dashboard label shows the store's unit_system. Unit-aware+ weights are out of scope.+2. **Per-zone bounds** → never. Method-scoped rules only; per-region bounds+ are separate methods.+3. **Timing** → Phase 1 rides the 6.0 core-rewrite finishing work+ (ItemTotal/Weight + Estimator seam + admin CRUD + Conditions card + data+ task); Channel/Market/CustomerGroup land later with payment rules.++## Open Questions++None currently.++## References++- `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)+- `flat_rate.rb:9-24`, `estimator.rb:61-71`, `shipping_calculator.rb:11`diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.tsindex 89edc56c53..1e003ae34b 100644--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@ -129,6 +129,7 @@ import type {PaymentMethodCreateParams,PaymentMethodType,PaymentMethodUpdateParams,+ PreferenceField,PriceBulkUpsertRow,PriceCreateParams,PriceListCreateParams,@@ -173,6 +174,7 @@ import type {CustomField,CustomFieldDefinition,DeliveryMethod,+ DeliveryMethodRule,DeliveryZone,Discount,Export,@@ -1236,6 +1238,64 @@ export class AdminClient {'/delivery_methods/calculators',options,),++ /** Eligibility rules on a delivery method (item total / weight bounds, …). */+ rules: {+ list: (+ deliveryMethodId: string,+ options?: RequestOptions,+ ): Promise<PaginatedResponse<DeliveryMethodRule>> =>+ this.request<PaginatedResponse<DeliveryMethodRule>>(+ 'GET',+ `/delivery_methods/${deliveryMethodId}/rules`,+ options,+ ),++ create: (+ deliveryMethodId: string,+ params: { type: string; active?: boolean; preferences?: Record<string, unknown> },+ options?: RequestOptions,+ ): Promise<DeliveryMethodRule> =>+ this.request<DeliveryMethodRule>('POST', `/delivery_methods/${deliveryMethodId}/rules`, {+ ...options,+ body: params,+ }),++ update: (+ deliveryMethodId: string,+ id: string,+ params: { active?: boolean; preferences?: Record<string, unknown> },+ options?: RequestOptions,+ ): Promise<DeliveryMethodRule> =>+ this.request<DeliveryMethodRule>(+ 'PATCH',+ `/delivery_methods/${deliveryMethodId}/rules/${id}`,+ { ...options, body: params },+ ),++ delete: (deliveryMethodId: string, id: string, options?: RequestOptions): Promise<void> =>+ this.request<void>('DELETE', `/delivery_methods/${deliveryMethodId}/rules/${id}`, options),+ },++ /** Registered rule kinds with preference schemas for building pickers. */+ ruleTypes: (+ options?: RequestOptions,+ ): Promise<{+ data: Array<{+ type: string+ name: string+ description: string+ preference_schema: PreferenceField[]+ }>+ }> =>+ this.request<{+ data: Array<{+ type: string+ name: string+ description: string+ preference_schema: PreferenceField[]+ }>+ }>('GET', '/delivery_method_rules/types', options),}readonly deliveryZones = {diff --git a/packages/admin-sdk/src/types/generated/DeliveryMethodRule.ts b/packages/admin-sdk/src/types/generated/DeliveryMethodRule.tsnew file mode 100644index 0000000000..e041367a8d--- /dev/null+++ b/packages/admin-sdk/src/types/generated/DeliveryMethodRule.ts@@ -0,0 +1,17 @@+// Typelizer digest aa3f7271558adddfc56659d58e2cf620+//+// DO NOT MODIFY: This file was automatically generated by Typelizer.++interface DeliveryMethodRule {+ id: string;+ active: boolean;+ created_at: string;+ updated_at: string;+ type: string;+ name: string;+ description: string;+ preferences: Record<string, unknown>;+ preference_schema: Array<{ key: string; type: string; default: unknown }>;+}++export default DeliveryMethodRule;diff --git a/packages/admin-sdk/src/types/generated/index.ts b/packages/admin-sdk/src/types/generated/index.tsindex 8b50d74113..2efca060bc 100644--- a/packages/admin-sdk/src/types/generated/index.ts+++ b/packages/admin-sdk/src/types/generated/index.ts@@ -1,4 +1,4 @@-// Typelizer digest 8271ff0a7517e31f05096608ee018af3+// Typelizer digest 6b82abfcfb9f93754fe40dbb09fffd80//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { default as Address } from './Address'@@ -17,6 +17,7 @@ export type { default as CustomFieldDefinition } from './CustomFieldDefinition'export type { default as CustomField } from './CustomField'export type { default as CustomerGroup } from './CustomerGroup'export type { default as Customer } from './Customer'+export type { default as DeliveryMethodRule } from './DeliveryMethodRule'export type { default as DeliveryMethod } from './DeliveryMethod'export type { default as DeliveryRate } from './DeliveryRate'export type { default as DeliveryZoneMember } from './DeliveryZoneMember'diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.tsindex f3cefe6c13..2742e0e395 100644--- a/packages/admin-sdk/src/types/index.ts+++ b/packages/admin-sdk/src/types/index.ts@@ -24,6 +24,7 @@ export type { default as CustomerGroup } from './generated/CustomerGroup'export type { default as CustomField } from './generated/CustomField'export type { default as CustomFieldDefinition } from './generated/CustomFieldDefinition'export type { default as DeliveryMethod } from './generated/DeliveryMethod'+export type { default as DeliveryMethodRule } from './generated/DeliveryMethodRule'export type { default as DeliveryRate } from './generated/DeliveryRate'export type { default as DeliveryZone } from './generated/DeliveryZone'export type { default as DeliveryZoneMember } from './generated/DeliveryZoneMember'diff --git a/packages/dashboard/src/hooks/use-delivery-methods.ts b/packages/dashboard/src/hooks/use-delivery-methods.tsindex 8de6d81e40..d292a1a537 100644--- a/packages/dashboard/src/hooks/use-delivery-methods.ts+++ b/packages/dashboard/src/hooks/use-delivery-methods.ts@@ -56,3 +56,19 @@ export function useDeleteDeliveryMethod() {},})}++export function useDeliveryMethodRules(deliveryMethodId: string | undefined) {+ return useQuery({+ queryKey: useResourceKey('delivery-methods', deliveryMethodId ?? 'noop', 'rules'),+ queryFn: () => adminClient.deliveryMethods.rules.list(deliveryMethodId as string),+ enabled: !!deliveryMethodId,+ })+}++export function useDeliveryMethodRuleTypes() {+ return useQuery({+ queryKey: useResourceKey('delivery-method-rule-types'),+ queryFn: () => adminClient.deliveryMethods.ruleTypes(),+ staleTime: 1000 * 60 * 30,+ })+}diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex aa49041073..a1441fe765 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -358,6 +358,11 @@"delivery_methods": {"add_cta": "إضافة طريقة توصيل","add_sheet_title": "طريقة توصيل جديدة",+ "conditions": {+ "add": "إضافة شرط",+ "empty": "لا توجد شروط — تُعرض الطريقة متى تطابقت مناطقها.",+ "title": "الشروط"+ },"create_description": "حدّد كيفية وصول الطلبات إلى العملاء: شحن أو تسليم رقمي أو استلام.","create_label": "إنشاء طريقة التوصيل","delete_confirm": {@@ -379,6 +384,7 @@"updated": "تم تحديث طريقة التوصيل"},"no_zones_hint": "لا توجد مناطق توصيل بعد — تنطبق الطريقة في كل مكان.",+ "pickup_locations_hint": "بدون اختيار، تُعرض جميع مواقع المخزون المفعّل فيها الاستلام.","search_placeholder": "البحث في طرق التوصيل…"},"delivery_zones": {@@ -586,6 +592,9 @@"fulfillment_type": {"label": "نوع التنفيذ"},+ "pickup_locations": {+ "label": "مواقع الاستلام"+ },"storefront_visible": {"help": "يمكن للعملاء اختيار هذه الطريقة عند الدفع."},@@ -2254,8 +2263,12 @@"flat_percent": "Flat Percent","max_items": "Max Items","max_quantity": "الحد الأقصى للكمية",+ "maximum_item_total": "الحد الأقصى لإجمالي المنتجات",+ "maximum_weight": "الحد الأقصى للوزن","min_quantity": "الحد الأدنى للكمية","minimal_amount": "Minimal Amount",+ "minimum_item_total": "الحد الأدنى لإجمالي المنتجات",+ "minimum_weight": "الحد الأدنى للوزن","normal_amount": "Normal Amount","percent": "نسبة مئوية","preferred_amount": "كمية",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 70586f414a..c9a68ec540 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -358,6 +358,11 @@"delivery_methods": {"add_cta": "Versandart hinzufügen","add_sheet_title": "Neue Versandart",+ "conditions": {+ "add": "Bedingung hinzufügen",+ "empty": "Keine Bedingungen — die Methode wird angeboten, sobald ihre Zonen passen.",+ "title": "Bedingungen"+ },"create_description": "Konfiguriere, wie Bestellungen die Kundschaft erreichen: Versand, digital oder Abholung.","create_label": "Versandart erstellen","delete_confirm": {@@ -379,6 +384,7 @@"updated": "Versandart aktualisiert"},"no_zones_hint": "Noch keine Lieferzonen definiert — die Methode gilt überall.",+ "pickup_locations_hint": "Ohne Auswahl werden alle abholfähigen Lagerorte angeboten.","search_placeholder": "Versandarten durchsuchen…"},"delivery_zones": {@@ -586,6 +592,9 @@"fulfillment_type": {"label": "Fulfillment-Typ"},+ "pickup_locations": {+ "label": "Abholorte"+ },"storefront_visible": {"help": "Kundschaft kann diese Methode im Checkout wählen."},@@ -2254,8 +2263,12 @@"flat_percent": "Fester Prozentsatz","max_items": "Maximale Artikelanzahl","max_quantity": "Höchstmenge",+ "maximum_item_total": "Maximale Artikelsumme",+ "maximum_weight": "Maximalgewicht","min_quantity": "Mindestmenge","minimal_amount": "Mindestbetrag",+ "minimum_item_total": "Mindest-Artikelsumme",+ "minimum_weight": "Mindestgewicht","normal_amount": "Normalbetrag","percent": "Prozent","preferred_amount": "Betrag",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 0b5fd27e42..b633697ebc 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -358,6 +358,11 @@"delivery_methods": {"add_cta": "Add delivery method","add_sheet_title": "New delivery method",+ "conditions": {+ "add": "Add condition",+ "empty": "No conditions — this method is offered whenever its zones match.",+ "title": "Conditions"+ },"create_description": "Configure how orders reach customers: shipping, digital delivery or pickup.","create_label": "Create delivery method","delete_confirm": {@@ -379,6 +384,7 @@"updated": "Delivery method updated"},"no_zones_hint": "No delivery zones defined yet — the method applies everywhere.",+ "pickup_locations_hint": "No selection means every pickup-enabled stock location is offered.","search_placeholder": "Search delivery methods…"},"delivery_zones": {@@ -586,6 +592,9 @@"fulfillment_type": {"label": "Fulfillment type"},+ "pickup_locations": {+ "label": "Pickup locations"+ },"storefront_visible": {"help": "Customers can select this method at checkout."},@@ -2254,8 +2263,12 @@"flat_percent": "Flat Percent","max_items": "Max Items","max_quantity": "Maximum quantity",+ "maximum_item_total": "Maximum item total",+ "maximum_weight": "Maximum weight","min_quantity": "Minimum quantity","minimal_amount": "Minimal Amount",+ "minimum_item_total": "Minimum item total",+ "minimum_weight": "Minimum weight","normal_amount": "Normal Amount","percent": "Percent","preferred_amount": "Amount",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex ae4eda899d..f9ce82d3e4 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -358,6 +358,11 @@"delivery_methods": {"add_cta": "Ajouter une méthode","add_sheet_title": "Nouvelle méthode de livraison",+ "conditions": {+ "add": "Ajouter une condition",+ "empty": "Aucune condition — la méthode est proposée dès que ses zones correspondent.",+ "title": "Conditions"+ },"create_description": "Configurez comment les commandes parviennent aux clients : expédition, numérique ou retrait.","create_label": "Créer la méthode","delete_confirm": {@@ -379,6 +384,7 @@"updated": "Méthode de livraison mise à jour"},"no_zones_hint": "Aucune zone définie — la méthode s’applique partout.",+ "pickup_locations_hint": "Sans sélection, tous les entrepôts avec retrait activé sont proposés.","search_placeholder": "Rechercher des méthodes…"},"delivery_zones": {@@ -586,6 +592,9 @@"fulfillment_type": {"label": "Type de traitement"},+ "pickup_locations": {+ "label": "Points de retrait"+ },"storefront_visible": {"help": "Les clients peuvent choisir cette méthode au paiement."},@@ -2254,8 +2263,12 @@"flat_percent": "Pourcentage fixe","max_items": "Nombre maximal d'articles","max_quantity": "Quantité maximale",+ "maximum_item_total": "Total articles maximal",+ "maximum_weight": "Poids maximal","min_quantity": "Quantité minimale","minimal_amount": "Montant minimal",+ "minimum_item_total": "Total articles minimal",+ "minimum_weight": "Poids minimal","normal_amount": "Montant normal","percent": "Pourcentage","preferred_amount": "Montant",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 5abcf3168e..7c4a8f12a8 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -362,6 +362,11 @@"delivery_methods": {"add_cta": "Dodaj metodę dostawy","add_sheet_title": "Nowa metoda dostawy",+ "conditions": {+ "add": "Dodaj warunek",+ "empty": "Brak warunków — metoda jest oferowana, gdy pasują jej strefy.",+ "title": "Warunki"+ },"create_description": "Skonfiguruj, jak zamówienia trafiają do klientów: wysyłka, dostawa cyfrowa lub odbiór.","create_label": "Utwórz metodę dostawy","delete_confirm": {@@ -383,6 +388,7 @@"updated": "Zaktualizowano metodę dostawy"},"no_zones_hint": "Brak stref dostawy — metoda obowiązuje wszędzie.",+ "pickup_locations_hint": "Brak wyboru oznacza, że oferowane są wszystkie lokalizacje z włączonym odbiorem.","search_placeholder": "Szukaj metod dostawy…"},"delivery_zones": {@@ -590,6 +596,9 @@"fulfillment_type": {"label": "Typ realizacji"},+ "pickup_locations": {+ "label": "Punkty odbioru"+ },"storefront_visible": {"help": "Klienci mogą wybrać tę metodę przy kasie."},@@ -2282,8 +2291,12 @@"flat_percent": "Stały procent","max_items": "Maksymalna liczba pozycji","max_quantity": "Maksymalna ilość",+ "maximum_item_total": "Maksymalna wartość produktów",+ "maximum_weight": "Maksymalna waga","min_quantity": "Minimalna ilość","minimal_amount": "Kwota minimalna",+ "minimum_item_total": "Minimalna wartość produktów",+ "minimum_weight": "Minimalna waga","normal_amount": "Kwota normalna","percent": "Procent","preferred_amount": "Kwota",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 197ced3c35..add2005af8 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -358,6 +358,11 @@"delivery_methods": {"add_cta": "添加配送方式","add_sheet_title": "新建配送方式",+ "conditions": {+ "add": "添加条件",+ "empty": "无条件——只要区域匹配即提供该方式。",+ "title": "条件"+ },"create_description": "配置订单送达客户的方式:物流、数字交付或自提。","create_label": "创建配送方式","delete_confirm": {@@ -379,6 +384,7 @@"updated": "配送方式已更新"},"no_zones_hint": "尚未定义配送区域——该方式适用于所有地区。",+ "pickup_locations_hint": "未选择时,将提供所有启用自提的库存地点。","search_placeholder": "搜索配送方式…"},"delivery_zones": {@@ -586,6 +592,9 @@"fulfillment_type": {"label": "履约类型"},+ "pickup_locations": {+ "label": "自提地点"+ },"storefront_visible": {"help": "客户可在结账时选择该方式。"},@@ -2254,8 +2263,12 @@"flat_percent": "固定百分比","max_items": "最大件数","max_quantity": "最大数量",+ "maximum_item_total": "最高商品总额",+ "maximum_weight": "最大重量","min_quantity": "最小数量","minimal_amount": "最小金额",+ "minimum_item_total": "最低商品总额",+ "minimum_weight": "最小重量","normal_amount": "标准金额","percent": "百分比","preferred_amount": "金额",diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-methods.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-methods.tsxindex 2f84151928..ea593813c2 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-methods.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/delivery-methods.tsx@@ -1,17 +1,23 @@import { zodResolver } from '@hookform/resolvers/zod'-import type { DeliveryMethod } from '@spree/admin-sdk'+import type { DeliveryMethod, DeliveryMethodRule, PreferenceField } from '@spree/admin-sdk'import {adminClient,Can,mapSpreeErrorsToForm,+ PreferencesForm,ResourceTable,resourceSearchSchema,Subject,usePermissions,+ useResourceKeyBuilder,} from '@spree/dashboard-core'import {Button,Checkbox,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,Field,FieldError,FieldGroup,@@ -33,9 +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 } from 'lucide-react'-import { useEffect } from 'react'+import { PlusIcon, Trash2Icon } from 'lucide-react'+import { useEffect, useState } from 'react'import { Controller, type UseFormReturn, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { z } from 'zod/v4'@@ -44,9 +51,12 @@ import {useDeleteDeliveryMethod,useDeliveryCalculators,useDeliveryMethod,+ useDeliveryMethodRules,+ useDeliveryMethodRuleTypes,useUpdateDeliveryMethod,} from '../../../../hooks/use-delivery-methods'import { useDeliveryZones } from '../../../../hooks/use-delivery-zones'+import { useStockLocations } from '../../../../hooks/use-stock-locations'import { useTaxCategories } from '../../../../hooks/use-tax-categories'import {DELIVERY_METHOD_DEFAULTS,@@ -249,6 +259,7 @@ function EditDeliveryMethodSheet({calculator_preferences:(deliveryMethod.calculator_preferences as Record<string, unknown>) ?? {},delivery_zone_ids: deliveryMethod.delivery_zone_ids ?? [],+ stock_location_ids: deliveryMethod.stock_location_ids ?? [],})}}, [deliveryMethod, form])@@ -279,6 +290,7 @@ function EditDeliveryMethodSheet({<div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4"><DeliveryMethodFormFields form={form} /></div>+ <ConditionsSection deliveryMethodId={id} /><SheetFooter><Buttontype="button"@@ -304,11 +316,131 @@ function EditDeliveryMethodSheet({)}+// ---------------------------------------------------------------------------+// Conditions (eligibility rules) — live-mutating, separate from the form+// ---------------------------------------------------------------------------++function ConditionsSection({ deliveryMethodId }: { deliveryMethodId: string }) {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const buildKey = useResourceKeyBuilder()+ const { data: rules } = useDeliveryMethodRules(deliveryMethodId)+ const { data: ruleTypes } = useDeliveryMethodRuleTypes()++ 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 availableTypes = (ruleTypes?.data ?? []).filter((type) => !existingTypes.has(type.type))++ return (+ <div className="flex flex-col gap-3 border-t p-4">+ <div className="flex items-center justify-between">+ <span className="font-medium text-sm">{t('admin.delivery_methods.conditions.title')}</span>+ {availableTypes.length > 0 && (+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button type="button" variant="outline" size="sm" disabled={addMutation.isPending}>+ <PlusIcon className="size-4" />+ {t('admin.delivery_methods.conditions.add')}+ </Button>+ }+ />+ <DropdownMenuContent align="end">+ {availableTypes.map((type) => (+ <DropdownMenuItem key={type.type} onClick={() => addMutation.mutate(type.type)}>+ {type.name}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )}+ </div>++ {(rules?.data ?? []).length === 0 && (+ <p className="text-muted-foreground text-sm">+ {t('admin.delivery_methods.conditions.empty')}+ </p>+ )}++ {(rules?.data ?? []).map((rule) => (+ <ConditionRuleRow+ key={rule.id}+ rule={rule}+ onSave={(preferences) => updateMutation.mutate({ id: rule.id, preferences })}+ onRemove={() => removeMutation.mutate(rule.id)}+ saving={updateMutation.isPending}+ />+ ))}+ </div>+ )+}++function ConditionRuleRow({+ rule,+ onSave,+ onRemove,+ saving,+}: {+ rule: DeliveryMethodRule+ onSave: (preferences: Record<string, unknown>) => void+ 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)++ 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>+ <Button+ type="button"+ variant="ghost"+ size="icon-sm"+ onClick={onRemove}+ aria-label={t('admin.actions.delete')}+ >+ <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>+ )}+ </div>+ )+}+function DeliveryMethodFormFields({ form }: { form: UseFormReturn<DeliveryMethodFormValues> }) {const { t } = useTranslation()const { errors } = form.formStateconst { data: calculators } = useDeliveryCalculators()const { data: zones } = useDeliveryZones()+ const { data: stockLocations } = useStockLocations()const { data: taxCategories } = useTaxCategories()const fulfillmentType = form.watch('fulfillment_type')@@ -325,11 +457,7 @@ function DeliveryMethodFormFields({ form }: { form: UseFormReturn<DeliveryMethod}))const selectedCalculator = (calculators?.data ?? []).find((c) => c.type === calculatorType)- const preferenceSchema = (selectedCalculator?.preference_schema ?? []) as Array<{- key: string- type: string- default: unknown- }>+ const preferenceSchema = (selectedCalculator?.preference_schema ?? []) as PreferenceField[]const taxCategoryOptions = [{ value: '', label: t('admin.common.none') },@@ -393,6 +521,48 @@ function DeliveryMethodFormFields({ form }: { form: UseFormReturn<DeliveryMethod/></Field>+ {fulfillmentType === 'pickup' && (+ <Field>+ <FieldLabel>{t('admin.fields.delivery_method.pickup_locations.label')}</FieldLabel>+ <Controller+ name="stock_location_ids"+ control={form.control}+ render={({ field }) => (+ <div className="flex flex-col gap-2">+ <span className="text-muted-foreground text-xs">+ {t('admin.delivery_methods.pickup_locations_hint')}+ </span>+ {(stockLocations?.data ?? []).map((location) => {+ const checked = field.value.includes(location.id)+ return (+ <label+ key={location.id}+ htmlFor={`pickup-location-${location.id}`}+ className="flex items-center gap-2 text-sm"+ >+ <Checkbox+ id={`pickup-location-${location.id}`}+ checked={checked}+ onCheckedChange={(next) => {+ field.onChange(+ next+ ? [...field.value, location.id]+ : field.value.filter(+ (locationId: string) => locationId !== location.id,+ ),+ )+ }}+ />+ {location.name}+ </label>+ )+ })}+ </div>+ )}+ />+ </Field>+ )}+{(fulfillmentType === 'shipping' || fulfillmentType === 'pickup_point') && (<><Field>@@ -421,28 +591,17 @@ function DeliveryMethodFormFields({ form }: { form: UseFormReturn<DeliveryMethod/></Field>- {preferenceSchema- .filter((preference) => preference.type !== 'boolean')- .map((preference) => (- <Field key={preference.key}>- <FieldLabel htmlFor={`calculator-${preference.key}`}>- {t(`admin.fields.calculator.${preference.key}.label`, {- defaultValue: preference.key,- })}- </FieldLabel>- <Controller- name={`calculator_preferences.${preference.key}`}- control={form.control}- render={({ field }) => (- <Input- id={`calculator-${preference.key}`}- value={(field.value as string | number | undefined)?.toString() ?? ''}- onChange={(e) => field.onChange(e.target.value)}- />- )}- />- </Field>- ))}+ <Controller+ name="calculator_preferences"+ control={form.control}+ render={({ field }) => (+ <PreferencesForm+ schema={preferenceSchema}+ values={(field.value ?? {}) as Record<string, unknown>}+ onChange={field.onChange}+ />+ )}+ /><Field><FieldLabel>{t('admin.fields.delivery_method.delivery_zones.label')}</FieldLabel>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.rbnew file mode 100644index 0000000000..c4e34209aa--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/delivery_method_rules_controller.rb@@ -0,0 +1,38 @@+module Spree+ module Api+ module V3+ module Admin+ class DeliveryMethodRulesController < ResourceController+ scoped_resource :settings++ # GET /api/v3/admin/delivery_method_rules/types+ # Registered rule kinds with preference schemas for admin pickers.+ def types+ authorize! :create, Spree::DeliveryMethodRule++ data = Spree.delivery_method_rules.map do |klass|+ {+ type: klass.api_type,+ name: klass.human_name,+ description: klass.human_description,+ preference_schema: klass.serialized_preference_schema+ }+ end++ render json: { data: data }+ end++ protected++ def model_class+ Spree::DeliveryMethodRule+ end++ def serializer_class+ Spree.api.admin_delivery_method_rule_serializer+ end+ end+ end+ end+ end+enddiff --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.rbnew file mode 100644index 0000000000..1487609ae5--- /dev/null+++ b/spree/api/app/controllers/spree/api/v3/admin/delivery_methods/rules_controller.rb@@ -0,0 +1,86 @@+module Spree+ module Api+ module V3+ module Admin+ module DeliveryMethods+ # Eligibility rules nested under a delivery method. `type` is the+ # wire shorthand from GET /delivery_method_rules/types.+ class RulesController < ResourceController+ scoped_resource :settings++ def create+ rule_class = Spree.delivery_method_rules.detect do |klass|+ klass.api_type == params[:type].to_s || klass.to_s == params[:type].to_s+ end++ if rule_class.nil?+ return render_error(+ code: ERROR_CODES[:validation_error],+ message: Spree.t('errors.messages.invalid_delivery_method_rule'),+ status: :unprocessable_entity+ )+ end++ @resource = rule_class.new(delivery_method: parent, active: active_param)+ assign_rule_preferences(@resource)+ authorize_resource!(@resource, :create)++ if @resource.save+ render json: serialize_resource(@resource), status: :created+ else+ render_validation_error(@resource.errors)+ end+ end++ def update+ @resource.active = active_param unless params[:active].nil?+ assign_rule_preferences(@resource)++ if @resource.save+ render json: serialize_resource(@resource)+ else+ render_validation_error(@resource.errors)+ end+ end++ protected++ def model_class+ Spree::DeliveryMethodRule+ end++ def serializer_class+ Spree.api.admin_delivery_method_rule_serializer+ end++ def scope+ parent.delivery_method_rules+ end++ def permitted_params+ params.permit(:type, :active, preferences: {})+ end++ private++ def parent+ @parent ||= Spree::DeliveryMethod.accessible_by(current_ability, :update).find_by_prefix_id!(params[:delivery_method_id])+ end++ def active_param+ params[:active].nil? ? true : ActiveModel::Type::Boolean.new.cast(params[:active])+ end++ def assign_rule_preferences(rule)+ (permitted_params[:preferences] || {}).each do |key, value|+ next unless rule.has_preference?(key)++ rule.set_preference(key, value)+ end+ end+ end+ end+ end+ end+ end+enddiff --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.rbnew file mode 100644index 0000000000..a3c241f6f5--- /dev/null+++ b/spree/api/app/serializers/spree/api/v3/admin/delivery_method_rule_serializer.rb@@ -0,0 +1,33 @@+module Spree+ module Api+ module V3+ module Admin+ class DeliveryMethodRuleSerializer < BaseSerializer+ typelize type: :string, active: :boolean,+ preferences: 'Record<string, unknown>',+ preference_schema: "Array<{ key: string; type: string; default: unknown }>",+ name: :string, description: :string++ attributes :active, created_at: :iso8601, updated_at: :iso8601++ # Wire shorthand (e.g. `item_total_rule`), matching the types+ # discovery endpoint.+ attribute :type do |rule|+ rule.class.api_type+ end++ attribute :name do |rule|+ rule.class.human_name+ end++ attribute :description do |rule|+ rule.class.human_description+ end++ attribute :preferences, &:serialized_preferences+ attribute :preference_schema, &:serialized_preference_schema+ end+ end+ end+ end+enddiff --git a/spree/api/config/routes.rb b/spree/api/config/routes.rbindex b457dbb378..71390ad046 100644--- a/spree/api/config/routes.rb+++ b/spree/api/config/routes.rb@@ -299,6 +299,12 @@ Spree::Core::Engine.add_routes docollection doget :calculatorsend+ resources :rules, controller: 'delivery_methods/rules', only: [:index, :show, :create, :update, :destroy]+ end+ resources :delivery_method_rules, only: [] do+ collection do+ get :types+ endendresources :delivery_zonesdiff --git a/spree/api/lib/spree/api/dependencies.rb b/spree/api/lib/spree/api/dependencies.rbindex 4a9b25170c..aec6107333 100644--- a/spree/api/lib/spree/api/dependencies.rb+++ b/spree/api/lib/spree/api/dependencies.rb@@ -94,6 +94,7 @@ module Spreeadmin_discount_serializer: 'Spree::Api::V3::Admin::DiscountSerializer',admin_tax_line_serializer: 'Spree::Api::V3::Admin::TaxLineSerializer',admin_delivery_zone_serializer: 'Spree::Api::V3::Admin::DeliveryZoneSerializer',+ admin_delivery_method_rule_serializer: 'Spree::Api::V3::Admin::DeliveryMethodRuleSerializer',admin_delivery_zone_member_serializer: 'Spree::Api::V3::Admin::DeliveryZoneMemberSerializer',admin_fee_serializer: 'Spree::Api::V3::Admin::FeeSerializer',admin_customer_serializer: 'Spree::Api::V3::Admin::CustomerSerializer',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.rbnew file mode 100644index 0000000000..a1b58584c6--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/delivery_method_rules_controller_spec.rb@@ -0,0 +1,20 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::DeliveryMethodRulesController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ before { request.headers.merge!(headers) }++ describe 'GET #types' do+ it 'lists registered rule kinds with preference schemas' do+ 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')+ 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')+ end+ end+enddiff --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.rbnew file mode 100644index 0000000000..02e281c9e9--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/admin/delivery_methods/rules_controller_spec.rb@@ -0,0 +1,87 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Admin::DeliveryMethods::RulesController, type: :controller do+ render_views++ include_context 'API v3 Admin authenticated'++ let!(:delivery_method) { create(:shipping_method, name: 'Standard') }++ before { request.headers.merge!(headers) }++ describe 'GET #index' do+ let!(:rule) do+ Spree::DeliveryMethodRules::ItemTotalRule.create!(+ delivery_method: delivery_method, preferences: { minimum_amount: 25 }+ )+ end++ it 'lists the method rules with schema-driven config' do+ get :index, params: { delivery_method_id: delivery_method.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ row = json_response['data'].first+ expect(row['type']).to eq('item_total_rule')+ expect(row['active']).to be(true)+ expect(row['preferences']['minimum_amount']).to eq(25.0)+ expect(row['preference_schema'].map { |field| field['key'] }).to contain_exactly('minimum_amount', 'maximum_amount')+ end+ end++ describe 'POST #create' do+ it 'creates a rule from the wire shorthand' do+ post :create, params: {+ delivery_method_id: delivery_method.prefixed_id,+ type: 'weight_rule',+ preferences: { maximum_weight: 30 }+ }, as: :json++ expect(response).to have_http_status(:created)+ expect(json_response['type']).to eq('weight_rule')+ expect(delivery_method.delivery_method_rules.sole.preferred_maximum_weight).to eq(30)+ end++ it 'rejects unregistered types' do+ post :create, params: { delivery_method_id: delivery_method.prefixed_id, type: 'bogus_rule' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end++ it 'rejects a duplicate rule kind' do+ Spree::DeliveryMethodRules::WeightRule.create!(delivery_method: delivery_method)++ post :create, params: { delivery_method_id: delivery_method.prefixed_id, type: 'weight_rule' }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ end+ end++ describe 'PATCH #update' do+ let!(:rule) { Spree::DeliveryMethodRules::ItemTotalRule.create!(delivery_method: delivery_method) }++ it 'updates preferences and active flag' do+ patch :update, params: {+ delivery_method_id: delivery_method.prefixed_id,+ id: rule.prefixed_id,+ active: false,+ preferences: { minimum_amount: 50 }+ }, as: :json++ expect(response).to have_http_status(:ok)+ rule.reload+ expect(rule.active).to be(false)+ expect(rule.preferred_minimum_amount).to eq(50)+ end+ end++ describe 'DELETE #destroy' do+ let!(:rule) { Spree::DeliveryMethodRules::ItemTotalRule.create!(delivery_method: delivery_method) }++ it 'removes the rule' do+ delete :destroy, params: { delivery_method_id: delivery_method.prefixed_id, id: rule.prefixed_id }, as: :json++ expect(response).to have_http_status(:no_content)+ expect(delivery_method.delivery_method_rules.count).to eq(0)+ end+ end+enddiff --git a/spree/core/app/models/spree/calculator/shipping/flat_rate.rb b/spree/core/app/models/spree/calculator/shipping/flat_rate.rbindex eb0cbf660f..1e6ed1555f 100644--- a/spree/core/app/models/spree/calculator/shipping/flat_rate.rb+++ b/spree/core/app/models/spree/calculator/shipping/flat_rate.rb@@ -6,11 +6,11 @@ module Spreepreference :amount, :decimal, default: 0preference :currency, :string, default: -> { Spree::Store.default.default_currency }- preference :minimum_item_total, :decimal, default: nil, nullable: true- preference :maximum_item_total, :decimal, default: nil, nullable: true+ preference :minimum_item_total, :decimal, default: nil, nullable: true, deprecated: 'Use a Spree::DeliveryMethodRules rule on the delivery method instead; removed in Spree 6.1.'+ preference :maximum_item_total, :decimal, default: nil, nullable: true, deprecated: 'Use a Spree::DeliveryMethodRules rule on the delivery method instead; removed in Spree 6.1.'- preference :minimum_weight, :decimal, default: nil, nullable: true- preference :maximum_weight, :decimal, default: nil, nullable: true+ preference :minimum_weight, :decimal, default: nil, nullable: true, deprecated: 'Use a Spree::DeliveryMethodRules rule on the delivery method instead; removed in Spree 6.1.'+ preference :maximum_weight, :decimal, default: nil, nullable: true, deprecated: 'Use a Spree::DeliveryMethodRules rule on the delivery method instead; removed in Spree 6.1.'def self.descriptionSpree.t(:shipping_flat_rate_per_order)diff --git a/spree/core/app/models/spree/delivery_method.rb b/spree/core/app/models/spree/delivery_method.rbindex 0a04d2007b..3f60c34abf 100644--- a/spree/core/app/models/spree/delivery_method.rb+++ b/spree/core/app/models/spree/delivery_method.rb@@ -27,6 +27,12 @@ module Spreehas_many :delivery_rates, class_name: 'Spree::DeliveryRate', inverse_of: :delivery_methodhas_many :fulfillments, through: :delivery_rates, class_name: 'Spree::Fulfillment'+ has_many :delivery_method_stock_locations, class_name: 'Spree::DeliveryMethodStockLocation',+ dependent: :destroy, inverse_of: :delivery_method+ has_many :delivery_method_rules, class_name: 'Spree::DeliveryMethodRule',+ dependent: :destroy, inverse_of: :delivery_method+ has_many :pickup_locations, through: :delivery_method_stock_locations, source: :stock_location+has_many :delivery_method_zones, class_name: 'Spree::DeliveryMethodZone',foreign_key: 'delivery_method_id'has_many :delivery_zones, through: :delivery_method_zones, class_name: 'Spree::DeliveryZone'@@ -114,6 +120,25 @@ module Spree@provider ||= (fulfillment_provider.presence || 'Spree::FulfillmentProvider::Manual').constantize.newend+ # 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.+ #+ # @param package [Spree::Stock::Package]+ # @return [Boolean]+ def eligible_for_package?(package)+ delivery_method_rules.select(&:active).all? { |rule| rule.eligible?(package) }+ end++ # Stock locations this method can fulfill from. For pickup methods an+ # empty set means every active pickup-enabled location qualifies.+ #+ # @return [ActiveRecord::Relation<Spree::StockLocation>]+ def available_pickup_locations+ configured = pickup_locations.merge(Spree::StockLocation.active)+ configured.exists? ? configured : Spree::StockLocation.active.pickup_enabled+ end+# The third-party pickup point network behind a pickup_point method.## @return [Spree::PickupPointProvider::Base, nil]diff --git a/spree/core/app/models/spree/delivery_method_rule.rb b/spree/core/app/models/spree/delivery_method_rule.rbnew file mode 100644index 0000000000..fb3ff79a9d--- /dev/null+++ b/spree/core/app/models/spree/delivery_method_rule.rb@@ -0,0 +1,53 @@+module Spree+ # Eligibility constraint on a delivery method, evaluated against the stock+ # package in the Estimator's method filter — the single seam every rate+ # consumer flows through, so calculator- and provider-priced methods obey+ # the same rules. AND semantics across a method's active rules; a method+ # with no rules is eligible everywhere.+ # See docs/plans/6.0-delivery-method-rules.md.+ class DeliveryMethodRule < Spree.base_class+ include Spree::PreferenceSchema++ has_prefix_id :dmrule++ belongs_to :delivery_method, class_name: 'Spree::DeliveryMethod',+ inverse_of: :delivery_method_rules, touch: true++ delegate :store, to: :delivery_method++ attribute :active, :boolean, default: true++ validates :type, :delivery_method, presence: true+ # One instance of each rule kind per method — duplicates would either be+ # a no-op or contradict themselves under AND semantics.+ validates :type, uniqueness: { scope: [:delivery_method_id, *spree_base_uniqueness_scope] }+ validate :type_must_be_registered++ scope :active, -> { where(active: true) }++ # @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)+ end++ # @return [String] localized description for the rule kind+ def self.human_description+ Spree.t("delivery_method_rule_types.#{api_type}.description", default: '')+ end++ # @param package [Spree::Stock::Package]+ # @return [Boolean]+ def eligible?(_package)+ raise NotImplementedError, "Please implement 'eligible?(package)' in your rule: #{self.class.name}"+ end++ private++ def type_must_be_registered+ return if type.blank?+ return if Spree.delivery_method_rules.any? { |rule| rule.to_s == type }++ errors.add(:type, Spree.t(:invalid_delivery_method_rule, scope: [:errors, :messages], default: 'is not a registered delivery method rule'))+ end+ end+enddiff --git a/spree/core/app/models/spree/delivery_method_rules/item_total_rule.rb b/spree/core/app/models/spree/delivery_method_rules/item_total_rule.rbnew file mode 100644index 0000000000..94a76a5822--- /dev/null+++ b/spree/core/app/models/spree/delivery_method_rules/item_total_rule.rb@@ -0,0 +1,19 @@+module Spree+ module DeliveryMethodRules+ # Bounds the method by the package's item total (inclusive min/max in the+ # owner's currency). Empty preferences pass — half-configured rules fail+ # open per-rule, matching the PromotionRule/PriceRule convention.+ class ItemTotalRule < Spree::DeliveryMethodRule+ preference :minimum_amount, :decimal, default: nil, nullable: true+ preference :maximum_amount, :decimal, default: nil, nullable: true++ def eligible?(package)+ total = package.item_total+ return false if preferred_minimum_amount.present? && total < preferred_minimum_amount+ return false if preferred_maximum_amount.present? && total > preferred_maximum_amount++ true+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/delivery_method_rules/weight_rule.rb b/spree/core/app/models/spree/delivery_method_rules/weight_rule.rbnew file mode 100644index 0000000000..39594fcd26--- /dev/null+++ b/spree/core/app/models/spree/delivery_method_rules/weight_rule.rb@@ -0,0 +1,19 @@+module Spree+ module DeliveryMethodRules+ # Bounds the method by the package weight (inclusive min/max). Compares+ # raw numbers in the store's implicit weight unit — the same semantics as+ # variant weights themselves.+ class WeightRule < Spree::DeliveryMethodRule+ preference :minimum_weight, :decimal, default: nil, nullable: true+ preference :maximum_weight, :decimal, default: nil, nullable: true++ def eligible?(package)+ weight = package.weight+ return false if preferred_minimum_weight.present? && weight < preferred_minimum_weight+ return false if preferred_maximum_weight.present? && weight > preferred_maximum_weight++ true+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/permission_sets/configuration_management.rb b/spree/core/app/models/spree/permission_sets/configuration_management.rbindex dafdfc43e6..f7bbe73788 100644--- a/spree/core/app/models/spree/permission_sets/configuration_management.rb+++ b/spree/core/app/models/spree/permission_sets/configuration_management.rb@@ -19,6 +19,7 @@ module Spree# Delivery configurationcan :manage, Spree::DeliveryMethod+ can :manage, Spree::DeliveryMethodRulecan :manage, Spree::DeliveryZonecan :manage, Spree::DeliveryZoneMembercan :manage, Spree::ShippingCategorydiff --git a/spree/core/app/models/spree/stock/estimator.rb b/spree/core/app/models/spree/stock/estimator.rbindex 8f244c1fff..859f388d54 100644--- a/spree/core/app/models/spree/stock/estimator.rb+++ b/spree/core/app/models/spree/stock/estimator.rb@@ -64,6 +64,7 @@ module Spreeship_method.available_to_display?(display_filter) &&ship_method.include?(order.ship_address) &&+ ship_method.eligible_for_package?(package) &&calculator.available?(package) &&(calculator.preferences[:currency].blank? ||calculator.preferences[:currency] == currency)diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex 4fc140731d..80dc993006 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -862,6 +862,13 @@ en:delete: Deletedeleted: Deleteddelivery: Delivery+ delivery_method_rule_types:+ item_total_rule:+ description: Limits the delivery method to carts within an item total range+ name: Item total+ weight_rule:+ description: Limits the delivery method to packages within a weight range+ name: Weightdepth: Depthdescription: Descriptiondestination: Destination@@ -930,6 +937,7 @@ en:discount_value_type_invalid: value_type must be flat or percentexactly_one_adjustable: must be attached to exactly one adjustableexactly_one_of_cart_or_order: must belong to exactly one of cart or order+ invalid_delivery_method_rule: is not a registered delivery method ruleinvalid_order_routing_rule: is not a registered order routing ruleinvalid_order_routing_strategy: is not a registered order routing strategyinvalid_storefront_access: is not a valid storefront access leveldiff --git a/spree/core/db/migrate/20260729130001_create_spree_delivery_method_rules.rb b/spree/core/db/migrate/20260729130001_create_spree_delivery_method_rules.rbnew file mode 100644index 0000000000..d6e904f883--- /dev/null+++ b/spree/core/db/migrate/20260729130001_create_spree_delivery_method_rules.rb@@ -0,0 +1,19 @@+class CreateSpreeDeliveryMethodRules < ActiveRecord::Migration[7.2]+ def change+ create_table :spree_delivery_method_rules do |t|+ t.string :type, null: false+ t.references :delivery_method, null: false+ t.boolean :active+ if t.respond_to?(:jsonb)+ t.jsonb :preferences+ else+ t.json :preferences+ end++ t.timestamps+ end++ add_index :spree_delivery_method_rules, [:delivery_method_id, :type], unique: true,+ name: 'idx_delivery_method_rules_uniqueness'+ end+enddiff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rbindex a24ecbced6..f45e6cb990 100644--- a/spree/core/lib/spree/core.rb+++ b/spree/core/lib/spree/core.rb@@ -309,6 +309,14 @@ module SpreeRails.application.config.spree.stock_splitters = valueend+ def self.delivery_method_rules+ Rails.application.config.spree.delivery_method_rules+ end++ def self.delivery_method_rules=(value)+ Rails.application.config.spree.delivery_method_rules = value+ end+def self.order_routingRails.application.config.spree.order_routingenddiff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rbindex fba31de4eb..a9cfeb0425 100644--- a/spree/core/lib/spree/core/engine.rb+++ b/spree/core/lib/spree/core/engine.rb@@ -14,6 +14,7 @@ module Spree:fulfillment_providers,:fulfillment_types,:stock_splitters,+ :delivery_method_rules,:order_routing,:promotions,:pricing,@@ -112,6 +113,12 @@ module Spreeapp.config.spree.order_routing.rules = []end+ # Seeded early for the same reason as order routing: initializer files+ # append custom rule kinds. Core defaults concatenate in after_initialize.+ initializer 'spree.register.delivery_method_rules', before: :load_config_initializers do |app|+ app.config.spree.delivery_method_rules = []+ end+initializer 'spree.register.metafields' do |app|app.config.spree.metafields = MetafieldsEnvironment.newapp.config.spree.metafields.types = []@@ -195,6 +202,12 @@ module SpreeSpree::OrderRouting::Rules::DefaultLocation]+ # 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+ ]+Rails.application.config.spree.calculators.promotion_actions_create_adjustments = [Spree::Calculator::FlatPercentItemTotal,Spree::Calculator::FlatRate,diff --git a/spree/core/lib/tasks/delivery_method_rules_migration.rake b/spree/core/lib/tasks/delivery_method_rules_migration.rakenew file mode 100644index 0000000000..987cd8816e--- /dev/null+++ b/spree/core/lib/tasks/delivery_method_rules_migration.rake@@ -0,0 +1,51 @@+# frozen_string_literal: true++# 5.6 → 6.0: fold the FlatRate calculator's eligibility bound preferences+# into DeliveryMethodRule rows (docs/plans/6.0-delivery-method-rules.md).+# The calculator preferences keep working as a deprecation bridge through+# 6.0; this task moves the data so the bridge can drop in 6.1.+namespace :spree do+ desc 'Convert FlatRate calculator eligibility bounds into delivery method rules'+ task migrate_calculator_bounds_to_delivery_method_rules: :environment do+ converted = 0++ Spree::Calculator::Shipping::FlatRate.where(calculable_type: %w[Spree::DeliveryMethod Spree::ShippingMethod]).find_each do |calculator|+ delivery_method = Spree::DeliveryMethod.unscoped.find_by(id: calculator.calculable_id)+ next unless delivery_method++ prefs = calculator.preferences || {}+ min_total = prefs[:minimum_item_total]+ max_total = prefs[:maximum_item_total]+ min_weight = prefs[:minimum_weight]+ max_weight = prefs[:maximum_weight]++ if (min_total.present? || max_total.present?) &&+ !delivery_method.delivery_method_rules.exists?(type: 'Spree::DeliveryMethodRules::ItemTotalRule')+ delivery_method.delivery_method_rules.create!(+ type: 'Spree::DeliveryMethodRules::ItemTotalRule',+ preferences: { minimum_amount: min_total, maximum_amount: max_total }+ )+ converted += 1+ end++ if (min_weight.present? || max_weight.present?) &&+ !delivery_method.delivery_method_rules.exists?(type: 'Spree::DeliveryMethodRules::WeightRule')+ delivery_method.delivery_method_rules.create!(+ type: 'Spree::DeliveryMethodRules::WeightRule',+ preferences: { minimum_weight: min_weight, maximum_weight: max_weight }+ )+ converted += 1+ end++ # Clear the migrated bounds so the calculator's legacy nil-guards stop+ # double-enforcing (the rules own eligibility now).+ if min_total.present? || max_total.present? || min_weight.present? || max_weight.present?+ calculator.update_columns(+ preferences: prefs.except(:minimum_item_total, :maximum_item_total, :minimum_weight, :maximum_weight)+ )+ end+ end++ puts "migrate_calculator_bounds_to_delivery_method_rules done. #{converted} rules created."+ end+enddiff --git a/spree/core/spec/models/spree/delivery_method_rule_spec.rb b/spree/core/spec/models/spree/delivery_method_rule_spec.rbnew file mode 100644index 0000000000..216cf75715--- /dev/null+++ b/spree/core/spec/models/spree/delivery_method_rule_spec.rb@@ -0,0 +1,128 @@+require 'spec_helper'++describe Spree::DeliveryMethodRule, type: :model do+ let(:store) { @default_store }+ let(:delivery_method) { create(:shipping_method) }+ let(:package) do+ order = create(:order_with_line_items, store: store, line_items_price: 20)+ Spree::Stock::Coordinator.new(order).packages.first+ end++ describe 'validations' do+ it 'rejects unregistered types' do+ rule = Spree::DeliveryMethodRule.new(type: 'Spree::DeliveryMethodRules::ItemTotalRule', delivery_method: delivery_method)+ expect(rule).to be_valid++ rule = Spree::DeliveryMethodRule.new(delivery_method: delivery_method)+ rule.type = 'Kernel'+ expect(rule).not_to be_valid+ expect(rule.errors[:type]).to be_present+ end++ it 'allows one instance of each rule kind per method' do+ Spree::DeliveryMethodRules::ItemTotalRule.create!(delivery_method: delivery_method)+ duplicate = Spree::DeliveryMethodRules::ItemTotalRule.new(delivery_method: delivery_method)++ expect(duplicate).not_to be_valid+ end+ end++ describe Spree::DeliveryMethodRules::ItemTotalRule do+ it 'bounds by item total inclusively and fails open when unconfigured' do+ rule = described_class.new(delivery_method: delivery_method)+ expect(rule.eligible?(package)).to be(true)++ rule.preferred_minimum_amount = package.item_total+ expect(rule.eligible?(package)).to be(true)++ rule.preferred_minimum_amount = package.item_total + 1+ expect(rule.eligible?(package)).to be(false)++ rule.preferred_minimum_amount = nil+ rule.preferred_maximum_amount = package.item_total - 1+ expect(rule.eligible?(package)).to be(false)+ end+ end++ describe Spree::DeliveryMethodRules::WeightRule do+ it 'bounds by package weight' do+ rule = described_class.new(delivery_method: delivery_method)+ expect(rule.eligible?(package)).to be(true)++ rule.preferred_maximum_weight = package.weight - 1+ expect(rule.eligible?(package)).to be(false)+ end+ end++ describe 'Estimator enforcement' do+ let(:order) { create(:order_with_line_items, store: store, ship_address: create(:address)) }++ it 'drops ineligible methods from rate estimation' do+ fulfillment = order.fulfillments.first || begin+ order.create_proposed_shipments+ order.fulfillments.first+ end+ method = fulfillment.refresh_rates.map(&:delivery_method).first+ expect(method).to be_present++ method.delivery_method_rules.create!(+ type: 'Spree::DeliveryMethodRules::ItemTotalRule',+ preferences: { minimum_amount: 1_000_000 }+ )++ expect(fulfillment.reload.refresh_rates.map(&:delivery_method_id)).not_to include(method.id)+ end++ it 'keeps methods whose rules pass' do+ order.create_proposed_shipments if order.fulfillments.none?+ fulfillment = order.fulfillments.first+ method = fulfillment.refresh_rates.map(&:delivery_method).first++ method.delivery_method_rules.create!(+ type: 'Spree::DeliveryMethodRules::ItemTotalRule',+ preferences: { minimum_amount: 1 }+ )++ expect(fulfillment.reload.refresh_rates.map(&:delivery_method_id)).to include(method.id)+ end++ it 'ignores inactive rules' do+ order.create_proposed_shipments if order.fulfillments.none?+ fulfillment = order.fulfillments.first+ method = fulfillment.refresh_rates.map(&:delivery_method).first++ method.delivery_method_rules.create!(+ type: 'Spree::DeliveryMethodRules::ItemTotalRule',+ active: false,+ preferences: { minimum_amount: 1_000_000 }+ )++ expect(fulfillment.reload.refresh_rates.map(&:delivery_method_id)).to include(method.id)+ end+ end++ describe 'spree:migrate_calculator_bounds_to_delivery_method_rules' do+ before(:all) do+ Rake::Task.define_task(:environment) unless Rake::Task.task_defined?(:environment)+ load Spree::Core::Engine.root.join('lib', 'tasks', 'delivery_method_rules_migration.rake')+ end++ it 'converts FlatRate bounds into rules and clears the preferences' do+ calculator = delivery_method.calculator+ expect(calculator).to be_a(Spree::Calculator::Shipping::FlatRate)+ calculator.update_columns(preferences: calculator.preferences.merge(minimum_item_total: 25, maximum_weight: 10))++ task = Rake::Task['spree:migrate_calculator_bounds_to_delivery_method_rules']+ task.reenable+ task.invoke++ rules = delivery_method.delivery_method_rules.reload+ item_rule = rules.detect { |rule| rule.is_a?(Spree::DeliveryMethodRules::ItemTotalRule) }+ weight_rule = rules.detect { |rule| rule.is_a?(Spree::DeliveryMethodRules::WeightRule) }++ expect(item_rule.preferred_minimum_amount).to eq(25)+ expect(weight_rule.preferred_maximum_weight).to eq(10)+ expect(calculator.reload.preferences[:minimum_item_total]).to be_nil+ end+ end+end