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.

61.2 KB
Raw Blame

Fulfillment & Delivery Rework

Status: In Progress — Phases 1–5 implemented; remaining 6.0 work is the seller axis (gated) — see "Implementation status" Target: Spree 6.0 Depends on: 6.0-product-types.md (fulfillment_types addendum 2026-07-27 — ProductType replaces ShippingCategory; shipped, including the fulfillment_types column), 6.0-cart-order-split.md (where fulfillments/rates live pre-completion), 6.0-order-routing.md (packages come from for_allocation), 6.0-normalize-state-to-status.md. Coordinates with: 6.0-delivery-rate-provider.md (owns store_id on DeliveryMethod; calculators stay per decisions.md 2026-07-27), 5.5-6.0-display-on-to-boolean.md (storefront_visible — DeliveryMethod moved off the Spree::DisplayOn concern 2026-08-05), 6.0-multi-vendor-marketplace.md (seller_id, lifecycle events, delivery_amount). Gates: 6.0-6.1-split-adjustments.md and 6.0-typed-stock-movements.md are born with fulfillment_id — this plan's Phase 1 must land before both. Author: Damian + Claude Last updated: 2026-09-03 (question 15 superseded — the carrier axis moves onto Spree::Delivery in 6.0, see 6.0-shipping-labels-and-deliveries.md)

Summary

Rename the shipping domain to delivery/fulfillment vocabulary, drop ShippingCategory (replaced by ProductType#fulfillment_types), and add a FulfillmentProvider strategy interface for extensible fulfillment types (shipping, pickup, pickup point, digital, local delivery, custom).

Three changes in one:

  1. Rename — Shipment → Fulfillment, ShippingMethod → DeliveryMethod, ShippingRate → DeliveryRate, InventoryUnit → FulfillmentItem
  2. Drop ShippingCategory — ProductType#fulfillment_types + DeliveryMethod#fulfillment_type control delivery eligibility
  3. Add FulfillmentProvider — strategy interface for 3rd-party integrations and custom fulfillment types; replaces the broken ShipmentHandler name-constantize mechanism

Calculators are NOT touched by this plan. The 2026-07-27 decision (decisions.md) keeps ShippingCalculator + Calculator::Shipping::*; rate estimation is the delivery-rate-provider plan's domain. Zone replacement ships in 6.0 via 6.0-delivery-zones.md — this plan's Phase 1 births spree_delivery_method_zones pointing at DeliveryZone (born correct, never re-migrated).

Implementation status (verified 2026-08-06 against feat/fulfillment-delivery-rework, since merged to main)

Phases 1a, 1b, 2, 3, 4 and 5 are implemented. Verified in code: the rename migrations (20260728000004/5) including every FK and the orders column pair; model renames with one-release deprecation shells (Spree::Shipment, ShippingMethod, InventoryUnit, FulfilmentChanger are constant aliases); Package#eligible_delivery_methods + Stock::Splitter::FulfillmentType; ProductType#fulfillment_types with registry-backed inclusion validation; all five providers plus PickupPointProvider::Base; the Spree.fulfillment_types / Spree.fulfillment_providers registries; lifecycle events with shipment.* dual-emit and order.fulfilled / Order#fully_fulfilled?; dual cart_id/order_id owner with exactly-one validation; Estimator location gating via serves_location?; pickup discovery endpoints and the fulfillment_providers discovery route; admin delivery-method and delivery-zone CRUD; FulfillmentMailer (with a ShipmentMailer shell); return_items.fulfillment_item_id; and both data rake tasks wired into the 5.6→6.0 upgrade manifest.

Landed 2026-08-05 (this plan's remaining 6.0 cleanup): storefront_visible is now the authoritative column on DeliveryMethod — the model no longer includes Spree::DisplayOn, the boolean carries a null: false, default: true DB default, and display_on survives only as a deprecated reader/writer pair. The magic-integer DISPLAY_ON_FRONT_END/BACK_END rate filter became DeliveryMethod::STOREFRONT / BACKOFFICE with #available_to?(audience) (#available_to_display? kept as a deprecated bridge that still accepts the old integers). shipping_method_categories / shipping_categories are flagged deprecated: true, and the product factory no longer auto-assigns a ShippingCategory. The visibility backfill clears display_on as it converts, making the conversion one-shot — otherwise a re-run would silently revert a visibility change an admin made after the upgrade.

CSV shipping_category is a clean break, not a bridge (2026-08-05). The column is gone from both the import schema and the export presenter, replaced by product_type (export never had it before, so import and export now agree). Rationale: ShippingCategory already had zero live behavior — delivery eligibility runs entirely through ProductType#fulfillment_types via Package#eligible_delivery_methods, and nothing reads the category for routing. Carrying a deprecated CSV column plus a name-matching bridge would have been maintaining a translation layer onto a model that no longer decides anything. Also removed as part of the same sweep: shipping_category_id from permitted product attributes (replaced by product_type_id, which was never permitted — a real gap), the shipping_category Ransack association on Product (now product_type), the dead Store#default_shipping_category/#digital_shipping_category helpers, PermittedAttributes.shipping_category_attributes, and the two dangling API serializer registrations (the admin one pointed at a class that never existed).

Ruby-level readers keep working through 6.0, unlike the CSV column — the break there is justified because a CSV field is data a merchant re-exports, while a model reader is code an extension calls. Product#shipping_category and #shipping_methods stay as deprecated: true associations, and Variant#shipping_category/#shipping_category_id stay as explicit Spree::Deprecation.warn delegates (a plain delegate can't warn). Variant also gained product_type/product_type_id delegates alongside them. All four die with the table in 6.1.

Internal method vocabulary follows the models (2026-08-05). Core code now calls the delivery/fulfillment names everywhere; the shipping-era names survive one release as Spree::Deprecation.warn bridges. Renamed: Stock::Estimator#shipping_rates → #delivery_rates (and its internals — calculate_/choose_default_/sort_, plus the shipping_methods filter seam → #delivery_methods, which host apps override — #delivery_methods dispatches through the legacy name when a subclass or decorator has redefined it, so existing overrides keep filtering until 6.1 rather than being silently skipped), Stock::Package#shipping_rates/#to_shipment → #delivery_rates/#to_fulfillment, Stock::Coordinator#shipments → #fulfillments, Order#line_items_without_shipping_rates → #line_items_without_delivery_rates, Order#refresh_shipment_rates → #refresh_delivery_rates, Order#ensure_available_shipping_rates → #ensure_available_delivery_rates (private — no bridge), and LineItem#shipping_cost/#display_shipping_cost → #delivery_cost/#display_delivery_cost. Spree::Cart gets no deprecation bridges at all — it is new in 6.0, so no legacy caller can exist; its equivalent is simply #ensure_available_delivery_rates.

Four latent bugs fixed in the renamed methods (2026-08-06). Surfaced by review while the surrounding code was being renamed; each was reproduced before the fix and is covered by a regression spec:

  • LineItem#delivery_cost double-counted. has_many :fulfillments, through: :fulfillment_items yields one row per unit, so a fulfillment holding several of a line item's units was charged once per unit (measured: 60 instead of 30). Now fulfillments.distinct.
  • LineItem#delivery_cost aborted on the first skippable fulfillment. The guards used return inside sum, which exits the whole method rather than the block — a canceled fulfillment ordered before an active one zeroed out the entire line item (measured: 0 instead of 10). Now next.
  • Order#line_items_without_delivery_rates was memoized across a destroy. ensure_available_delivery_rates calls fulfillments.destroy_all and then re-reads the list, so the cached value described fulfillments that no longer existed. Memoization removed, and the list is captured before the destroy so the error message keeps its product names.
  • Fulfillment#refresh_rates could leave nothing selected. When the previously chosen method dropped out of the new quote (audience change, eligibility rule, zone edit), selected_rate came back nil and the fulfillment lost its selection. It now falls back to the estimator's own pick.

Pickup work beyond what has shipped is deferred to 6.1 (2026-08-06 — 6.0 is packed). Everything already in code stays in 6.0 unchanged: the pickup/pickup_point fulfillment types and providers, PickupPointProvider::Base + PickupPointOption, the store discovery endpoints, DeliveryMethodStockLocation, and the full checkout selection flow (point chosen at the delivery step via pickup_point_external_id, server-validated, frozen into pickup_point_data). Deferred to 6.1 as one unit:

  • Contract hardening: (1) PickupPointProvider subclasses constructed with new(delivery_method) instead of new — today DeliveryMethod#pickup_point_provider_instance passes no arguments, leaving providers no path to delivery_method.store.integrations for credentials (same constructor shape as DeliveryRateProvider::Base); (2) find_nearby accepts optional zipcode:/query: alongside latitude:/longitude: — postcode/city search is the standard EU checkout pattern. Map-widget storefronts (InPost Geowidget) are unaffected either way — they skip find_nearby and only use the server-side find_by_external_id validation.
  • Reference network provider: none in 6.0 or promised for 6.1 core — community/later, plus a how-to guide written when the contract is hardened.
  • Not selectable in 6.0: pickup_point is removed from the dashboard FULFILLMENT_TYPES const (schema enum + select options) and from the Spree.fulfillment_types registry in engine.rb — so the type-select never offers it and the model's inclusion validation rejects setting it. Existing rows carrying the token stay loadable (validation runs on change only) and the pickup_points/selection endpoints still serve them. All other backend code, columns, endpoints and translations stay as shipped. Re-registering the token in 6.1 re-enables the whole surface.

Mitigation for deferring a signature change on a public class: the pickup point provider interface is not documented in 6.0 at all — the v6 developer docs cover only the delivery rate provider interface. A class-level comment on PickupPointProvider::Base notes the constructor and find_nearby signature change in 6.1. With no docs inviting third-party providers, the 6.1 change breaks no sanctioned contract. Accepted trade-off for keeping 6.0 scope down; do not add pickup-provider docs or guides in any 6.0 work.

Remaining for 6.0: only the seller axis (belongs_to :seller replacing the Spree::SellerConcern decorator seam, DeliveryMethodStockLocation seller-consistency validation, and refusing pickup_stock_policy: 'any' on seller-owned locations). It is gated on 6.0-multi-vendor-marketplace.md shipping the seller_id column in its schema wave. Everything else outstanding is Phase 6 (6.1) cleanup.

Shipped earlier (verified 2026-07-27, HEAD 4e5b6fd)

The following predates the phase work above and must NOT be redone:

  • API v3 speaks the new vocabulary over the old models: FulfillmentSerializer, DeliveryMethodSerializer, DeliveryRateSerializer (+ Admin variants), fulfillments routes and controllers (store carts + admin orders), dual old/new registrations in api/lib/spree/api/dependencies.rb:111-128, 191-213. FulfillmentSerializer already emits status (from state), fulfilled_at (from shipped_at), and a computed fulfillment_type (digital? ? 'digital' : 'shipping').
  • Prefix IDs claimed: ful_ (Shipment), dm_ (ShippingMethod), fi_ (InventoryUnit), dr_ (via Shipment#selected_delivery_rate_id, whose YARD comment cites this plan).
  • Order aliases: alias_attribute :fulfillment_status, :shipment_state and alias_attribute :delivery_total, :shipment_total (order.rb:211-213) — the Phase 1 column renames must remove these aliases in the same change.
  • Spree::Fulfillments::Create service (core/app/services/spree/fulfillments/create.rb), registered as Spree.fulfillment_create_service.
  • StockLocation pickup columns (shipped 2026-05-08): kind, pickup_enabled, pickup_stock_policy, pickup_ready_in_minutes, pickup_instructions + indexes. Do not re-add. Reviewed 2026-08-02 — all five stay (shipped 5.x schema + admin API contract; pickup_stock_policy is genuinely per-location: which counters accept ship-to-store transfers varies by counter). Rule going forward: no new per-fulfillment-type column sets on spree_stock_locations — future capabilities (local-delivery radius, courier windows, …) express through the provider/method/DeliveryMethodStockLocation axis, not location columns. kind is currently unread by business logic and reserved for 6.0-inventory-operations.md (warehouse vs store operations); do not drop or repurpose without checking that plan.
  • admin-sdk generated types are already clean (zero shipment references). The dashboard has since followed: its only remaining shipment hits are one translation key and legitimate shipping_address references.

(All of the above has since been superseded by the phase work — see "Implementation status".)

Entity Rename Map

Current (5.x) 6.0 Prefix ID Table
Spree::Shipment Spree::Fulfillment ful_ (shipped) spree_fulfillments
Spree::ShippingMethod Spree::DeliveryMethod dm_ (shipped) spree_delivery_methods
Spree::ShippingRate Spree::DeliveryRate dr_ spree_delivery_rates
Spree::ShippingMethodZone Spree::DeliveryMethodZone — spree_delivery_method_zones (born joining Spree::DeliveryZone — see 6.0-delivery-zones.md)
Spree::InventoryUnit Spree::FulfillmentItem fi_ (shipped) spree_fulfillment_items
Spree::FulfilmentChanger (sic) Spree::FulfillmentChanger — (PORO — fixes the single-L/double-L collision)
Spree::ShipmentHandler removed → FulfillmentProvider — —
Spree::ShippingCategory Dropped (Phase 6) — spree_shipping_categories dropped in 6.1
Spree::ShippingMethodCategory Dropped — spree_shipping_method_categories dropped in 6.1
— (new) Spree::DeliveryMethodStockLocation — spree_delivery_method_stock_locations

Fulfillment numbers: existing H-prefixed numbers are opaque identifiers and stay untouched (unique index on number); new fulfillments generate F-prefixed numbers. No data migration.

Key Decisions (do not deviate without discussion)

Naming

  • Fulfillment = the act of getting items to the customer; the record tracking it. Replaces Shipment.
  • DeliveryMethod = the option presented at checkout. Replaces ShippingMethod.
  • DeliveryRate = the price quote for a delivery method on a fulfillment. Replaces ShippingRate.
  • FulfillmentItem = an item within a fulfillment (variant + quantity — the quantity column and its validation already exist on InventoryUnit today). Replaces InventoryUnit.
  • FulfillmentProvider = strategy handling create/track/cancel mechanics per fulfillment type. New; replaces ShipmentHandler (whose name-constantize factory can never match — no subclass exists and the seeded method name "Digital Delivery" can't constantize).

ProductType replaces ShippingCategory — and Package#shipping_methods is the real thing being replaced

ShippingCategory's load-bearing job is not the model — it's Stock::Package#shipping_methods (package.rb:73-80), which intersects delivery methods through categories and is the sole input to Stock::Estimator#shipping_methods. Drop the category without replacing this and mixed carts get zero rates, tripping ensure_available_shipping_rates and blocking checkout (asserted by order_routing/strategy/parity_spec.rb:426-452).

Replacement semantics:

  • ProductType#fulfillment_types (JSON array, default ['shipping']; see the 2026-07-27 addendum in 6.0-product-types.md). Products without a ProductType default to ['shipping'] — the reconciliation between optional ProductType and today's effectively-mandatory ShippingCategory (Product presence-validates + auto-assigns one today, product.rb:133, 153, 945-951).
  • DeliveryMethod#fulfillment_type (single string) must be included in every package item's fulfillment_types for the method to be eligible.
  • Package#eligible_delivery_methods replaces Package#shipping_methods: intersect items' fulfillment types. Then subtract per-product exclusions via Product.excluded_delivery_method_ids (JSON array column) — superseded 2026-08-06: the column is dropped; the restriction case ("fragile item can't ship express") is Spree::DeliveryMethodRules::ExcludedProductsRule, enforced at the Estimator's rule seam like every other eligibility constraint. See 6.0-delivery-method-rules.md.
  • Stock::Splitter::ShippingCategory → Stock::Splitter::FulfillmentType — packages stay homogeneous by fulfillment type, so mixed carts (physical + digital) still split automatically. Splitter::Digital folds into it.
  • The eligibility seam stays inside Stock::Estimator#shipping_methods (per the delivery-rate-provider plan, which owns filtering — including the marketplace seller gate). This plan changes the inputs to that filter, not its location. No separate DeliveryMethods::Available service.

The digital discriminator moves off the calculator class

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

SUPERSEDED (2026-08-09): fulfillment types are replaced by Delivery 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-delivery-profiles.md: ShippingCategory is promoted (table renamed) into store-scoped Spree::DeliveryProfile, 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.

Historical (superseded 2026-08-09 by 6.0-delivery-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)

class Spree::FulfillmentProvider::Base
  def can_fulfill?(fulfillment) = true
  def create_fulfillment(fulfillment) = raise(NotImplementedError)  # → { tracking_number:, tracking_url: }
  def cancel_fulfillment(fulfillment) = raise(NotImplementedError)
  def tracking_url(fulfillment) = nil
  def documents(fulfillment) = []
end

Built-ins: Manual (default — current admin-driven behavior), Digital, Pickup, PickupPoint. Third-party: SpreeEasyPost::FulfillmentProvider, SpreeShipStation::FulfillmentProvider. Stored as a string class name on DeliveryMethod, constantized at call time. Registered via Spree.fulfillment_providers.

Digital auto-fulfillment is new behavior, not a refactor. Today digital shipments sit at ready until an admin clicks Ship (Shipment#shippable? exists precisely for that button), and DigitalLinks are created by a checkout state-machine callback (checkout.rb:87-89 — nested inside if states[:payment], non-idempotent, one link per line item regardless of quantity). FulfillmentProvider::Digital takes over both: on order completion it fires fulfill! directly and generates DigitalLinks idempotently, per quantity. This also gives the multi-vendor ledger its "digital seller order earns immediately after payment" path.

Lifecycle events are first-class (multi-vendor ledger depends on them)

Fulfillment gets publishes_lifecycle_events plus explicit transition events: fulfillment.ready, fulfillment.fulfilled, fulfillment.canceled, fulfillment.resumed. Order-level: when the last fulfillment reaches fulfilled, publish order.fulfilled — the signal 6.0-multi-vendor-marketplace.md's seller_transfer.due subscriber keys on ("all the seller order's fulfillments fulfilled"). Order#fully_fulfilled? is the matching queryable predicate.

Webhook contract break: today Shipment publishes shipment.* events and webhooks (Shipment::Webhooks, Shipment::CustomEvents). Event names rename with the model; 6.0 dual-emits shipment.shipped alongside fulfillment.fulfilled for one release with a deprecation note in webhook docs, dropped in 6.1.

Seller axis (marketplace)

seller_id (nullable) on DeliveryMethod — the column ships in the marketplace plan's schema wave; this plan's model carries belongs_to :seller, optional: true, replacing the Enterprise SellerConcern decorator seam (shipping_method.rb:10-12). Semantics (owned by the delivery-rate plan's Estimator filter): seller_id present → offered only on that seller's packages; nil → marketplace-wide. Store vs seller are different axes: store = tenant + credential scope (store_id, owned by the delivery-rate plan), seller = seller within it.

DeliveryMethodStockLocation validates seller consistency: when both the method and the stock location carry a seller_id, they must match — otherwise one seller's pickup counter could serve another seller's items. Pickup stock checks are package-scoped, never order.variants. pickup_stock_policy: 'any' (ship-to-store transfers) is incompatible across seller boundaries and is refused when the location is seller-owned.

Owner is cart-or-order

Checkout — where fulfillments and delivery rates are created and selected — happens on the Cart under copy-on-completion semantics. Fulfillment follows the house pattern: nullable cart_id / order_id with an exactly-one validation, re-pointed at Spree::Carts::Complete (and again at seller split). DeliveryRate carries no owner columns (settled 2026-07-28) — a rate belongs to its fulfillment and derives the owner through it; spree_shipping_rates has neither FK today, and duplicating the pair would be drift risk at every re-pointing. belongs_to :order hard-required is known-wrong and must not be implemented.

Fulfillment#delivery_amount (commission base)

delivery_amount = cost + discounts.sum(:amount) — the selected rate's cost net of fulfillment-attached Discount rows (negative, from 6.0-6.1-split-adjustments.md). This is the base 6.0-multi-vendor-marketplace.md uses for include_shipping commission (CommissionLine fulfillment-scoped). cost remains the denormalized column it is today.

Status model — two axes, delivered is first-class (2026-08-11)

Fulfillment#status describes what the merchant did with the package — nothing else. Four values, plain string via Spree::HasStatus, state machine removed:

unfulfilled ──► fulfilled ──► delivered
      └───────► canceled        (resume: canceled ──► unfulfilled)
  • unfulfilled replaces both pending and ready. Those were payment and stock facts wearing a fulfillment costume: determine_state re-derived them from order.paid? on every recalculation, so a refund flipped a fulfillment between pending and ready with no physical change — the single most misunderstood part of the model. Whether a fulfillment can be fulfilled (order paid or auto-capture-on-dispatch, no backordered units) becomes a guard in Fulfillments::Fulfill's validate step — it rejects with a reason and is staff-overridable, like return eligibility. determine_state and the ready/pend events are deleted; cart-side fulfillments are always unfulfilled.
  • fulfilled keeps its meaning: handed over — to the carrier, or ready at the counter for pickup.
  • delivered is new and terminal: confirmed receipt. Reached by carrier tracking, a staff "mark as delivered" (works with no carrier integration), or later customer confirmation via the Store API. Fulfillments::MarkDelivered sets delivered_at and publishes fulfillment.delivered. The returns eligibility window and the EU 14-day withdrawal period both anchor on a delivery date the model never had — this is where it comes from.
  • ready_for_pickup dies as a status. For pickup fulfillments fulfilled means "ready at the counter" (the provider's fulfill side effect notifies the customer) and delivered means picked up. Presentation is modality-aware; the status vocabulary is not.

The second axis — tracking_status — is the carrier's story: data, never a machine. Nullable string + tracking_details JSON + estimated_delivery_at, overwritten on every carrier update, no transition graph: pre_transit, in_transit, out_for_delivery, available_for_pickup, delivered, return_to_sender, failure, unknown. Bounced packages, failed delivery attempts and damage surface here (and can feed a claim) without ever mutating status. The core entry point is Fulfillments::UpdateTracking — writes the axis, calls MarkDelivered when the carrier reports delivery. The EasyPost gem feeds it from tracker webhooks: every label we buy already has a tracker whose updates are currently thrown away (only the public URL is stored). Trackers for hand-entered tracking numbers cost money each, so creating them is opt-in on the integration.

Order rollup domain becomes backorder | canceled | partial | unfulfilled | fulfilled | delivered (+ nil): delivered when every non-canceled fulfillment is delivered, fulfilled when every one is fulfilled-or-beyond, partial for mixes; backorder still short-circuits (item-level fact, unchanged).

Removing the machine supersedes "the machine stays" (question 13, decisions.md 2026-08-10). That call was made while the machine still held guards worth keeping; with pending/ready gone it holds two transitions and the event publishes — exactly what HasStatus + workflows already provide for Return/Exchange/Claim. Transition legality moves inline into the workflows (Fulfill from unfulfilled/canceled, Cancel from unfulfilled, Resume to unfulfilled, MarkDelivered from fulfilled). The FulfillmentItem machine (on_hand/backordered/shipped/returned) is untouched — stock bookkeeping, owned by 6.0-typed-stock-movements.md.

Data migration (both the 6-0-dev mapping and the 5.6→6.0 manifest step): pending|ready → unfulfilled; ready_for_pickup → fulfilled; pickup-modality fulfilled rows → delivered (under the old machine, pickup "fulfilled" meant the customer took the package — that is confirmed receipt); shipping-modality fulfilled stays fulfilled (delivery genuinely unknown).

SUPERSEDED (2026-08-11): the section below preserved the pending/ready machine

Superseded by "Status model — two axes" above (decisions.md 2026-08-11): pending/ready/ready_for_pickup collapse into unfulfilled, the machine is removed, and the lifecycle extends past handover to delivered.

Historical — Status semantics — corrected against the real machine

The rename is shipped → fulfilled (column state → status per the normalize plan), preserving today's guards and hooks, which the earlier draft dropped:

  • ready keeps its determine_state == 'ready' guard (the #2040 fix — no ready fulfillments on unpaid orders).
  • pend (ready → pending) stays — used when an order becomes unpayable again.
  • resume keeps both conditional targets (canceled → ready when determine_state says so, else canceled → pending).
  • ready_for_pickup is cancelable (cancel accepts it) and reachable from ready (not just pending).
  • All after_transition hooks survive: restock/unstock, StateChange audit rows, events + webhooks (renamed per above).
  • The three update_columns escape hatches that bypass the machine (update_amounts, Shipment#update!, ShipmentHandler#update_order_shipment_state) are rewritten to go through the machine or explicitly documented as freeze-safe.

Order rollup keeps backorder. The earlier draft omitted it; backorder short-circuits the whole computation and feeds Order#allow_cancel? and the not_shipped scope. Domain of Order#fulfillment_status: backorder, canceled, partial, pending, ready, fulfilled (renamed from shipped), plus nil. ready_for_pickup/picked_up roll up as ready/fulfilled. Computation semantics are otherwise unchanged (including the [canceled, X] collapse rules).

Pickup location selection flows through order routing

A customer's merchant-pickup choice writes Order#preferred_stock_location_id, so it flows through the existing PreferredLocation routing rule (6.0-order-routing.md) instead of bypassing routing with a direct stock_location_id write. Fulfillment#stock_location always comes from the routing strategy's for_allocation packages — never a bare detect.

Delivery predicates — one meaning per name (settled 2026-08-02)

Digital and both pickup kinds ARE deliveries — they just don't ship to a customer address. Three predicates, never interchangeable (implemented on the Purchase concerns; Order#delivery_required? / #requires_ship_address? are deprecated bridges, removed 6.1):

  • digital? / some_digital? — item-composition facts only, never flow gates.
  • delivery_step_required? — the checkout delivery step applies: the customer must choose a delivery option (shipping + pickup kinds yes; digital-only no — the provider auto-fulfills).
  • shipping_address_required? — checkout must collect a customer ship address. Selected delivery methods are the source of truth: DeliveryMethod#requires_address? delegates to the fulfillment provider (FulfillmentProvider::Base#requires_address? → true; Digital/Pickup/PickupPoint override false) — no type const, host apps extend by registering a provider. Before any selection: pickup intent (preferred_stock_location_id) waives it, otherwise the items' possible fulfillment_types are matched against the store's configured address-requiring delivery methods — deliberately no digital? special case anywhere. requires_zone_check? follows requires_address? (zones describe the customer destination), which also fixed pickup_point methods wrongly zone-checking against the customer address. The provider is an explicit choice, never derived from the type in the model (no naming-convention magic): Manual stays the column default and the dashboard suggests a type-specific provider when the admin picks a fulfillment type, via GET /admin/delivery_methods/fulfillment_providers (each provider declares self.fulfillment_types; empty = handles any). The field renders only when more than one registered provider matches the chosen type, so it stays hidden until a carrier integration is installed.

Resolved 2026-08-02 — pickup flow correctness (shipped together as one unit):

  • Rebuild triggers: a destination is an address OR a pickup intent. Carts::Update#try_advance rebuilds proposals on saved_change_to_preferred_stock_location_id? (set, changed, or cleared) exactly like address/market changes. Whether anything is proposed is one rule, Purchase::Addresses#can_propose_deliveries? — a shipping address, a pickup intent, or items no delivery profile ships to an address — read by both Checkout::Advance and every Cart#rebuild_fulfillments!, including the one after an item change. Until it holds the cart has no proposals, so the storefront shows no delivery option before the address (2026-10-01, V-3718). A pure-pickup cart completes checkout without ever having a shipping address.
  • Estimator location gating: Stock::Estimator#shipping_methods filters on DeliveryMethod#serves_location?(package.stock_location), delegated to the fulfillment provider. Base → true (shipping/digital/pickup_point are source-agnostic); FulfillmentProvider::Pickup → the package must be sourced from an eligible pickup location (available_pickup_locations: the configured DeliveryMethodStockLocation set, else all active pickup-enabled), or some eligible location must accept remote stock (pickup_stock_policy: 'any' — the ship-to-store case, which a strict source gate would otherwise outlaw). This makes DeliveryMethodStockLocation load-bearing in rating, not just in the storefront listing endpoint.
  • Coverage checks are pickup-item-scoped: the store pickup_locations?cart_id= coverage check skips line items whose product fulfillment_types exclude pickup — a tracked digital variant in a mixed cart must not disqualify a counter.
  • Cart-side sourcing still comes from the Coordinator across all stocked locations; honoring the chosen counter remains order-side routing (PreferredLocation rule) per "Pickup location selection flows through order routing" above.

Design Details

DeliveryMethod

class Spree::DeliveryMethod < Spree.base_class
  has_prefix_id :dm

  acts_as_paranoid
  include Spree::SingleStoreResource   # store_id: migration owned by 6.0-delivery-rate-provider.md
  include Spree::CalculatedAdjustments # calculators STAY — decisions.md 2026-07-27
  include Spree::Metafields
  include Spree::Metadata

  belongs_to :store, class_name: 'Spree::Store'
  belongs_to :seller, class_name: 'Spree::Seller', optional: true  # marketplace; nil = marketplace-wide
  belongs_to :tax_category, -> { with_deleted }, class_name: 'Spree::TaxCategory', optional: true

  has_many :delivery_rates, class_name: 'Spree::DeliveryRate', inverse_of: :delivery_method
  has_many :fulfillments, through: :delivery_rates
  has_many :delivery_method_zones, class_name: 'Spree::DeliveryMethodZone', dependent: :destroy
  has_many :delivery_zones, through: :delivery_method_zones, class_name: 'Spree::DeliveryZone'  # 6.0-delivery-zones.md
  has_many :delivery_method_stock_locations, class_name: 'Spree::DeliveryMethodStockLocation', dependent: :destroy
  has_many :pickup_locations, through: :delivery_method_stock_locations, source: :stock_location

  # storefront_visible boolean replaces Spree::DisplayOn (5.5-6.0-display-on-to-boolean.md,
  # converted in this plan's Phase 1 wave). Do NOT include Spree::DisplayOn.
  validates :name, :fulfillment_type, presence: true
  validates :estimated_transit_business_days_min, :estimated_transit_business_days_max,
            numericality: { greater_than_or_equal_to: 1 }, allow_nil: true

  attribute :fulfillment_type, :string, default: 'shipping'
  attribute :fulfillment_provider, :string, default: 'Spree::FulfillmentProvider::Manual'
  attribute :pickup_point_provider, :string  # only for pickup_point type
  # rate_provider string column comes from 6.0-delivery-rate-provider.md

  scope :by_fulfillment_type, ->(type) { where(fulfillment_type: type) }

  def digital? = fulfillment_type == 'digital'
  def pickup? = fulfillment_type == 'pickup'
  def pickup_point? = fulfillment_type == 'pickup_point'
  def requires_address? = !digital? && !pickup?

  def provider = @provider ||= fulfillment_provider.constantize.new
end

Fulfillment

class Spree::Fulfillment < Spree.base_class
  has_prefix_id :ful
  include Spree::Metadata

  publishes_lifecycle_events

  # Owner — exactly one (cart pre-completion, order after; re-pointed at Carts::Complete)
  belongs_to :order, class_name: 'Spree::Order', touch: true, optional: true
  belongs_to :cart, class_name: 'Spree::Cart', optional: true
  belongs_to :address, class_name: 'Spree::Address', optional: true      # nil for pickup/digital
  belongs_to :stock_location, -> { with_deleted }, class_name: 'Spree::StockLocation'

  attribute :pickup_point_data, :json   # frozen snapshot of the selected third-party point
  attribute :fulfillment_type, :string  # copied from selected delivery method

  has_many :fulfillment_items, class_name: 'Spree::FulfillmentItem', dependent: :delete_all
  has_many :delivery_rates, -> { order(:cost) }, class_name: 'Spree::DeliveryRate', dependent: :delete_all
  has_one :selected_delivery_rate, -> { where(selected: true) }, class_name: 'Spree::DeliveryRate'
  has_many :discounts, class_name: 'Spree::Discount', dependent: :destroy   # split-adjustments
  has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy

  # status column — plain string, no machine (2026-08-11 status-model decision).
  # Transitions live in Fulfillments::{Fulfill,Cancel,Resume,MarkDelivered};
  # each validates the current status inline and publishes its event.
  has_status :unfulfilled, :fulfilled, :delivered, :canceled

  # Carrier axis — data written by Fulfillments::UpdateTracking, never a machine:
  # tracking_status, tracking_details (JSON), estimated_delivery_at, delivered_at

  def delivery_method = selected_delivery_rate&.delivery_method

  # Commission base for multi-vendor include_shipping (cost net of fulfillment discounts)
  def delivery_amount = cost + discounts.sum(:amount)
end

FulfillmentItem is today's InventoryUnit renamed — the quantity column, its greater_than: 0 validation, the split/extract machinery, and has_many :return_items (FK renamed inventory_unit_id → fulfillment_item_id) all carry over unchanged.

Store API flows (pickup)

Merchant pickup: GET /delivery_methods?fulfillment_type=pickup → GET /delivery_methods/:id/pickup_locations (pickup-enabled StockLocations with package-scoped stock) → select with stock_location_id, which writes Order#preferred_stock_location_id (routing rule picks it up). Third-party points: GET /delivery_methods/:id/pickup_points?latitude=&longitude= (?zipcode=/?query= arrive with the 6.1 contract hardening; calls the method's PickupPointProvider#find_nearby; ephemeral value objects, never persisted) → select with pickup_point_external_id → validated via find_by_external_id, frozen into fulfillment.pickup_point_data. PickupPointProvider::Base + PickupPointOption struct as previously designed.

Migration Path

Phase 1 as previously drafted was one ~20-operation migration; per CLAUDE.md (data transformations never in migrations) and the verification findings it is now split. The earlier draft's migration is void — it re-added shipped columns, targeted the nonexistent spree_product_types, and migrated a spree_store_shipping_methods join table that has never existed (see decisions.md 2026-03-16 correction).

Phase 0 — gates ✅ shipped

  • 6.0-product-types.md shipped — including the fulfillment_types column (owned by that plan's Phase 1 migration; previously orphaned between the two plans).
  • 6.0-cart-order-split.md fleshed out enough to confirm the owner shape (Open Question 1).
  • 6.0-delivery-rate-provider.md Phase 1 (store_id) — independent, can land before or after.
  • 6.0-typed-stock-movements.md confirmed born with fulfillment_id (dependency inverted from the earlier draft).

Phase 1a — renames (schema only) ✅ shipped

  • Tables per the rename map; FK columns: delivery_rates.{shipment_id→fulfillment_id, shipping_method_id→delivery_method_id}, fulfillment_items.shipment_id→fulfillment_id, delivery_method_zones.shipping_method_id→delivery_method_id, return_items.inventory_unit_id→fulfillment_item_id (missed by the earlier draft), orders.{shipment_state→fulfillment_status, shipment_total→delivery_total} (removing the shipped aliases in the same change).
  • display_on → storefront_visible boolean on spree_delivery_methods, jointly with 5.5-6.0-display-on-to-boolean.md Phase 2 (answering its coordination request).
  • Rename affected indexes (spree_shipping_rates_join_index — keep its uniqueness, it's the one-rate-per-method invariant).

Phase 1b — new columns/tables (additive) ✅ shipped

  • delivery_methods: fulfillment_type (nullable, indexed — default 'shipping' lives on the model per house rule; existing rows backfilled by the Phase 2 data task), fulfillment_provider (nullable — model default Manual, #provider falls back on blank), pickup_point_provider.
  • fulfillments: fulfillment_type, pickup_point_data (JSON, jsonb-guarded), cart_id (per owner decision).
  • spree_delivery_method_stock_locations join (unique on the pair).
  • products.excluded_delivery_method_ids (JSON, jsonb-guarded). Dropped 2026-08-06 (never writable through any API/UI) — replaced by ExcludedProductsRule + spree_delivery_method_rule_products; see 6.0-delivery-method-rules.md.
  • NOT here: StockLocation pickup columns (shipped), store_id (delivery-rate plan), seller_id (marketplace wave).

Phase 2 — data rake tasks (spree:migrate_shipping_to_delivery) ✅ shipped

  1. Polymorphic/stored strings (missed entirely by the earlier draft): spree_state_changes.stateful_type + name, spree_adjustments.adjustable_type, spree_stock_movements.originator_type — 'Spree::Shipment' → 'Spree::Fulfillment'.
  2. fulfillment_type backfill: methods with a DigitalDelivery calculator → 'digital' + FulfillmentProvider::Digital; all others 'shipping'. Copy to existing fulfillments from their selected method.
  3. ShippingCategory → ProductType: digital categories → Digital ProductType (fulfillment_types: ['digital']) assigned to their products (the sanctioned one-time assignment per the product-types addendum); everything else rides the ['shipping'] default — no ProductType auto-created.
  4. display_on value conversion (both/front_end → visible), per the display-on plan.

Batched, idempotent, resumable — same guarantees as the split-adjustments migration.

Phase 3 — model renames + behavior ✅ shipped

  • Model/file renames + one-release deprecation aliases (Spree::Shipment = Spree::Fulfillment etc.). ShippingCategory gets no alias — referencing it raises NameError (the earlier draft's = nil would produce confusing NoMethodErrors instead).
  • FulfilmentChanger → FulfillmentChanger; ShipmentHandler removed in favor of providers.
  • Fix raw-SQL/table-name literals that survive renames silently until query time: reverse_chronological, with_free_shipping_promotion?, Package#shipping_categories SQL, determine_state string literals.
  • Package#eligible_delivery_methods + Splitter::FulfillmentType; digital discriminator moved to columns; Product#digital?/#fulfillment_types on ProductType; remove ShippingCategory validations/auto-assign from Product in this phase (the column drops in 6.1 — products must stay saveable in between).
  • Order rollup rename with backorder preserved; CanCanCan grants; permitted attributes; seeds (incl. Seeds::DigitalDelivery and the hardcoded 'Digital'/'Default' store category readers); factories (product_factory assigns a shipping category to every product — whole-suite impact).

Phase 4 — providers + events ✅ shipped

  • FulfillmentProvider::{Base,Manual,Digital,Pickup,PickupPoint} wired into transitions; PickupPointProvider::Base + option struct; Spree.fulfillment_providers / Spree.fulfillment_types registries.
  • Lifecycle events + order.fulfilled; shipment.* → fulfillment.* webhook migration with one-release dual-emit.
  • DigitalLink creation moves from the checkout callback into FulfillmentProvider::Digital (idempotent, per-quantity).

Phase 5 — remaining surfaces ✅ shipped (except the seller axis, gated on the marketplace schema wave)

  • API: switch FulfillmentSerializer#fulfillment_type from computed to column-backed; pickup endpoints (/pickup_locations, /pickup_points); storefront_visible exposure; regenerate the type pipeline. (Most serializer/route work already shipped — see "Already shipped".)
  • Emails gem (20 files — never mentioned in the earlier draft): shipment_mailer, subscriber, templates → fulfillment vocabulary.
  • Dashboard (8 files still on shipment vocabulary) + CSV import/export contract + user docs. The legacy Rails admin's 26 shipping files are deleted with spree/admin at 6.0, not renamed — admin fulfillment management lives in the dashboard via Admin API/SDK.
    • CSV resolved 2026-08-05: product_type is required immediately, no mapping and no deprecation window. This supersedes the earlier "importers get a mapping + deprecation window" intent — a compatibility mapping would translate onto a model that no longer decides anything (see the CSV note above). shipping_category is gone from both import and export.

Phase 6 — cleanup + deferred pickup work (6.1)

  • Pickup point contract hardening (deferred 2026-08-06): PickupPointProvider constructor → new(delivery_method), find_nearby gains zipcode:/query:, store pickup_points endpoint passes them through; drop the experimental marker and publish the custom-pickup-point-provider how-to guide.
  • Drop deprecation aliases, spree_shipping_categories + spree_shipping_method_categories, products.shipping_category_id, dual-emitted shipment.* events, the dangling admin_shipping_category_serializer / v2 platform registrations.
  • Also added by the 2026-08-05 work: DeliveryMethod#display_on / #display_on= / #available_to_display?, the DISPLAY_ON_FRONT_END/BACK_END constants and the DeliveryMethod.normalize_audience shim that accepts them, the deprecated: true shipping_method_categories / shipping_categories associations on DeliveryMethod, the deprecated: true shipping_category / shipping_methods associations on Product, Variant#shipping_category / #shipping_category_id, and the spree_delivery_methods.display_on column. Plus the method bridges listed above: Estimator#shipping_rates/#shipping_methods, Package#shipping_rates/#to_shipment, Coordinator#shipments, Order#line_items_without_shipping_rates, Order#refresh_shipment_rates, and LineItem#shipping_cost/#display_shipping_cost. The CSV surface needs no cleanup — it was cut outright in 6.0.
  • FulfillmentSerializer#fulfillment_type can drop its computed fallback once every install has run spree:migrate_shipping_to_delivery.
  • Multiple tracking numbers per fulfillment (spree_fulfillment_trackings) — pulled into 6.0 as Spree::Delivery by 6.0-shipping-labels-and-deliveries.md (2026-09-03). The row absorbs the whole carrier axis as this deferral required; the fulfillment keeps only tracking/tracking_url as a primary-delivery summary, and the 6.0-edge tracking columns are removed in place rather than bridged.

Phase 7 — status model + delivery tracking ✅ shipped (2026-08-11; fulfill ordering amended 2026-08-12)

Amendment (2026-08-12, decisions.md "The label leads, fulfilled follows"): Fulfillments::PurchaseLabel is the explicit pre-ship label step (loud failures, no status change, no email); Fulfillments::Fulfill buys the label BEFORE marking fulfilled so the shipped email always carries tracking, and a failure after a partial split leaves the split parcel unfulfilled rather than rolling it back. Providers declare generates_labels? and must make create_fulfillment idempotent. Admin API: PATCH .../purchase_label; fulfillment serializer exposes documents + provider_generates_labels; dashboard has Buy label / Print label and a client-generated packing slip.

  • Schema: tracking_status, tracking_details (JSON), estimated_delivery_at, delivered_at on spree_fulfillments.
  • Swap the machine for HasStatus; move transition legality into the four workflows; add Fulfillments::MarkDelivered + Fulfillments::UpdateTracking; delete determine_state.
  • Rollup, serializers, SDK types, dashboard status rendering (modality-aware pickup labels), fulfillment.delivered event.
  • EasyPost: tracker webhook endpoint in the gem feeding UpdateTracking; opt-in tracker creation for hand-entered tracking numbers.
  • Data mapping (6-0-dev migration + 5.6→6.0 manifest step): see the Key Decisions section for the per-modality rules.

Constraints on Current Work

  • Use "delivery method" / "fulfillment" in all new API v3 code. No new shipping_method / shipment references. New tables referencing shipments are born with fulfillment_id.
  • Don't add features to ShippingCategory or InventoryUnit — both are being replaced.
  • Don't include Spree::DisplayOn in new models (display-on plan constraint); use storefront_visible. On DeliveryMethod the boolean column is already authoritative — never read or write display_on there, and filter rate audiences with DeliveryMethod::STOREFRONT / BACKOFFICE, not the legacy DISPLAY_ON_* integers.
  • Don't build on ShipmentHandler — it's removed; fulfillment mechanics belong to providers.
  • Don't touch calculators here — kept per decisions.md 2026-07-27; rate estimation belongs to the delivery-rate-provider plan. Zone→DeliveryZone belongs to 6.0-delivery-zones.md (this plan only births the join table correctly).

Resolved Questions

  1. Fulfillment status naming + rollup. Superseded 2026-08-11 by question 14 — the rename itself stands, the preserved machine does not. shipped → fulfilled (fulfilled_at); Order column → fulfillment_status. The domain and the "guards, pend, conditional resume preserved" clause are replaced by the two-axis status model.

  2. Store scoping is NOT this plan's. store_id on DeliveryMethod is owned by 6.0-delivery-rate-provider.md Phase 1 (greenfield + derived backfill — there was never a join table; see decisions.md 2026-03-16 correction). The earlier draft's PaymentMethod claim is obsolete — that shipped in 5.6 and was amended 2026-07-23 (PaymentMethodRule).

  3. fulfillment_types as JSON column on ProductType (jsonb-guarded), owned by the 6.0-product-types.md addendum.

  4. Lifecycle events: fulfillment.{ready,fulfilled,canceled,resumed} + order.fulfilled; one-release dual-emit of legacy shipment.* webhooks.

  5. Digital auto-fulfillment is new behavior implemented by FulfillmentProvider::Digital (fires fulfill! + DigitalLinks on completion); today nothing auto-fulfills.

  6. delivery_amount = cost + fulfillment discounts — the multi-vendor include_shipping commission base.

  7. Pickup selection routes through Order#preferred_stock_location_id and the PreferredLocation routing rule; stock checks are package-scoped; pickup_stock_policy: 'any' refused for seller-owned locations.

  8. Fulfillment numbers: existing H numbers stay; new records use F.

  9. Owner shape (2026-07-27 cart-order-split expansion; refined 2026-07-28): dual cart_id/order_id exactly-one on Fulfillment — no polymorphism; DeliveryRate carries no owner columns and derives through its fulfillment. Phase 1b's cart_id is unblocked.

  10. Webhook dual-emit window: one release (2026-07-28) — 6.0 dual-emits shipment.* alongside fulfillment.* with a deprecation note in webhook docs; 6.1 drops the legacy names.

  11. ready_for_pickup is a first-class Store API status (2026-07-28) — superseded 2026-08-11 by question 14: the status dies; a pickup customer acts on fulfilled (which for pickup modality means "ready at the counter"), and clients render modality-aware labels. delivered = picked up.

  12. Partial fulfillment is a workflow, not a state-machine event (2026-08-10). Shipping only some of a fulfillment's units splits it first, and split-then-ship in an after_transition callback is the shape 6.0-service-workflows.md prohibits. Spree::Fulfillments::Fulfill takes fulfillment: plus optional per-line-item quantities: absent, it fulfills everything (today's behavior); given a subset, it splits and fulfills the new fulfillment in one transaction. The admin fulfill endpoint gains an optional items param. The state machine stays exactly as resolved in question 1 — the workflow calls it, mirroring Fulfillments::Create's mark_shipped. See decisions.md 2026-08-10.

  13. Fulfillment side effects leave the state machine; the machine keeps the status column (2026-08-10). Amends question 1's "all transition hooks are preserved". after_cancel (restock + provider.cancel_fulfillment) and after_resume (re-unstock) no longer run as after_transition callbacks — they are steps in Spree::Fulfillments::Cancel / ::Resume, with the provider call an external_step so carrier I/O never sits inside the transaction holding the stock movements. What the machine keeps: the status column, the transition graph and its guards, and the publish_*_event callbacks, which describe the status change itself. Fulfillment#after_cancel/#after_resume survive one release as deprecated shells and are the only trace left on the model. The stock movements live in the workflow steps themselves, not in model methods the workflows call: adding #restock_units/#unstock_units to Fulfillment was tried and rejected, because new public model surface created for workflows to call is exactly what breaks when the machine is removed later. Orders::Cancel/::Resume delegate to the fulfillment workflows rather than reimplementing them; Cancel passes notify_provider: false so the order flow batches carrier calls into its own external_step after the transaction commits (a nested external_step would raise, correctly). Fulfillments::Fulfill gained an explicit unstock for the canceled → fulfilled path the resume callback used to cover. The closing claim of this decision — "the dangerous callbacks move, the machine stays" — is superseded by question 14 (2026-08-11): the Fulfillment machine goes too. The side-effect relocation itself stands and made the removal cheap. The other machines (Payment, InventoryUnit, ReturnAuthorization, GiftCard) remain a separate wave. See decisions.md 2026-08-10 and 2026-08-11.

  14. Status model simplified to two axes; delivered is first-class; the machine is removed (2026-08-11). unfulfilled → fulfilled → delivered plus canceled, plain HasStatus; payment/stock gating becomes a Fulfillments::Fulfill validate guard; carrier truth lives on the separate tracking_status axis fed by Fulfillments::UpdateTracking (EasyPost tracker webhooks; manual trackers opt-in). Full decision in Key Decisions → "Status model — two axes". Motivation: merchants consistently reported the lifecycle ending at handover — no confirmed receipt, no bounce, no failed attempt — and nobody understood pending vs ready, which encoded payment state, not fulfillment state. Adds fulfillment.delivered to the question-4 event list and gives the returns window and EU withdrawal period their anchor (delivered_at). See decisions.md 2026-08-11.

  15. One tracking number per fulfillment; a trackings model is 6.1 work (2026-08-11). Parcels that physically diverge are split fulfillments — each with its own items, status, carrier lifecycle and delivered_at, which a flat list of numbers cannot express. A separate spree_fulfillment_trackings model serves only the several-boxes-one- shipment case and must absorb the entire carrier axis when it comes. See decisions.md 2026-08-11.

    Superseded 2026-09-03 by 6.0-shipping-labels-and-deliveries.md: the model lands in 6.0 as Spree::Delivery (polymorphic owner — Fulfillment or Return), taking the entire carrier axis with it exactly as this question required. Split fulfillments remain the answer for parcels that diverge in contents; several parcels on one fulfillment is the several-boxes-one-shipment case. UpdateTracking moves to Spree::Deliveries::. See decisions.md 2026-09-03.

Open Questions

None at this time.

References

  • Current models: spree/core/app/models/spree/{shipment,shipping_method,shipping_category,inventory_unit}.rb
  • Real state machine + hooks: shipment.rb:73-110; rollup: order_updater.rb:140-178; number generator: shipment.rb:7
  • Eligibility gate being replaced: stock/package.rb:73-80 + stock/estimator.rb:61-71; parity spec: spec/models/spree/order_routing/strategy/parity_spec.rb:426-452
  • Shipped API surface: api/app/serializers/spree/api/v3/fulfillment_serializer.rb, api/lib/spree/api/dependencies.rb:111-128
  • Related plans: 6.0-product-types.md (fulfillment_types addendum), 6.0-delivery-rate-provider.md, 6.0-cart-order-split.md, 6.0-order-routing.md, 6.0-6.1-split-adjustments.md, 6.0-typed-stock-movements.md, 6.0-returns-exchanges-claims.md, 6.0-multi-vendor-marketplace.md, 5.5-6.0-display-on-to-boolean.md, decisions.md (2026-07-27 calculators/Zone; 2026-03-16 corrected store-scoping)