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
Merge branch 'main' into feature/v-3526
Łukasz Adamczykecd19fc14add
diff --cc CLAUDE.mdindex 58342ce327,17e4a820df..c6b64174a6--- a/CLAUDE.md+++ b/CLAUDE.md@@@ -21,12 -21,14 +21,14 @@@ Active plans (6.0 target, work pending)- `6.0-remove-master-variant.md` — Eliminate is_master, add default_variant_id FK on Product. **Shipped to 6-0-dev (PR #14265):** is_master removed from all models, default_variant_id + `spree:remove_master_variant` data-migration rake landed; only the physical is_master column drop remains (6.1 cleanup).- `6.0-typed-stock-movements.md` — Replace generic StockMovement with typed kinds + concrete FKs- `6.0-normalize-state-to-status.md` — Rename state → status on Payment, Shipment, InventoryUnit, ReturnAuthorization, GiftCard- - `6.0-fulfillment-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+ - `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-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain. **COMPLETE (2026-08-05):** all three entities (+ permanent `ReturnLineItem`/`ExchangeLineItem`/`ClaimLineItem` line items), `Spree::HasStatus`, all fifteen workflows (each with a leading `validate` hook), `Refund#originator`, admin + store v3 APIs (transitions as PATCH member actions; no destroy — cancel instead), dashboard pages. Legacy chain **removed**: ReturnAuthorization/CustomerReturn/Reimbursement/ReimbursementType/legacy ReturnItem + eligibility validators + ReturnsCalculator classes all deleted, but their **tables deliberately survive to 6.1** as the data migration's source and rollback path. `spree:upgrade:migrate_returns` (`Spree::ReturnsMigrator`, defined in the rake file like its sibling upgrade tasks; anonymous-AR readers) is in the 5.6→6.0 manifest after the adjustments step; it needs no cursor because the preserved `number` is uniquely indexed on the new tables, so "what's left" is a `where.not(number: ...)` query and an interrupted run resumes for free. `ReturnAuthorizationReason`→`ReturnReason` (alias one release) + new `ClaimReason`; `Metafields` on all three. Capability replacements: `Spree::ReturnMailer#refunded_email` on `return.refunded` (replaces the reimbursement email), `Order#outstanding_balance` drops the reimbursement term (refunds already net out of `payment_total`), `Return#refunded_total` counts store credits too, `StoreCreditCategory.default_refund_category` (alias kept). **Reasons** ship admin-only CRUD (`/api/v3/admin/{return,claim,refund}_reasons`, `settings` scope) + a combined Settings → Reasons dashboard page + reason pickers on the create dialogs; `mutable` is never client-writable and the immutability guard lives on `Spree::NamedType` (`can_be_deleted?` + rename/destroy guards) because secret API keys authorize by scope and never consult CanCanCan. **No state machines (2026-08-02):** plain `status` string + inclusion validation; all fifteen transitions are workflows (`Returns::Receive`, `Exchanges::Fulfill`, `Claims::Resolve`, …) with `validate` hooks for return-eligibility policy and refunds as `external_step`. Nothing happens in a model or transition callback. Statuses live in a `class_attribute` via the core `Spree::HasStatus` concern (`has_status` + additive `add_status(value, after:)`, generating predicates and scopes) — extensible by design, additive only, and no transition graph (that would be a state machine again). **Return eligibility is a hook, not a policy engine (2026-08-03):** no window/restocking-fee/final-sale flag in core — a `validate` handler decides, enforcing for customers while letting staff override (it reads `created_by`), and region-varying policy reads `order.market`. Medusa/Saleor/Vendure ship no policy at all; Shopify's engine has no API. A `ReturnPolicy` model can arrive later behind the same hook.- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename (RefreshToken shipped in 5.4)-- `6.0-tax-provider.md` — Per-Market TaxProvider, replaces TaxRate.adjust + Calculator; TaxRate gets direct country/state FKs (tax decoupled from Zone; Zone model dropped in 6.0 via `6.0-delivery-zones.md`); reference provider: Avalara (decisions.md 2026-07-30)+- `6.0-tax-provider.md` — Per-Market TaxProvider (market selects the provider, providers stateless/argless; global config class stays as fallback), replaces TaxRate.adjust + Calculator; reference provider: Avalara (decisions.md 2026-07-30). **Shipped to 6-0-dev (core-rewrite waves):** `Spree::TaxProvider::Base`/`Internal` as the sole TaxLine write path, called from `Carts::RecalculateTotals` behind the `money_frozen?` freeze. **Contract refined 2026-08-05 after the spree/spree#14056 review (decisions.md):** TaxLine gains `taxability_reason` + jurisdiction snapshot (e-invoice category/exemption codes derived at invoicing time, never stored); new `Spree::TaxIdentifier` model (customer/cart/order dual-FK, frozen order snapshot; validation via the kind-keyed `Spree.tax_id_validators` registry + async job on the geocoding precedent — NOT a provider method, and no registry client in core); exemptions = typed `estimate` input via `tax_resolve_exemptions_service` (boolean `exempt?` removed, no flags anywhere); explicit `tax_date:`; `refund(order, return_items, tax_date:)`; capability declarations (Internal declares no US local tax / no reverse charge / no one-stop-shop thresholds; `estimate` keeps its no-op return — a structured result + indeterminacy channel deferred as safely additive). **Phases 3-5 in development:** the enriched contract, `Spree::TaxIdentifier` + validator registry, exemption value objects, per-Market selection with commit/void/refund as external steps, and the Zone decoupling (rates carry `country_id`/`state_id`; `spree_tax_rates.zone_id` stays through 6.0 as the conversion source). **Phases 3-5 + the Zone decoupling shipped to `feature/v-3526` (PR #14410).** **Phase 7 is next and no longer gated (2026-08-07):** it pulls the minimal Company tree forward out of the B2B plan — Company → CompanyLocation → CompanyContact, `company_location_id` on both carts and orders, `company_id` as a fourth TaxIdentifier owner, `Spree::TaxExemptionCertificate` hanging off Company scoped by country/state, and the `ResolveExemptions` body; **no `tax_exempt` boolean anywhere** (supersedes the B2B plan's sketches), and Catalog/pricing/visibility stay 6.1. Pending after that: Phase 6 `spree_tax_avalara`, **Phase 8 cross-border pricing with tax-inclusive prices** (2026-08-11 live pass: `Pricing::Context.from_order` never carried the cart's market so market-scoped price lists were unreachable from a cart; `recalculate_for_address_change!` called the non-persisting `update_price`; restatement was applied even to prices set for the destination — the rule is now derive net-fixed unless the winning price list carries a `geographic?` rule, Shopify's model), Phase 9 6.1 cleanup (drop `zone_id`, `null: false` on the tax `store_id`s, decide `Market#tax_inclusive`). Still open: delivery-rate tax display bypasses the provider- - `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider wrapping Stock::Estimator (calculators stay — 2026-07-27 reversal), `store_id` on ShippingMethod, enriched DeliveryRate (carrier/service/date/metadata); monorepo ships one reference multi-carrier provider (Shippo/EasyPost, pick pending — decisions.md 2026-07-29); method rows stay regional (no cross-market method entity)+ - `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider wrapping Stock::Estimator (calculators stay — 2026-07-27 reversal), `store_id` on ShippingMethod; monorepo ships one reference multi-carrier provider (**EasyPost** — decisions.md 2026-08-06 reversal: BYOCA fit for larger merchants + only maintained official Ruby SDK; Shippo's ruby gem dead since 2020); method rows stay regional (no cross-market method entity). **Dynamic carrier rates (2026-08-09):** a carrier method is the carrier connection — `estimates(package)` returns one Estimate per service, each becoming its own named DeliveryRate (unique (fulfillment, method) rate index dropped; `DeliveryRate#name` falls back to the method name); `Spree::DeliveryMethodService` rows narrow/rename/mark-up services (no rows = all, method-level markup columns as default); selection + EasyPost label buy key off the selected rate's carrier/service; seeds/sample data reshaped Shopify-style (Domestic + International zones with basic methods)- `6.0-delivery-zones.md` — Zone → DeliveryZone with postal-code-range/prefix members (country-scoped); owns the full ~183-reference Zone consumer inventory; `Spree::Zone` dropped entirely by end of 6.0 (2026-07-27 — 6.0 is the breaking-change window)+ - `6.0-integrations-admin.md` — **Implemented (2026-08-06).** `Spree::Integration` as the single credential surface for all provider seams (delivery rates/tax/fulfillment/pickup points): explicit `Spree.integrations` registry, Admin API v3 CRUD + types discovery (reusing `PreferenceSchema`/`Masking` — secrets are `:password` preferences), dashboard `/settings/integrations` gallery grouped by `integration_group`. Verify-before-activate (`active: true` runs `can_connect?`, 422 on failure), ephemeral connection status. Constraints now: provider gems ship an Integration subclass (no env-var credential contracts for per-store providers); no per-provider credential UIs — pickers deep-link to the integrations page.- `6.0-rich-text-descriptions.md` — Drop ActionText **entirely** at 6.0 (incl. CustomFields::RichText values + Order/User internal notes; gem dependency removed), store sanitized HTML in text columns, serve `field` + `field_html`, **write via `field_html`** (read/write symmetry). description_html serializer shipped 5.4; sanitizer shipped in **5.6.2** with a permissive-but-safe configurable allowlist + `sanitize_rich_text` step in the 5.5→5.6 upgrade manifest (decisions.md 2026-07-27/28), tightened to the Tiptap set at 6.0- `6.0-inventory-operations.md` — StockTransfer lifecycle (draft → ready_to_ship → in_transit → received with partial receive), new `Spree::PurchaseOrder` + `Spree::Supplier` (renamed from Vendor — `Spree::Vendor` is the marketplace seller, see decisions.md 2026-07-14) replacing today's "external receive" hack, variant + stock-location stock history panels. Consumes the typed-movement primitives from `6.0-typed-stock-movements.md`.- `6.0-replace-taxons-with-categories.md` — Split Taxon into Category (hierarchy) + Collection (flat/rule-based). **Shipped to 6-0-dev (PR #14302):** the Category surface (5.5–5.6) plus the 6.0 core — `spree_taxons`→`spree_categories` table rename + inheritance flip (`Spree::Category < Spree.base_class`, `Spree::Taxon` alias kept), the full `Collection` stack (model + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data migration, and de-ruling Category. Pending (all 6.1): channel-aware `CollectionRules::AvailableOn` (ships interim now, rides with channels) + dropping `spree_taxon_rules`/`Taxonomy`. No brand feature in 6.0 — brands are modeled as a Category/Collection; `brand_taxon`/`brand_name` removed with `Taxonomy`.diff --cc docs/plans/6.0-delivery-zones.mdindex 0e8806d153,44ab172ece..1459dbebbd--- a/docs/plans/6.0-delivery-zones.md+++ b/docs/plans/6.0-delivery-zones.md@@@ -1,10 -1,13 +1,13 @@@# Delivery Zones (Zone → DeliveryZone)+ > **Amendment 2026-08-09 (`6.0-delivery-profiles.md`):** delivery zones become owned by a delivery profile (`delivery_profile_id`), and a delivery method binds to at most ONE zone (`delivery_zone_id`; the method↔zone m:n join is dropped). Zone membership mechanics (country/state/postal ranges) are unchanged.++-**Status:** Phases A and B shipped, C mostly shipped; `Spree::Zone` removal (Phase D) blocked on the tax provider — see "Implementation status"+**Status:** Phases A and B shipped, C mostly shipped; `Spree::Zone` removal (Phase D) unblocked on the tax side as of 2026-08-07 — see "Implementation status"**Target:** Spree 6.0-**Depends on:** `6.0-tax-provider.md` Phase 5 (tax decoupled from Zone — prerequisite for dropping the model; **not yet shipped, this is the live blocker**), `6.0-fulfillment-and-delivery.md` Phase 1 (`spree_delivery_method_zones` born pointing at DeliveryZone — **shipped**). Coordinates with: `6.0-delivery-rate-provider.md` (the Estimator's zone check swaps to DeliveryZone matching; provider interface unaffected).+**Depends on:** `6.0-tax-provider.md` Phase 5 (tax decoupled from Zone — prerequisite for dropping the model; **cleared 2026-08-07**, see below), `6.0-fulfillment-and-delivery.md` Phase 1 (`spree_delivery_method_zones` born pointing at DeliveryZone — **shipped**). Coordinates with: `6.0-delivery-rate-provider.md` (the Estimator's zone check swaps to DeliveryZone matching; provider interface unaffected).**Author:** Damian + Claude-**Last updated:** 2026-08-05+**Last updated:** 2026-08-07## Summarydiff --cc docs/plans/decisions.mdindex 26a14f3511,ec699652b6..3622f43b9d--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@@ -1,50 -1,235 +1,282 @@@+ ## 2026-08-12: The label leads, fulfilled follows (amends the Phase 7 fulfill flow)++ A warehouse prints the label, sticks it on the box, hands the box over — and+ only then is the parcel fulfilled. The fulfill workflow used to invert that:+ status flipped and the shipped email queued first, the label bought after,+ which meant the merchant could not print a label without telling the customer+ the parcel had shipped, the email raced the label purchase for its tracking+ number, and a failed purchase surfaced only after the customer heard.++ Two changes. `Fulfillments::PurchaseLabel` is the explicit pre-ship step:+ buys the checkout-quoted rate through the provider, attaches tracking and the+ label document, leaves the status untouched and sends nothing — and fails+ loudly, because nothing has left the building yet. And `Fulfillments::Fulfill`+ reordered its internals to split → buy label (external step) → mark fulfilled,+ so the fulfilled event always sees the provider's tracking number; a label+ failure there still degrades to "no label yet" per the provider doctrine,+ since a carrier outage must never stop a merchant recording a parcel that+ physically left.++ Two contracts changed with it: providers must make `create_fulfillment`+ idempotent (a label bought in the explicit step is returned, not re-bought,+ when fulfill later runs), declared via `FulfillmentProvider.generates_labels?`;+ and a failure after a partial-fulfillment split no longer rolls the split+ back — a label may already be bought for the split parcel, and rolling the+ parcel away would orphan a paid label. The split survives unfulfilled and a+ retry picks it up.++ Packing slips are the platform's document, not the carrier's — generated+ client-side from data the order screen already holds, no prices, no admin+ shell around them. Plan: `6.0-fulfillment-and-delivery.md`.++ ## 2026-08-11: One tracking number per fulfillment; multiple trackings deferred to 6.1++ A fulfillment carries exactly one tracking number, one carrier and one carrier+ lifecycle. When a shipment physically diverges into parcels, the answer is the+ split flow the partial-fulfillment work already provides: each parcel becomes+ its own fulfillment with its own items, status, tracking and `delivered_at`.+ That is strictly more expressive than a list of tracking numbers on one+ record — a bare list cannot say which items are in the box that bounced, and+ delivery becomes all-or-nothing across the list.++ What a separate tracking model would add is the narrower case: one logical+ shipment in several boxes the merchant does not want to manage as separate+ fulfillments (furniture in three cartons, a pallet of mixed packages).+ Deferred to 6.1, deliberately after the carrier-axis work landed, because the+ cost is now clear: `tracking_status`, `estimated_delivery_at`, `delivered_at`+ and webhook matching all live on the fulfillment, and a+ `spree_fulfillment_trackings` row would have to absorb that whole axis —+ per-parcel carrier status, webhooks matched to a row, the fulfillment+ delivered only when every row is — plus deprecation bridges for the+ fulfillment-level columns that are public API since 6.0.++ Design constraint recorded for whoever builds it: the tracking row takes the+ entire carrier axis with it. Splitting the axis across fulfillment and+ tracking rows — status here, delivered_at there — recreates the two-sources+ problem the 6.0 status rework just removed.+ Plan: `6.0-fulfillment-and-delivery.md` (Phase 6, resolved question 15).++ ## 2026-08-11: Fulfillment status model — two axes, `delivered` first-class, machine removed (supersedes part of 2026-08-10)++ `Fulfillment#status` collapses to `unfulfilled → fulfilled → delivered` plus+ `canceled`, plain string via `HasStatus`, state machine deleted. `pending` and+ `ready` were payment and stock facts wearing a fulfillment costume —+ `determine_state` re-derived them from `order.paid?` on every recalculation, so+ a refund flipped a fulfillment's status with no physical change, and merchants+ never understood them. That gating becomes a validate guard in+ `Fulfillments::Fulfill` (rejects with a reason, staff-overridable).+ `ready_for_pickup` dies as a status: pickup `fulfilled` means "ready at the+ counter", `delivered` means picked up, presentation is modality-aware.++ `delivered` is the new terminal state — confirmed receipt, the thing merchants+ kept asking for (the lifecycle used to end at handover). Set by carrier+ tracking, a staff button, or later customer confirmation, via+ `Fulfillments::MarkDelivered` (`delivered_at`, `fulfillment.delivered` event).+ The returns eligibility window and the EU 14-day withdrawal period anchor on+ `delivered_at`.++ Carrier truth is a second axis, data not a machine: `tracking_status` ++ `tracking_details` + `estimated_delivery_at`, overwritten per update+ (`pre_transit … delivered, return_to_sender, failure`), written by+ `Fulfillments::UpdateTracking`. Bounces and failed attempts surface there+ without mutating `status`. The EasyPost gem feeds it from tracker webhooks —+ every purchased label already has a tracker whose updates were being thrown+ away; trackers for hand-entered numbers cost money each, so opt-in.++ This supersedes the 2026-08-10 "the dangerous callbacks move, the machine+ stays" conclusion: with `pending`/`ready` gone the machine held two transitions+ and its event publishes, which is what `HasStatus` + workflows already do for+ Return/Exchange/Claim. The side-effect relocation stands and made removal+ cheap. The FulfillmentItem machine and the other machines (Payment,+ ReturnAuthorization, GiftCard) are unaffected. Status mapping for existing+ rows: `pending|ready → unfulfilled`, `ready_for_pickup → fulfilled`,+ pickup-modality `fulfilled → delivered`, shipping-modality `fulfilled` stays.+ Plan: `6.0-fulfillment-and-delivery.md` (Key Decisions → "Status model — two+ axes", Resolved Question 14, Phase 7).++ ## 2026-08-11: The order edit screen stages edits and saves in bulk (reverses 2026-08-10)++ The 6.0 admin order edit screen was specified to write immediately — one+ interaction, one request — and shipped that way: a dialog per quantity change, a+ confirm dialog per removal. That is the wrong shape for an order editor and the+ constraint behind it was wrong.++ It now works as a form. Quantities are inputs, a row's `x` marks it removed+ (struck through, reversible), Save applies the batch and Discard drops it.++ **Why the original constraint was wrong.** It existed to forbid a *persisted*+ per-domain draft: a shadow order in the database that+ `6.1-order-change-substrate.md` Phase 3 would have to migrate onto `OrderChange`.+ That reasoning holds. But it was extended to cover transient React form state,+ which is a different thing entirely — a form holding "quantity 2 -> 3, line 4+ removed" until submit persists nothing, so there is nothing to unpick later. It+ is the same dirty-tracked form pattern the dashboard uses everywhere else.++ **Staged edits fit the substrate better, not worse.** `OrderChange` is+ `begin -> request -> confirm -> cancel`: accumulate actions, then confirm. A+ screen that already batches behind Save maps onto that directly, and Phase 3+ becomes additive (a totals delta, `begin` on entry). The immediate-write version+ is the one that would have needed reshaping, having no confirm moment at all.++ **Immediate writes were also worse on their own terms.** Every keystroke in a+ quantity field fired a request and re-summed the order server-side, and removing+ a line was irreversible with only a confirm dialog in the way. Staging gives the+ merchant a Discard.++ **Accepted limitation.** There is no bulk line-item endpoint, so Save issues N+ calls against the existing per-item routes and a mid-batch failure leaves+ earlier writes applied. The screen reports what succeeded and keeps the rest+ staged. Deliberately not fixed with a new bulk endpoint: Phase 3's+ `OrderChanges::Confirm` applies every action in one transaction, so building one+ now would be work thrown away.++ **What stays forbidden:** persisting pending edits in any schema, and computing+ a projected total client-side to fake a preview — 6.0 cannot project totals, and+ an approximation would disagree with the server.++## 2026-08-11: Cross-border tax-inclusive pricing derives net-fixed, except where the merchant priced that geography++A live pass against a running server found three defects in one seam — what a customer is charged+when the destination's VAT rate differs from the home zone's. `6.0-tax-provider.md` gains Phase 8 to+fix them (the 6.1 cleanup renumbers to Phase 9).++**The rule, which is Shopify's:** a price from a price list whose rules include a geographic one+(`MarketRule`, `ZoneRule`) is **final** — charged exactly as entered, never restated. Everything else+**derives net-fixed**: home rate out, destination rate on, via `VatPriceCalculation`. The merchant's+net is preserved and the gross moves.++**Why this matters beyond tax.** Two of the three defects are pricing defects, not tax defects:++1. `Pricing::Context.from_order` never carried the owner's `market`, so cart line pricing followed+ the request's `x-spree-country` hint (or the store default) instead of the cart's own market.+ Measured: a catalogue request with the hint served a French price list at 99.00 while the cart on+ that same French market priced at 100.00, and the wrong figure persisted. **Market-scoped price+ lists were therefore unreachable from a cart** — they work for the catalogue only.+2. `Cart#recalculate_for_address_change!` called `LineItem#update_price`, which assigns without+ saving, where `recalculate_price` persists. A destination change computed the restated price and+ discarded it; a later quantity change wrote it. So what a cross-border customer paid depended on+ the order of operations.++**Constraints this places on other work:** cart-stage pricing must read the cart's own market, never+`Spree::Current` (catalogue requests keep that fallback, having no owner); any new `PriceRule`+subclass must answer `geographic?`, since that predicate now decides whether its list's prices are+exempt from restatement; and re-pricing paths must stay behind+`Carts::Complete#verify_expected_total`, whose `cart_changed` failure is what makes a mid-checkout+price movement disclosable instead of silent.++**Restatement is a capability of the Internal provider, not of the platform.** `VatPriceCalculation`+derives both the home and destination rate from `TaxRate` rows, so it only works where those rows are+the whole truth. An absent row is ambiguous — *no tax is due here* or *tax is computed by an engine* —+and the code reads it as the former. Measured: German home zone, Japanese destination, no Japanese+rates, and 100.00 is charged as **84.03**. Correct for a genuine zero-rated export; wrong for a market+whose engine simply has no rows in that table, where it makes every foreign destination look like an+export. So restatement runs for Internal and is skipped elsewhere, with a geo-scoped price list as the+external-provider merchant's way to state destination prices. Shopify arrived at the same separation:+dynamic tax-inclusive pricing reads a standard-rate table and is explicitly unsupported alongside+AvaTax. A+read-only `rate_for` on the provider contract would dissolve the limitation and stays deferred with+the delivery-option quote question, which is the same problem for a different surface.++Surveyed for this: Shopify, WooCommerce, Magento/Adobe Commerce, BigCommerce, Saleor, Medusa,+Vendure, commercetools. Net-fixed is the majority default (WooCommerce, Magento, Shopify, Vendure);+the headless platforms (Saleor, commercetools, Medusa) refuse to derive at all and require a price+per channel/region.+ ## 2026-08-10: Fulfillment side effects move to workflows; the state machine keeps the status column++ Answers "should Fulfillment follow Order and lose its state machine?" with+ **partly, deliberately**. The side effects move; the machine stays.++ `Fulfillment#after_cancel` restocked every unit **and** called+ `provider.cancel_fulfillment` — network I/O (an EasyPost label refund, a 3PL+ stand-down) running inside the save transaction that held the stock movements.+ That is precisely the failure `6.0-service-workflows.md` cites as the reason+ transition callbacks are the wrong place for side effects: a slow carrier holds+ row locks, and a failing one rolls back a restock that already happened at the+ warehouse.++ `Spree::Fulfillments::Cancel` and `::Resume` now own that work — restock and+ status inside one transaction, the provider call as an `external_step` after it+ commits. `Fulfillments::Fulfill` (added the same day for partial shipments)+ gained an explicit unstock for the `canceled -> fulfilled` path the resume+ callback used to cover; missing it would have shipped goods without taking them+ off the shelf.++ **What the machine keeps:** the status column, the transition graph and its+ guards, and the `publish_*_event` callbacks. Publishing an event *describes* the+ status change rather than being a side effect of it, so it belongs where the+ transition is. The graph is real validation work — the narrow exception+ `6.0-service-workflows.md` already allows.++ **Why not remove the machine outright.** Four other models still carry machines+ (Payment, InventoryUnit, ReturnAuthorization, GiftCard). Removing one at a time+ means re-litigating the same design in five separate rounds, and Fulfillment's+ `ready`/`resume` guards are conditional on `determine_state`, so replacing them+ is not mechanical. A full removal is a planned wave with its own document, not a+ refactor folded into fulfillment UI work. This also amends+ `6.0-fulfillment-and-delivery.md` resolved question 1, which had promised all+ transition hooks were preserved.++ **Composition constraint, and the wrong turn taken first.** `Orders::Cancel`+ and `Orders::Resume` cancel or resume every fulfillment from inside the order's+ own transaction, and a nested `external_step` raises `ContractError` by design.+ The first attempt worked around this by putting the restock bodies on the model+ as public `#restock_units`/`#unstock_units` and having both layers call them.+ That was wrong twice over: it violates the rule that workflows write behavior+ inline as named steps rather than delegating to model business methods, and it+ plants new public model surface that would have to be torn out again when the+ machine is eventually removed — the opposite of the direction the model is+ moving.++ The right shape: the stock movements are written inline in the workflow steps,+ and `Fulfillments::Cancel` takes a `notify_provider:` flag so a caller that+ already holds a transaction can suppress the external step and batch the+ carrier calls into its own. `Orders::Cancel` passes `notify_provider: false`+ and notifies after commit; `Orders::Resume` nests cleanly because Resume has no+ external step. **The general rule: when a workflow with an `external_step` must+ run inside another's transaction, give it a flag to defer the external half —+ do not push the shared behavior down onto the model.**++ ## 2026-08-10: Order editing splits from fulfillment management; two OrderChange questions resolved++ The 6.0 admin order detail page grows a **separate edit screen** at+ `/orders/$orderId/edit` owning post-placement line-item mutation — add, remove,+ change quantity. The order detail page keeps fulfillment management (what ships,+ from where, under which delivery method); it no longer offers line-item editing.+ The split follows the reference layout and, more importantly, matches how+ `6.1-order-change-substrate.md` Phase 3 wants to wrap the edit surface in a+ change set without disturbing fulfillment UI.++ The 6.0 screen **writes immediately and shows no totals delta**. Projecting+ totals without writing rows is impossible before the OrderChange substrate+ lands, and the alternative — buffering edits in React state so the UI can fake a+ preview — is a per-domain draft living in the browser, which the substrate plan+ explicitly forbids. The money math still goes through a value-object-returning+ service so Phase 3 re-points it at `OrderChanges::Preview` without touching+ callers.++ Two of that plan's open questions are settled as a consequence:++ *A change set belongs to one `Order`, never to an `OrderGroup`.* Multi-vendor+ fans a cart into N child orders under one group, and the marketplace plan's+ Decision 8 keeps line items, fulfillments and totals on the children — the group+ holds only customer, payment and addresses. Change sets mutate child-owned rows,+ so they bind to the child. Cross-vendor edits are N change sets, which is also+ where the money belongs: each vendor settles against its own order.++ *A pending change set does not hold stock.* Stock reservations are scoped to+ checkout — held against a cart, extended by customer activity, expired by a job.+ An admin editing a placed order is neither, so reusing that machinery would+ create reservations with no expiry trigger. `add_item` takes stock at confirm,+ and confirm is where an out-of-stock action fails.++ Also settled for the backend: **partial fulfillment ships as a+ `Spree::Fulfillments::Fulfill` workflow**, not by extending the state machine.+ `Spree::Fulfillment` keeps its machine (preserved deliberately per+ `6.0-fulfillment-and-delivery.md` resolved question 1), but shipping a *subset*+ means splitting first, and split-then-ship inside an `after_transition` callback+ is exactly the shape `6.0-service-workflows.md` prohibits. The workflow wraps the+ machine as a low-level mechanic, mirroring how `Fulfillments::Create` already+ wraps `mark_shipped`.## 2026-08-09: Metadata consolidated to one column — `public_metadata` dropped, `private_metadata` renamed@@@ -107,79 -292,128 +339,201 @@@ never in metadataPlan: `docs/plans/6.0-consolidate-metadata-columns.md`.+## 2026-08-07: The tax plan builds the minimal Company tree; the B2B release keeps Catalog++Exemption certificates need an entity to hang off, and `Spree::Company` does not+exist — `6.1-channels-catalogs-b2b.md` targets 6.1. Rather than leave the tax+plan's last phase blocked behind a release, `6.0-tax-provider.md` Phase 7 builds+**Company → CompanyLocation → CompanyContact** plus+`Spree::TaxExemptionCertificate`, and the B2B release inherits those models+instead of defining them.++**Why the whole tree and not just Company.** The contact record is what lets a+logged-in B2B buyer's own cart resolve a company without staff touching the+order. Company alone would mean exemption works only on admin-created orders —+the wrong limitation for a self-serve wholesale channel. The location is what+the Cart and Order reference (`company_location_id` on both, following+`channel_id`/`market_id`), because that is the FK the B2B plan already specifies+for orders; a direct `company_id` would save one hop now and cost a schema+reversal later.++**Supersedes the B2B plan on one point: no `tax_exempt` boolean.** That plan's+Company and CompanyLocation sketches both carry one. It is not being built. A+flag cannot say which jurisdiction it holds in or which lines it covers, and+removing the boolean `exempt?` from the provider contract was the substance of+the 2026-08-05 refinement — reintroducing it a layer down would undo it.+Exemption is a certificate resolved into a typed `Spree::TaxExemption` entry.+**`6.1-channels-catalogs-b2b.md` still needs this note added to its own Key+Decisions** — deliberately not edited yet, at the author's instruction.++**Explicitly not pulled forward:** Catalog, CatalogProduct, CatalogAssignment,+`default_catalog_id`, per-company pricing, `Products::ForContext` visibility, the+Company → CustomerGroup link, and roles/approvals/purchase limits/invoicing.+Certificates hang off Company scoped by their own country/state columns, so no+per-location duplication.++**Constraint going forward:** pulling a model forward out of another plan takes+the model, not the feature. If a field only makes sense for the deferred feature,+it waits with it.++## 2026-08-07: The pricing zone dimension ships with the tax provider, but the price-rule design stays with delivery-zones++`6.0-delivery-zones.md`'s ownership table gives the `Pricing::Context` zone+dimension and the `Spree::Current` zone attribute to that plan, "with+tax-provider". It landed in the tax provider work instead, because the two+cannot be separated: `Pricing::Context.from_order` read `order.tax_zone`, so it+broke the moment `Purchase::Taxation#tax_zone` was removed — which the same+table assigns to the tax plan.++`Spree::Current.tax_country` returns a `Spree::Country` rather than the ISO+string that plan's constraints section specified, matching the already-shipped+`Purchase::Taxation#tax_country`. An ISO code would mean a country lookup on+every read, and the price rule compares stored ids.++**Where the line was drawn.** `PriceRules::ZoneRule` also reads the zone+dimension, so it had to change or crash. It now decides by country, keeps its+class name (the `type` column persists it), stays out of the rule registry, and+`spree:migrate_tax_zones` restates each row's stored zones as the countries they+contained — state-level zones widen to the whole country, which the task+reports. What was **not** done: promoting it to a first-class `CountryRule` with+a factory and a registry entry. That is a customer-visible pricing feature no+plan called for, and it belongs to the plan that owns Zone's removal.++**Constraint going forward:** "something must change or it crashes" licenses the+minimum that keeps it working, not a redesign. When a forced edit reaches into+another plan's surface, do the minimum and hand the design decision back in that+plan's own document.++**Corollary (2026-08-07).** The same reasoning ruled out guarding the window+between `db:migrate` and the data task. A review found that an unconverted rule+matches every country, and the first fix made such a row refuse to apply. That+was also scope creep: the 6.0 data tasks are steps in the upgrade manifest, so+"code deployed, task not yet run" is not a state Spree supports, and inventing+behaviour for it adds a permanent branch to a hot path to cover a transient.+Don't design for half-upgraded installs; make the task correct and say what it+did.+ ## 2026-08-09: Origin groups and per-currency delivery pricing in 6.0++ Two same-day additions to the delivery-profiles model, both Damian-approved+ mid-review of PR #14404.++ **`Spree::DeliveryOriginGroup` (pulled forward from the 6.1 open+ question).** Zones are per-profile (the profile-based platforms' shape;+ sharing across profiles was considered and rejected — editing a shared zone+ would silently change other profiles' coverage). Within a profile, origin+ groups partition the fulfillment origins: every zone and method belongs to+ one group, so "same products, different warehouse, different rates" is one+ profile with two groups instead of hand-narrowed method duplicates. The+ auto-created nameless default group (no members = all locations) keeps the+ layer invisible for single-origin stores. The profile ↔ stock-location join+ is replaced by group membership (profile coverage = union of its groups);+ per-method ships-from narrowing retires for shipping methods, and+ `DeliveryMethodStockLocation` stays pickup-only (collection counters).+ Admin API: nested origin_groups CRUD under delivery_profiles; the+ profile-level `stock_location_ids` shorthand reads/writes the default+ group.++ **Per-currency delivery pricing (kills method-per-currency).** Amount-based+ shipping calculators (FlatRate, PerItem, DigitalDelivery) gain an `amounts`+ hash — one explicit amount per currency, no FX, mirroring product prices;+ a currency without an amount hides the method for those carts. The legacy+ single `amount`+`currency` pair stays as the fallback for its own currency,+ so upgraded 5.x stores quote unchanged. Percent calculators are+ currency-agnostic and drop the currency gate; PriceSack/FlexiRate keep+ strict single-currency matching. The Estimator consults+ `calculator.supports_currency?` instead of exact-matching the currency+ preference. Carrier quotes: `DeliveryRateProvider::Estimate` gains+ `currency`, EasyPost passes the carrier's `rate.currency` through, and the+ Estimator drops estimates quoted in another currency than the cart's — a+ number in the wrong currency must never reach checkout (EasyPost has no+ quote-currency parameter; multi-currency carrier setups use+ per-currency carrier accounts). The pricing card renders one amount per+ supported store currency; the default currency maps to the legacy amount+ preference.++ ## 2026-08-09: Fulfillment profiles — ShippingCategory promoted, not removed++ Reverses three recorded decisions inside the 6.0 window: "fulfillment types+ are NOT a model", "named delivery groups are the 6.1-if-needed successor to+ profiles" (both `6.0-fulfillment-and-delivery.md`), and live-by-reference+ `fulfillment_types` on ProductType (`6.0-product-types.md`). Full design in+ `6.0-delivery-profiles.md`.++ **The model.** `Spree::DeliveryProfile` — store-scoped STI, one default+ per store, kinds registered via `Spree.delivery_profile_types`+ (`DeliveryProfiles::Shipping` default, `::Digital`) — groups products+ for delivery: profile ↔ stock locations (origins, empty = all), profile →+ delivery zones (destinations), profile → delivery methods (each with an+ optional single zone and optional ships-from narrowing via the generalized+ method↔location join). Products carry `delivery_profile_id` directly;+ ProductType stamps its template profile at creation and never manages it+ afterwards. Carts split per profile. **Classes only, no string+ vocabularies (refined same day):** the method's `fulfillment_type` column+ is dropped (not renamed to modality), `Spree.fulfillment_types` and the+ ProductType array are deleted; behavior routes through class predicates —+ `FulfillmentProvider` subclasses answer `digital?`/`pickup?`/+ `pickup_point?`/`requires_address?`, rate providers declare+ `requires_address?` instead of type lists, and the profile kind declares+ `digital?`/`requires_shipping_address?` and validates composition (a+ Digital profile accepts only digital-provider methods; a carrier rate+ provider only prices methods that ship to an address). A location-group+ layer was considered and dropped — per-method narrowing covers+ multi-origin stores, and groups can arrive additively later.++ **Why reverse now.** No rewrite window after 6.0; custom string types were+ second-class (provider declarations could never include them, so a custom+ type could not use carrier rate providers); the origin axis simply did not+ exist for shipping methods; and the fulfillment_types array was the sole+ live-by-reference exception to the product-type template doctrine.++ **Migration by rename.** `spree_shipping_categories` →+ `spree_delivery_profiles` and `spree_products.shipping_category_id` →+ `delivery_profile_id`: 5.x products arrive assigned, the 5.x Digital+ category becomes the Digital profile. `spree:migrate_delivery_profiles`+ (5.6→6.0 manifest) handles what a rename cannot: store assignment for the+ formerly-global categories (duplicate + remap when shared), folding+ non-narrowing categories into the store default profile, digital-kind+ detection, and collapsing the method m:n+ (`spree_shipping_method_categories`, kept to 6.1 as source) into the+ single method FK — loud warnings wherever flattening loses information.+++ ## 2026-08-09: Dynamic carrier rates — one delivery method, many named rates++ Supersedes the one-rate-per-method model in `6.0-delivery-rate-provider.md`+ (its unique-index gate is hereby exercised): a carrier-backed DeliveryMethod+ is the carrier connection, `DeliveryRateProvider::Base#estimates(package)`+ returns one Estimate per service, and every service becomes its own named+ `DeliveryRate` at checkout ("UPS Ground", "USPS Priority Mail"). This also+ finally delivers the "one Carrier shipping method per market, the provider+ returns whatever serves the address" aspiration recorded in the 2026-07-29+ aggregator survey, which the previous schema could not.++ **Merchant controls** (Shopify's knob set plus label overrides, which+ Shopify lacks): a new `Spree::DeliveryMethodService` row model — one row per+ carrier service, unique on (method, carrier, service) — narrows which+ services are offered (no rows = everything, current and future) and carries+ per-service `label`, `markup_flat`, `markup_percent`; method-level markup+ columns are the fallback. Rows, not preferences: independent per-service+ controls need a real model with real validation and API round-tripping.++ **Consequences.** `spree_delivery_rates` lost its unique+ (fulfillment, delivery_method) index and gained `name` (nil for calculator+ rates — `DeliveryRate#name` falls back to the method name, preserving the+ old delegate behavior). Selection across re-quotes and EasyPost label+ purchase key off the selected rate's carrier/service, not method config.+ The EasyPost method-metadata carrier/service binding is deleted. Seeds and+ sample data reshaped Shopify-style: Domestic + International delivery zones+ per store with basic flat-rate methods, replacing the continental sprawl.++ **Competitive grounding** (researched 2026-08-09): Shopify persists service+ selection + handling fee on the zone's carrier-rate entry and quotes live+ (labels not renamable); Medusa materializes one ShippingOption per service+ from the provider catalog; Saleor delegates everything to apps; Vendure is+ one-method-one-quote. The two-entity method→services shape is the+ normalized version of what Shopify/Woo store as config blobs, and Spree+ ends up expressing all four models.+## 2026-08-07: `Claim#claim_type` dropped — the reason vocabulary is the only "what went wrong" axisReverses the two-axis design in `6.0-returns-exchanges-claims.md`, whichdiff --cc packages/admin-sdk/src/admin-client.tsindex 89539a8532,483737a681..6c44640919--- a/packages/admin-sdk/src/admin-client.ts+++ b/packages/admin-sdk/src/admin-client.ts@@@ -204,9 -209,7 +212,10 @@@ import typeStoreUpdateParams,TaxCategoryCreateParams,TaxCategoryUpdateParams,+ TaxExemptionCertificateParams,+ TaxIdentifierParams,+ TaxRateParams,+ TrackingCarrierOption,VariantCreateParams,VariantUpdateParams,WebhookEndpointCreateParams,diff --cc packages/admin-sdk/src/types/generated/Fulfillment.tsindex 61dc29a7f5,64ebd02cb5..e38b88d50a--- a/packages/admin-sdk/src/types/generated/Fulfillment.ts+++ b/packages/admin-sdk/src/types/generated/Fulfillment.ts@@@ -1,7 -1,7 +1,7 @@@- // Typelizer digest eefb847081348b9e928061359e49ef60-// Typelizer digest 655bed4fb7a03ad6348066525b7e062b++// Typelizer digest a6ce9755793869194d5eed84c3e4c026//// DO NOT MODIFY: This file was automatically generated by Typelizer.-import type {DeliveryMethod, StockLocation, DeliveryRate, FulfillmentItem, Order} from '@/types'+import type {DeliveryMethod, StockLocation, DeliveryRate, TaxLine, FulfillmentItem, Order} from '@/types'interface Fulfillment {id: string;@@@ -29,8 -34,8 +34,9 @@@delivery_method?: DeliveryMethod;stock_location?: StockLocation;delivery_rates?: Array<DeliveryRate>;+ tax_lines?: Array<TaxLine>;metadata: Record<string, unknown>;+ tracking_details: Record<string, unknown> | null;adjustment_total: string;pre_tax_amount: string;created_at: string;diff --cc packages/admin-sdk/src/types/generated/index.tsindex 7fa2dd7664,7d680b4b32..694e900521--- a/packages/admin-sdk/src/types/generated/index.ts+++ b/packages/admin-sdk/src/types/generated/index.ts@@@ -1,4 -1,4 +1,4 @@@- // Typelizer digest 0860d2a5cb38d80c615d11ec68e6aed1-// Typelizer digest d30e852b2d7ac8dea87d7faae6c043fb++// Typelizer digest 0b73b2f9288a9667db08b7519f1a4841//// DO NOT MODIFY: This file was automatically generated by Typelizer.export type { default as Address } from './Address'diff --cc packages/sdk/src/types/generated/Fulfillment.tsindex 354c4c97ee,b0d9eed3fd..c9a8dcceed--- a/packages/sdk/src/types/generated/Fulfillment.ts+++ b/packages/sdk/src/types/generated/Fulfillment.ts@@@ -1,7 -1,7 +1,7 @@@- // Typelizer digest 22963ae2bf35d9f53b9223c4541d5db7-// Typelizer digest fff9d58972c610a62f61535d4d7b3cf2++// Typelizer digest e3654a95ab4a56e25b6e7de8b765adb8//// DO NOT MODIFY: This file was automatically generated by Typelizer.-import type {DeliveryMethod, StockLocation, DeliveryRate} from '@/types'+import type {DeliveryMethod, StockLocation, DeliveryRate, TaxLine} from '@/types'interface Fulfillment {id: string;diff --cc spree/api/config/initializers/typelizer.rbindex 09741591df,f1245f4509..2cf537cff1--- a/spree/api/config/initializers/typelizer.rb+++ b/spree/api/config/initializers/typelizer.rb@@@ -23,10 -23,9 +23,10 @@@ Rails.application.config.after_initiali# Serializers that exist only for Admin API or events — no Store API controllerstore_excluded = %w[Asset CartPromotion OrderPromotion- StockItem StockMovement StockTransfer ShippingCategory+ StockItem StockMovement StockTransferReport Export Import ImportRowTaxCategory Exchange ExchangeLineItem+ Company].to_set# Store SDK — no prefix, package provides namespacediff --cc spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rbindex cc66d19964,08cba77f6a..487ab25864--- a/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/orders_controller_spec.rb@@@ -423,38 -423,25 +423,57 @@@ RSpec.describe Spree::Api::V3::Admin::Oexpect(json_response['email']).to eq('[email protected]')end+ # Staff assigning the business an order is for — the only route to an+ # exemption for a buyer who acts for several companies, until session-level+ # selection is settled with channels and catalogs.+ context 'assigning the business the order is for' do+ let(:company) { create(:company, store: store) }+ let(:location) { create(:company_location, company: company) }++ it 'sets the branch and reports the company' do+ patch :update, params: { id: order.prefixed_id, company_location_id: location.prefixed_id }, as: :json++ expect(response).to have_http_status(:ok)+ expect(json_response['company_location_id']).to eq(location.prefixed_id)+ expect(json_response['company_id']).to eq(company.prefixed_id)+ expect(order.reload.company).to eq(company)+ end++ it 'refuses a branch belonging to another store' do+ elsewhere = create(:company_location, company: create(:company, store: create(:store)))++ patch :update, params: { id: order.prefixed_id, company_location_id: elsewhere.prefixed_id }, as: :json++ expect(response).to have_http_status(:unprocessable_content)+ expect(order.reload.company_location_id).to be_nil+ end++ it 'clears the branch when passed nothing' do+ order.update!(company_location: location)++ patch :update, params: { id: order.prefixed_id, company_location_id: nil }, as: :json++ expect(response).to have_http_status(:ok)+ expect(order.reload.company_location_id).to be_nil+ # The admin order edit screen submits every row it shows in one request:+ # changed quantities as their new value, struck-out rows as zero.+ context 'with a whole edited order in one request' do+ let(:order) { create(:order_with_line_items, store: store, line_items_count: 2) }+ let(:kept) { order.line_items.first }+ let(:removed) { order.line_items.last }++ it 'applies the quantity changes and the removals together' do+ patch :update, params: {+ id: order.prefixed_id,+ items: [+ { variant_id: kept.variant.prefixed_id, quantity: 3 },+ { variant_id: removed.variant.prefixed_id, quantity: 0 }+ ]+ }, as: :json++ expect(response).to have_http_status(:ok)+ expect(order.reload.line_items).to contain_exactly(kept)+ expect(kept.reload.quantity).to eq(3)endenddiff --cc spree/core/app/models/spree/cart.rbindex b697d9e4b8,db3d625555..1379af1c04--- a/spree/core/app/models/spree/cart.rb+++ b/spree/core/app/models/spree/cart.rb@@@ -73,10 -72,9 +73,10 @@@ module Sprehas_many :variants, through: :line_itemshas_many :products, through: :variantshas_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy, inverse_of: :cart+ has_one :tax_identifier, class_name: 'Spree::TaxIdentifier', dependent: :destroy, inverse_of: :carthas_many :discounts, class_name: 'Spree::Discount', dependent: :destroy, inverse_of: :carthas_many :fees, class_name: 'Spree::Fee', dependent: :destroy, inverse_of: :cart- has_many :fulfillments, class_name: 'Spree::Fulfillment', dependent: :destroy, inverse_of: :cart do+ has_many :fulfillments, -> { order(:created_at, :id) }, class_name: 'Spree::Fulfillment', dependent: :destroy, inverse_of: :cart dodef statespluck(:status).uniqenddiff --cc spree/core/app/models/spree/current.rbindex a959d16582,3f164d5fff..196242545c--- a/spree/core/app/models/spree/current.rb+++ b/spree/core/app/models/spree/current.rb@@@ -4,7 -4,20 +4,18 @@@ module Spre# All attributes are automatically reset between requests by Rails.# Fallback chains ensure sensible defaults when attributes are not explicitly set.class Current < ::ActiveSupport::CurrentAttributes- attribute :store, :channel, :market, :currency, :locale, :content_locale, :tax_country, :price_lists, :global_pricing_context- attribute :store, :channel, :market, :currency, :locale, :content_locale, :zone, :default_tax_zone, :price_lists, :global_pricing_context, :provider_cache-- resets { @default_tax_zone_loaded = false }++ attribute :store, :channel, :market, :currency, :locale, :content_locale, :tax_country, :price_lists, :global_pricing_context, :provider_cache++ # Scratch space for provider strategies to memoize a call across the+ # request — part of the delivery rate provider contract (nothing in core+ # writes to it): a carrier gem keys its quote here so several delivery+ # methods sharing one carrier cost a single API round-trip rather than+ # one each. Keys must be namespaced by the provider (see the custom+ # delivery rate provider guide).+ # @return [Hash]+ def provider_cache+ super || (self.provider_cache = {})+ end# Returns the current store, falling back to the default store.# @return [Spree::Store]diff --cc spree/core/app/models/spree/product.rbindex 85fcbece8d,b9b3eb6075..3b5f4572fd--- a/spree/core/app/models/spree/product.rb+++ b/spree/core/app/models/spree/product.rb@@@ -900,9 -917,23 +917,23 @@@ module Spreenddef assign_default_tax_category- self.tax_category = Spree::TaxCategory.default if new_record? && self[:tax_category_id].blank?+ self.tax_category = Spree::TaxCategory.default(assignable_store) if new_record? && self[:tax_category_id].blank?end+ def stamp_template_delivery_profile+ return if delivery_profile_id.present?++ self.delivery_profile_id = product_type&.delivery_profile_id ||+ (store && Spree::DeliveryProfile.default_for(store)&.id)+ end++ def delivery_profile_must_belong_to_store+ return if delivery_profile.nil? || store.nil?+ return if delivery_profile.store_id == store_id++ errors.add(:delivery_profile, :invalid)+ end+def run_touch_callbacksrun_callbacks(:touch)enddiff --cc spree/core/app/workflows/spree/orders/cancel.rbindex 761d666d1c,64aed2b141..5e647108b5--- a/spree/core/app/workflows/spree/orders/cancel.rb+++ b/spree/core/app/workflows/spree/orders/cancel.rb@@@ -50,8 -50,8 +50,9 @@@ module Sprerun_hooks :after_cancelend+ external_step :notify_fulfillment_providersexternal_step :settle_payments+ external_step :void_taxstep :recompute_totals, with: -> { Spree.order_recalculate_totals_workflow }step :update_statuses, with: -> { Spree.order_update_statuses_service }order.publish_event('order.canceled', order.event_payload.merge(notify_customer: notify_customer))diff --cc spree/core/config/locales/en.ymlindex 7c70baaa30,eae690690b..14af453352--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@@ -887,7 -883,8 +883,9 @@@ endiscount_value_type_invalid: value_type must be flat or percentexactly_one_adjustable: must be attached to exactly one adjustableexactly_one_of_cart_or_order: must belong to exactly one of cart or order+ exactly_one_tax_identifier_owner: must belong to exactly one of customer, cart or order+ integration_connection_failed: could not connect with the saved credentials+ integration_type_not_registered: is not a registered integrationinvalid_delivery_method_rule: is not a registered delivery method ruleinvalid_oauth_state: Invalid or expired authentication state. Please start the sign-in again.invalid_order_routing_rule: is not a registered order routing rulediff --cc spree/core/lib/spree/core/engine.rbindex 0a5eead169,b23e0dee45..9296cfa15f--- a/spree/core/lib/spree/core/engine.rb+++ b/spree/core/lib/spree/core/engine.rb@@@ -10,13 -10,14 +10,15 @@@ module Spre:dependencies,:payment_methods,:adjusters,- :tax_provider,+ :default_tax_provider,+ :tax_providers,:password_validator,:fulfillment_providers,- :fulfillment_types,+ :tracking_carriers,:stock_splitters,:delivery_method_rules,+ :delivery_rate_providers,+ :delivery_profile_types,:order_routing,:promotions,:pricing,diff --cc spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rbindex b40d9384eb,bcc8c6c76a..b83bf8123a--- a/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb+++ b/spree/core/spec/lib/tasks/six_zero_data_migrations_spec.rb@@@ -10,7 -11,7 +11,8 @@@ describe '6.0 data migration tasks' dload Spree::Core::Engine.root.join('lib', 'tasks', 'products.rake')load Spree::Core::Engine.root.join('lib', 'tasks', 'order_market_backfill.rake')load Spree::Core::Engine.root.join('lib', 'tasks', 'store_binding_migration.rake')+ load Spree::Core::Engine.root.join('lib', 'tasks', 'tax_zones_migration.rake')+ load Spree::Core::Engine.root.join('lib', 'tasks', 'fulfillment_statuses_migration.rake')endlet(:store) { @default_store }@@@ -111,152 -111,75 +112,221 @@@endend+ describe 'spree:backfill_tax_store_ids' do+ it 'assigns the default store to unbound rows and skips bound ones' do+ other_store = create(:store)+ bound_category = create(:tax_category)+ bound_category.update_columns(store_id: other_store.id)+ legacy_category = create(:tax_category)+ legacy_category.update_columns(store_id: nil)+ legacy_rate = create(:tax_rate)+ legacy_rate.update_columns(store_id: nil)++ run_task('spree:backfill_tax_store_ids')++ expect(legacy_category.reload.store_id).to eq(@default_store.id)+ expect(legacy_rate.reload.store_id).to eq(@default_store.id)+ expect(bound_category.reload.store_id).to eq(other_store.id)+ end++ it 'binds soft-deleted rows too' do+ deleted_rate = create(:tax_rate)+ deleted_rate.destroy+ deleted_rate.update_columns(store_id: nil)++ run_task('spree:backfill_tax_store_ids')++ expect(Spree::TaxRate.with_deleted.find(deleted_rate.id).store_id).to eq(@default_store.id)+ end+ end++ describe 'spree:migrate_tax_zones' do+ let(:germany) { Spree::Country.find_by(iso: 'DE') || create(:country, iso: 'DE', name: 'Germany') }+ let(:france) { Spree::Country.find_by(iso: 'FR') || create(:country, iso: 'FR', name: 'France') }++ def zone_with(*zoneables)+ zone = Spree::Zone.create!(name: "Tax Zone #{Time.current.to_f}#{rand(1000)}", kind: 'country')+ zoneables.each { |zoneable| zone.zone_members.create!(zoneable: zoneable) }+ zone+ end++ def unconverted_rate(zone, **attributes)+ create(:tax_rate, **attributes).tap do |rate|+ rate.update_columns(country_id: nil, state_id: nil, zone_id: zone.id)+ end+ end++ it 'copies a single-country zone onto the rate' do+ rate = unconverted_rate(zone_with(germany))++ run_task('spree:migrate_tax_zones')++ expect(rate.reload.country).to eq(germany)+ expect(rate.state).to be_nil+ end++ it 'splits a multi-country zone into one rate per country' do+ rate = unconverted_rate(zone_with(germany, france), amount: 0.19)++ expect { run_task('spree:migrate_tax_zones') }.to change(Spree::TaxRate, :count).by(1)++ countries = Spree::TaxRate.where(name: rate.name).map(&:country)+ expect(countries).to contain_exactly(germany, france)+ expect(Spree::TaxRate.where(name: rate.name).map(&:amount).uniq).to eq([0.19])+ end++ it 'keeps a state member as a country and state pair' do+ state = create(:state, country: germany, abbr: 'BE', name: 'Berlin')+ rate = unconverted_rate(zone_with(state))++ run_task('spree:migrate_tax_zones')++ expect(rate.reload.country).to eq(germany)+ expect(rate.state).to eq(state)+ end++ it 'leaves a memberless zone as an every-country rate' do+ rate = unconverted_rate(zone_with)++ run_task('spree:migrate_tax_zones')++ expect(rate.reload.country).to be_nil+ end++ it 'is idempotent' do+ unconverted_rate(zone_with(germany, france))+ run_task('spree:migrate_tax_zones')++ expect { run_task('spree:migrate_tax_zones') }.not_to change(Spree::TaxRate, :count)+ end++ context 'price rules restricted by zone' do+ let(:price_list) { create(:price_list) }++ def legacy_rule(zone)+ create(:zone_price_rule, price_list: price_list).tap do |rule|+ rule.update_columns(preferences: { zone_ids: [zone.id.to_s] })+ end+ end++ it 'restates the zone as the countries it contained' do+ rule = legacy_rule(zone_with(germany, france))++ run_task('spree:migrate_tax_zones')++ expect(rule.reload.preferred_country_ids).to contain_exactly(germany.id.to_s, france.id.to_s)+ end++ # A state-level zone can only be expressed as its states' countries,+ # which lets the rule through for the rest of that country too.+ it 'widens a state-level zone to the country' do+ state = create(:state, country: germany, abbr: 'BE', name: 'Berlin')+ rule = legacy_rule(zone_with(state))++ run_task('spree:migrate_tax_zones')++ expect(rule.reload.preferred_country_ids).to eq([germany.id.to_s])+ end++ it 'is idempotent over a legacy row' do+ rule = legacy_rule(zone_with(germany))+ run_task('spree:migrate_tax_zones')+ converted = rule.reload.preferred_country_ids++ run_task('spree:migrate_tax_zones')++ expect(rule.reload.preferred_country_ids).to eq(converted)+ expect(rule.reload.preferences).not_to have_key(:zone_ids)+ end++ it 'leaves a rule the merchant already set countries on alone' do+ rule = create(:zone_price_rule, price_list: price_list, country_ids: [france.id])++ run_task('spree:migrate_tax_zones')++ expect(rule.reload.preferred_country_ids).to eq([france.id.to_s])+ end++ # A zone that was deleted and one that never had members both leave no+ # country to restrict by, so the rule stops narrowing its price list.+ # The task reports the count; there is nothing to fall back on.+ it 'clears a rule whose zones resolve to no country' do+ rule = legacy_rule(zone_with)++ run_task('spree:migrate_tax_zones')++ expect(rule.reload.preferred_country_ids).to be_empty+ expect(rule.preferences).not_to have_key(:zone_ids)+ end+ describe 'spree:migrate_delivery_profiles' do+ # 5.x rows arrive store-less and kind-less; the legacy method↔category+ # m:n is read straight from the surviving table.+ let(:method_categories) { Class.new(ActiveRecord::Base) { self.table_name = 'spree_shipping_method_categories' } }++ def legacy_category!(name)+ profile = Spree::DeliveryProfiles::Shipping.create!(store: store, name: name)+ profile.update_columns(store_id: nil, type: nil)+ profile+ end++ it 'folds a non-narrowing category into the store default profile' do+ category = legacy_category!('Default Category')+ method = create(:shipping_method, store: store)+ method_categories.create!(shipping_method_id: method.id, shipping_category_id: category.id)+ Spree::DeliveryMethod.unscoped.where(store: store).find_each do |delivery_method|+ method_categories.find_or_create_by!(shipping_method_id: delivery_method.id, shipping_category_id: category.id)+ end+ product = create(:product, store: store)+ product.update_columns(delivery_profile_id: category.id)++ run_task('spree:migrate_delivery_profiles')++ expect(product.reload.delivery_profile).to eq(store.default_delivery_profile)+ expect(Spree::DeliveryProfile.exists?(category.id)).to be(false)+ end++ it 'keeps a narrowing category as a profile and moves its solely-linked method in' do+ category = legacy_category!('Oversized')+ oversized_method = create(:shipping_method, store: store, name: 'Freight')+ create(:shipping_method, store: store, name: 'Regular')+ method_categories.create!(shipping_method_id: oversized_method.id, shipping_category_id: category.id)+ product = create(:product, store: store)+ product.update_columns(delivery_profile_id: category.id)++ run_task('spree:migrate_delivery_profiles')++ profile = Spree::DeliveryProfile.find(category.id)+ expect(profile.store).to eq(store)+ expect(profile).to be_a(Spree::DeliveryProfiles::Shipping)+ expect(oversized_method.reload.delivery_profile_id).to eq(profile.id)+ expect(product.reload.delivery_profile_id).to eq(profile.id)+ end++ it 'detects a digital-only category as a Digital profile' do+ category = legacy_category!('Digital Goods')+ digital_method = create(:digital_delivery_method, store: store)+ create(:shipping_method, store: store)+ method_categories.create!(shipping_method_id: digital_method.id, shipping_category_id: category.id)+ product = create(:product, store: store)+ product.update_columns(delivery_profile_id: category.id)++ run_task('spree:migrate_delivery_profiles')++ profile = Spree::DeliveryProfile.find(category.id)+ expect(profile).to be_a(Spree::DeliveryProfiles::Digital)+ expect(product.reload.delivery_profile_id).to eq(profile.id)+ end++ it 'is idempotent' do+ category = legacy_category!('Oversized')+ method = create(:shipping_method, store: store, name: 'Freight')+ create(:shipping_method, store: store, name: 'Regular')+ method_categories.create!(shipping_method_id: method.id, shipping_category_id: category.id)+ product = create(:product, store: store)+ product.update_columns(delivery_profile_id: category.id)++ run_task('spree:migrate_delivery_profiles')+ expect { run_task('spree:migrate_delivery_profiles') }.not_to change(Spree::DeliveryProfile, :count)endenddiff --cc spree/core/spec/models/spree/current_spec.rbindex 8acba06c6d,7929fbda10..0744a68131--- a/spree/core/spec/models/spree/current_spec.rb+++ b/spree/core/spec/models/spree/current_spec.rb@@@ -286,5 -323,32 +286,23 @@@ RSpec.describe Spree::Current d# After reset, global_pricing_context should be fetched freshexpect(described_class.instance_variable_get(:@global_pricing_context)).to be_nilend-- it 'clears memoized default_tax_zone' do- create(:zone, default_tax: true)- described_class.default_tax_zone-- described_class.reset-- expect(described_class.instance.instance_variable_get(:@default_tax_zone_loaded)).to be false- endend++ describe '#provider_cache' do+ it 'defaults to a hash providers can memoize into' do+ described_class.provider_cache[:quote] = 'cached'++ expect(described_class.provider_cache[:quote]).to eq('cached')+ end++ # Carrier quotes are request-scoped; leaking them across requests would+ # price one customer's checkout with another's destination.+ it 'is cleared between requests' do+ described_class.provider_cache[:quote] = 'cached'++ described_class.reset++ expect(described_class.provider_cache).to eq({})+ end+ endend