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.

59.0 KB
Raw Blame

6.0 Core Rewrite — Implementation Task List

This is a working task tracker, not a plan. Plans of record: 6.0-cart-order-split.md, 6.0-fulfillment-and-delivery.md, 6.0-6.1-split-adjustments.md. Where this file and a plan disagree, the plan wins.

Status: Implemented — all waves complete (Wave 7, the last, closed 2026-07-29; task list verified against HEAD ee39a89, 2026-07-28) UI rule: all admin UI work targets packages/dashboard via Admin API v3 + @spree/admin-sdk. spree/admin is legacy and is not touched — and per Decision 2 it stops loading in the dev server (T0.3). Ordering rule: data-transformation rake tasks are the last wave (user constraint). Schema migrations (renames/additive) are not data migrations and land with their wave.


Scope

In scope — the three plans end-to-end, plus the minimum viable slices of prerequisite plans they hard-depend on:

Prerequisite slice Why it's unavoidable
6.0-product-types.md Phase 1 only Hard blocker: ProductType#fulfillment_types replaces ShippingCategory; Spree::ProductType doesn't exist yet
6.0-delivery-zones.md Phase A + shipping-side Phase C spree_delivery_method_zones must be born joining DeliveryZone (never re-migrated); Estimator address check needs a matcher
6.0-tax-provider.md minimal Base + Internal Split-adjustments forbids reimplementing TaxRate.adjust; the provider is the only sanctioned TaxLine writer

Out of scope (seams left ready, ride separately): rest of product-types (custom-field-definition join, live-template propagation, its API/dashboard), full tax-provider (per-Market column, real commit/void wiring, exemption certificates, TaxRate country/state decoupling), 6.0-delivery-rate-provider.md (store_id + rate provider seam), 6.0-typed-stock-movements.md (unblocked by Wave 2), multi-vendor (F3 split hook ships as a no-op single partition), returns/exchanges/claims, normalize leftovers (Payment/ReturnAuthorization/GiftCard state→status), the spree_zones table drop (blocked on tax decoupling).


Decisions (settled interactively 2026-07-28 — recorded in decisions.md + the plans' Resolved Questions)

  1. Product-types: minimal Phase 1 only — rename + store ownership + fulfillment_types + product_type_id. Rest of that plan is its own effort.
  2. spree_admin is dropped from the starter Gemfile on the 6.0 line (→ T0.3). The gem stays in the monorepo untouched (already out of CI); one-release constant aliases still ship for extensions + emails.
  3. checkout_flow: hard removal, migration guide to Checkout::Registry, no shim.
  4. DeliveryRate gets no owner columns — owner derives through fulfillment.owner.
  5. Reaper defaults: guest 30d / customer 90d / empty 48h, config preferences; money-safety exclusion unconditional.
  6. Webhook dual-emit: exactly one release (shipment.* dropped in 6.1).
  7. ready_for_pickup: first-class Store API status (rollup still reports ready).
  8. partially_canceled: derived predicate, not a stored status value.

Why this order (the four load-bearing choices)

  1. Fulfillment renames before split-adjustments tables — the typed tables are born with fulfillment_id (both plans mandate born-correct, never-migrated columns).
  2. Split-adjustments + fulfillment providers before the Cart flip — Carts::Complete's copy contract (line items, addresses, fulfillments + selected rates, typed money lines) is written once, against final vocabulary. Flipping first would mean writing throwaway copy code for legacy shipments/polymorphic adjustments.
  3. Machine removal is its own wave after the flip — requirements-driven checkout must be live and UpdateStatuses in place before spree_orders.state and Order::Checkout are deleted.
  4. Data rake tasks last — every task reads legacy structures that deliberately stay in place: spree_adjustments (read-only through 6.0 as audit/rollback), spree_zones (until tax decouples), ShippingCategory tables (drop in 6.1), incomplete orders (converted to carts by completed_at, not state).

Each wave must land with its engine suites green (parallel_rspec core + api + emails, plus dashboard tests where touched) before the next starts.


Wave 0 — Prerequisites (minimum viable slices)

T0.1 ProductType Phase 1 (6.0-product-types.md P1, minimal cut) — ✅ done 2026-07-28

  • Migration: spree_prototypes → spree_product_types (+ both join-table renames and FK/column renames per the plan's Phase 1 migration verbatim), add_reference :spree_products, :product_type, store reference, fulfillment_types json/jsonb (nullable, no DB default), products_count, unique index fix on the categories join, spree_product_type_translations table. (Old indexes dropped up front, re-added under stable names — auto-rename would exceed PG's 63-char limit.)
  • Models: Spree::ProductType (store-owned via SingleStoreResource, translatable name, Metafields/Metadata, model-level fulfillment_types default ['shipping'], digital?, requires_shipping?, dependent: :restrict_with_error on products), OptionTypeProductType, ProductTypeCategory; inverse associations on OptionType/Category renamed + dependent: :destroy added.
  • Product: belongs_to :product_type (optional, counter_cache) + additive sync_associations_from_product_type replacing the replace-semantics prototype callback; remove attr_accessor :prototype_id + :prototype_id from PermittedAttributes.
  • Spree::Prototype = Spree::ProductType one-release alias; prototype_factory → product_type_factory (alias kept — testing_support is public API); registries (Spree.metafields.enabled_resources, Spree.translatable_resources); locale keys; remove dangling platform_prototype_serializer registration.
  • Not here: ProductTypeCustomFieldDefinition join, product-types Admin API/dashboard, live-template propagation callbacks (after_create/after_destroy on the option-type join). Those ride with the full product-types effort. Store backfill/orphan-cleanup rake task authored in Wave 7.

T0.2 Drop spree_admin from the dev-server stack (Decision 2) — local half done 2026-07-28

  • DONE 2026-07-29: spree/spree-starter branch 6-0-dev created + pushed (commit b23d55d) dropping spree_admin (React Dashboard is the only admin UI; stays a transitive install until spree_adyen/spree_paypal_checkout drop their gemspec dependency — never required) and spree_stripe (its engine pushes a tax-rate calculator before core populates the registry and broke boot; returns as a Spree.tax_provider adapter with the monorepo move). Monorepo server:create/server-setup.sh now clone -b 6-0-dev (override via SPREE_STARTER_BRANCH); local server/Gemfile synced; boot verified with Spree::Admin::Engine undefined.
  • Keep the gem in the monorepo untouched; the one-release constant aliases from Waves 2/3 are for extensions and the emails gem, not for it.

T0.3 DeliveryZone model (6.0-delivery-zones.md Phase A) — ✅ done 2026-07-28

  • Tables: spree_delivery_zones (single consolidated metadata column per the Collection precedent), spree_delivery_zone_members (typed member_type: country FK / state FK / postal with country_id + postal_code_from/to range or postal_code_prefix).
  • Models: DeliveryZone (dz_) / DeliveryZoneMember (dzm_) with include?/match?, numeric-postal country allowlist gating range members (extensible class_attribute :range_capable_country_codes), postal columns normalized on write, Spree::Address.normalize_zipcode + #normalized_zipcode (single home for zip normalization).
  • :delivery_zone factory (+ :delivery_zone_with_country, :delivery_zone_member). No consumers swapped yet (that's T2.5).

Wave 1 — Cart/Order split: schema + dormant Cart (6.0-cart-order-split.md P1 + slices of P3)

Checkout keeps running on Order through Waves 1–4. The Cart table/model exist but are dormant.

T1.1 Schema — ✅ done 2026-07-28

  • create_table :spree_carts: store/market/channel/currency/locale/customer binding (born-correct customer_id), email, ship/bill address refs, accept_marketing, special instructions, last_ip_address, has_secure_token column, single metadata column, completed_at, completing_at, lock_version, indexed updated_at/completed_at/token. No status column.
  • spree_line_items.cart_id (nullable, indexed). order_id stays permanently.
  • spree_orders.cart_id + unique index (the completion idempotency key).
  • Rename spree_orders.payment_state → payment_status (indexed; one-release alias_attribute :payment_state, :payment_status). (shipment_state waits for T2.1 where it becomes fulfillment_status.)
  • Rename state_lock_version → lock_version, semantics preserved — plus self.lock_optimistically = false on Order and Cart (a column literally named lock_version would otherwise activate Rails' built-in optimistic locking and change save semantics; the API's manual OrderLock concern stays the owner).

T1.2 Owner pattern + registry ownership — ✅ done 2026-07-28

  • LineItem: exactly-one cart_id/order_id validation replacing hard order presence; #owner method (order || cart); internal line_item.order reads migrated to owner (pricing context, tax zone, currency, promo allocation). Order-machine-specific reads (has_checkout_step?, OrderInventory, TaxRate.adjust, reservation exclusion) stay order-guarded (order&.) — they're replaced wholesale in Waves 3/5, and passing a Cart into where(order:) would id-collide.
  • Spree::Cart model skeleton (cart_ prefix id): associations, validations, token, metadata — not yet the checkout owner. :cart factory name reclaimed for Spree::Cart (the legacy bare incomplete-Order :cart factory deleted; its one usage became :order — identical semantics).
  • Checkout::Registry owns its ordered step list (base_step_names, writer for installs that reorder) — Order.checkout_step_names circular dependency cut.
  • Pulled forward from Wave 5 (forced by the Spree::Cart class/namespace collision): legacy Spree::Cart::* services split per Key Decision 8 — 4 actually-dead deleted (Create, Update, ChangeCurrency, EstimateShippingRates) along with the zero-caller OrderContents façade (sole Cart::Update caller); 9 alive moved mechanically to Spree::Carts::* (DI registrations repointed, dead registrations + unread api storefront_cart_* re-exports removed). Behavioral rework stays in T5.1.
  • Ability/permission wiring for Cart — landed in Wave 5 (DefaultCustomer permission set grants Cart + owner-aware LineItem rules).

Wave 2 — Fulfillment & Delivery renames + eligibility (6.0-fulfillment-and-delivery.md P1a/P1b/P3 + delivery-zones shipping-side C)

The big mechanical wave. Whole-suite blast radius via factories; one-release constant aliases keep spree/admin and spree/emails compiling until their sweeps.

T2.1 Rename migrations (schema only — P1a) — ✅ done 2026-07-29

  • Tables per rename map: spree_shipments→spree_fulfillments, spree_shipping_methods→spree_delivery_methods, spree_shipping_rates→spree_delivery_rates, spree_inventory_units→spree_fulfillment_items, spree_shipping_method_zones→spree_delivery_method_zones.
  • FK/column renames: 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, zone_id→delivery_zone_id} (born joining DeliveryZone), return_items.inventory_unit_id→fulfillment_item_id.
  • state→status on spree_fulfillments and spree_fulfillment_items (this wave owns these two normalize renames).
  • spree_orders.shipment_state→fulfillment_status, shipment_total→delivery_total — removing the shipped alias_attribute bridges in the same change (one-release deprecation aliases the other way).
  • display_on → storefront_visible boolean on spree_delivery_methods (schema here; value backfill in Wave 7; scopes/available_to_display? swap to the boolean; factories set it directly).
  • Index renames — spree_shipping_rates_join_index keeps its uniqueness (one-rate-per-method invariant).

T2.2 New columns/tables (P1b) — ✅ done 2026-07-29 (no DB defaults per Decision; model-level)

  • spree_delivery_methods: fulfillment_type (nullable, indexed; model-level default 'shipping'), fulfillment_provider (nullable; model-level default Manual + blank-fallback in #provider), pickup_point_provider. DB defaults deliberately avoided (house rule); existing rows ride the T7.1 backfill.
  • spree_fulfillments: fulfillment_type, pickup_point_data (json/jsonb-guarded), cart_id (nullable — owner pattern).
  • spree_delivery_method_stock_locations join (unique on the pair) + model with vendor-consistency validation stubbed for the marketplace wave.
  • spree_products.excluded_delivery_method_ids (json/jsonb-guarded). Superseded 2026-08-06: column dropped (was never writable); replaced by ExcludedProductsRule + spree_delivery_method_rule_products (6.0-delivery-method-rules.md, feat/product-exlcluded-delivery-methods).
  • Settled (Decision 4): no owner columns on spree_delivery_rates — owner derives through fulfillment.owner.
  • Not here (shipped or other plans): StockLocation pickup columns, store_id (delivery-rate plan), vendor_id (marketplace wave).

T2.3 Model renames + behavior (P3) — ✅ done 2026-07-29

  • Models/files: Fulfillment (ful_), DeliveryMethod (dm_), DeliveryRate (dr_), FulfillmentItem (fi_), DeliveryMethodZone; one-release aliases (Spree::Shipment = Spree::Fulfillment etc.). ShippingCategory gets no alias — NameError on reference.
  • FulfilmentChanger → FulfillmentChanger; ShipmentHandler removed (providers replace it in Wave 4).
  • Status machine preserved exactly: ready guard (#2040), pend, conditional resume, ready_for_pickup reachable from ready + cancelable, all after_transition hooks (restock/unstock, StateChange rows, set_fulfilled_at); shipped→fulfilled, shipped_at→fulfilled_at; the three update_columns escape hatches rewritten through the machine or documented freeze-safe. New numbers F-prefixed; existing H numbers untouched.
  • Raw-SQL/table-literal fixes that survive renames silently: reverse_chronological, with_free_shipping_promotion?, Package#shipping_categories SQL, determine_state string literals.
  • Order side: association renames (fulfillments, delivery_total), rollup rename with backorder preserved (domain: backorder|canceled|partial|pending|ready|fulfilled + nil; ready_for_pickup/picked_up roll up as ready/fulfilled), not_shipped-scope and allow_cancel? reads updated.
  • CanCanCan grants, PermittedAttributes, seeds (incl. Seeds::DigitalDelivery + the hardcoded 'Digital'/'Default' category readers), factories (shipment_factory→fulfillment_factory etc. with aliases; product_factory stops assigning shipping categories — whole-suite impact).

T2.4 Eligibility rework — ShippingCategory retired from behavior (needs T0.1) — ✅ done 2026-07-29

  • Package#eligible_delivery_methods replaces Package#shipping_methods: intersect package items' fulfillment_types (via ProductType, ['shipping'] fallback when typeless) with DeliveryMethod#fulfillment_type. Seam stays inside Stock::Estimator#shipping_methods. (The "minus per-product excluded_delivery_method_ids" subtraction was removed 2026-08-06 — that constraint now lives in ExcludedProductsRule at the rule seam.)
  • Stock::Splitter::ShippingCategory → Splitter::FulfillmentType (homogeneous packages by fulfillment type); Splitter::Digital folds in.
  • Digital discriminator to columns: DeliveryMethod#digital?/pickup?/pickup_point?/requires_address?; .digital scope; Product#digital? + net-new Product#fulfillment_types via ProductType; DigitalDelivery calculator demoted to plain zero-cost (calculators stay — decisions.md 2026-07-27).
  • Remove ShippingCategory presence-validation/auto-assign from Product now (tables/columns drop in 6.1; products must stay saveable in between).
  • Parity spec target: mixed carts still split + get rates (order_routing/strategy/parity_spec.rb:426-452 rewritten to the new inputs).

T2.5 Delivery-zones shipping consumers (delivery-zones Phase C, shipping slice) — ✅ done 2026-07-29

  • DeliveryMethod has_many :delivery_zones; #include?(address) over DeliveryZone; Estimator zone-check swap.
  • Store#countries_with_shipping_coverage rewritten on DeliveryZone members.
  • Factories: delivery methods worldwide-by-default (no zones); Zone.global monkey-patch retired from the shipping path (zone factories stay for tax until the tax plan). Permission sets grant DeliveryZone.
  • Spree::Zone itself stays (tax + legacy admin) — its removal is tax-provider Phase 5 + delivery-zones Phase D, out of scope.

Wave 2 outcome notes (2026-07-29)

  • Deprecation bridges are the standing convention (Damian): legacy associations are Rails 8.1 deprecated: true twins (core gemspec floor bumped to >= 8.1 for rails/rails#55285); legacy methods/scopes warn via Spree::Deprecation then delegate; alias_attribute for columns; constant-assignment aliases for classes. Internal Spree code uses real names only — twin associations carry separate AR caches, and mixing names inside one flow caused real stale-object bugs (auto-capture, set_shipments_cost, Prioritizer#hash_item, Exchange#perform!, unsaved to_shipment graphs).
  • Rails 8.1's strict association resolution rejects alias constants in class_name: and inference — every class_name: now names the real class.
  • Calculator#compute dispatches by class name, so Fulfillment objects route through a new compute_fulfillment → compute_shipment bridge preserving the historical calculator extension point.
  • Retired with no bridge (plan-sanctioned): ShipmentHandler (inlined into after_fulfill until Wave 4 providers), Stock::Splitter::ShippingCategory + Splitter::Digital (classes + specs deleted; Splitter::FulfillmentType registered), ShippingCategory#includes_digital_shipping_method? (zero callers), Zone↔shipping-method associations, the market factory's zone scaffolding.
  • Wave 7 additions discovered: T7.1 must also convert status values (spree_fulfillments.status and spree_orders.fulfillment_status: 'shipped' → 'fulfilled'); FulfillmentItem unit statuses keep 'shipped'.
  • Fulfillments::Create keeps accepting status: 'shipped' (registers as fulfilled); the machine gained ready_for_pickup + mark_ready_for_pickup per plan; new numbers F-prefixed.
  • Suite convergence: 371 → 298 → 173 → 83 → 44 → 9 → 0 across six full-suite iterations.

Wave 3 — Split Adjustments (6.0-6.1-split-adjustments.md P0/P1/P3 + minimal TaxProvider) — still on the Order-based checkout

Runs after Wave 2 (tables born with fulfillment_id). Can proceed in parallel with Wave 4.

T3.1 Order-level freeze (P0 — precondition, built and tested first)

  • OrderUpdater refuses adjustment recalculation on completed orders. This must exist before the Adjustment state machine goes.

T3.2 Typed tables (P1)

  • spree_tax_lines: owner XOR cart_id/order_id, nullable tax_rate_id, adjustable XOR line_item_id/fulfillment_id/fee_id, amount + rate (null: false), label (null: false), included (null: false), provider_id, data json, metadata. Plain FK indexes, no upsert identity.
  • spree_discounts: owner XOR, nullable promotion_action_id/promotion_id, adjustable XOR, amount null: false + DB CHECK ≤ 0, label, kind, code (indexed), value, value_type, metadata.
  • spree_fees: owner XOR, line_item_id/fulfillment_id both-nullable (both nil ⇒ order-level), amount null: false + CHECK ≥ 0, label, kind null: false, metadata; index [order_id, kind].
  • spree_orders.fee_total.

T3.3 Models + adjusters

  • TaxLine (tl_), Discount (disc_), Fee (fee_) per plan code blocks (+ Spree::Metadata, XOR validations, scopes); Order/Cart/LineItem/Fulfillment associations incl. the through-associations.
  • Spree::Adjusters::Base + Adjusters::Promotion: candidate computation returns all candidates; winner-only selection isolated in one method (6.1 stacking slots in there); clamping so net never goes below zero; provenance snapshots (code/value/value_type); dependent: :nullify from the promotion side.
  • FreeShipping → fulfillment-attached Discount, persisted even at zero; Order#has_free_shipping? tests row existence.
  • Order-level discount distribution: largest-remainder, prorated over each line's remaining discounted base, weights frozen at placement.
  • Manual paths: Discount(kind: 'manual') (line-targeted or order-distributed) and Fee (order-level or attached); ad-hoc credits are manual Discounts, never negative Fees.
  • Promotion STI namespace rename REVERTED in Wave 6 (2026-07-29, Damian): promotion rule/action class names stay Spree::Promotion::Rules::* / Spree::Promotion::Actions::* (incl. CreateItemAdjustments) — the rename wasn't required by the split; typed-Discount behavior kept under the legacy names. No STI type-column data task needed.

T3.4 Minimal TaxProvider (the sanctioned TaxLine writer)

  • Spree::TaxProvider::Base (estimate required; commit/void/refund no-op stubs) + Spree::TaxProvider::Internal computing directly from TaxRate data (rate × discounted base; VAT included-in-price math) — no Calculator::DefaultTax indirection; zone matching stays as today (TaxRate.match over Spree::Zone) until the tax plan decouples it.
  • Write contract: replace-all set semantics per estimate (delete target items' TaxLines, insert fresh — kills stale tax after address changes); internal rows keep tax_rate_id + snapshot rate/label/provider_id: 'internal'.
  • Spree.tax_provider seam (global default → Internal; per-Market resolution arrives with the full tax plan). Renamed Spree.default_tax_provider and now returns a class, with the tax plan's per-market selection.
  • Removed: TaxRate.adjust, AdjustmentSource, Calculator::DefaultTax, Adjuster::Tax. TaxRate becomes pure configuration.
  • The exempt? predicate this task first sketched is gone: exemption is typed evidence passed into estimate (Spree::TaxExemption via tax_resolve_exemptions_service), not a boolean a provider answers — see docs/plans/decisions.md 2026-08-05.

T3.5 Typed recalculation + consumer rewrite

  • OrderUpdater: two-pass preserved — discount/fee adjusters persist the discounted taxable base (+ pre_tax_amount), then the sale's tax provider estimate (Spree.tax_provider at the time; now owner.tax_provider); totals via grouped SUMs from typed tables; all denormalized columns kept (incl. taxable_adjustment_total/non_taxable_adjustment_total) + new fee_total; freeze guard from T3.1.
  • Consumers rewritten off source_type/eligible: the ~12 Order readers (order_level_promo_total, shipping_discount, valid_promotion_ids, cart_promo_total, has_free_shipping?, fully_discounted?, taxable_amount, …), Promotion#credits_count (distinct orders with the promotion's discounts), coupon handlers, CouponCodesHandler, OrderPromotion#amount, cross-adjustable negative-total guard, OrderMerger, Cart::Empty, refund calculators (DefaultRefundAmount reads the line's own discounts).
  • Removed: Spree::Adjustment model, Adjustable::AdjustmentsUpdater, Adjustable::Adjuster::*, PromotionAccumulator (dead). spree_adjustments table kept read-only through 6.0 (audit + rollback reference).
  • CanCanCan: grants on TaxLine/Discount/Fee replace Adjustment grants.
  • Factories + the ~65 affected spec files.

Wave 3 outcome notes (2026-07-29)

  • Adjuster is order-scoped, not adjustable-scoped. Spree::Adjusters::Base#initialize(order); Adjusters::Promotion recomputes candidates from connected promotions (plus extra_promotions: during activation), competes per group (line / fulfillment / order-wide), and cleans everything it didn't write this pass. Winner-only policy lives solely in #select_applicable (the 6.1 stacking seam). Actions share PromotionAction#apply_via_adjuster: perform = "does this action yield a candidate?" — losing promotions still connect to the order so they keep competing on later recalculations (reinstatement without stored losers).
  • Cross-order negative-total guard dropped from CreateItemDiscounts#compute_amount — it double-counted the very rows being recomputed; per-line clamping over the remaining discounted base owns the floor now (order net = Σ line nets ≥ 0 since every discount is line-attached).
  • Behavior change (spec'd): an order-level discount distributes nothing when line bases are exhausted (Order#cart_promo_total spec updated -110 → -100 with rationale). Legacy let order-level rows ride on top of fully-discounted lines with shipping absorbing the difference.
  • Order#discounts now means typed rows. The 5.4 alias discounts order_promotions is gone; the three API serializers keep the wire shape via many :order_promotions, key: :discounts.
  • Recalculation reentrancy rules: LineItem after_save no longer runs the updater (services own it — running it mid-mutation cached order.line_items and hid later items); Fulfillment#update_adjustments skips creation (previously_new_record? — recursing mid-fulfillments= dropped records) and completed orders; OrderUpdater#update resets line_items/fulfillments association caches at entry.
  • Internal provider details: fees without a tax category tax against the default TaxCategory; store_pre_tax_amount moved into the provider; TaxRate#adjustment_label is the public label snapshot; TaxRate.tax_lines is dependent: :nullify (rows outlive rates; next estimate drops them). Cart gained dormant tax_address/tax_zone. DeliveryRate#tax_amount computes inline from rate config (no calculator).
  • api engine (ahead of Wave 6): read-only /admin/orders/:id/adjustments endpoints + serializer removed; ?expand=adjustments dropped from admin order/line_item/fulfillment serializers. Typed replacements (tax_lines/discounts/fees CRUD) ship in Wave 6 as planned.
  • Suite convergence: core 299 → 112 → 0 (7499 examples), emails 102/0. Twin-cache lesson reconfirmed in factories (order.shipments.reload → real names).

Wave 4 — Fulfillment providers + lifecycle events (6.0-fulfillment-and-delivery.md P4) — parallelizable with Wave 3

  • T4.1 Provider strategy: FulfillmentProvider::{Base,Manual,Digital,Pickup,PickupPoint}; string class name on DeliveryMethod, constantized at call time; Spree.fulfillment_providers + Spree.fulfillment_types registries (open strings, no inclusion validation); wired into fulfillment transitions.
  • T4.2 Digital auto-fulfillment (new behavior): FulfillmentProvider::Digital fires fulfill! on order completion and creates DigitalLinks idempotently, per quantity — the non-idempotent checkout-callback link creation is removed here (wired from today's finalize!; re-pointed to pipeline step F5 in Wave 5).
  • T4.3 Events: fulfillment.{ready,fulfilled,canceled,resumed} + publishes_lifecycle_events; order.fulfilled when the last fulfillment fulfills + Order#fully_fulfilled?; one-release dual-emit of legacy shipment.* webhooks (Decision 6 — dropped 6.1); PickupPointProvider::Base + PickupPointOption struct (find_nearby/find_by_external_id; ephemeral, frozen into fulfillment.pickup_point_data on selection).

Wave 4 outcome notes (2026-07-29)

  • Provider wiring: Fulfillment#provider resolves through the selected delivery method with a Manual fallback; fulfill transition gated by provider.can_fulfill?; after_fulfill runs provider.create_fulfillment (returned tracking persisted unless an admin already entered one); after_cancel runs provider.cancel_fulfillment.
  • Digital: ensure_links_for is the public idempotent per-quantity primitive. Order#auto_fulfill_provider_fulfillments (called from finalize!) fulfills auto-fulfill providers through the machine, then tops up links for digital-ASSET line items shipping through other providers (vinyl+download combos keep their completion-time links). Order#create_digital_links is a deprecated delegate; the checkout callback is gone.
  • Digital delivery method factory + Seeds::DigitalDelivery now set fulfillment_provider: 'Spree::FulfillmentProvider::Digital' (the Wave 7 backfill maps DigitalDelivery-calculator methods the same way).
  • Events: fulfillment.{ready,fulfilled,canceled,resumed} + order.fulfilled; legacy shipment.* + order.shipped dual-emitted in the same publishers (removed 6.1); old publish_shipment_* methods are warn-delegates. Order#fully_fulfilled? real, fully_shipped? deprecated.
  • Registries: Spree.fulfillment_providers (4 built-ins) + Spree.fulfillment_types (5 open strings) as Environment members.

Wave 5 — The flip: Cart becomes the checkout owner (6.0-cart-order-split.md P3 + P4)

Wave 5 outcome notes (2026-07-29 — COMPLETE, all gates green)

Gates: core 6643/0 (parallel), api 2474/0 (parallel), emails 102/0. One commit. Migration layout after the 2026-07-29 review consolidation: 20260728000003_create_spree_carts fully defines spree_carts (all money/count columns with DB defaults, standardized names discount_total/total_quantity, coupon_code, gift_card_id, lock_version default 0), 20260729100001 keeps only the cross-table owner refs (cart_id on order_promotions/payment_sessions/payments/stock_reservations/coupon_codes) + remove_column :spree_orders, :state, 20260729100002 (order_id nullable on stock_reservations/payment_sessions), 20260729120001 renames spree_orders promo_total→discount_total, item_count→total_quantity (legacy names stay as alias_attribute bridges one release; internal code uses real names). spree_carts.market_id/channel_id are null: false at the DB (2026-07-29 — every store owns a bootstrap default market/channel); spree_orders keeps them nullable through 6.0 (pre-5.5 rows) — the spree:backfill_order_markets manifest step resolves market from store defaults (channel_id was already backfilled by the 5.4→5.5 channels step) and the NOT NULL constraints land in 6.1.

  • Cart owns checkout end to end. Full surface on Spree::Cart (totals + DisplayMoney incl. store-credit/gift-card money, checkout steps via Requirements, market/channel presence resolution, warnings, rebuild_fulfillments! idempotent proposal rebuild + prune_undeliverable_fulfillments!, merge!/associate_user!, store-credit quartet + total_available_store_credit/could_use_store_credit?/total_minus_store_credits, gift card apply/remove/redeem/recalculate ported, update_hooks registry unioned with Order's so legacy Order-registered hooks fire during checkout). CartUpdater < OrderUpdater.
  • Machine gone. Order::Checkout is a lean data module (checkout_steps/current/completed via Requirements + newsletter/user-record/default-addresses). No state column, no next!/checkout_flow/insert_checkout_step/update_from_params. Lifecycle = status draft/placed/canceled + derived predicates; cancel/resume keep side effects verbatim. Orders::UpdateStatuses is the sole payment/fulfillment status writer.
  • Carts::Complete three-phase pipeline (replay → lock+TTL takeover → in-lock recalc → drift guard 409 → validate → draft order + copy contract; offline payment collapses into finalize; external outside txn with Y3 compensation; finalize idempotent). Admin/B2B path Orders::Complete delegates into it and now honors payment_pending:/notify_customer: (kwargs restored for the admin API).
  • Owner XOR everywhere (LineItem, Payment, PaymentSession, Fulfillment, StockReservation, OrderPromotion, CouponCode, typed lines) with a uniform order= cart-routing bridge on every dual-FK model: assigning a Spree::Cart to the legacy order association routes to the cart FK (extensions assign current_order, which is now a Cart). PaymentSession#owner= lets gateways stay owner-agnostic (Gateway::Bogus uses it); session internals (store delegate, find_or_create_payment!, defaults) swept to owner. Fulfillment#selected_shipping_rate_id=/cost-recalc hooks owner-dispatched. Payment-session serializer: order_id reports owner (bridge), new cart_id attribute.
  • Deprecated twins added on Cart (shipments, create_proposed_shipments, set_shipments_cost) so legacy call sites keep working one release.
  • Test support: walkthrough cart-first; cart/line_item/payment/payment_session/stock_reservation factories owner-aware; order factory state: transient shim. Spec rewrites: checkout_spec machine-free (steps/default-addresses/finalize side effects incl. gift-card redemption); state_machine_spec → lifecycle; carts/complete, checkout/advance/update, api store cart+integration specs converted to Cart fixtures; user_methods raw state='complete' SQL → completed_at IS NOT NULL.
  • Deferred to Wave 6: cart_id proper exposure/naming across serializers (order_id bridge documented), drafts cart_id: nil admin scoping, requirements-shaped store surface.

The point of no return; biggest single wave. Everything before it exists so this copy contract is written once.

T5.1 Cart behavior

  • Full Cart model: binding settles the three inconsistent creation paths (market/channel/locale always set); recalculation-on-write — address/market change → re-price, re-tax (provider estimate on the cart), idempotent delivery-proposal rebuild (destructive create_proposed_shipments behavior dies); item changes → totals + reservation Release/Reserve/Extend dispatch carried over from Carts::Update.
  • Fulfillments, delivery rates, and typed money lines are created cart-owned during checkout (owner XOR flips to cart_id).
  • Carts::{Create,Update,UpsertItems} operate on Cart + get DI registration; current_order → current_cart built through Carts::Create.
  • Legacy Spree::Cart::* services: 8 dead ones deleted; 6 re-homed (AddItem/SetQuantity/RemoveLineItem → carts items flow; Associate; Empty; RemoveOutOfStockItems; CompareLineItems → merge strategy).
  • Merge strategy seam (Spree::Dependencies.cart_merge_strategy) + default preserving OrderMerger behavior minus its bugs (currency-mismatch surfaced, no silent >10 overflow destroy).
  • Tiered expiry reaper (guest 30d / customer 90d / empty 48h — config preferences, Decision 5) on indexed updated_at, batched; never reaps carts with authorized/pending payment sessions or transactions.
  • Carts::Validate: full battery (lines present/in stock/not discontinued, email, addresses, delivery selected, payment coverage, guest policy) returning structured { step, field, code, message } errors; also exposed read-only for checkout-readiness rendering.

T5.2 Carts::Complete — three-phase pipeline

  • PREPARE (one txn): replay via completion_result(cart) (order or order_group); with_lock + completing_at with TTL takeover; in-lock recalculation; expected_total drift guard (409 cart_changed); Validate; reservation availability check + hold extension; draft Order creation with copies (line items re-pointed, typed lines per the split-adjustments copy contract, fulfillments + selected rates, address copies, email/currency/locale/market/channel, guest token carried, R number) + unique orders.cart_id.
  • PAYMENT: offline methods (Check, terms, COD, bank transfer, store credit, gift cards, manual) collapse into FINALIZE — single txn, nothing to compensate; external gateways outside any txn with Y3 compensation (destroy draft + copies, clear completing_at, 422 payment_failed); completion gates on "valid payment covers total", never paid?; gift card payments resized by every totals recalculation, P3's included (decisions.md 2026-09-24), and store credit voided last; allow_checkout_on_gateway_error external-only.
  • FINALIZE (one txn, every step idempotent): inventory finalize + unstock + reservation release (single home — fixes the admin-path asymmetry); counters behind persisted flags (coupon, gift card redeem, promo credits); vendor-split hook F3 (no-op single partition); draft→placed + cart.completed_at + UpdateStatuses; after_commit events (order.placed/order.completed), digital fulfillment via provider, account creation/newsletter as non-fatal side jobs.
  • Resumability structural (status: 'draft' + cart_id + completed_at: nil = finalize pending); completion-recovery sweeper job (retries FINALIZE for stale drafts with paid coverage; alerts on persistent failure; never auto-refunds); webhook writer (Payments::HandleWebhook) converges on the same service — 30s delay becomes latency optimization only.
  • Mutation guards: completing_at → 409 cart_locked on item/address/discount writes; lock_version → 409 stale_cart.
  • Admin/B2B Orders::Complete path reuses the same service (idempotency + inventory + reservation release in one place).
  • API contract: the full outcome table (200 order/order_group incl. replay; 422 validation errors in requirements shape; 422 payment_failed; 409 cart_changed/completion_in_progress/cart_locked).

T5.3 Machine removal (P4)

  • Delete Order::Checkout, the spree_orders.state column, checkout_flow/insert_checkout_step/remove_checkout_step, next!/advance/can_go_to_state? (Decision 3: hard removal + migration guide, no shim).
  • Order lifecycle without a machine: status draft/placed/canceled; completed? ≡ completed_at; can_ship?/uneditable?/allow_cancel?/LINE_ITEM_REMOVABLE_STATES-style predicates re-expressed; partially_canceled derived predicate (Decision 8); awaiting_return/returned not carried (returns plan).
  • Orders::Cancel/Resume/Approve flip status with today's side effects verbatim (restock/void/refund branches).
  • confirmation_required? computed from data only (config + selected payment methods); no state fallback on confirm failure.
  • Order state_changes writes dropped (lifecycle events are the audit); payment/fulfillment StateChange rows unaffected.
  • Ransack whitelist: state out; status/payment_status/fulfillment_status in.
  • The six out-of-band state writers (address services etc.) become cart-recalculation triggers.

T5.4 UpdateStatuses (single writer)

  • Spree::Orders::UpdateStatuses — the only writer of payment_status + fulfillment_status; quantize to currency precision before comparing; subtract granted/pending refunds; domains incl. overcharged/voided (payment) and backorder (fulfillment, owned by the fulfillment plan); triggered from payment/refund/fulfillment/return event subscribers, never inline from controllers; replaces OrderUpdater#update_payment_state/update_shipment_state.

T5.5 Test support rewrite

  • order_walkthrough cart-first; order/cart factories (order factories build completed orders through the real completion service or direct construction — decide pattern here); whole-suite green across engines.

Wave 6 — API / SDK / Dashboard / emails / docs

Wave 6 outcome notes (2026-07-29 — COMPLETE)

Backend (T6.1/T6.2). Admin nested /orders/:id/{tax_lines,discounts,fees} (tax read-only; discounts manual-CRUD with 422 discount_not_editable on promotion rows; fees full CRUD, kind defaults surcharge) — all mutations run OrderUpdater#resum_typed_totals!, the sanctioned post-placement edit path (re-sums rows into totals WITHOUT re-running promotion competition/tax estimation; works on completed orders). Spree::Orders::Discounts::Create (DI order_discount_create_service; originally shipped as Orders::AddManualDiscount, renamed pre-release to match the Fees::Create naming) computes flat/percent line-item rows or distributes order-level via the extracted Spree::Adjusters::LargestRemainder. Net-new admin delivery_methods CRUD (+/calculators discovery with preference schemas; flat calculator_type/calculator_preferences params; prefixed tax_category_id/delivery_zone_ids) + delivery_zones CRUD (typed members by country_code/state_abbr/postal prefix-or-range; members replaces the set atomically). Store delivery_methods discovery (storefront_visible scope, fulfillment_type filter) + /:id/pickup_locations (pickup-enabled stock locations, cart_id narrows to full-cart local coverage) + /:id/pickup_points?latitude&longitude via DeliveryMethod#pickup_point_provider_instance. Cart pickup selection: preferred_stock_location_id — a real column + belongs_to, same shape as Order (the 2026-07-29 preference approach was reversed 2026-08-01: spree_carts has no preferences column, so the preference never persisted); prefixed-ID resolution + the pickup-enabled/store-scoping rule live in Carts::Update, mirroring Orders::Create; copied to the order column at completion; pickup_point_external_id on cart fulfillment update validated via provider and frozen into pickup_point_data. FulfillmentSerializer: status column-backed, fulfillment_type column-with-fallback, pickup_point_data + selected_delivery_rate_id exposed, real-name associations. Admin orders scope excludes transient completion drafts (draft + cart_id set). AppliedPromotionSerializer rename frees DiscountSerializer (+TaxLine/Fee/DeliveryZone/DeliveryZoneMember serializers, registry keys, payment-session serializer gets cart_id + owner-bridged order_id). ConfigurationManagement grants DeliveryMethod/DeliveryZone/Member.

Directives landed mid-wave (Damian): (1) market + channel required on Cart AND Order (belongs_to without optional). Supporting invariant: every store owns a bootstrap default market — Stores::Markets#ensure_default_market is unconditional (country fallback: creation param → legacy default_country column → US, created if the countries table is empty), inherits the store's column configuration (currency/locale/supported_locales), and is flagged bootstrap_default so the MarketCountry shipping-coverage validation skips it (plus a DeliveryMethod.none? bootstrap exemption). Store column edits to default_locale/default_currency sync onto the default market (diff-based, not dirty-tracking); supported_currencies_list/supported_locales_list are now the union of markets + legacy columns; Market#ensure_single_default resets the owning store's association caches; markets cascade-delete with their store via destroyed_by_association; Current.market always resolves. defined_preferences no longer picks up preferred_* association writers (Order#preferred_stock_location= phantom), preference readers/writers tolerate NULL preferences columns. (2) Promotion STI namespace rename REVERTED — classes stay Spree::Promotion::Rules::*/Spree::Promotion::Actions::* incl. CreateItemAdjustments (typed-Discount behavior under legacy names; wire type back to create_item_adjustments; single calculator registry key; T7.5 type-column task dropped; decisions.md 2026-03-16 marked reversed). (3) Cart totals columns get DB-level defaults (0/0.0) in migration 100001; dummy apps rebuilt. (4) preferred_stock_location_id on Cart was briefly a preference, reversed 2026-08-01 to a real column (create_spree_carts migration): spree_carts carries no preferences column, so preference writes were in-memory only and the pickup choice was silently lost on save. (5) docs/developer updates skipped (full Spree 6 docs rewrite comes separately).

Final gates after directives: core 7438/0, api 2525/0, emails 103/0 (all parallel where applicable), dashboard tsc+vitest+e2e green, both SDK suites green.

Emails (T6.4). FulfillmentMailer#fulfilled_email + views; ShipmentMailer#shipped_email deprecated delegate; FulfillmentEmailSubscriber on fulfillment.fulfilled (replaces the shipment subscriber — dual-emit means one subscription only); FulfillmentHelper + deprecated ShipmentHelper; FulfillmentPreview; partials on real names; payment-link email → storefront /checkout/:token/payment URL; fulfillment_mailer.* locale keys (legacy keys kept one release).

SDK + Dashboard (T6.3). admin-sdk: orders.{taxLines,discounts,fees} replace orders.adjustments (removed clean), deliveryMethods (+calculators()), deliveryZones, DeliveryMethodParams/DeliveryZoneParams; sdk: deliveryMethods.{list,get,pickupLocations,pickupPoints}; typelizer + Zod + OpenAPI (store+admin) regenerated; both SDK test suites green. Dashboard: order-detail AdjustmentLinesCard (tax grouped by label, discounts with promo lock, fees; Add discount flat/percent + order/line target; Add fee) on store-scoped query keys; settings pages Delivery Methods (fulfillment_type-aware form, calculator discovery-driven preference fields, zone checkboxes, transit days, storefront_visible) + Delivery Zones (typed member editor incl. postal prefix/range) with tables/hooks/schemas/nav (Subject.DeliveryMethod/DeliveryZone); webhook event groups shipment→fulfillment; section_fulfillments label; i18n in all 6 locales (en/de/fr/zh-CN/ar/pl); e2e delivery-settings.spec.ts 4/4 (real API create paths; surfaced + fixed the missing-calculator 422 via model-level FlatRate(0) default).

Finishing work (2026-07-29, post-review autonomous block — scheduled by the delivery-method-rules timing decision):

  • Fulfillment finishing list DONE: Spree::DeliveryMethodStockLocation model wired (associations + DeliveryMethod#available_pickup_locations — configured set, else all pickup-enabled), store pickup_locations endpoint scoped to it + honors pickup_stock_policy ('any' offers pickup regardless of local stock), admin API stock_location_ids (serializer + params) + dashboard pickup-locations picker (pickup type only, i18n ×6), CSV product import gains product_type column (find-or-create per store) with shipping_category kept as a labeled-deprecated mapping until the 6.1 drop, Shipments* identifier sweep in the order detail page.
  • Delivery-method-rules Phase 1 DONE (plan 6.0-delivery-method-rules.md): spree_delivery_method_rules table + Spree::DeliveryMethodRule STI (ItemTotalRule/WeightRule, preference-schema-driven, registry Spree.delivery_method_rules seeded in the engine Environment struct), enforcement via DeliveryMethod#eligible_for_package? in the Estimator's method filter (single line — all three entry points covered), FlatRate's four bound preferences carry deprecated: warnings, spree:migrate_calculator_bounds_to_delivery_method_rules task + manifest step, admin nested /delivery_methods/:id/rules CRUD + /delivery_method_rules/types discovery + serializer + ability, admin-sdk deliveryMethods.rules/ruleTypes, dashboard Conditions section in the edit sheet (add/edit/remove rules via PreferencesForm, i18n ×6). Specs: 8/0 model+estimator+data-task, 7/0 API.
  • Coupon code wired fully (Damian direction): adjuster candidacy on the PERSISTED cart code (in-memory assignments stay handler-only) with activation/deactivation on recalculation + order_promotions join sync; PromotionHandler::Coupon#remove clears the persisted code; gift-card branch restores the dirty attribute before locking; store discount_codes POST persists real-but-not-yet-eligible codes (:coupon_code_not_eligible → success-with-pending, Shopify parity) and rejects unknown/expired without persisting; cart serializer exposes coupon_code. A batch (multi_codes) code is held by the cart from the moment it is saved, and candidacy requires that hold — without it one code discounted every cart that saved it (decisions.md 2026-09-29). Orders too: spree_orders.coupon_code column (migration 140001, indexed), copied at completion, on store+admin order serializers, in the ransack whitelist. Order/Cart writers normalize via super. Coupon battery 212/0 core + 95/0 api; retry spec covers threshold-crossing activation/deactivation and removal.
  • Market backfill trimmed to market-only (spree:backfill_order_markets) after Damian's catch — channel_id is already covered by the 5.4→5.5 channels manifest step on every upgrade path.

Docs (T6.5). SKIPPED per Damian (2026-07-29): docs/developer gets a full Spree 6 rewrite separately — no incremental doc edits now. Only CLAUDE.md plan statuses + docs/plans/* updated; docs/api-reference/*.yaml regenerated (build artifact of the rswag pipeline, not docs work).

T6.1 Store API v3

  • carts/fulfillments_controller requirements-driven (drop the cart.next loop); completion endpoint returns the Wave-5 contract.
  • Pickup flows: GET /store/delivery_methods?fulfillment_type=pickup, …/:id/pickup_locations (pickup-enabled StockLocations, package-scoped stock), …/:id/pickup_points?latitude&longitude; selection writes Order#preferred_stock_location_id (routing rule) / validated pickup_point_external_id frozen into pickup_point_data.
  • FulfillmentSerializer#fulfillment_type computed → column-backed; storefront_visible exposure; ready_for_pickup returned as its own status (Decision 7).

T6.2 Admin API v3

  • /admin/orders/:id/{tax_lines,discounts,fees} replace /admin/orders/:id/adjustments: tax_lines read-only; discounts/fees full CRUD for manual rows (promotion-sourced rows 422 on edit); mutations run recalculation on the changed base — this is the sanctioned post-placement edit path and works on completed orders.
  • Net-new delivery_methods CRUD controller (none exists today) + nested delivery_method_stock_locations; delivery_zones CRUD with typed members.
  • Fulfillments admin surface completed (create via Fulfillments::Create, ready/fulfill/cancel/track through providers); admin Drafts list scoped cart_id: nil; status filters (status/payment_status/fulfillment_status).
  • Scopes (read_orders/write_orders, delivery settings scopes) + CanCanCan abilities on the typed models.

T6.3 SDK + Dashboard

  • admin-sdk: orders.{taxLines,discounts,fees} replacing orders.adjustments (unreleased — break cleanly); deliveryMethods, deliveryZones; fulfillments updates. Full type pipeline: typelizer → Zod → integration specs → rswag:specs:swaggerize → SDK tests.
  • Dashboard order detail: typed panels (tax grouped by rate/label, discounts, fees) + "Add fee"/"Add discount" (amount-or-percent via value/value_type, target picker order/line), <Can>-gated, RHF + Zod + mapSpreeErrorsToForm; fulfillment vocabulary + status/actions sweep (remaining shipment refs: orders/$orderId.tsx, schemas/webhook-endpoint.ts event list — dual-emit names).
  • Dashboard settings: Delivery Methods page (fulfillment_type, provider selects, pickup locations, storefront_visible, zone picker) and Delivery Zones page (typed member editor incl. postal ranges/prefixes).
  • i18n keys in all locale files (en/de/fr/zh-CN/ar/pl, dashboard + dashboard-core); e2e specs for the new pages.

T6.4 Emails

  • Fulfillment vocabulary sweep (~20 files: shipment_mailer → fulfillment, subscriber, templates); _purchased_items_table partials iterate typed associations (no .eligible/source_type); payment-link email checkout_state_url(token, :payment) → cart checkout URL.

T6.5 Docs + guides

  • developer docs updates dropped — full Spree 6 docs rewrite happens separately (Damian 2026-07-29); CLAUDE.md plan-status updates done.

Wave 7 — Data migrations (LAST) + upgrade manifest

Wave 7 outcome notes (2026-07-29 — COMPLETE)

Four rake tasks + the T7.5 backfill, all wired into lib/spree/upgrades/5_6_to_6_0/manifest.yml (machine-runnable via rake spree:upgrade); specced in spec/lib/tasks/six_zero_data_migrations_spec.rb (12 examples: happy paths + idempotency + reconciliation freeze + completed-order untouchability).

  • spree:migrate_shipping_to_delivery (lib/tasks/delivery_migration.rake): polymorphic strings (StateChange.stateful_type, StockMovement.originator_type, legacy spree_adjustments.adjustable_type via a table-bound anonymous AR class), StateChange name 'shipment'→'fulfillment' + prev/next 'shipped'→'fulfilled', fulfillments.status 'shipped'→'fulfilled', delivery-method fulfillment_type/fulfillment_provider backfill (DigitalDelivery calculators → digital + Digital provider, rest shipping/Manual) copied onto existing fulfillments via their selected rate, digital shipping categories → per-store Digital ProductType assignment (created on demand), display_on → storefront_visible boolean. Batched (BATCH_SIZE env), value-narrowed idempotency.
  • spree:migrate_zones_to_delivery_zones: legacy Zone ids in spree_delivery_method_zones.delivery_zone_id (the rename migration reuses the column) → new DeliveryZones with country/state members + join re-point; metadata.migrated_from_zone_id marker for idempotency; id-collision ambiguity logged + skipped (run right after db:migrate, before creating new zones); tax zones untouched; unreferenced shipping zones logged.
  • spree:migrate_adjustments_to_typed_rows: per-order transactional mapping (TaxRate→TaxLine w/ rate snapshot + provider_id internal; eligible PromotionAction→Discount with promotion/code snapshots, order-level distributed largest-remainder via the shared Spree::Adjusters::LargestRemainder; nil-source by sign → manual Discount / surcharge Fee; unknown sources → Fee with provenance metadata; ReturnAuthorization → skip + freeze). Totals never touched; reconciliation (promo vs discounts, additional tax vs tax lines, 1-cent tolerance) freezes + logs non-reconciling orders in private_metadata. spree_adjustments intact as rollback source. Skips orders with any typed rows.
  • spree:migrate_incomplete_orders_to_carts (the final flip): incomplete = completed_at nil AND canceled_at nil; one Cart per order (token/binding/addresses/totals copied, timestamps preserved, market/channel resolved via the ensure_* helpers since save skips validation, pickup column copied directly); ALL dual-FK records re-owned in place (LineItem, Fulfillment, Payment, PaymentSession, StockReservation, CouponCode, OrderPromotion, TaxLine, Discount, Fee — update_all(cart_id:, order_id: nil), money moves never copies); FulfillmentItem.order_id nulled, Order StateChanges deleted, hollow order row deleted. Payment-session orders convert LAST. Completed + canceled orders untouched.
  • spree:product_types:backfill (T7.5, in products.rake): store-less product types → default store, orphaned option-type joins removed, product counters reset. (Promotion STI type-column task DROPPED — namespace rename reverted in Wave 6.)
  • T7.6 manifest: five new steps appended to the 5.6→6.0 manifest in dependency order (shipping→delivery, zones, adjustments→typed, orders→carts, product-types) with operator notes incl. the zones-before-new-delivery-zones ordering constraint and the typed-rows-before-carts dependency. Developer-facing upgrade doc deferred with the rest of the Spree 6 docs rewrite.

All batched, idempotent, resumable. They read legacy structures that stay in place (see "Why this order" #4).

  • T7.1 spree:migrate_shipping_to_delivery: stored polymorphic strings (spree_state_changes.stateful_type+name, spree_adjustments.adjustable_type, spree_stock_movements.originator_type: 'Spree::Shipment'→'Spree::Fulfillment'); fulfillment_type backfill (DigitalDelivery-calculator methods → 'digital' + Digital provider, rest 'shipping'; copied to existing fulfillments); ShippingCategory → ProductType (digital categories → Digital ProductType assigned to their products — the sanctioned one-time assignment; everything else rides the ['shipping'] default); display_on value conversion.
  • T7.2 spree:migrate_zones_to_delivery_zones: shipping-referenced Zones → DeliveryZones (name/description + country/state members); tax-only zones left for the tax plan; unreferenced zones logged + skipped.
  • T7.3 Adjustments → typed rows: mapping table per plan (TaxRate→TaxLine w/ rate copy + provider_id: 'internal'; eligible PromotionAction→Discount w/ snapshots; ineligible skipped; nil-source by sign → manual Discount / order-level Fee 'surcharge'; ReturnAuthorization skipped + order marked recalculation-frozen; unknown sources → Fee with class in metadata); order-level rows distributed largest-remainder; order totals byte-for-byte untouched; per-order reconciliation asserts typed sums match legacy totals (non-reconciling orders logged + frozen, never force-balanced); line-level shift logging.
  • T7.4 Incomplete orders → Carts: one Cart per incomplete order (token/binding/addresses); line items re-owned (cart_id set, order_id nulled); hollow order rows deleted; mid-payment orders converted last with payment sessions re-linked; completed orders untouched (cart_id: nil).
  • T7.5 Small companions: product-types backfill (store_id → Store.default, orphaned join rows deleted, reset_counters). (Promotion STI type-column task dropped — the namespace rename was reverted in Wave 6.)
  • T7.6 Upgrade manifest: documented 5.6→6.0 order (migrate, then tasks in the sequence above), rollback notes (spree_adjustments intact and re-derivable through 6.0; spree_carts conversion reversible until the old rows age out), operator checklist.

Traceability (plan phase → task)

Plan Phase Task
cart-order-split P1 schema T1.1
cart-order-split P2 data T7.4
cart-order-split P3 model+services T1.2, T5.1, T5.2, T5.5
cart-order-split P4 machine removal T5.3, T5.4
cart-order-split P5 API/SDK/docs T6.1, T6.3, T6.4, T6.5
fulfillment P0 gates T0.1, T0.3, T1.1
fulfillment P1a/P1b schema T2.1, T2.2
fulfillment P2 data T7.1
fulfillment P3 models+eligibility T2.3, T2.4, T2.5
fulfillment P4 providers+events T4.1–T4.3
fulfillment P5 surfaces T6.1–T6.4
split-adjustments P0 freeze T3.1
split-adjustments P1 tables T3.2
split-adjustments P2 data T7.3
split-adjustments P3 models T3.3, T3.4, T3.5
split-adjustments P4 API/SDK/admin T6.2, T6.3
product-types P1 (minimal) T0.1, T7.5
delivery-zones A + C(shipping) T0.3, T2.5, T7.2
tax-provider minimal Internal T3.4

Rough sizing

Wave Size Dominant risk
0 M Prototype rename ripples (permitted attrs, factories)
1 M LineItem owner touches pricing/tax/inventory paths
2 XL Whole-suite factory churn; silent raw-SQL survivors
3 XL Promotion/refund money math parity; ~65 spec files
4 M Digital auto-fulfillment is new behavior
5 XL Completion pipeline correctness (idempotency, payment edges); order_walkthrough rewrite
6 L Net-new admin surfaces (delivery methods/zones) + full type pipeline
7 L–M Reconciliation logic in T7.3; ordering guarantees in T7.4