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
Plan fulfillment profiles: ShippingCategory promoted, not removed
Damian Legawiec6f83ce6c3a00
diff --git a/CLAUDE.md b/CLAUDE.mdindex 73052acedd..b937a71b11 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -21,6 +21,7 @@ Active plans (6.0 target, work pending):- `6.0-remove-master-variant.md` — Eliminate is_master, add default_variant_id FK on Product. **Shipped to 6-0-dev (PR #14265):** is_master removed from all models, default_variant_id + `spree:remove_master_variant` data-migration rake landed; only the physical is_master column drop remains (6.1 cleanup).- `6.0-typed-stock-movements.md` — Replace generic StockMovement with typed kinds + concrete FKs- `6.0-normalize-state-to-status.md` — Rename state → status on Payment, Shipment, InventoryUnit, ReturnAuthorization, GiftCard+- `6.0-fulfillment-profiles.md` — **Design finalized 2026-08-09.** `Spree::FulfillmentProfile` = ShippingCategory promoted via table rename (`spree_shipping_categories`→`spree_fulfillment_profiles`, `products.shipping_category_id`→`fulfillment_profile_id`): store-scoped, one default per store, products reference it directly (ProductType stamps a template profile at creation only — restores template doctrine). Profile ↔ stock locations (origins, empty=all) + profile→zones + profile→methods; method `fulfillment_type`→`modality` (`Spree::DeliveryMethod.modalities` class_attribute; `Spree.fulfillment_types` registry DELETED), method binds ≤1 zone (m:n join dropped), optional ships-from narrowing per method (no location-group layer — considered, dropped). Capabilities derive from profile methods (`digital?`, pickupable, address requirement); carts split per profile. `spree:upgrade:migrate_fulfillment_profiles` handles store assignment/default flags/method m:n collapse (`spree_shipping_method_categories` survives to 6.1 as source). ShippingCategory/ShippingMethodCategory classes + associations deleted. Supersedes the string-registry + "named groups 6.1" decisions.- `6.0-fulfillment-and-delivery.md` — Shipment→Fulfillment, ShippingMethod→DeliveryMethod, drop ShippingCategory, FulfillmentProvider strategy, pickup (merchant StockLocation) + pickup_point (third-party PickupPointProvider). **Shipped to 6-0-dev (Waves 2+4+6):** renames + deprecated twins, providers (Manual/Digital/Pickup/PickupPoint), dual-emit events, store pickup discovery endpoints, admin delivery_methods/delivery_zones CRUD + dashboard settings pages, FulfillmentMailer; Wave 7 shipping→delivery data migration remains. Pickup work beyond shipped code deferred to 6.1 (2026-08-06): contract hardening (`new(delivery_method)` ctor, `find_nearby` zipcode/query) + how-to guide; `PickupPointProvider::Base` stays **undocumented in 6.0** (v6 docs cover only the delivery rate provider interface) — never add pickup-provider docs in 6.0 work. 6.0 built-in fulfillment types: `shipping`/`pickup`/`digital` — `pickup_point` unregistered until 6.1, `local_delivery` cut (= shipping + postal-code zone)- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain. **COMPLETE (2026-08-05):** all three entities (+ permanent `ReturnLineItem`/`ExchangeLineItem`/`ClaimLineItem` line items), `Spree::HasStatus`, all fifteen workflows (each with a leading `validate` hook), `Refund#originator`, admin + store v3 APIs (transitions as PATCH member actions; no destroy — cancel instead), dashboard pages. Legacy chain **removed**: ReturnAuthorization/CustomerReturn/Reimbursement/ReimbursementType/legacy ReturnItem + eligibility validators + ReturnsCalculator classes all deleted, but their **tables deliberately survive to 6.1** as the data migration's source and rollback path. `spree:upgrade:migrate_returns` (`Spree::ReturnsMigrator`, defined in the rake file like its sibling upgrade tasks; anonymous-AR readers) is in the 5.6→6.0 manifest after the adjustments step; it needs no cursor because the preserved `number` is uniquely indexed on the new tables, so "what's left" is a `where.not(number: ...)` query and an interrupted run resumes for free. `ReturnAuthorizationReason`→`ReturnReason` (alias one release) + new `ClaimReason`; `Metafields` on all three. Capability replacements: `Spree::ReturnMailer#refunded_email` on `return.refunded` (replaces the reimbursement email), `Order#outstanding_balance` drops the reimbursement term (refunds already net out of `payment_total`), `Return#refunded_total` counts store credits too, `StoreCreditCategory.default_refund_category` (alias kept). **Reasons** ship admin-only CRUD (`/api/v3/admin/{return,claim,refund}_reasons`, `settings` scope) + a combined Settings → Reasons dashboard page + reason pickers on the create dialogs; `mutable` is never client-writable and the immutability guard lives on `Spree::NamedType` (`can_be_deleted?` + rename/destroy guards) because secret API keys authorize by scope and never consult CanCanCan. **No state machines (2026-08-02):** plain `status` string + inclusion validation; all fifteen transitions are workflows (`Returns::Receive`, `Exchanges::Fulfill`, `Claims::Resolve`, …) with `validate` hooks for return-eligibility policy and refunds as `external_step`. Nothing happens in a model or transition callback. Statuses live in a `class_attribute` via the core `Spree::HasStatus` concern (`has_status` + additive `add_status(value, after:)`, generating predicates and scopes) — extensible by design, additive only, and no transition graph (that would be a state machine again). **Return eligibility is a hook, not a policy engine (2026-08-03):** no window/restocking-fee/final-sale flag in core — a `validate` handler decides, enforcing for customers while letting staff override (it reads `created_by`), and region-varying policy reads `order.market`. Medusa/Saleor/Vendure ship no policy at all; Shopify's engine has no API. A `ReturnPolicy` model can arrive later behind the same hook.- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename (RefreshToken shipped in 5.4)diff --git a/docs/plans/6.0-delivery-zones.md b/docs/plans/6.0-delivery-zones.mdindex 3705dadfce..d530c25785 100644--- a/docs/plans/6.0-delivery-zones.md+++ b/docs/plans/6.0-delivery-zones.md@@ -1,5 +1,8 @@# Delivery Zones (Zone → DeliveryZone)+> **Amendment 2026-08-09 (`6.0-fulfillment-profiles.md`):** delivery zones become owned by a fulfillment profile (`fulfillment_profile_id`), and a delivery method binds to at most ONE zone (`delivery_zone_id`; the method↔zone m:n join is dropped). Zone membership mechanics (country/state/postal ranges) are unchanged.++**Status:** Phases A and B shipped, C mostly shipped; `Spree::Zone` removal (Phase D) blocked on the tax provider — see "Implementation status"**Target:** Spree 6.0**Depends on:** `6.0-tax-provider.md` Phase 5 (tax decoupled from Zone — prerequisite for dropping the model; **not yet shipped, this is the live blocker**), `6.0-fulfillment-and-delivery.md` Phase 1 (`spree_delivery_method_zones` born pointing at DeliveryZone — **shipped**). Coordinates with: `6.0-delivery-rate-provider.md` (the Estimator's zone check swaps to DeliveryZone matching; provider interface unaffected).diff --git a/docs/plans/6.0-fulfillment-and-delivery.md b/docs/plans/6.0-fulfillment-and-delivery.mdindex cde92d7c8f..dfe244f0f6 100644--- a/docs/plans/6.0-fulfillment-and-delivery.md+++ b/docs/plans/6.0-fulfillment-and-delivery.md@@ -102,13 +102,17 @@ Replacement semantics:`ShippingMethod#digital?`, `#requires_zone_check?`, and the `.digital` scope currently test `calculator.is_a?(DigitalDelivery)` (`shipping_method.rb:42, 57, 128`; memoized via `MEMOIZED_METHODS :17`), and `Product#digital?` derives through a four-hop chain (product → category → methods → calculator class). All of these move to columns: `DeliveryMethod#fulfillment_type == 'digital'` and `ProductType#digital?`. The `DigitalDelivery` calculator stays (calculators are kept) but becomes a plain zero-cost calculator — its `available?` gating is superseded by fulfillment-type eligibility. `Seeds::DigitalDelivery` updates to set `fulfillment_type: 'digital'`.-### Fulfillment types are a strict registered set (revised 2026-08-02; supersedes "open strings, no inclusion validation")+### SUPERSEDED (2026-08-09): fulfillment types are replaced by Fulfillment Profiles++The registered-string design below, the "NOT a model" doctrine, and the "Named delivery groups (6.1-if-needed)" section further down are superseded by `6.0-fulfillment-profiles.md`: ShippingCategory is promoted (table renamed) into store-scoped `Spree::FulfillmentProfile`, products reference profiles directly, method `fulfillment_type` becomes `modality`, and the `Spree.fulfillment_types` registry is deleted. Kept below for history.++### Historical — Fulfillment types are a strict registered set (revised 2026-08-02; supersedes "open strings, no inclusion validation")`shipping`, `pickup` (merchant location), `digital` built in for 6.0; extensible via `Spree.fulfillment_types << 'same_day_courier'` in an initializer. `pickup_point` (third-party point — InPost locker, DHL ServicePoint) is deferred to 6.1 (2026-08-06, see Implementation status). `local_delivery` was **cut from the built-in set entirely** (2026-08-06): by this plan's own modality-vs-segment test it is not a modality — same address requirement, zone mechanism, provider and lifecycle as `shipping`; "local delivery to postcodes X–Y" is a `shipping` method with a postal-code DeliveryZone. It returns only if it ever grows real provider behavior (delivery windows, courier assignment), registered together with that provider. 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/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.-**Named delivery groups — the if-needed 6.1 successor to profiles (2026-08-06).** ShippingCategory stays removed even though the removal is unreleased. Competitor context, stated honestly: Medusa's ShippingProfile and Shopify's shipping profiles are the same design as ShippingCategory (product-level FK to a named group, options scoped to the group, carts split per group) — so per-product delivery grouping entities are common; what the 6.0 stack replaces them with covers all three of the category's jobs (eligibility via `fulfillment_types` matching, splitting via `Splitter::FulfillmentType`, per-product restrictions via `DeliveryMethodRules::ExcludedProductsRule`). The one genuine loss is the *named grouping as a management surface*: tagging 1,000 products "Oversized" once beats listing them individually on an exclusion rule (worse ergonomics at scale). If real merchant demand materializes, the comeback is NOT the old category (mandatory column, join table to methods, digital-via-calculator hack) but an additive construct in existing machinery — a named eligibility/exclusion set that products reference, or a `DeliveryMethodRule` kind matching a product group. 6.1-if-needed, evidence first. Also clarified 2026-08-06: dropping the category loses nothing at the variant level — Spree never had a variant-level shipping category (`spree_variants` has no such column back through the consolidated 4.3 schema; `Variant#shipping_category` was pure product delegation; Solidus is the fork that added one). Mixed physical/digital within one product is a pre-existing gap, with the reserved relief valve recorded in `6.0-product-types.md` (per-product/per-variant `fulfillment_types` override, 6.1-if-needed).+**Historical (superseded 2026-08-09 by `6.0-fulfillment-profiles.md` — profiles shipped in 6.0). Named delivery groups — the if-needed 6.1 successor to profiles (2026-08-06).** ShippingCategory stays removed even though the removal is unreleased. Competitor context, stated honestly: Medusa's ShippingProfile and Shopify's shipping profiles are the same design as ShippingCategory (product-level FK to a named group, options scoped to the group, carts split per group) — so per-product delivery grouping entities are common; what the 6.0 stack replaces them with covers all three of the category's jobs (eligibility via `fulfillment_types` matching, splitting via `Splitter::FulfillmentType`, per-product restrictions via `DeliveryMethodRules::ExcludedProductsRule`). The one genuine loss is the *named grouping as a management surface*: tagging 1,000 products "Oversized" once beats listing them individually on an exclusion rule (worse ergonomics at scale). If real merchant demand materializes, the comeback is NOT the old category (mandatory column, join table to methods, digital-via-calculator hack) but an additive construct in existing machinery — a named eligibility/exclusion set that products reference, or a `DeliveryMethodRule` kind matching a product group. 6.1-if-needed, evidence first. Also clarified 2026-08-06: dropping the category loses nothing at the variant level — Spree never had a variant-level shipping category (`spree_variants` has no such column back through the consolidated 4.3 schema; `Variant#shipping_category` was pure product delegation; Solidus is the fork that added one). Mixed physical/digital within one product is a pre-existing gap, with the reserved relief valve recorded in `6.0-product-types.md` (per-product/per-variant `fulfillment_types` override, 6.1-if-needed).### FulfillmentProvider is a strategy (not a DB model)diff --git a/docs/plans/6.0-fulfillment-profiles.md b/docs/plans/6.0-fulfillment-profiles.mdnew file mode 100644index 0000000000..1c12915757--- /dev/null+++ b/docs/plans/6.0-fulfillment-profiles.md@@ -0,0 +1,92 @@+# Fulfillment Profiles++**Status:** Design Finalized+**Target:** Spree 6.0+**Depends on:** `6.0-fulfillment-and-delivery.md` (shipped waves), `6.0-delivery-rate-provider.md` (dynamic carrier rates), `6.0-delivery-zones.md`, `6.0-product-types.md`+**Author:** Damian Legawiec + Claude (design sessions 2026-08-09)+**Last updated:** 2026-08-09++## Summary++`Spree::FulfillmentProfile` is the store-scoped grouping that decides how a set of products ships: which origins can fulfill them, which destination zones apply, and which delivery methods are offered. Products reference a profile directly (nil falls back to the store's default profile); carts split per profile; a package's candidate methods are exactly its profile's methods filtered by origin and destination. The model is **ShippingCategory promoted, not replaced**: the 5.x table and the product foreign key are renamed in place, so historical data migrates by rename rather than by copy.++This supersedes three earlier decisions: "fulfillment types are NOT a model", "named delivery groups are 6.1-if-needed", and live-by-reference `fulfillment_types` on ProductType. Rationale for reversing inside the 6.0 window: there is no rewrite window in 6.1; custom string types were second-class (providers declare handled types, so a custom type could not use any carrier rate provider); the origin axis (stock locations ↔ methods) did not exist for shipping methods at all; and the array-on-ProductType was the sole live-by-reference exception to the product-type template doctrine.++## The model++```+Spree::Store ─────────────────────────────── has many; exactly ONE default per store+ ▼+Spree::FulfillmentProfile spree_fulfillment_profiles (prefix fp_)+ │ store_id · name · default · position (renamed spree_shipping_categories)+ │ "General" (default) · "Oversized" · "Digital"+ │+ ├──< Spree::Product spree_products.fulfillment_profile_id+ │ (renamed shipping_category_id; nullable → default profile fallback)+ │ ProductType.fulfillment_profile_id = creation-time template:+ │ stamps the product at creation, never manages it afterwards+ │+ ├──< profile ↔ StockLocation join spree_fulfillment_profile_locations+ │ which origins can fulfill this profile; no rows ⇒ every store location+ │+ ├──< Spree::DeliveryZone gains fulfillment_profile_id+ │ country/state/postal members unchanged+ │+ └──< Spree::DeliveryMethod+ fulfillment_profile_id (required)+ delivery_zone_id (nullable; must belong to the same profile;+ nil = no destination restriction — digital,+ pickup, or genuinely worldwide shipping)+ modality (renamed fulfillment_type: shipping | pickup |+ digital; validated against+ Spree::DeliveryMethod.modalities, a+ class_attribute extensions append to)+ ships-from narrowing (existing DeliveryMethodStockLocation join,+ optional subset of the profile's locations;+ empty = all; Pickup keeps its policy override)+ rate/fulfillment providers · calculator · markup · carrier services ·+ rules — unchanged from the dynamic-carrier-rates work+```++No location-group layer: named origin bundles were considered (2026-08-09) and dropped — per-method ships-from narrowing expresses the multi-origin case ("UPS from the US warehouse, DPD from the EU one") without a third entity, and a group layer can be added additively in 6.1 if merchants outgrow that.++## Runtime flow++1. **Split** — `Stock::Splitter::FulfillmentProfile` (replaces `Splitter::FulfillmentType`) partitions cart contents by each item's resolved profile.+2. **Allocate** — the Coordinator allocates a profile's items only from stock locations the profile covers (its join; empty = all).+3. **Quote** — for a package (profile, origin): candidates are the profile's methods whose ships-from set covers the origin, whose zone is nil or includes the ship address, passing the existing rule/calculator/audience filters; rate providers then fan out (multi-rate carriers untouched).+4. **Derive, never declare twice** — `Product#digital?` ⇐ its profile's methods are all digital-modality; pickupable ⇐ the profile contains a pickup method; the order requires an address ⇐ any item's profile has a method whose provider `requires_address?`.++## Key Decisions (do not deviate without discussion)++- **Profile on the Product, template on the ProductType (2026-08-09).** `fulfillment_profile_id` lives on `spree_products`; ProductType's own `fulfillment_profile_id` is stamped onto products at creation only. This restores the uniform "creation-time template" doctrine that the `fulfillment_types` array violated, and makes a product's shipping behavior inspectable on the product itself.+- **Migration by rename, not by copy (2026-08-09).** `spree_shipping_categories` → `spree_fulfillment_profiles`; `spree_products.shipping_category_id` → `fulfillment_profile_id`. 5.x products arrive assigned; the 5.x "Digital" category becomes the Digital profile. What the rename cannot express is handled by `spree:upgrade:migrate_fulfillment_profiles`: store assignment (5.x categories were global; products are single-owner since 5.5, so each profile goes to the store whose products use it, duplicated + remapped when shared — loudly logged), default-profile flagging ("Default"-named else most-used, else a created "General"), and collapsing `spree_shipping_method_categories` (m:n) into the method's single `fulfillment_profile_id` (unambiguous for one binding; default profile + LOUD warning for several). The m:n table survives to 6.1 solely as that task's source.+- **Modality is a method concern.** `fulfillment_type` on the method is renamed `modality` and means the delivery mechanics (shipping/pickup/digital). The `Spree.fulfillment_types` registry (engine config + `Spree.fulfillment_types` accessors) is deleted outright — unreleased 6.0-dev surface. The vocabulary is `Spree::DeliveryMethod.modalities` (class_attribute, default `%w[shipping pickup digital]`); provider `fulfillment_types` declarations keep their name and mean modalities.+- **`ProductType#fulfillment_types` array is removed** (column + validation) in favor of the template profile reference. Capabilities derive from the profile's methods rather than being declared on the product side.+- **Zones belong to the profile; a method belongs to at most one zone.** The `spree_delivery_method_zones` m:n join is dropped (backfilled to the first zone with a warning on multiples). A method with no zone has no destination restriction.+- **One default profile per store**, enforced like `StockLocation#default` (`ensure_one_default`); undeletable; created by a `Store` `after_create` hook and by seeds/upgrade for existing stores. Non-default profiles are deletable only when no products reference them (model-level guard, per the RBAC axis-B convention).+- **Competitor names never appear in code or comments** — grounding stays in plan documents.++## Migration Path++1. Structural migration (6.0, `[8.1]`): renames + new columns/joins as diagrammed; adds `store_id`/`default`/`position` to the renamed profiles table (nullable until the upgrade task assigns them; `null: false` tightening lands in 6.1); drops `spree_delivery_method_zones` after backfill.+2. `Spree::ShippingCategory` + `Spree::ShippingMethodCategory` classes, deprecated associations (`Product#shipping_category*`, `Variant#shipping_category*`, `DeliveryMethod#shipping_categories*`), factories, permission-catalog subject, and typelizer entry are deleted. The permission catalog gains `Spree::FulfillmentProfile`.+3. `spree:upgrade:migrate_fulfillment_profiles` in the 5.6→6.0 manifest (resumable, anonymous-AR readers for the m:n) performs the judgement work listed above.+4. 6.1: drop `spree_shipping_method_categories`, tighten profile `store_id` constraints.++## Constraints on Current Work++- New delivery features must resolve eligibility through the profile chain — never reintroduce parallel product-side capability arrays.+- Anything reading `fulfillment_type` on methods means modality now; do not overload modality for product segmentation (that is what profiles are for).+- The Store API surface for profiles is read-only derivation (product serializers may expose digital/pickupable); profile management is Admin API only.++## Open Questions++- Whether ships-from narrowing needs promotion to named origin groups (6.1, evidence-first — additive).+- Multi-currency/multi-market interplay: profiles are store-scoped; market-aware profiles deferred to the channels/markets work.++## References++- Supersedes sections of `6.0-fulfillment-and-delivery.md` ("Fulfillment types are a strict registered set", "Named delivery groups"), `6.0-product-types.md` (fulfillment_types array), `6.0-delivery-zones.md` (store-level zone ownership).+- decisions.md 2026-08-09 entries (dynamic carrier rates; fulfillment profiles).+- PR #14404.diff --git a/docs/plans/6.0-product-types.md b/docs/plans/6.0-product-types.mdindex d46952f6e3..932e7c7ed6 100644--- a/docs/plans/6.0-product-types.md+++ b/docs/plans/6.0-product-types.md@@ -1,5 +1,8 @@# ProductType (Prototype → ProductType)+> **Amendment 2026-08-09 (`6.0-fulfillment-profiles.md`):** `fulfillment_types` on ProductType is removed. The type now carries a `fulfillment_profile_id` **template** stamped onto products at creation — restoring the creation-time-template doctrine this plan established; the array was its only live-by-reference exception. Products reference their profile directly.++**Status:** All phases shipped (Phase 2 rescoped and completed 2026-08-06) — see "Implementation status"**Target:** Spree 6.0**Depends on:** Custom Fields system (Metafields, shipped 5.4; 6.0 vocabulary per `5.4-6.0-custom-fields-rename.md`), `6.0-store-scoped-custom-field-definitions.md` (definitions become store-owned — the joins here validate same-store). Coordinates with: `6.0-replace-taxons-with-categories.md` (this plan ships **before** the Taxon→Category table rename; the `class_name` flip happens in that plan's wave). Consumed by: `6.0-fulfillment-and-delivery.md` (`fulfillment_types` replaces ShippingCategory — that plan cannot ship before this one).diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 9df5ee468c..f425293dff 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -59,6 +59,46 @@ never in metadata.Plan: `docs/plans/6.0-consolidate-metadata-columns.md`.+## 2026-08-09: Fulfillment profiles — ShippingCategory promoted, not removed++Reverses three recorded decisions inside the 6.0 window: "fulfillment types+are NOT a model", "named delivery groups are the 6.1-if-needed successor to+profiles" (both `6.0-fulfillment-and-delivery.md`), and live-by-reference+`fulfillment_types` on ProductType (`6.0-product-types.md`). Full design in+`6.0-fulfillment-profiles.md`.++**The model.** `Spree::FulfillmentProfile` — store-scoped, one default per+store — groups products for delivery: profile ↔ stock locations (origins,+empty = all), profile → delivery zones (destinations), profile → delivery+methods (each with a `modality` — the renamed `fulfillment_type` column —+an optional single zone, and optional ships-from narrowing via the+generalized method↔location join). Products carry `fulfillment_profile_id`+directly; ProductType stamps its template profile at creation and never+manages it afterwards. Carts split per profile; capabilities derive+(`digital?`, pickupable, address requirement) from the profile's methods+instead of being declared product-side. A location-group layer was+considered and dropped — per-method narrowing covers multi-origin stores,+and groups can arrive additively later.++**Why reverse now.** No rewrite window after 6.0; custom string types were+second-class (provider declarations could never include them, so a custom+type could not use carrier rate providers); the origin axis simply did not+exist for shipping methods; and the fulfillment_types array was the sole+live-by-reference exception to the product-type template doctrine.++**Migration by rename.** `spree_shipping_categories` →+`spree_fulfillment_profiles` and `spree_products.shipping_category_id` →+`fulfillment_profile_id`: 5.x products arrive assigned, the 5.x Digital+category becomes the Digital profile. `spree:upgrade:migrate_fulfillment_profiles`+handles what a rename cannot: store assignment for the formerly-global+categories (duplicate + remap when shared), default flagging, and+collapsing the method m:n (`spree_shipping_method_categories`, kept to 6.1+as source) into the single method FK — loud warnings wherever flattening+loses information. The `Spree.fulfillment_types` registry and the+ProductType array are deleted outright; modality vocabulary lives on+`Spree::DeliveryMethod.modalities`.++## 2026-08-09: Dynamic carrier rates — one delivery method, many named ratesSupersedes the one-rate-per-method model in `6.0-delivery-rate-provider.md`diff --git a/spree/core/app/models/spree/fulfillment_profile.rb b/spree/core/app/models/spree/fulfillment_profile.rbnew file mode 100644index 0000000000..982ccd4e21--- /dev/null+++ b/spree/core/app/models/spree/fulfillment_profile.rb@@ -0,0 +1,59 @@+module Spree+ # The grouping that decides how a set of products ships. Products+ # reference a profile directly (nil = the store's default profile); the+ # profile owns location groups, whose zones own the delivery methods.+ # Carts split per profile, and a package's candidate methods are exactly+ # its profile's methods.+ class FulfillmentProfile < Spree.base_class+ include Spree::SingleStoreResource++ has_prefix_id :fp++ acts_as_list scope: :store++ belongs_to :store, class_name: 'Spree::Store'++ has_many :location_groups, -> { order(:position) }, class_name: 'Spree::FulfillmentLocationGroup',+ dependent: :destroy, inverse_of: :fulfillment_profile+ has_many :products, class_name: 'Spree::Product', dependent: :nullify, inverse_of: :fulfillment_profile+ has_many :delivery_zones, through: :location_groups, class_name: 'Spree::DeliveryZone'+ has_many :delivery_methods, through: :location_groups, class_name: 'Spree::DeliveryMethod'++ validates :name, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }++ after_create :ensure_default_location_group++ scope :order_default, -> { order(default: :desc, position: :asc) }++ # Every store has exactly one default profile — the home of products that+ # reference none. Undeletable; demoted only by promoting another.+ def self.default_for(store)+ where(store: store, default: true).first+ end++ # The default profile is load-bearing (products fall back to it) and+ # other profiles must be empty of products before deletion.+ def can_be_deleted?+ !default? && products.none?+ end++ # The union of the profile's groups' locations — where its products can+ # be allocated from. A group with no explicit members means every store+ # location, making the whole union the full set.+ #+ # @return [ActiveRecord::Relation<Spree::StockLocation>]+ def fulfillable_stock_locations+ groups = location_groups.includes(:stock_locations).to_a+ return store.stock_locations.none if groups.empty?+ return store.stock_locations if groups.any? { |group| group.stock_locations.empty? }++ store.stock_locations.where(id: groups.flat_map { |group| group.stock_locations.map(&:id) })+ end++ private++ def ensure_default_location_group+ location_groups.create!(name: nil) if location_groups.empty?+ end+ end+end