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.

17.7 KB
Raw Blame

Delivery Method Rules

Status: In Progress — Phase 1 implemented (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), 6.0-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-08-06

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) 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 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 6.0-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), 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 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).
  • 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

Base class + rules

# 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

# 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 (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

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. 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

  • 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

  • 6.0-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), 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)