Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Update plans
Damian Legawiec81f9549cbb05
diff --git a/CLAUDE.md b/CLAUDE.mdindex 9996a6540b..bd1f7e944d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -16,7 +16,7 @@ Active plans (6.0 target, work pending):- `6.0-b2b-storefront-purchasing.md` — Storefront company self-service (account section: members, invitations, address book, company orders; the invitation acceptance page the mailer already links) + company-aware checkout (buying-for picker on cart **and** checkout, company address book replacing the personal one at the address step). **Implemented, in review 2026-08-27** (spree/spree#14498 + spree/storefront#214). **No polymorphic owner on Cart/Order** — a purchase keeps two buyer-side parties (`customer_id` + `company_id`), the industry dual axis; OSS ships plain machinery, the polished buyer portal is Enterprise. Backend grew past the planned one-guard widening: `Spree::HasAddressBook` lets an owner declare where its default slots live (a customer's `bill_address_id` vs a company's `default_bill_address_id`) so `Addresses::Create`/`Update` work for any owner — they silently dropped a company's default flag before; default flags are three-state (claim / give up / say nothing) and released by conditional UPDATE, never read-then-write; `Company#address_book` is the inherited reading list, and reads inherit while writes stay with the owning node. **Constraints now:** never branch on an address owner's class — ask the owner (`has_address_book`); a new owner declares its slots or its defaults silently no-op; nothing storefront-side may branch on a member's "role" (OSS has none — gate on standing).- `6.0-catalog-agreement-rework.md` — Implementation of the one-question-per-entity catalog consequences (design finalized 2026-08-30; extracted from the `6.0-b2b-companies-and-catalogs.md` amendment block so its Implemented status stops hiding unbuilt work; **sequence Wave 1 — everything catalog-shaped builds on it**; **fully implemented** — phases 1–3 2026-08-30 (schema inversion, resolver leak fix, rule supersession), phase 4 2026-08-31: inline `price_list` payload, agreement editor, products-with-prices view (`?expand=catalog_price` on the catalog's nested products listing, resolved by `Spree::Catalogs::ResolvePrices` into `explicit`/`automatic`/`base` and rendered as columns on the assortment rows), a create wizard writing once on Finish (Details → Audience → Products → Pricing → Review, on the shared `Wizard`/`WizardProgress` shell in dashboard-ui), removal warnings; the transitional `Catalog#price_list_id` accessors removed — the inline payload is the only binding; **catalogs are born inactive** and go live through `Spree::Catalogs::Activate`/`Deactivate` (hooks `after_activate`/`after_deactivate` for cache sweeps and company notifications; activation refused for a catalog with no assignments unless it is a channel's default)): the binding inversion (`spree_price_lists.catalog_id` replaces `spree_catalogs.price_list_id`; catalogs migration rewritten in place — unreleased edge; generic rule matching skips owned lists by FK in `PriceList.for_context`, closing the deactivated-catalog leak in `bound_price_list_ids`, which is deleted along with its `Spree::Current` memoization; the catalog↔list binding is applied in an `after_save`, never on assignment — a rejected save must not silently release a list store-wide); `PriceRules::CustomerGroupRule`/`UserRule` **grandfathered like `ChannelRule`** (revised 2026-08-30: kept working indefinitely, `superseded?` hides them from the rule picker — NO deprecation warning, NO removal date, NO data task; migrating who-gets-which-price automatically is a silent-price-change risk merchants gain nothing from). **Constraints now:** no new reads of `spree_catalogs.price_list_id` or `bound_price_list_ids` (the `Catalog#price_list_id` accessors are gone — bind through `price_list`, deferred into the save); no new features on the grandfathered price rules (audience targeting is catalog assignment, channel pricing is the default catalog); catalog-page features (terms, pricing card) mount on the agreement editor, never parallel surfaces; a catalog's resolved price is read through `Spree::Catalogs::ResolvePrices` or its `catalog_price` expansion — never re-derived client-side, since an adjusted amount is computed on read and never stored (that reading answers "what will this agreement charge", so it ignores the catalog's `active` flag — what a buyer actually pays is `PricingProvider::Internal`'s question); going live is never a form field — activation is its own act through the workflows, so a plain Save cannot change whether an agreement applies.-- `6.0-b2b-wholesale-shipping.md` — Wholesale/freight shipping (design finalized 2026-08-30, nothing built): **`Spree::PackageType`** — store-scoped packaging vocabulary (`box|envelope|carton|pallet|container`, one default per store Channel-style) absorbing the four `default_package_*` store preferences (one-release bridges; deliberately NOT `Spree::Package` — `Stock::Package` is the in-memory packer); variant packing chain `carton_package_type_id` + `units_per_carton` + `carton_weight` + `cartons_per_pallet` (geometry on the shared carton row, packing facts on the variant; Unit → Carton → Pallet → CBM/weight); unit-aware `Spree::FreightSummary` (units/cartons/pallets/CBM/gross weight, `complete?` flag) built on the currently-unused `Stock::Package#volume` chain via a new `Spree::Measurement` conversion helper; shipment tiers = `DeliveryMethodRules::VolumeRule` (CBM min/max) + `CompanyRule` (`company_presence`) — **no new delivery profile kind** (the same product ships parcel retail and carton wholesale, and a product has one profile); **unpriced rates are first-class** (`unpriced` on Estimate + `spree_delivery_rates`, estimator skips markup, UIs render "quoted after review" — never a $0 rate that displays as Free) returned by `DeliveryRateProvider::Freight`, whose rate `metadata` snapshots the summary + deposit terms (frozen at completion — duties doctrine, never re-derived); **deposits are collected, not displayed**: deposit terms → `Cart#amount_due_at_checkout`, `Carts::Complete` validates payments against the deposit (base = order total at placement), order completes `partially_paid` with the existing `outstanding_balance` (2026-08-30 amendment: the method-level `deposit_percentage` is a *default source* feeding the order's `payment_terms` snapshot — see `6.0-6.1-b2b-payment-terms.md`); the forwarder's quote lands later as `Fee(kind: 'freight')` through `/admin/orders/:id/fees`. **Constraints now:** all volume/CBM math goes through the unit-aware helper (raw dimension-column multiplication is forbidden — the `WeightRule` raw-number shortcut does not extend to volume); no new readers of the `default_package_*` preferences; never model quote-later as a zero-cost priced rate; carton geometry never becomes variant columns; nothing may assume a completed order is paid in full (check `payment_status`/`outstanding_balance`); post-placement freight charges are Fees, never delivery-rate edits.+- `6.0-b2b-wholesale-shipping.md` — Wholesale/freight shipping (design finalized 2026-08-30, nothing built): **`Spree::PackageType`** — store-scoped packaging vocabulary (`box|envelope|carton|pallet|container`, one default per store Channel-style) absorbing the four `default_package_*` store preferences (one-release bridges; deliberately NOT `Spree::Package` — `Stock::Package` is the in-memory packer); variant packing chain `carton_package_type_id` + `units_per_carton` + `carton_weight` + `cartons_per_pallet` (geometry on the shared carton row, packing facts on the variant; Unit → Carton → Pallet → CBM/weight); unit-aware `Spree::FreightSummary` (units/cartons/pallets/CBM/gross weight, `complete?` flag) built on the currently-unused `Stock::Package#volume` chain via a new `Spree::Measurement` conversion helper; shipment tiers = `DeliveryMethodRules::VolumeRule` (CBM min/max) + `CompanyRule` (`company_presence`) — **no new delivery profile kind** (the same product ships parcel retail and carton wholesale, and a product has one profile); **unpriced rates are first-class** (`unpriced` on Estimate + `spree_delivery_rates`, estimator skips markup, UIs render "quoted after review" — never a $0 rate that displays as Free) returned by `DeliveryRateProvider::Freight`, whose rate `metadata` snapshots the summary + deposit terms (frozen at completion — duties doctrine, never re-derived); **deposits are collected, not displayed**: deposit terms → `Cart#amount_due_at_checkout`, `Carts::Complete` validates payments against the deposit (base = order total at placement), order completes `partially_paid` with the existing `outstanding_balance` (2026-08-30 amendment: the method-level `deposit_percentage` is a *default source* feeding the order's `payment_terms` snapshot — see `6.0-6.1-b2b-payment-terms.md`); the forwarder's quote lands later as `Fee(kind: 'freight')` through `/admin/orders/:id/fees`. **Constraints now:** all volume/CBM math goes through the unit-aware helper (raw dimension-column multiplication is forbidden — the `WeightRule` raw-number shortcut does not extend to volume); no new readers of the `default_package_*` preferences; never model quote-later as a zero-cost priced rate; carton geometry never becomes variant columns; nothing may assume a completed order is paid in full (check `payment_status`/`outstanding_balance`); post-placement freight charges are Fees, never delivery-rate edits; freight tracking (PRO/container number) is a hand-entered `Spree::Delivery` row and its delivered state is staff-confirmed, while a bill of lading is never a `ShippingLabel` (cross-referenced 2026-09-03 from `6.0-shipping-labels-and-deliveries.md`).- `6.0-b2b-quantity-rules.md` — B2B MOQ + order multiples + purchase unit (design finalized 2026-08-30 under the one-question-per-entity doctrine — decisions.md): variant base columns `minimum_order_quantity`/`order_multiple`/`purchase_unit` (`unit|carton`, display-only vocabulary — stored quantities stay units) binding every cart, enforced as named steps in `Carts::AddItem`/`UpsertItems` on the RESULTING line quantity and re-checked at `Carts::Complete` (staff/admin unrestricted; server refuses invalid quantities naming the nearest valid neighbors — **never silently rounds**); storefront steppers step by the multiple / count cartons ("2 CTNS — 48 units"). **Commercial terms are Catalog data:** the catalog-wide default = `minimum_order_quantity` + `order_multiple` **columns on `spree_catalogs`** (same pair at three levels: variant base → catalog default → override), contextual per-SKU tiers = `spree_catalog_quantity_rules` (catalog_id, variant_id both null: false, one plain unique index — strictly overrides), and the cart-level minimum = `spree_catalog_order_minimums` (per-currency rows, never one amount + a currency column) — **deliberately typed tables per grain, never one generic catalog_rules table or an STI rule family** (hot-path indexed lookups + DB uniqueness; rules are matching predicates, terms are values — typed-adjustments doctrine), all resolved **per-field nearest-agreement-wins** through `Catalog.for_context` (override row → catalog columns → variant base; a channel minimum is just its default catalog's terms; a terms-only catalog with empty assortment is legitimate); serializers expose the buyer's *resolved* rules + the minimum/shortfall. The earlier same-day `ChannelRule` STI family is superseded — access gating (`storefront_access`/`guest_checkout`) stays as Channel preferences because gating binds before identity exists. **Constraints now:** nothing below the cart layer may read quantity rules (stock/allocation/fulfillment stay unit-pure); new item mutations keep routing through `AddItem`/`UpsertItems`; commercial terms are catalog rows/columns resolved per-field — no purchase-term settings on Channel, no term columns on variants beyond the base rules; never move gating onto catalogs.- `6.0-price-list-automatic-pricing.md` — Automatic price adjustments (design finalized 2026-08-30): `spree_price_lists.price_adjustment_percentage` (signed decimal, nil = fixed list; `adjust_compare_at` boolean) — the resolver derives base × factor **on read** for variants without an explicit row (explicit amounts override per variant × currency; nil-amount placeholder rows fall through), currency-rounded, currency-agnostic (applies to every base currency), **never materialized** (no refresh jobs, no drift; resolution cache keys must include the base price's version). Combined with `VolumeRule` this gives automatic % volume discounts with zero rows to maintain. **Catalog-owned lists only** (revised 2026-08-31): a percentage has no product scope of its own — the owning catalog's assortment is what scopes it — so `price_adjustment_percentage` is refused on a standalone list by validation, and the Pricing card lives on the catalog page, never the standalone price-list page. A standalone list with no rules, no catalog and no products is refused activation. Product-scoped store-wide percentage discounts are a Promotion's job. **Constraints now:** no job/rake/import may write price rows computed from an adjustment; price exports/feeds/reports must resolve through the pricing provider once adjustment lists exist; "how numbers are made" lives on PriceList, never Catalog.- `6.0-b2b-customer-po-numbers.md` — Buyer PO reference on orders (design finalized 2026-08-30): `po_number` string on cart + order (industry-exact name; copied at completion; staff may correct post-placement as a plain write — it is not money) + optional **`po_document`** private-storage attachment (direct upload, spoofing-protected, blob re-attached to the order at completion — no competitor has order-native PO upload) + **`po_number_required` boolean on `Spree::Company`** (per-company is the market's control granularity; deliberately NOT a catalog term — buyer process ≠ agreement; not governance, so the OSS-companies constraint holds) enforced as a `Carts::Complete` validation (`code: 'po_number_required'`, staff-created orders skip); `po_number` ransackable + the dashboard order search matches number OR PO; surfaced on admin order page, customer order history, confirmation email, and every future order-facing document. The Enterprise quote plan's `customer_reference`/attachment were replaced by these order fields (amended 2026-08-30). **Constraints now:** never model the buyer PO as a payment method or couple it to tender choice; `po_number` (buyer reference) and `Spree::PurchaseOrder` (merchant procurement, inventory-operations) never mix — no shared endpoints/serializers/vocabulary; new order-facing documents/emails render `po_number` when present; post-placement PO edits never route through the order-change substrate.@@ -35,7 +35,8 @@ Active plans (6.0 target, work pending):- `6.0-normalize-state-to-status.md` — Rename state → status on Payment, Shipment, InventoryUnit, ReturnAuthorization, GiftCard- `6.0-document-numbers.md` — Document number customization (**implemented 2026-08-13**): `Spree::Core::NumberGenerator` module factory → **`has_spree_number prefix: 'R'`** (macro from `Spree::HasNumber`, included into `Spree::Base` — no per-model include) + runtime `Spree.number_generators` registry (`Sequential` | `Random` strategies). **Sequential is the 6.0 default** (per-`(store, resource_type)` `spree_number_sequences` counter, `with_lock`, start 1001), random opt-in; merchant settings = one "Order numbers" card (prefix/suffix/format/start as Store preferences) — orders only. Fulfillment + Payment numbers become **derived methods** (`R1001-F1`/`R1001-P1`; stored value honored on legacy rows, columns frozen — never write them; gateway `order_id` = `payment.number`); every other numbered model keeps its stored number (Import/Export mail theirs, so they stayed numbered too), and `Spree::PurchaseOrder` must be born with `has_spree_number prefix: 'PO'`. Saving a numbered record with `validate: false` requires calling `generate_number` first. Never parse/regex a `number`; mostly-gapless, never legal invoice numbering.- `6.0-delivery-profiles.md` — **Implemented in PR #14404 (2026-08-09).** `Spree::DeliveryProfile` = ShippingCategory promoted via table rename (`spree_shipping_categories`→`spree_delivery_profiles`, `products.shipping_category_id`→`delivery_profile_id`): store-scoped STI (kinds `DeliveryProfiles::Shipping`/`::Digital` via `Spree.delivery_profile_types`), one default per store, products reference it directly and it's required (auto-assigned: type template else store default; ProductType stamps at creation only — template doctrine). Profile ↔ stock locations (origins, empty=all) + profile→zones + profile→methods; method binds ≤1 zone (m:n join dropped), optional ships-from narrowing per method (no location-group layer — considered, dropped). **Classes only, NO string vocabularies:** method `fulfillment_type` column dropped, `Spree.fulfillment_types` registry + ProductType array deleted; behavior = `FulfillmentProvider` class predicates (`digital?`/`pickup?`/`pickup_point?`/`requires_address?`), rate-provider `requires_address?`, profile kind `digital?`/`requires_shipping_address?` + composition validations. Carts split per profile (`Splitter::DeliveryProfile`); Coordinator allocates only from profile-covered locations. `spree:migrate_delivery_profiles` (5.6→6.0 manifest) does store assignment/kind detection/non-narrowing fold-in/method m:n collapse (`spree_shipping_method_categories` survives to 6.1 as source). ShippingCategory/ShippingMethodCategory classes + associations deleted. Supersedes the string-registry + "named groups 6.1" decisions.-- `6.0-fulfillment-and-delivery.md` — Shipment→Fulfillment, ShippingMethod→DeliveryMethod, drop ShippingCategory, FulfillmentProvider strategy, pickup (merchant StockLocation) + pickup_point (third-party PickupPointProvider). **Shipped to 6-0-dev (Waves 2+4+6):** renames + deprecated twins, providers (Manual/Digital/Pickup/PickupPoint), dual-emit events, store pickup discovery endpoints, admin delivery_methods/delivery_zones CRUD + dashboard settings pages, FulfillmentMailer; Wave 7 shipping→delivery data migration remains. Pickup work beyond shipped code deferred to 6.1 (2026-08-06): contract hardening (`new(delivery_method)` ctor, `find_nearby` zipcode/query) + how-to guide; `PickupPointProvider::Base` stays **undocumented in 6.0** (v6 docs cover only the delivery rate provider interface) — never add pickup-provider docs in 6.0 work. Delivery mechanics live on provider classes (`pickup_point` provider ships but stays unregistered until 6.1; `local_delivery` cut = shipping + postal-code zone); the string fulfillment-type registry was deleted by `6.0-delivery-profiles.md`. **Partial fulfillment (2026-08-10, resolved question 12):** shipping a subset is `Spree::Fulfillments::Fulfill` (optional per-line-item `items:` + `tracking:` + `notify_customer:`; splits then fulfills in one transaction) — never a state-machine event, since split-then-ship in an `after_transition` is what service-workflows prohibits. **Side effects left the machine (2026-08-10, question 13):** `after_cancel`/`after_resume` are gone as transition callbacks — restock + carrier stand-down live in `Fulfillments::Cancel`/`::Resume` as inline steps (provider call is an `external_step`; `notify_provider: false` lets `Orders::Cancel` delegate and batch carrier I/O after its own transaction), `after_cancel`/`after_resume` are deprecated shells and the only trace left on the model — never add public model methods for workflows to call. **Status model (2026-08-11, question 14): the machine is REMOVED.** `status` = plain `HasStatus` `unfulfilled → fulfilled → delivered | canceled` (`pending`/`ready`/`ready_for_pickup` collapse — payment/stock gating is a `Fulfillments::Fulfill` validate guard, pickup renders modality-aware labels); `delivered` = confirmed receipt (`Fulfillments::MarkDelivered`, `delivered_at`, `fulfillment.delivered`) — the returns window + EU withdrawal anchor; carrier truth is the separate `tracking_status` axis (data, never a machine) written by `Fulfillments::UpdateTracking`, fed by EasyPost tracker webhooks (opt-in trackers for hand-entered numbers). Rollup domain `backorder | canceled | partial | unfulfilled | fulfilled | delivered`. **Phase 7 shipped 2026-08-11** (core + API + dashboard + EasyPost tracker webhook + `spree:migrate_fulfillment_statuses`); **label leads, fulfilled follows (2026-08-12):** `Fulfillments::PurchaseLabel` = explicit pre-ship label buy (loud failure, no email); `Fulfill` buys label BEFORE marking fulfilled (email always carries tracking; post-split failure keeps the split, never rolls it back); providers declare `generates_labels?` + idempotent `create_fulfillment`. **One tracking number per fulfillment (2026-08-11, question 15):** diverging parcels are split fulfillments; a `spree_fulfillment_trackings` model is 6.1 work and must absorb the entire carrier axis (per-row status/`delivered_at`, webhook matching by row) — never split the axis across fulfillment and tracking rows+- `6.0-fulfillment-and-delivery.md` — Shipment→Fulfillment, ShippingMethod→DeliveryMethod, drop ShippingCategory, FulfillmentProvider strategy, pickup (merchant StockLocation) + pickup_point (third-party PickupPointProvider). **Shipped to 6-0-dev (Waves 2+4+6):** renames + deprecated twins, providers (Manual/Digital/Pickup/PickupPoint), dual-emit events, store pickup discovery endpoints, admin delivery_methods/delivery_zones CRUD + dashboard settings pages, FulfillmentMailer; Wave 7 shipping→delivery data migration remains. Pickup work beyond shipped code deferred to 6.1 (2026-08-06): contract hardening (`new(delivery_method)` ctor, `find_nearby` zipcode/query) + how-to guide; `PickupPointProvider::Base` stays **undocumented in 6.0** (v6 docs cover only the delivery rate provider interface) — never add pickup-provider docs in 6.0 work. Delivery mechanics live on provider classes (`pickup_point` provider ships but stays unregistered until 6.1; `local_delivery` cut = shipping + postal-code zone); the string fulfillment-type registry was deleted by `6.0-delivery-profiles.md`. **Partial fulfillment (2026-08-10, resolved question 12):** shipping a subset is `Spree::Fulfillments::Fulfill` (optional per-line-item `items:` + `tracking:` + `notify_customer:`; splits then fulfills in one transaction) — never a state-machine event, since split-then-ship in an `after_transition` is what service-workflows prohibits. **Side effects left the machine (2026-08-10, question 13):** `after_cancel`/`after_resume` are gone as transition callbacks — restock + carrier stand-down live in `Fulfillments::Cancel`/`::Resume` as inline steps (provider call is an `external_step`; `notify_provider: false` lets `Orders::Cancel` delegate and batch carrier I/O after its own transaction), `after_cancel`/`after_resume` are deprecated shells and the only trace left on the model — never add public model methods for workflows to call. **Status model (2026-08-11, question 14): the machine is REMOVED.** `status` = plain `HasStatus` `unfulfilled → fulfilled → delivered | canceled` (`pending`/`ready`/`ready_for_pickup` collapse — payment/stock gating is a `Fulfillments::Fulfill` validate guard, pickup renders modality-aware labels); `delivered` = confirmed receipt (`Fulfillments::MarkDelivered`, `delivered_at`, `fulfillment.delivered`) — the returns window + EU withdrawal anchor; carrier truth is the separate `tracking_status` axis (data, never a machine) written by `Fulfillments::UpdateTracking`, fed by EasyPost tracker webhooks (opt-in trackers for hand-entered numbers). Rollup domain `backorder | canceled | partial | unfulfilled | fulfilled | delivered`. **Phase 7 shipped 2026-08-11** (core + API + dashboard + EasyPost tracker webhook + `spree:migrate_fulfillment_statuses`); **label leads, fulfilled follows (2026-08-12):** `Fulfillments::PurchaseLabel` = explicit pre-ship label buy (loud failure, no email); `Fulfill` buys label BEFORE marking fulfilled (email always carries tracking; post-split failure keeps the split, never rolls it back); providers declare `generates_labels?` + idempotent `create_fulfillment`. **One tracking number per fulfillment (2026-08-11, question 15) — superseded 2026-09-03 by `6.0-shipping-labels-and-deliveries.md`:** the carrier axis moves whole onto `Spree::Delivery` rows in 6.0+- `6.0-shipping-labels-and-deliveries.md` — Labels and parcels become records (design finalized 2026-09-03, nothing built): **`Spree::ShippingLabel`** (prefix `lbl`, store-scoped, polymorphic `owner` = `Fulfillment` | `Return` per the 2026-08-22 tax-identifier ruling; `source` `purchased` | `uploaded`, `integration_id`, `external_id`, `carrier`/`service`, frozen `tracking_number`, `cost` + `currency` = what the merchant paid — admin-only, never shopper money, `format`, `has_status :purchased, :refund_requested, :refunded`, private-storage `file` fetched from the provider right after purchase and streamed by the API) and **`Spree::Delivery`** (prefix `dlv`, same polymorphic owner, `shipping_label_id` unique-nullable, `tracking_number` unique per owner, `tracking_url`, `carrier`, `status` = the carrier axis with `pending` replacing today's nil, `estimated_delivery_at`/`delivered_at`, `details`). The delivery **absorbs the entire carrier axis**: webhooks match a delivery scoped to the integration's store, `Deliveries::UpdateTracking` (renamed from `Fulfillments::`) writes one row and rolls the fulfillment to `delivered` when every sibling is; the fulfillment keeps `status`, `fulfilled_at`, `delivered_at` as lifecycle stamps and **only `tracking` + `tracking_url`** (5.6 API) as a permanent primary-delivery summary — `tracking_carrier`/`tracking_status`/`tracking_details`/`estimated_delivery_at` come out of their 20260811 migrations in place (unreleased). Workflows: `ShippingLabels::Purchase`/`Refund`/`Record`, thin `Fulfillments::PurchaseLabel` + `Returns::PurchaseLabel`; core owns idempotency (refuses on an active label — providers drop their `metadata` keys); provider contract `purchase_label(owner)` → `Spree::LabelPurchase` value object + `refund_label(label)`, `documents` no longer reports the label; EasyPost buys `is_return` shipments for returns. Admin API: nested `labels` (`POST` = buy, or record an uploaded label when `file` is given; `download` streamed; `refund`) and `deliveries` (CRUD + `mark_delivered`) under `/orders/:id/fulfillments/:id/` and `labels` under `/orders/:id/returns/:id/`; `purchase_label` stays one release as an alias; sellers upload but never purchase; Store API gains `fulfillment.deliveries[]` + a customer return-label download. **Constraints now:** never write `spree_fulfillments.tracking*`/`estimated_delivery_at`/`tracking_details` in new code (tracking is a `Delivery` via `Deliveries::Create` or the `tracking:` shortcut on `Fulfill`/`Update`); no provider reads or writes `fulfillment.metadata` for label state; a label's `cost` never feeds `fulfillment.cost` or a store serializer; webhook matching resolves a `Delivery`, never `Fulfillment.where(tracking:)`; return labels attach to the `Return` as owner — no `return_label_url`, no URL in `metadata`; a `Return` delivery never auto-receives; `Fulfillment#delivered` is a rollup no integration sets directly; `Delivery#carrier` is free text — never validated against `Spree.tracking_carriers` (a forwarder's PRO number must be enterable); freight paperwork (bill of lading, placards, packing lists) is never a `ShippingLabel` — it is `OrderDocument`/client prints (`6.1-b2b-order-documents.md`). **Name settled against the wholesale plan (2026-09-03):** `Parcel` was chosen and withdrawn because `6.0-b2b-wholesale-shipping.md` uses "parcel" as the antonym of freight; `Delivery` is the modality-neutral word (a parcel or three pallets under one PRO), and the two-meanings cost beside `DeliveryMethod`/`DeliveryRate` is accepted.- `6.0-digital-assets.md` — **Waves 1–6 SHIPPED and merging in 6.0 (waves 1–5 2026-08-10, hardened 2026-08-12; wave 6 provider-backed assets 2026-08-12; OpenAPI regenerated + dashboard E2E added 2026-08-27, branch mergeable); wave 7 (license-code pools) DEFERRED to 6.1 — design finalized 2026-08-12, purely additive (new table + provider on the shipped wave-6 mechanism, no wave-1–6 behavior change).** `Spree::Digital` → `Spree::DigitalAsset` (table + FK renamed; `DigitalLink` keeps its name) with one-release bridges: constant alias, deprecated `digitals` twins, dual-emitted `digital.*` events, `PermittedAttributes.digital_attributes`, legacy `store/digitals/:token` route. Shipped: Admin API v3 (assets nested under products with private-storage direct upload, `digital_links` read + `reset`, order `resend_digital_links`; catalog — assets ride `products`, links ride `orders`), dashboard (product Digital files card, order links card, store Downloads settings), `Spree::DigitalAssetMailer#files_ready_email` on `order.placed` (+ resend), customer `GET /store/customers/me/digital_links` + store SDK resource, `digital_link.downloaded` event (no log table), signed-URL download transport clamped to the link's own expiry with `digital_asset_link_expire_time` capped at 1h, phantom `:digital` product param removed. Per-asset nullable `authorized_clicks`/`authorized_days` fall back to store settings — a recorded exception to the store-scoped-configuration no-fallback rule. **Wave 6 (shipped 2026-08-12):** NO `kind` column — the provider IS the discriminator. A single nullable `provider_type` (class name); blank resolves to `Spree::DigitalAssetProvider::File` (the default, = today's signed-URL behaviour), a class name to that provider — exactly like `DeliveryMethod#provider_class`. Validation/metadata/create-form key off `provider_class` (which declares `requires_attachment?`), never a string. **No `Spree::Integration` binding** (deliberately unlike delivery-rate/tax providers, which connect marketplace services): a digital-asset provider is bespoke glue into one company's internal legacy software, host-app code that self-configures — no `integration_id`, no `requires_integration?`, no picker. `download_url` generalizes to `deliver` returning a `Spree::DigitalDelivery` value object (redirect URL **or** inline value like a license key). Registered via `Spree.digital_asset_providers`; core ships only the `File` provider. Link-per-unit with resolve-on-download; a provider failure returns 403 without spending the click. **Per-asset provider settings (shipped 2026-08-12):** shared config (endpoint/credential) stays the provider's own concern; *per-asset* config (which pool, which external SKU) is declared with a class-level `setting :key, :type` DSL (`Base.settings_schema` = the `PreferenceSchema` wire shape, but NOT `Preferable` — the provider is a stateless per-call strategy) and stored on the asset in `metadata['provider']` (`DigitalAsset` gained `Spree::Metadata` + a `metadata` column; `provider_settings` accessor), read in `deliver` via `digital_asset.provider_settings`. Primitive field types only (`:string`/`:number`/`:boolean`/`:select`); the `providers` discovery endpoint carries `settings_schema`; the dashboard renders a generic sheet — no provider ships React. **Constraints now:** new code uses `DigitalAsset`/`digital_assets` names only; **nothing outside the model may assume an attachment is present — reach for `deliver`/`downloadable?`, never `attachment`** (a provider-backed asset has none); download-flow code treats the deliverable as opaque; **do NOT add an `Integration` FK/credential surface to `DigitalAsset`** (providers self-configure); shared credentials/endpoints are never a `setting` (per-asset values only) and provider settings stay namespaced under `metadata['provider']`; emailed download URLs keep resolving across renames one release; the generated OpenAPI specs were regenerated 2026-08-27 (reproducible swaggerize). **Wave 7 (DEFERRED to 6.1, OPEN SOURCE):** license-code pools — the "sell game keys" feature. `Spree::LicenseCode` (belongs to a `DigitalAsset`; a `value` string OR an attached scan/photo; nullable `digital_link_id` = redeemed state) + a `LicensePool` provider built on the shipped wave-6 provider mechanism (text → `inline_value`, image → `redirect_url`). CSV import via `Spree::Import` (text codes only; images upload individually). **Claim-once-pin-to-link:** first download claims a code and pins it, later views re-show the SAME code (click limit caps views, never burns a second code). **Pool count IS the variant's stock** — `count_on_hand` synced to `codes.available.count` so it sells out via the existing `can_supply?` path (a real `Stock::Quantifier` integration — a digital variant returns INFINITY today, a pool variant must return its finite count). **Constraint:** keep `count_on_hand` and unredeemed-code count in sync **transactionally** on import + redeem — drift blocks stock or oversells; never compute lazily in checkout.- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain. **COMPLETE (2026-08-05):** all three entities (+ permanent `ReturnLineItem`/`ExchangeLineItem`/`ClaimLineItem` line items), `Spree::HasStatus`, all fifteen workflows (each with a leading `validate` hook), `Refund#originator`, admin + store v3 APIs (transitions as PATCH member actions; no destroy — cancel instead), dashboard pages. Legacy chain **removed**: ReturnAuthorization/CustomerReturn/Reimbursement/ReimbursementType/legacy ReturnItem + eligibility validators + ReturnsCalculator classes all deleted, but their **tables deliberately survive to 6.1** as the data migration's source and rollback path. `spree:upgrade:migrate_returns` (`Spree::ReturnsMigrator`, defined in the rake file like its sibling upgrade tasks; anonymous-AR readers) is in the 5.6→6.0 manifest after the adjustments step; it needs no cursor because the preserved `number` is uniquely indexed on the new tables, so "what's left" is a `where.not(number: ...)` query and an interrupted run resumes for free. `ReturnAuthorizationReason`→`ReturnReason` (alias one release) + new `ClaimReason`; `Metafields` on all three. Capability replacements: `Spree::ReturnMailer#refunded_email` on `return.refunded` (replaces the reimbursement email), `Order#outstanding_balance` drops the reimbursement term (refunds already net out of `payment_total`), `Return#refunded_total` counts store credits too, store credit issued with `originator` + `memo` only (categories dropped 2026-08-18). **Reasons** ship admin-only CRUD (`/api/v3/admin/{return,claim,refund}_reasons`, `settings` scope) + a combined Settings → Reasons dashboard page + reason pickers on the create dialogs; `mutable` is never client-writable and the immutability guard lives on `Spree::NamedType` (`can_be_deleted?` + rename/destroy guards) because secret API keys authorize by scope and never consult CanCanCan. **No state machines (2026-08-02):** plain `status` string + inclusion validation; all fifteen transitions are workflows (`Returns::Receive`, `Exchanges::Fulfill`, `Claims::Resolve`, …) with `validate` hooks for return-eligibility policy and refunds as `external_step`. Nothing happens in a model or transition callback. Statuses live in a `class_attribute` via the core `Spree::HasStatus` concern (`has_status` + additive `add_status(value, after:)`, generating predicates and scopes) — extensible by design, additive only, and no transition graph (that would be a state machine again). **Return eligibility is a hook, not a policy engine (2026-08-03):** no window/restocking-fee/final-sale flag in core — a `validate` handler decides, enforcing for customers while letting staff override (it reads `created_by`), and region-varying policy reads `order.market`. Medusa/Saleor/Vendure ship no policy at all; Shopify's engine has no API. A `ReturnPolicy` model can arrive later behind the same hook.- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename (RefreshToken shipped in 5.4)diff --git a/docs/plans/6.0-b2b-wholesale-shipping.md b/docs/plans/6.0-b2b-wholesale-shipping.mdindex dabda0a234..b3d891805d 100644--- a/docs/plans/6.0-b2b-wholesale-shipping.md+++ b/docs/plans/6.0-b2b-wholesale-shipping.md@@ -4,7 +4,7 @@**Target:** Spree 6.0**Depends on:** Delivery Profiles (6.0-delivery-profiles.md), Delivery Method Rules (6.0-delivery-method-rules.md), Delivery Rate Provider (6.0-delivery-rate-provider.md), B2B Companies & Catalogs (6.0-b2b-companies-and-catalogs.md), Duties & Custom Fees (6.0-duties-and-custom-fees.md), Service Workflows (6.0-service-workflows.md)**Author:** Damian + Claude-**Last updated:** 2026-08-31+**Last updated:** 2026-09-03 (cross-reference to `6.0-shipping-labels-and-deliveries.md`: freight tracking rows, BOL never a label)## Summary@@ -144,6 +144,20 @@ endfuture label/BOL work); nothing in the tier math depends on them — tiersare volume ranges on rules, so a merchant can configure tiers without everdefining a pallet row.++> **Cross-reference (2026-09-03, `6.0-shipping-labels-and-deliveries.md`).**+> A freight consignment's tracking — the forwarder's PRO or container+> number — is a `Spree::Delivery` row on the fulfillment, hand-entered with a+> free-text `carrier` and a pasted `tracking_url`, and `delivered` is+> staff-confirmed through the fulfillment's `mark_delivered` (no webhook ever+> arrives for a container). The model was named `Delivery` rather than+> `Parcel` precisely because this plan uses "parcel" as the antonym of+> freight. Freight paperwork — bill of lading, pallet placards, packing+> list — is **never** a `Spree::ShippingLabel` (that table holds carrier+> labels with a cost and a refund lifecycle); it goes to `Spree::OrderDocument`+> or the client-side prints in `6.1-b2b-order-documents.md`. The "future+> label/BOL work" anchor above is recorded there as a deferred nullable+> `package_type_id` on `spree_deliveries`.- Admin API: `/api/v3/admin/package_types` CRUD under the `settings` scope;dashboard page under Settings → Shipping.diff --git a/docs/plans/6.0-fulfillment-and-delivery.md b/docs/plans/6.0-fulfillment-and-delivery.mdindex bfa7bc8066..704cc2156d 100644--- a/docs/plans/6.0-fulfillment-and-delivery.md+++ b/docs/plans/6.0-fulfillment-and-delivery.md@@ -4,7 +4,7 @@**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-08-10 (partial fulfillment lands as `Fulfillments::Fulfill` — resolved question 12)+**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@@ -409,7 +409,7 @@ Batched, idempotent, resumable — same guarantees as the split-adjustments migr- 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`): the tracking row absorbs the whole carrier axis — per-row status/`delivered_at`, webhook matching by row, fulfillment delivered when every row is; fulfillment-level columns become bridges. Until then, parcels that diverge are split fulfillments (decisions.md 2026-08-11).+- ~~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)@@ -512,6 +512,14 @@ dashboard has Buy label / Print label and a client-generated packing slip.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 QuestionsNone at this time.diff --git a/docs/plans/6.0-returns-exchanges-claims.md b/docs/plans/6.0-returns-exchanges-claims.mdindex 05affa4d96..b1a4f74403 100644--- a/docs/plans/6.0-returns-exchanges-claims.md+++ b/docs/plans/6.0-returns-exchanges-claims.md@@ -953,6 +953,17 @@ DELETE /api/v3/admin/return_reasons/:idcore ships the seam when there is something real behind it, not aspeculative column.+ **Superseded 2026-09-03** by `6.0-shipping-labels-and-deliveries.md`:+ the real thing now exists. A return label is a `Spree::ShippingLabel`+ whose polymorphic `owner` is the `Return`, bought through+ `Returns::PurchaseLabel` (EasyPost `is_return` shipment from the+ customer's address to the return's stock location), mounted at+ `/admin/orders/:order_id/returns/:id/labels`, and downloadable by the+ customer on the Store API. The inbound parcel is a `Spree::Delivery` on+ the return, whose `delivered` report **never** calls `Returns::Receive` —+ arrival is not inspection. The interim "URL in `metadata`" advice is+ withdrawn; nothing in core reads it.+3. **Partial returns/exchanges.** No separate "case" or "ticket" model. All three entities belong to Order — `order.returns`, `order.exchanges`, `order.claims` gives the full picture. The admin UI shows a unified "Post-sale" tab on the order page listing all three chronologically. If correlation is needed (e.g., "this claim was filed because the exchange arrived damaged"), use the `metadata` JSON column.4. **Line-item naming (2026-08-05).** `ReturnLineItem` / `ExchangeLineItem` / `ClaimLineItem` are permanent, not a coexistence workaround. They mirror `Spree::LineItem` and a post-drop rename to `*Item` would cost table + serializer + SDK + dashboard churn for a shorter name.diff --git a/docs/plans/6.0-shipping-labels-and-deliveries.md b/docs/plans/6.0-shipping-labels-and-deliveries.mdnew file mode 100644index 0000000000..289b11cdc0--- /dev/null+++ b/docs/plans/6.0-shipping-labels-and-deliveries.md@@ -0,0 +1,482 @@+# Shipping Labels and Deliveries++**Status:** Draft — design finalized 2026-09-03, nothing built+**Target:** Spree 6.0+**Depends on:** `6.0-fulfillment-and-delivery.md` (status model, `PurchaseLabel`, `UpdateTracking`), `6.0-delivery-rate-provider.md` (EasyPost reference provider), `6.0-returns-exchanges-claims.md` (the `Return` owner). Coordinates with: `6.0-b2b-wholesale-shipping.md` (freight consignments are deliveries too; freight paperwork is not a label), `6.1-b2b-order-documents.md` (where a bill of lading goes).+**Author:** Damian Legawiec+**Last updated:** 2026-09-03++## Summary++A shipping label is today three provider-private keys written into+`fulfillment.metadata` by the EasyPost gem, surfaced through a per-read+`provider.documents(fulfillment)` call, and bought or refunded through a+`PATCH .../purchase_label` member action. That leaves Spree not knowing what the+merchant paid the carrier, unable to reprint once the carrier's hosted URL is+gone, unable to buy a second label after a refund, and with nowhere to put a+return label. The carrier journey of a parcel is in the same shape: one tracking+number and one carrier status per fulfillment, in seven columns on+`spree_fulfillments`, with a `spree_fulfillment_trackings` model deferred to 6.1+and required to absorb that whole axis when it comes.++This plan promotes both into first-class records now, while 6.0 is still the+breaking window. **`Spree::ShippingLabel`** is a purchased (or uploaded)+carrier document with a cost, a file in private storage, a lifecycle+(`purchased → refund_requested → refunded`) and a polymorphic `owner` — a+`Fulfillment` for outbound parcels, a `Return` for inbound ones.+**`Spree::Delivery`** is one tracked consignment's carrier journey — a parcel,+or three pallets under one PRO number — with tracking number, carrier,+tracking status, estimate and arrival time, the same polymorphic owner, and+optionally born from a label. The fulfillment keeps its merchant lifecycle+(`unfulfilled → fulfilled → delivered`) and rolls `delivered` up from its+deliveries. Both become nested REST resources under the fulfillment in the+Admin API; `purchase_label` and `mark_delivered` stop being the only doors.++## Key Decisions (do not deviate without discussion)++- **The label is a record, the delivery is a record, delivered stays a+ transition (2026-09-03, probed and confirmed).** `POST .../deliveries` was+ considered as the way to say "it arrived" and rejected, because a delivery+ row is born when a tracking number is attached — at fulfil time or label+ purchase, days before anything arrives — so `POST` already means "this+ fulfilment went out as another consignment". Arrival is a state change on+ an existing row, and every lifecycle transition in the Admin API+ (`fulfill`, `cancel`, `capture`, `approve`, `receive`) is a `PATCH` member+ action. The fulfilment-level `mark_delivered` stays beside a per-delivery+ twin for three reasons: some fulfilments have no delivery rows at all+ (pickup, hand delivery, freight with no carrier feed) and still need to+ become `delivered` for the returns window; staff saying "it arrived"+ outranks the carrier and closes every open consignment in one call; and+ `Fulfillments::MarkDelivered` already carries public hooks. The alternative+ — redefining a delivery as a *handover* so a pickup gets a row with no+ tracking number and `delivered_at` set, making the status a pure rollup —+ was rejected because that row would be a flag wearing a table.+- **`Spree::Delivery` is the name (2026-09-03, revisited twice).** The row+ must be modality-neutral: `6.0-b2b-wholesale-shipping.md` uses "parcel" as+ the antonym of freight ("different from parcel shipping"), and a freight+ consignment is one PRO or container number covering several pallets, so+ `Spree::Parcel` — briefly chosen — contradicted the sibling plan's fixed+ vocabulary. `Spree::Tracking` is the tracking industry's own resource name+ but collides permanently with `Fulfillment#tracking`, the 5.6 string field+ that stays; `TrackingStatus` names one column of the row; `FulfillmentTracking`+ (the 6.1 deferral's name) is wrong for a `Return` owner. Carriers say+ "track your delivery" for a parcel and a pallet alike. Accepted trade-off:+ the word now carries two meanings in the codebase — `DeliveryMethod`,+ `DeliveryRate`, `DeliveryProfile` and `DeliveryZone` describe what a store+ offers, a `Delivery` is one consignment actually travelling. Workflows live+ under `Spree::Deliveries::`, which no existing namespace uses.+- **Polymorphic `owner` on both tables (2026-09-03).** One concept — a carrier+ document, a consignment in flight — held by different kinds of party, which+ is the 2026-08-22 tax-identifier ruling, not the dual-FK case (a type string+ hiding several meanings). `Fulfillment` and `Return` are the 6.0 owners;+ exchanges ship their replacements through fulfillments, so they need no+ owner of their own. Cardinality is declared owner-side: a fulfillment+ `has_many` of each, a return `has_many` of each.+- **The delivery absorbs the entire carrier axis (honours decisions.md+ 2026-08-11).** `tracking`, `tracking_carrier`, `tracking_status`,+ `tracking_details`, `estimated_delivery_at` move to `spree_deliveries`.+ Webhooks match a delivery row, `UpdateTracking` takes a `delivery:`, and a+ fulfillment is `delivered` when every one of its deliveries is — or when+ staff say so for a fulfillment that has none. `delivered_at` on the+ fulfillment stays as the lifecycle stamp (the returns window and withdrawal+ anchor), exactly like `fulfilled_at`: it is when the fulfillment became+ delivered, a rollup, not a second copy of the carrier's report.+- **The fulfillment keeps `tracking` and `tracking_url`, nothing else+ (2026-09-03).** Those two fields shipped in the 5.6 Store API, so they stay+ permanently as a read-only summary of the **primary delivery** (the+ earliest row) — single-parcel storefronts and the fulfilled email stay+ one-field simple, and `tracking:` (with `tracking_carrier:`) on+ `Fulfillments::Fulfill`/`Update` stays as the write shortcut that creates+ or corrects that delivery. Everything the 6.0 edge added to the+ fulfillment — `tracking_carrier`, `tracking_carrier_name`,+ `tracking_status`, `tracking_details`, `estimated_delivery_at` — is+ **removed** from the serializers and the table rather than bridged: it was+ never released, so there is nobody to bridge for, and the four columns come+ out of their own 20260811 migrations in place (the unreleased-edge rule the+ catalog and company work already used). `delivered_at` and `fulfilled_at`+ stay: they are lifecycle stamps, not carrier data.+- **One label, at most one delivery (2026-09-03).** A purchased label mints a+ delivery carrying its tracking number; the delivery points back through+ `shipping_label_id` (unique). Hand-entered tracking is a delivery with no+ label. A refunded label's delivery is removed only if the consignment never+ moved (the fulfillment is still `unfulfilled`); once fulfilled, the journey+ is history and stays.+- **Idempotency moves into core (2026-09-03).** `Fulfillments::PurchaseLabel`+ refuses when the owner already has a non-refunded label. Providers no longer+ need `metadata` keys to avoid double-buying; the contract for+ `create_fulfillment` idempotency (decisions.md 2026-08-12) is retired+ because the workflow never asks twice.+- **Purchase is a typed result, never a hash (2026-09-03).** A label-generating+ provider implements `purchase_label(owner)` returning a+ `Spree::LabelPurchase` value object (`ActiveModel::Model` + `Attributes`:+ `external_id`, `carrier`, `service`, `tracking_number`, `tracking_url`,+ `cost`, `currency`, `format`, `file_url`, `metadata`) and+ `refund_label(shipping_label)` returning the resulting status.+ `create_fulfillment`/`cancel_fulfillment` stay for providers whose dispatch+ is not a label (a 3PL pick, a pickup counter). `documents(owner)` stays for+ documents that are not the label — customs forms, commercial invoices —+ and stops reporting the label.+- **The file lives in Spree (2026-09-03).** Right after purchase the label+ file is fetched from the provider's URL into a private-storage attachment on+ the row (same declaration and spoofing protection as `po_document`). The+ download endpoint streams the attachment, and proxies the provider URL only+ while the fetch is still pending. Merchants reprint without the carrier+ account being connected, and a disconnected integration never breaks a+ warehouse.+- **Cost is recorded, never displayed to the shopper (2026-09-03).** `cost` ++ `currency` on the label is what the merchant paid the carrier — accounting+ data, admin-only. It never touches the order's shipping charge (`cost` on+ the fulfillment is what the customer was charged) and never appears on a+ store serializer.+- **Uploaded labels are in scope (2026-09-03).** Merchants without a carrier+ integration buy postage elsewhere and still need the PDF and the cost on+ the consignment. `POST .../labels` with a signed blob id records a+ `source: 'uploaded'` label (tracking number, carrier, cost, currency) and+ mints its delivery through `ShippingLabels::Record`; the same request+ without a file purchases through the provider. The serializer's `source`+ tells them apart, and refund is refused on an uploaded label (nothing to+ refund — the merchant deletes it instead, which is the one destroy the+ resource allows). Sellers get upload but never purchase.+- **Freight paperwork is not a shipping label (2026-09-03, wholesale+ cross-check).** A bill of lading, a pallet placard or a packing list is+ issued by the forwarder or printed by the merchant; it has no cost to+ refund and no carrier lifecycle. It goes to `Spree::OrderDocument`+ (`6.1-b2b-order-documents.md`) or the client-side prints, never to a+ `source: 'uploaded'` label. What freight *does* share with parcels is the+ delivery row: the forwarder's PRO or container number is hand-entered as a+ delivery with a free-text `carrier` and a pasted `tracking_url`, and+ `delivered` is staff-confirmed through `mark_delivered` — which is exactly+ why that fulfilment-level action stays.+- **Return labels ship in this plan (2026-09-03).** The `Return` owner is+ what makes the polymorphic shape earn its keep, so it is written in 6.0:+ `Returns::PurchaseLabel` (thin, like the fulfillment twin) over+ `ShippingLabels::Purchase(owner: return_record)`, the EasyPost provider+ buying an `is_return` shipment from the customer's address back to the+ return's stock location, the same `labels` controller mounted under+ `/orders/:order_id/returns/:return_id/`, a customer download on the Store+ API, and a `Return` delivery for the inbound parcel whose `delivered`+ report **never** auto-receives — `Returns::Receive` stays a staff act+ because arrival is not inspection. The returns plan's interim "URL in+ `metadata`" advice is withdrawn.+- **No transition graph, no state machine.** `ShippingLabel` uses+ `has_status`; every status change is a workflow (`ShippingLabels::Purchase`,+ `::Refund`, `::Record` for uploads). `Delivery#status` is the carrier's+ vocabulary and stays data written by `Deliveries::UpdateTracking` — a+ `pending` value replaces today's `nil` so the creating workflow sets it and+ the column never carries a database default.++## Design Details++### Models++**`Spree::ShippingLabel`** (`spree_shipping_labels`, prefix `lbl`,+`Spree::SingleStoreResource`, `Spree::Metadata`, `has_status :purchased,+:refund_requested, :refunded`)++| Column | Notes |+| --- | --- |+| `owner_type`, `owner_id` | polymorphic, `null: false`, indexed together |+| `store_id` | `null: false` |+| `integration_id` | nullable — the connected carrier account that sold it; nil for uploaded labels |+| `source` | `purchased` \| `uploaded`, `null: false` |+| `external_id` | provider's shipment/label id |+| `carrier`, `service` | strings, carrier key from `Spree.tracking_carriers` when known |+| `tracking_number` | the number printed on the label — a frozen purchase fact; the delivery holds the live one |+| `cost`, `currency` | `decimal(10,2)` default 0 + string; what the merchant paid |+| `format` | `pdf` \| `png` \| `zpl` |+| `status` | string, set by the workflow |+| `refunded_at` | datetime |+| `metadata` | JSON — provider ids (tracker id, original file URL) |+| `file` | `has_one_attached`, `Spree.private_storage_service_name`, content type limited to PDF/PNG/ZPL, spoofing-protected |++Associations: `belongs_to :owner, polymorphic: true`, `belongs_to :store`,+`belongs_to :integration, optional: true`, `has_one :delivery`. Scopes:+`active` (`where.not(status: 'refunded')`). `Fulfillment has_many+:shipping_labels, as: :owner, dependent: :destroy`; `Return` the same.++**`Spree::Delivery`** (`spree_deliveries`, prefix `dlv`,+`Spree::SingleStoreResource`)++| Column | Notes |+| --- | --- |+| `owner_type`, `owner_id` | polymorphic, `null: false` |+| `store_id` | `null: false` |+| `shipping_label_id` | nullable, unique index — the label that minted it |+| `tracking_number` | `null: false`, indexed (webhook lookup); unique per owner. A parcel's carrier number, or a freight PRO / container number |+| `tracking_url` | nullable — a pasted link or the provider's tracker page; the resolved URL falls back to the carrier template then format detection, as today |+| `carrier` | free-text string. Detected from the number when not given (today's `detect_tracking_carrier`); `Spree.tracking_carriers` supplies URL templates and display names, never validation — a forwarder's name is a legal value |+| `service` | string, nullable |+| `status` | `pending` \| `pre_transit` \| `in_transit` \| `out_for_delivery` \| `available_for_pickup` \| `delivered` \| `return_to_sender` \| `failure` \| `unknown` — the carrier axis, inclusion-validated, no graph |+| `estimated_delivery_at`, `delivered_at` | datetimes |+| `details` | JSON — the carrier payload worth keeping (scan history, signature, failure reason) |++Associations: `belongs_to :owner, polymorphic: true`, `belongs_to :store`,+`belongs_to :shipping_label, optional: true`. `Fulfillment has_many+:deliveries, as: :owner, dependent: :destroy` (ordered by `created_at`; the+first is the **primary delivery** the summary fields read). `Return` the same.++### Fulfillment lifecycle with deliveries++- `Fulfillments::Fulfill` — `tracking:` (and `tracking_carrier:`) still+ accepted as the one-parcel shortcut: it creates a delivery through+ `Deliveries::Create` inside the same transaction as the split. The label+ step becomes `external_step :purchase_label` calling+ `ShippingLabels::Purchase` when the provider generates labels and no active+ label exists; failure still degrades to "no label yet". The fulfilled email+ reads tracking from the primary delivery.+- `Fulfillments::PurchaseLabel` — thin: validate, refuse on an active label,+ delegate to `ShippingLabels::Purchase`. Kept as a workflow because its hooks+ (`validate`, `after_purchase_label`) are public since 2026-08-12.+- `Fulfillments::Update` — `tracking:` upserts the primary delivery (creates+ it, or corrects its number; a corrected number resets `status` to+ `pending`).+- `Fulfillments::Cancel` — `tell_provider_to_stand_down` refunds every active+ label through `ShippingLabels::Refund` (`notify_provider: false` still lets+ `Orders::Cancel` batch the carrier I/O), then the 3PL `cancel_fulfillment`.+- `Fulfillments::MarkDelivered` — staff confirmation. Marks every+ non-delivered delivery `delivered` at the given time (a human saying "it+ arrived" outranks a carrier that never sent the last scan), then the+ fulfillment. Unchanged signature. This is the freight path: no webhook ever+ arrives for a container.+- `Deliveries::UpdateTracking` (renamed from `Fulfillments::UpdateTracking`;+ `fulfillment_update_tracking_workflow` stays readable one release and+ resolves the primary delivery) — writes the carrier axis onto one row with+ `update_columns`, as today. When the report is `delivered` it stamps the row+ and, if every sibling delivery is delivered, delegates to+ `Fulfillments::MarkDelivered` with the latest `delivered_at`. A `Return`+ owner never auto-transitions anything: goods arriving is not goods+ inspected, and `Returns::Receive` stays a staff act. A per-delivery+ `mark_delivered` from staff is this workflow with `tracking_status:+ 'delivered'`.+- `Deliveries::Create` / `Deliveries::Destroy` — Tier 1 services (no hook+ earned). Destroy refuses a delivery that has a label — refund the label.++### Label workflows++- `ShippingLabels::Purchase(owner:)` — `validate` hook, `ensure_purchasable`+ (provider `generates_labels?`, owner not fulfilled/canceled, no active+ label, order not draft), `external_step :purchase` (provider+ `purchase_label(owner)` → `LabelPurchase`), then in one transaction create+ the label row and its delivery, then `external_step :store_file` (fetch+ `file_url` into the attachment; on failure enqueue+ `ShippingLabels::StoreFileJob` and leave the URL in `metadata`). Publishes+ `shipping_label.purchased`. Hook `after_purchase`.+- `ShippingLabels::Refund(shipping_label:)` — `validate`, `ensure_refundable`+ (status `purchased`, source `purchased`), `external_step :refund` (provider+ `refund_label` → `refund_requested` or `refunded`), write the status,+ remove the delivery when the owner never shipped. Publishes+ `shipping_label.refunded`. A provider whose refund resolves later reports+ it through its webhook by calling `ShippingLabels::ConfirmRefund` (plain+ service).+- `ShippingLabels::Record(owner:, file:, tracking_number:, carrier:, cost:,+ currency:)` — an uploaded label: creates a `source: 'uploaded'` row and+ its delivery, no provider involved.++### Provider contract (`Spree::FulfillmentProvider::Base`)++```ruby+def self.generates_labels? = false # unchanged+def purchase_label(owner) # → Spree::LabelPurchase | nil+def refund_label(shipping_label) # → 'refunded' | 'refund_requested' | false+def create_fulfillment(fulfillment) # unchanged — non-label dispatch+def cancel_fulfillment(fulfillment) # unchanged+def documents(owner) # unchanged shape, label excluded+def tracking_url(delivery) # was tracking_url(fulfillment); deprecated twin one release+```++The EasyPost provider implements `purchase_label` from today's+`buy_quoted`/`requote_and_buy` (returning `postage_label.label_url`,+`rate.rate`/`currency`, `label_file_type`; `is_return: true` when the owner+is a `Return`, shipping from the customer's address to the return's stock+location), `refund_label` from `cancel_fulfillment`, drops `remember_purchase`+and every `metadata['easypost_*']` read, and keeps `documents` for+`shipment.forms`. Its tracker webhook resolves the delivery by tracking+number scoped to the integration's store. The freight rate provider from the+wholesale plan pairs with the Manual fulfilment provider and generates no+labels; its consignments are hand-entered deliveries.++### Admin API (`spree/api`)++Nested under the order's fulfillment (there is no top-level fulfillments+resource in the Admin API). Both ride the `fulfillments` permission resource —+their subjects join its list.++```+GET /api/v3/admin/orders/:order_id/fulfillments/:fulfillment_id/labels+POST /api/v3/admin/orders/:order_id/fulfillments/:fulfillment_id/labels buy through the provider; with `file` (signed blob id), record an uploaded label+GET /api/v3/admin/orders/:order_id/fulfillments/:fulfillment_id/labels/:id+GET /api/v3/admin/orders/:order_id/fulfillments/:fulfillment_id/labels/:id/download streamed, read scope+PATCH /api/v3/admin/orders/:order_id/fulfillments/:fulfillment_id/labels/:id/refund+DELETE /api/v3/admin/orders/:order_id/fulfillments/:fulfillment_id/labels/:id uploaded labels only++GET /api/v3/admin/orders/:order_id/fulfillments/:fulfillment_id/deliveries+POST /api/v3/admin/orders/:order_id/fulfillments/:fulfillment_id/deliveries tracking_number, carrier, tracking_url+GET /api/v3/admin/orders/:order_id/fulfillments/:fulfillment_id/deliveries/:id+PATCH /api/v3/admin/orders/:order_id/fulfillments/:fulfillment_id/deliveries/:id correct number / carrier / url+DELETE /api/v3/admin/orders/:order_id/fulfillments/:fulfillment_id/deliveries/:id 422 when it has a label+PATCH /api/v3/admin/orders/:order_id/fulfillments/:fulfillment_id/deliveries/:id/mark_delivered+```++`PATCH .../fulfillments/:id/purchase_label` stays one release as a deprecated+alias of `POST .../labels` returning the fulfillment. `mark_delivered` on the+fulfillment is unchanged. The same `labels` controller mounts under+`/orders/:order_id/returns/:return_id/` for return labels.++Serializers: `Admin::ShippingLabelSerializer` (`id`, `owner_id`, `source`,+`status`, `carrier`, `service`, `tracking_number`, `cost`, `currency`,+`display_cost`, `format`, `download_url`, `refunded_at`, `metadata`,+timestamps) and `Admin::DeliverySerializer` extending a store+`DeliverySerializer` (`id`, `tracking_number`, `tracking_url`, `carrier`,+`carrier_name`, `status`, `estimated_delivery_at`, `delivered_at`; admin adds+`shipping_label_id`, `details`, timestamps). The fulfillment serializers embed+`deliveries` always (small, and the customer's question), keep `tracking` and+`tracking_url` as the primary delivery's summary, lose `tracking_carrier`,+`tracking_carrier_name`, `tracking_status`, `tracking_details` and+`estimated_delivery_at`; the admin one embeds `labels`; `documents` and+`provider_generates_labels` stay. Fulfillment write params keep `tracking` and+`tracking_carrier` (forwarded to the primary delivery) and nothing else+tracking-shaped.++Seller branch: sellers fulfill on manual methods only (Decision 13 of the+marketplace plan), so they get `deliveries` index/create/update/destroy and+`labels` index/upload/download/destroy under+`/seller/orders/:id/fulfillments/:id/` — never purchase or refund, which need+the operator's carrier account.++### Store API++`fulfillment.deliveries[]` on the order serializer beside the permanent+`tracking`/`tracking_url` summary. The only label surface is the customer's+return label: `GET /store/orders/:order_id/returns/:id/label` streams the+active label's file to the order's customer (or order-token holder) — the+label row itself is never serialized to the storefront, since its cost and+provider ids are merchant data.++### Dashboard++The fulfillment card lists deliveries (one badge per consignment with its+carrier status; "Add tracking" opens a sheet; a delivery with a label is not+deletable), renders the label row (Buy label → `POST labels`; Print →+`download`; Refund with a destructive confirm; Upload label for manual+methods), and shows postage cost. Return page gets the same label block.+Every string through i18next in all locales.++### Events++`shipping_label.purchased`, `shipping_label.refunded` (new, with an event+serializer). `fulfillment.delivered` unchanged. No per-scan delivery event —+the `after_update_tracking` hook is that surface, as today.++## Migration Path++1. **Schema** — one migration creating `spree_shipping_labels` and+ `spree_deliveries`. The two 20260811 fulfillment migrations are amended+ in place to stop adding `tracking_status`, `tracking_details`,+ `estimated_delivery_at` and `tracking_carrier` (unreleased edge — a dev+ database that already has them keeps harmless dead columns until+ `pnpm wt:template` rebuilds it). `spree_fulfillments.tracking` and its+ index stay: they are the 5.6 data the task below reads.+2. **Core** — models, `LabelPurchase`, workflows and services, provider base+ contract, `Fulfill`/`Update`/`Cancel`/`MarkDelivered`/`PurchaseLabel`+ rewired, `Deliveries::UpdateTracking`, `tracking`/`tracking_url` readers+ delegating to the primary delivery, `Spree::Dependencies` keys+ (`shipping_label_purchase_workflow`, `shipping_label_refund_workflow`,+ `shipping_label_record_workflow`, `delivery_update_tracking_workflow`,+ `return_purchase_label_workflow`; legacy+ `fulfillment_update_tracking_workflow` readable one release).+3. **Data task** — `spree:upgrade:migrate_deliveries` in the 5.6→6.0 manifest+ after `migrate_fulfillment_statuses`: every fulfillment with a `tracking`+ gets one `pending` delivery row carrying that number (a pasted link lands+ in `tracking_url`, the carrier is detected from the number as today);+ idempotent by `(owner, tracking_number)` existence. No label backfill: the+ EasyPost `metadata` keys only ever existed on the unreleased 6.0 edge.+4. **EasyPost** — `purchase_label` for both owners (`is_return` for a+ `Return`), `refund_label`, webhook matching by delivery, `documents`+ reduced to forms.+5. **API + SDK** — fulfillment- and return-nested `labels`, `deliveries`,+ store return-label download, serializers, typelizer/Zod/OpenAPI,+ admin-sdk and sdk resources, seller branch.+6. **Dashboard** — fulfillment card rework, return page label block, e2e.+7. **6.1** — drop `spree_fulfillments.tracking` and its index, remove the+ deprecated `purchase_label` alias, `fulfillment_update_tracking_workflow`+ and `tracking_url(fulfillment)`.++Phases 1–6 are one PR train on one branch; the data task ships with phase 3.++## Constraints on Current Work++- **Never write `spree_fulfillments.tracking*`, `estimated_delivery_at` or+ `tracking_details` in new code** — tracking is a `Delivery` row created+ through `Deliveries::Create` (or the `tracking:` shortcut on+ `Fulfillments::Fulfill`/`Update`, which does the same). `delivered_at` on+ the fulfillment is written only by `Fulfillments::MarkDelivered`.+- **No provider reads or writes `fulfillment.metadata` for label state.**+ Label facts live on `Spree::ShippingLabel`; a provider that needs to+ remember its own ids puts them in the label's `metadata`.+- **A label's `cost` is merchant accounting, never shopper money** — it never+ feeds `fulfillment.cost`, totals, or a store serializer.+- **Webhook matching resolves a `Delivery`, scoped to the integration's+ store** — never `Fulfillment.where(tracking:)`.+- **Return labels attach to the `Return` as its `owner`** — no+ `return_label_url` column, no URL in `metadata` (the returns plan's interim+ advice is withdrawn once this ships).+- **`Fulfillment#delivered` is a rollup**: a new owner or a new carrier+ integration may never mark a fulfillment delivered directly — it reports a+ delivery and lets `Deliveries::UpdateTracking` roll up.+- **No new readers of `tracking_status`, `tracking_carrier`,+ `estimated_delivery_at` or `tracking_details` on a fulfillment** — the+ storefront, emails and dashboard read `deliveries`; a fulfillment only ever+ summarizes `tracking` and `tracking_url`.+- **`Delivery#carrier` is free text.** `Spree.tracking_carriers` supplies+ URL templates and display names; nothing may validate a carrier against+ it, or a forwarder's PRO number becomes unenterable.+- **Freight paperwork is never a `ShippingLabel`.** A bill of lading,+ pallet placard or packing list goes to `Spree::OrderDocument` or the+ client-side prints (`6.1-b2b-order-documents.md`); the label table holds+ carrier labels only.+- **A `Return` delivery never transitions the return.** Anything that wants+ "the parcel came back" to do something hangs it on+ `Deliveries::UpdateTracking`'s `after_update_tracking` hook and calls+ `Returns::Receive` itself, staff-style.+- **Label files are private-storage attachments streamed by the API** —+ never a public blob URL on any serializer, never `attachment.url`.++## Open Questions++None blocking. Three items are deliberately deferred:++- **Refund outcome from the carrier.** `ShippingLabels::Refund` records what+ the provider answers synchronously (`refunded` or `refund_requested`). A+ provider that settles refunds later (EasyPost's `refund.successful` /+ `refund.rejected` events) can complete the story through+ `ShippingLabels::ConfirmRefund`, but a `refund_rejected` status and the+ webhook wiring wait for a merchant to ask — unblocked by that request.+- **Several labels for one delivery** (a multi-piece shipment under one+ tracking number). Not modeled: one label mints one delivery. Unblocked by+ a carrier provider that actually returns multi-piece labels.+- **Packaging on the delivery.** The wholesale plan names its `pallet` and+ `container` `PackageType` rows as "the natural anchor for future+ label/BOL work"; a nullable `package_type_id` (plus a count) on+ `spree_deliveries` is the additive hook — "3 pallets under PRO 4471923".+ Unblocked by the wholesale plan landing and a merchant needing the+ consignment's packaging recorded, not just its number.++## References++- `docs/plans/6.0-fulfillment-and-delivery.md` — resolved questions 14 and+ 15, the "label leads" amendment+- `docs/plans/decisions.md` — 2026-08-11 (one tracking number per+ fulfillment), 2026-08-12 (the label leads), 2026-08-22 (polymorphic tax+ identifier owner — the precedent for `owner` here), 2026-09-03 (this plan)+- `docs/plans/6.0-returns-exchanges-claims.md` — resolved question 2 (return+ labels ride with the carrier provider)+- `docs/plans/6.0-delivery-rate-provider.md` — EasyPost as the reference+ provider+- `docs/plans/6.0-b2b-wholesale-shipping.md` — freight tiers, the freight+ rate provider, `PackageType`, and the parcel-versus-freight vocabulary that+ settled the model's name+- `docs/plans/6.1-b2b-order-documents.md` — where bills of lading and+ packing lists live+- `spree/core/app/workflows/spree/fulfillments/{purchase_label,fulfill,cancel,mark_delivered,update_tracking}.rb`+- `spree/providers/easypost/app/models/spree_easypost/{fulfillment_provider,tracker_event}.rb`+- `spree/api/app/controllers/spree/api/v3/webhooks/fulfillments_controller.rb`diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 994f48f5a0..440a5f9ddc 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,11 @@+## 2026-09-03: Labels and parcels are records; the carrier axis moves onto `Spree::Delivery` in 6.0 (supersedes 2026-08-11 "multiple trackings deferred to 6.1")++**Context:** A shipping label was three EasyPost-private keys in `fulfillment.metadata`, surfaced by a per-read `provider.documents` call and bought through `PATCH .../purchase_label`. Spree never knew the postage cost, could not reprint once the carrier's hosted URL expired, could not buy a second label after a refund (idempotency keyed off the metadata), and had nowhere to put a return label — the returns plan had already sent that to "the URL in `metadata`". Tracking lived in seven columns on `spree_fulfillments`, one number per parcel, with a `spree_fulfillment_trackings` model deferred to 6.1 and required to absorb the whole axis when it came. Both were candidates for "promote to a model with RESTful routes"; only one of them is a thing.++**Decision:** Two new tables, both with a **polymorphic `owner`** (`Fulfillment` | `Return`) on the 2026-08-22 tax-identifier reasoning — one concept held by different parties, not a type string hiding several meanings. `Spree::ShippingLabel` is the purchased or uploaded carrier document: cost and currency (merchant accounting, admin-only), the file in private storage fetched from the provider at purchase, `purchased → refund_requested → refunded`, an `external_id`, and a frozen `tracking_number`. `Spree::Delivery` is one parcel's carrier journey — tracking number, carrier, carrier status (`pending` instead of nil), estimate, arrival, scan details — optionally minted by a label. `delivered` on the fulfillment stays a transition, not a model: marking delivered is the fulfillment's own status changing, and the fulfillment rolls it up from its deliveries (or from staff, for parcels that have none). Idempotency of the label buy moves into core — the workflow refuses on an active label, so providers stop keeping `metadata` keys. The provider contract grows a typed `purchase_label(owner) → Spree::LabelPurchase` and `refund_label(label)`; `create_fulfillment` stays for non-label dispatch. The 6.0 edge's fulfillment-level `tracking_carrier`/`tracking_status`/`tracking_details`/`estimated_delivery_at` are removed in place rather than bridged (never released); `tracking` and `tracking_url` (5.6 API) stay forever as the primary delivery's summary.++**Consequences:** The 2026-08-11 deferral's constraint held — the delivery takes the entire axis, nothing stays split between fulfillment and row — but the model lands in 6.0 and under a different name, because a `Return` owns parcels too and `FulfillmentTracking` cannot say so. The name was tested twice: `Delivery` was questioned for leaning toward the arrival event, `Parcel` was chosen and then withdrawn the same day when checked against `6.0-b2b-wholesale-shipping.md`, which uses "parcel" as the antonym of freight — a PRO number covering three pallets is not a parcel. `Tracking` collides with the 5.6 `Fulfillment#tracking` string that stays forever. `Delivery` is the modality-neutral word carriers use for a parcel and a pallet alike; the two-meanings cost beside `DeliveryMethod`/`DeliveryRate` is accepted. The same check settled that freight paperwork (bill of lading, placards, packing lists) is never a `ShippingLabel` — it belongs to `OrderDocument` in `6.1-b2b-order-documents.md` — and that `Delivery#carrier` is free text, never validated against the carrier registry, or a forwarder's number becomes unenterable. Return labels ship now on the same table (EasyPost `is_return`), with a `Return` delivery that never auto-receives: arrival is not inspection. Uploaded labels are in scope, so merchants on the Manual provider get a place for postage they bought elsewhere; `POST .../labels` purchases without a body and records with a `file`. Sellers may upload and track but never purchase or refund — those need the operator's carrier account. The routing rule this settles for the whole Admin API: a durable record with its own identity (label, delivery, refund) is a nested resource created by `POST`; a lifecycle transition (`fulfill`, `cancel`, `mark_delivered`, `capture`, `approve`) stays a `PATCH` member action. Plan: `6.0-shipping-labels-and-deliveries.md`.+## 2026-09-02: A 6.0 column rename is earned by public leakage, not by completeness**Context:** `5.4-store-api-naming-standardization.md` listed six database renames as its remaining 6.0 work — roughly 1,900 references. But the 5.4 model aliases already make every API response speak the new names, so the honest question was not "which renames are left" but "which ones still change anything a caller can see".