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
Mark split-adjustments plan shipped, add v6 promotion docs (#14392)
Damian Legawiecb98967e606aa
diff --git a/CLAUDE.md b/CLAUDE.mdindex f380a7eadd..c89ad80f01 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -18,7 +18,6 @@ Active plans (6.0 target, work pending):- `6.0-admin-spa.md` — React admin architecture, extension points, table registry, i18n + server-error mapping- `6.0-product-types.md` — Prototype → ProductType rename, MetafieldDefinition schema enforcement- `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-split-adjustments.md` — Replace polymorphic Adjustment with TaxLine, Discount, Fee. **Shipped to 6-0-dev (Waves 3+6):** typed rows + winner-only promotion adjuster + `Spree.tax_provider` live; admin `/orders/:id/{tax_lines,discounts,fees}` API + dashboard panels + `OrderUpdater#resum_typed_totals!` post-placement edit path; Wave 7 adjustments→typed data migration remains- `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@@ -36,6 +35,7 @@ Active plans (6.0 target, work pending):- `6.0-store-scoped-custom-field-definitions.md` — Add `store_id` + persisted `filter_key` to `Spree::MetafieldDefinition` (today global and computed), making uniqueness `(store_id, resource_type, filter_key)` with a DB index. Deferred from the 5.6 custom-field search/sort/filter work (schema change, not patch-safe). **Until then:** `filter_key` is a computed method — no Ransack predicates or `where`/`order` against it; definitions are global; uniqueness rests on a `CONCAT` validation with no index behind it.Multi-version plans (some phases shipped, some pending):+- `6.0-6.1-split-adjustments.md` — Replace polymorphic Adjustment with TaxLine, Discount, Fee. **6.0 implementation fully shipped to main** (typed tables + models, `Spree::Adjusters::*` winner-only promotion adjuster, `Spree.tax_provider` seam, admin `/orders/:id/{tax_lines,discounts,fees}` API + SDK + dashboard cards, `spree:migrate_adjustments_to_typed_rows` in the upgrade manifest; legacy `Adjustment`/`AdjustmentSource` deleted). v6 developer docs shipped (`docs/v6/developer/` taxes-discounts-fees + promotions + custom-promotion). Remaining: 6.1 drops `spree_adjustments` + deprecated shells and adds `Promotion#combines_with` stacking.- `5.4-store-api-naming-standardization.md` — Standardize API naming against industry (address fields, discounts, customer_note, label, brand/last4, etc.). 5.4 model/API aliases shipped; 6.0 column/table renames pending.- `5.4-6.0-eu-legal-compliance.md` — GDPR (data export/anonymization, consent timestamps), Omnibus (PriceHistory, lowest-in-30-days), Consumer Rights (withdrawal period). 5.4 PriceHistory + `prior_price` shipped; GDPR endpoints + withdrawal period still pending.- `5.4-6.0-custom-fields-rename.md` — Rename Metafields → Custom Fields. 5.4 API bridge + 5.5 `Spree::CustomField`/`CustomFieldDefinition` constant aliases shipped; 6.0 model/table rename pending.diff --git a/docs/docs.json b/docs/docs.jsonindex ef8f77bf10..5bc74418fa 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -990,7 +990,7 @@"developer/core-concepts/payments","developer/core-concepts/taxes","v6/developer/core-concepts/taxes-discounts-fees",- "developer/core-concepts/promotions",+ "v6/developer/core-concepts/promotions","developer/core-concepts/store-credits-gift-cards"]},@@ -1132,7 +1132,7 @@"group": "Promotions","icon": "tag","pages": [- "developer/how-to/custom-promotion"+ "v6/developer/how-to/custom-promotion"]},{diff --git a/docs/plans/5.4-store-api-bridges.md b/docs/plans/5.4-store-api-bridges.mdindex f0e0bdcdd5..88ef122d85 100644--- a/docs/plans/5.4-store-api-bridges.md+++ b/docs/plans/5.4-store-api-bridges.md@@ -136,7 +136,7 @@ end### 4. Adjustment totals naming-**Plan:** `6.0-split-adjustments.md`+**Plan:** `6.0-6.1-split-adjustments.md`The model split (Adjustment → TaxLine, Discount, Fee) happens in 6.0. But the serialized totals can be renamed now for clarity:diff --git a/docs/plans/6.0-split-adjustments.md b/docs/plans/6.0-6.1-split-adjustments.mdsimilarity index 93%rename from docs/plans/6.0-split-adjustments.mdrename to docs/plans/6.0-6.1-split-adjustments.mdindex a285c9f7b7..dd4916f3bf 100644--- a/docs/plans/6.0-split-adjustments.md+++ b/docs/plans/6.0-6.1-split-adjustments.md@@ -1,10 +1,26 @@# Split Adjustments into Typed Tables-**Status:** Draft-**Target:** Spree 6.0+**Status:** 6.0 complete (Phases 0–4 + data migration + v6 developer docs, verified 2026-08-05); remaining: Phase 5 cleanup + stacking in 6.1+**Target:** Spree 6.0 (typed model) + Spree 6.1 (legacy-table drop, promotion stacking)**Depends on:** `6.0-cart-order-split.md` (owner semantics — typed lines are written during the cart phase and copied on completion), `6.0-fulfillment-and-delivery.md` Phase 1 (tables are born with `fulfillment_id`, never migrated from `shipment_id`). Consumed by: `6.0-tax-provider.md` (providers write TaxLine), `6.0-multi-vendor-marketplace.md` (typed lines re-home at order split), `6.0-returns-exchanges-claims.md`, `6.0-normalize-state-to-status.md`.**Author:** Damian + Claude-**Last updated:** 2026-07-28+**Last updated:** 2026-08-05++## Implementation status (verified against main, 2026-08-05)++Shipped:++- **Schema** — `20260729000001_create_typed_adjustment_tables.rb`: `spree_tax_lines`, `spree_discounts`, `spree_fees`, `spree_orders.fee_total`.+- **Models** — `TaxLine`, `Discount`, `Fee` (+ shared `Spree::TypedAdjustmentLine` concern), `Spree::Adjusters::{Base, Promotion, LargestRemainder}`. Legacy `Adjustment`, `AdjustmentSource`, `Adjustable::*` deleted. Permission sets grant on the typed models.+- **Recalculation** — totals live in the `RecalculateTotals` workflows (cart + order twins); `OrderUpdater` is a deprecated shell (6.1-removed). `Carts::Complete#copy_typed_lines!` re-points rows at completion; `Carts::Empty` destroys the cart's typed rows; `Spree.tax_provider` seam defaults to `TaxProvider::Internal`.+- **Data migration** — `spree:migrate_adjustments_to_typed_rows` (idempotent, reconciles per-order totals, freezes non-reconciling orders), registered in the 5.6→6.0 upgrade manifest ahead of the carts migration.+- **API / SDK / Dashboard** — `/admin/orders/:id/tax_lines` (read-only) + `discounts`/`fees` (CRUD via order-locked services — the sanctioned post-placement edit path), typed serializers, admin-sdk `orders.{taxLines,discounts,fees}`, dashboard order-page tax/discount/fee cards with add-discount and add-fee forms; emails iterate typed associations.+- **Developer docs** — typed-model coverage under `docs/v6/developer/`: `core-concepts/taxes-discounts-fees.mdx`, `core-concepts/promotions.mdx`, `how-to/custom-promotion.mdx`. The v5 docs under `docs/developer/` stay untouched until release — they document the stable 5.x behavior (decision 2026-08-05).++Remaining:++- **Phase 5 (6.1)** — drop `spree_adjustments`, remove the migration rake task and the deprecated `OrderUpdater` shells.+- **Promotion stacking (6.1)** — `Promotion#combines_with`; the winner-only selection seam shipped isolated for it (Resolved Question 6).## Summary@@ -322,12 +338,12 @@ Conventions per `6.0-admin-api.md`: flat params, prefixed IDs, secret-key scopes4. `6.0-tax-provider.md` — providers become the sole TaxLine writers (never implement a "TaxRate.adjust writes TaxLines" step; at most a short-lived shim inside the Internal provider)5. `6.0-returns-exchanges-claims.md`, then `6.0-multi-vendor-marketplace.md` order splitting (consumes typed lines)-### Phase 0: Preconditions+### Phase 0: Preconditions — shipped- Order-level recalculation freeze in `OrderUpdater` (refuse adjustment recalculation on completed orders), with explicit admin edit paths (manual Fee/Discount CRUD) as the sanctioned post-placement mutation route. Built and tested **before** any state-machine removal.- Cart/order owner semantics finalized (see Depends on).-### Phase 1: Create new tables+### Phase 1: Create new tables — shippedKey schema points (full migration authored at implementation time):@@ -336,7 +352,7 @@ Key schema points (full migration authored at implementation time):- `spree_fees`: owner XOR FKs, `line_item_id`/`fulfillment_id` (both nullable — both nil = order-level), `amount null: false` + `CHECK (amount >= 0)`, `label null: false`, `kind null: false`, `metadata` JSON. Index on `[order_id, kind]`.- `spree_orders.fee_total` column.-### Phase 2: Data migration (rake task, never in-migration)+### Phase 2: Data migration (rake task, never in-migration) — shippedFor each `spree_adjustments` row:@@ -361,7 +377,7 @@ Order-level rows (`adjustable_type == 'Spree::Order'`): promotion and manual dis- **In-flight carts/incomplete orders** don't need faithful conversion — the new engine recalculates them from scratch on first touch.- **Rollback window:** `spree_adjustments` stays intact and read-only through all of 6.0 as the audit + rollback reference (typed tables can be dropped and re-derived by re-running the task). The 6.1 table drop is the point of no return.-### Phase 3: Model migration+### Phase 3: Model migration — shipped- New models + `Spree::Adjusters::Base`; remove `Adjustment`, `AdjustmentSource`, `Adjustable::AdjustmentsUpdater`, `Adjustable::Adjuster::*`, `PromotionAccumulator` (dead), `CalculatedAdjustments` usage for adjustments- `OrderUpdater` typed recalculation with freeze guard + two-pass ordering; cart counterpart@@ -369,9 +385,9 @@ Order-level rows (`adjustable_type == 'Spree::Order'`): promotion and manual dis- Tax side: Internal provider writes TaxLines (replace-all); `TaxRate` keeps no write path- Order/LineItem/Fulfillment readers rewritten (`order_level_promo_total`, `shipping_discount`, `valid_promotion_ids`, `cart_promo_total`, `has_free_shipping?`, `fully_discounted?`, `taxable_amount`, …); `OrderMerger`, `Cart::Empty`, refund calculators- CanCanCan permission sets: grants on `TaxLine`/`Discount`/`Fee` replace `Spree::Adjustment`-- Factories + specs (~65 files), `docs/developer/core-concepts/adjustments.mdx`, `custom-promotion.mdx`+- Factories + specs (~65 files). Docs: typed-model coverage lives in `docs/v6/developer/` (`core-concepts/taxes-discounts-fees.mdx`, `core-concepts/promotions.mdx`, `how-to/custom-promotion.mdx`); the v5 `docs/developer/` pages stay untouched until the 6.0 release-### Phase 4: API + serializer + SDK + admin surfaces+### Phase 4: API + serializer + SDK + admin surfaces — shipped- Admin API v3: `/admin/orders/:id/{tax_lines,discounts,fees}` endpoints replace `/adjustments` — tax_lines read-only, discounts/fees full CRUD for manual rows (see "Admin management surface"); typed serializers; `?expand=` updates on order/line_item/fulfillment serializers. Store API is already insulated (never exposed Adjustment rows)- Full type pipeline: typelizer → Zod → integration specs → OpenAPI; admin-sdk `orders.adjustments` → `orders.{taxLines,discounts,fees}` resources; dashboard order page typed panels + add-fee/add-discount forms. Admin SDK is unreleased — break cleanly, no bridgediff --git a/docs/plans/6.0-admin-api.md b/docs/plans/6.0-admin-api.mdindex 833ac9f1d0..7137f6555e 100644--- a/docs/plans/6.0-admin-api.md+++ b/docs/plans/6.0-admin-api.md@@ -195,7 +195,7 @@ This plan reflects the 6.0 model/naming landscape. Endpoints removed from 5.x or| `/api/v3/admin/reimbursement_types/*` | **removed** | Concept dropped || `/api/v3/admin/prototypes/*` | `/api/v3/admin/product_types/*` | `Prototype` → `ProductType` rename. See `6.0-product-types.md` || `/api/v3/admin/metafield_definitions/*` | `/api/v3/admin/custom_field_definitions/*` | `Metafield` → `CustomField` rename. See `5.4-6.0-custom-fields-rename.md` |-| `/api/v3/admin/orders/:id/adjustments/*` | `/api/v3/admin/orders/:id/tax_lines`, `discounts`, `fees` (read-only) | Polymorphic `Adjustment` → typed `TaxLine`, `Discount`, `Fee`. See `6.0-split-adjustments.md` |+| `/api/v3/admin/orders/:id/adjustments/*` | `/api/v3/admin/orders/:id/tax_lines`, `discounts`, `fees` (read-only) | Polymorphic `Adjustment` → typed `TaxLine`, `Discount`, `Fee`. See `6.0-6.1-split-adjustments.md` || `?expand=master_variant` | `?expand=default_variant` | `is_master` dropped, `default_variant_id` FK. See `6.0-remove-master-variant.md` || `?expand=images` | `?expand=media` | `Image` / `Asset` → `Media`. See `5.4-6.0-product-media-system.md` |@@ -480,7 +480,7 @@ Managed via nested payload on the Option Type (`option_values: [{ id, name, labe### Fees (nested under Orders, read-only; replaces Adjustments in 6.0)- [ ] `GET /api/v3/admin/orders/:order_id/fees`-> **6.0:** Polymorphic `Spree::Adjustment` is dropped. Tax, discount, and fee data is returned via typed, read-only endpoints. See `6.0-split-adjustments.md`.+> **6.0:** Polymorphic `Spree::Adjustment` is dropped. Tax, discount, and fee data is returned via typed, read-only endpoints. See `6.0-6.1-split-adjustments.md`.### Order Customer Assignmentdiff --git a/docs/plans/6.0-cart-order-split.md b/docs/plans/6.0-cart-order-split.mdindex 0385d85390..919f4aff6b 100644--- a/docs/plans/6.0-cart-order-split.md+++ b/docs/plans/6.0-cart-order-split.md@@ -2,7 +2,7 @@**Status:** Design finalized (expanded 2026-07-27 from the original stub), implementation not started**Target:** Spree 6.0-**Depends on:** API v3 conventions. **Gates (they depend on this plan):** `6.0-split-adjustments.md` (typed-line owner), `6.0-fulfillment-and-delivery.md` (fulfillment/rate owner), `6.0-multi-vendor-marketplace.md` Phase 3 (split fires inside `Carts::Complete`), `6.0-normalize-state-to-status.md` (Order.state removed here). This is the most upstream unstarted 6.0 refactor.+**Depends on:** API v3 conventions. **Gates (they depend on this plan):** `6.0-6.1-split-adjustments.md` (typed-line owner), `6.0-fulfillment-and-delivery.md` (fulfillment/rate owner), `6.0-multi-vendor-marketplace.md` Phase 3 (split fires inside `Carts::Complete`), `6.0-normalize-state-to-status.md` (Order.state removed here). This is the most upstream unstarted 6.0 refactor.**Author:** Damian + Claude**Last updated:** 2026-08-01@@ -281,4 +281,4 @@ None at this time.- Codebase inventory + competitor research (2026-07-27): checkout-flow anatomy (`order/checkout.rb:42-133` — 14 cart-phase / 8 completion / 11 post-completion callbacks), state-consumer census (public contract is step-shaped; scopes already on `completed_at`), OSS platform A `completeCartWorkflow`, OSS platform B `checkout_complete.py` (idempotency, `is_voucher_usage_increased`, expiry tiers), the hosted market leader Checkout-API shutdown, OSS platform C `default-order-process.ts`- Cautionary bugs: OSS platform A's repo#14095 (unfilterable derived status), #13882 (status stuck after return), the hosted market leader `financial_status:expired` filter divergence- Existing seams: `spree/core/app/services/spree/carts/*.rb`, `spree/core/app/models/spree/checkout/{requirements,registry,default_requirements}.rb`, `api/app/serializers/spree/api/v3/cart_serializer.rb`-- Related plans: `6.0-split-adjustments.md`, `6.0-fulfillment-and-delivery.md`, `6.0-multi-vendor-marketplace.md`, `6.0-returns-exchanges-claims.md`, `6.0-normalize-state-to-status.md`, `6.0-stock-reservations.md`+- Related plans: `6.0-6.1-split-adjustments.md`, `6.0-fulfillment-and-delivery.md`, `6.0-multi-vendor-marketplace.md`, `6.0-returns-exchanges-claims.md`, `6.0-normalize-state-to-status.md`, `6.0-stock-reservations.md`diff --git a/docs/plans/6.0-core-rewrite-tasks.md b/docs/plans/6.0-core-rewrite-tasks.mdindex aa98edee4f..8dee69bf8d 100644--- a/docs/plans/6.0-core-rewrite-tasks.md+++ b/docs/plans/6.0-core-rewrite-tasks.md@@ -1,6 +1,6 @@# 6.0 Core Rewrite — Implementation Task List-**This is a working task tracker, not a plan.** Plans of record: `6.0-cart-order-split.md`, `6.0-fulfillment-and-delivery.md`, `6.0-split-adjustments.md`. Where this file and a plan disagree, the plan wins.+**This is a working task tracker, not a plan.** Plans of record: `6.0-cart-order-split.md`, `6.0-fulfillment-and-delivery.md`, `6.0-6.1-split-adjustments.md`. Where this file and a plan disagree, the plan wins.**Branch:** `6-0-dev` (verified against HEAD `ee39a89`, 2026-07-28)**UI rule:** all admin UI work targets `packages/dashboard` via Admin API v3 + `@spree/admin-sdk`. `spree/admin` is legacy and is not touched — and per Decision 2 it stops loading in the dev server (T0.3).@@ -139,7 +139,7 @@ The big mechanical wave. Whole-suite blast radius via factories; one-release con----## Wave 3 — Split Adjustments (`6.0-split-adjustments.md` P0/P1/P3 + minimal TaxProvider) — still on the Order-based checkout+## Wave 3 — Split Adjustments (`6.0-6.1-split-adjustments.md` P0/P1/P3 + minimal TaxProvider) — still on the Order-based checkoutRuns after Wave 2 (tables born with `fulfillment_id`). Can proceed in parallel with Wave 4.diff --git a/docs/plans/6.0-delivery-rate-provider.md b/docs/plans/6.0-delivery-rate-provider.mdindex fdb23f3381..b0b956e6b5 100644--- a/docs/plans/6.0-delivery-rate-provider.md+++ b/docs/plans/6.0-delivery-rate-provider.md@@ -468,7 +468,7 @@ The Store API already speaks this vocabulary: `Spree::Api::V3::DeliveryRateSeria- **Don't add new shipping calculators for external carrier APIs.** Calculators are for internal arithmetic. Use the provider interface.- **Don't monkey-patch `Stock::Estimator`.** The provider dispatch is the intended seam.-- **Don't delete or deprecate `ShippingCalculator` or `Calculator::Shipping::*`.** They are load-bearing and staying. `CalculatedAdjustments` is shared with TaxRate and promotion actions; its fate belongs to `6.0-tax-provider.md` and `6.0-split-adjustments.md`, not here.+- **Don't delete or deprecate `ShippingCalculator` or `Calculator::Shipping::*`.** They are load-bearing and staying. `CalculatedAdjustments` is shared with TaxRate and promotion actions; its fate belongs to `6.0-tax-provider.md` and `6.0-6.1-split-adjustments.md`, not here.- **Don't add `pricing_type` / `preferred_amount` columns to ShippingMethod.** Superseded; see "Why calculators stay."- **New ShippingRate fields should fit the enriched model** (carrier, service_level, estimated_delivery_date, metadata).- **Never unconditionally set `selected` on refresh.** Preserve the existing behavior at `shipment.rb:355-361`.diff --git a/docs/plans/6.0-fulfillment-and-delivery.md b/docs/plans/6.0-fulfillment-and-delivery.mdindex 3e776c5222..454887385e 100644--- a/docs/plans/6.0-fulfillment-and-delivery.md+++ b/docs/plans/6.0-fulfillment-and-delivery.md@@ -2,7 +2,7 @@**Status:** Draft**Target:** Spree 6.0-**Depends on:** `6.0-product-types.md` (`fulfillment_types` addendum 2026-07-27 — ProductType replaces ShippingCategory; **hard blocker**, `Spree::ProductType` does not exist yet), `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` lands in the same migration wave), `6.0-multi-vendor-marketplace.md` (`vendor_id`, lifecycle events, `delivery_amount`). Gates: `6.0-split-adjustments.md` and `6.0-typed-stock-movements.md` are born with `fulfillment_id` — **this plan's Phase 1 must land before both**.+**Depends on:** `6.0-product-types.md` (`fulfillment_types` addendum 2026-07-27 — ProductType replaces ShippingCategory; **hard blocker**, `Spree::ProductType` does not exist yet), `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` lands in the same migration wave), `6.0-multi-vendor-marketplace.md` (`vendor_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-02@@ -113,7 +113,7 @@ Checkout — where fulfillments and delivery rates are created and selected —### `Fulfillment#delivery_amount` (commission base)-`delivery_amount = cost + discounts.sum(:amount)` — the selected rate's cost net of fulfillment-attached `Discount` rows (negative, from `6.0-split-adjustments.md`). This is the base `6.0-multi-vendor-marketplace.md` uses for `include_shipping` commission (`CommissionLine` fulfillment-scoped). `cost` remains the denormalized column it is today.+`delivery_amount = cost + discounts.sum(:amount)` — the selected rate's cost net of fulfillment-attached `Discount` rows (negative, from `6.0-6.1-split-adjustments.md`). This is the base `6.0-multi-vendor-marketplace.md` uses for `include_shipping` commission (`CommissionLine` fulfillment-scoped). `cost` remains the denormalized column it is today.### Status semantics — corrected against the real machine@@ -335,4 +335,4 @@ None at this time.- Real state machine + hooks: `shipment.rb:73-110`; rollup: `order_updater.rb:140-178`; number generator: `shipment.rb:7`- Eligibility gate being replaced: `stock/package.rb:73-80` + `stock/estimator.rb:61-71`; parity spec: `spec/models/spree/order_routing/strategy/parity_spec.rb:426-452`- Shipped API surface: `api/app/serializers/spree/api/v3/fulfillment_serializer.rb`, `api/lib/spree/api/dependencies.rb:111-128`-- Related plans: `6.0-product-types.md` (fulfillment_types addendum), `6.0-delivery-rate-provider.md`, `6.0-cart-order-split.md`, `6.0-order-routing.md`, `6.0-split-adjustments.md`, `6.0-typed-stock-movements.md`, `6.0-returns-exchanges-claims.md`, `6.0-multi-vendor-marketplace.md`, `5.5-6.0-display-on-to-boolean.md`, `decisions.md` (2026-07-27 calculators/Zone; 2026-03-16 corrected store-scoping)+- Related plans: `6.0-product-types.md` (fulfillment_types addendum), `6.0-delivery-rate-provider.md`, `6.0-cart-order-split.md`, `6.0-order-routing.md`, `6.0-6.1-split-adjustments.md`, `6.0-typed-stock-movements.md`, `6.0-returns-exchanges-claims.md`, `6.0-multi-vendor-marketplace.md`, `5.5-6.0-display-on-to-boolean.md`, `decisions.md` (2026-07-27 calculators/Zone; 2026-03-16 corrected store-scoping)diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.mdindex 41e3b654ac..128ec23665 100644--- a/docs/plans/6.0-multi-vendor-marketplace.md+++ b/docs/plans/6.0-multi-vendor-marketplace.md@@ -2,7 +2,7 @@**Status:** Draft — design in progress, implementation not started**Target:** Spree 6.0 (the "Marketplace" release)-**Depends on:** `6.0-cart-order-split.md` (Cart/Order split + dual-FK `LineItem` owner (`cart_id`/`order_id`, `#owner` method) — **expanded 2026-07-27; Phase 3 design can now freeze against it**), `6.0-split-adjustments.md` (TaxLine/Discount/Fee replace polymorphic Adjustment), `6.0-order-routing.md` (per-seller stock location), `6.0-fulfillment-and-delivery.md` (Fulfillment/DeliveryMethod vocabulary, per-vendor delivery selection), `6.0-admin-spa.md` (vendor panel composition), `6.0-admin-api.md` (Marketplace endpoints)+**Depends on:** `6.0-cart-order-split.md` (Cart/Order split + dual-FK `LineItem` owner (`cart_id`/`order_id`, `#owner` method) — **expanded 2026-07-27; Phase 3 design can now freeze against it**), `6.0-6.1-split-adjustments.md` (TaxLine/Discount/Fee replace polymorphic Adjustment), `6.0-order-routing.md` (per-seller stock location), `6.0-fulfillment-and-delivery.md` (Fulfillment/DeliveryMethod vocabulary, per-vendor delivery selection), `6.0-admin-spa.md` (vendor panel composition), `6.0-admin-api.md` (Marketplace endpoints)**Author:** Damian + Claude**Last updated:** 2026-07-27@@ -54,7 +54,7 @@ Mirror the core insight from both the legacy module and the industry references:- New model **`Spree::CommissionLine`** (NOT a revival of the legacy commission table, NOT a polymorphic `Adjustment`). One row per commissioned line item — plus one per fulfillment when the rate commissions delivery revenue (`include_shipping`, Decision 4) — storing a **snapshot** of `rate`, `amount`, and the resolved rule's identity.- Written by a service during/after `cart.complete!`, once. A later rate change does not touch existing lines.-- **Commission is NOT a `Spree::Fee`.** `6.0-split-adjustments.md`'s `Fee` is a *buyer-facing* charge — it rolls into `order.fee_total` and the order total the customer pays. Commission is a *platform ↔ vendor* settlement line the customer never sees; it must never touch order totals. `CommissionLine` is therefore its own off-order ledger table that merely follows the same typed-line design (concrete FKs, no polymorphic source, no state machine) as the split-adjustments family. The only real split-adjustments dependency is that tax lines / discounts / fees are line-item-attached, so they re-home cleanly to the child order during the split. (A *buyer-facing* marketplace service fee — StockX-style — would be a `Spree::Fee` with a `kind`; possible later, out of scope here.)+- **Commission is NOT a `Spree::Fee`.** `6.0-6.1-split-adjustments.md`'s `Fee` is a *buyer-facing* charge — it rolls into `order.fee_total` and the order total the customer pays. Commission is a *platform ↔ vendor* settlement line the customer never sees; it must never touch order totals. `CommissionLine` is therefore its own off-order ledger table that merely follows the same typed-line design (concrete FKs, no polymorphic source, no state machine) as the split-adjustments family. The only real split-adjustments dependency is that tax lines / discounts / fees are line-item-attached, so they re-home cleanly to the child order during the split. (A *buyer-facing* marketplace service fee — StockX-style — would be a `Spree::Fee` with a `kind`; possible later, out of scope here.)### 3. Commission taxation is a first-class field — this is the OSS differentiator@@ -255,7 +255,7 @@ The `OrderGroup` owns the customer + single payment + shared addresses; each chi- **Trigger & gate:** explicit call inside `Spree::Carts::Complete`, after payment authorization. The gate is **more than one fulfillment partition** — line items partition by the `vendor_id` snapshot, with `nil` (the operator's own first-party items) forming its own partition, and the split + `OrderGroup` happen **only when ≥ 2 partitions exist**. A mixed cart of vendor A + first-party items splits into two child orders (one with `vendor_id: nil`). A single-partition cart — all first-party, or all one vendor — completes as a **bare order exactly as today**: no group, no `PaymentSplit`; when that partition is a vendor's, the order still carries `vendor_id` and commission + ledger apply unchanged (Phase 2's compute-only mode is exactly this). Not a state-machine callback — and not the legacy shape either: the legacy module splits **~30 seconds after checkout** in a background job, leaving a window where the parent order exists un-split. 6.0 splits synchronously inside completion, so the checkout response already returns the finished `OrderGroup` and no `splitted`-pending state ever exists.- **Partition key:** `line_item.vendor_id`, denormalized from `variant.product.vendor` when the item is added (matching legacy behavior). Denormalization is load-bearing, not an optimization: the split, vendor ability scoping, and vendor order lists all key on it. Because product ownership *can* change while an item sits in a cart, `Carts::Complete` revalidates each line's `vendor_id` against the product's current vendor before partitioning and refreshes stale lines (re-running package/delivery validation) — the same cart-revalidation class as price or availability drift.- **Per-vendor delivery selection happens at checkout, before the split.** Today's Enterprise checkout already groups packages by vendor and lets the customer pick a delivery method per vendor package (user docs: multi-vendor-checkout); 6.0 keeps that UX. The cart's packages come from `6.0-order-routing.md` (`for_allocation` — vendor items allocate from that vendor's stock location), delivery options per package come from `6.0-delivery-rate-provider.md` filtered to the package's vendor: a `DeliveryMethod` with `vendor_id` is offered only on that vendor's packages; `vendor_id: nil` methods are marketplace-wide. The chosen method + rate travel with the package into that vendor's child order at split. **This is a hard requirement on the cart/order-split checkout design** (see Constraints).-- **Move semantics:** line items, their tax lines / discounts / fees (`6.0-split-adjustments.md`), fulfillment items, and fulfillments are assigned to the correct child `Order` (created from the cart partition); the owner FK on every typed line is rewritten to the child order. **Order-level `Fee` rows** (both adjustable FKs nil — e.g. a payment surcharge; allowed per split-adjustments 2026-07-27) prorate across child orders by item totals using the same largest-remainder rule as order-level discount distribution, their tax lines following the fee. Stock location per child comes from the routing strategy, not a bare `detect`.+- **Move semantics:** line items, their tax lines / discounts / fees (`6.0-6.1-split-adjustments.md`), fulfillment items, and fulfillments are assigned to the correct child `Order` (created from the cart partition); the owner FK on every typed line is rewritten to the child order. **Order-level `Fee` rows** (both adjustable FKs nil — e.g. a payment surcharge; allowed per split-adjustments 2026-07-27) prorate across child orders by item totals using the same largest-remainder rule as order-level discount distribution, their tax lines following the fee. Stock location per child comes from the routing strategy, not a bare `detect`.- **Group status:** derived, not a column. The `OrderGroup` is "fully fulfilled" when all its orders are, "partially canceled" when some are, etc. — computed across `order_group.orders`, replacing the legacy `all_shipments`/`splitted?`/`cancel_parent_order` workarounds (which existed only because the legacy parent was itself an `Order`).### OrderGroup model@@ -565,7 +565,7 @@ This is **new OSS code**, not a rename of existing core — there is no in-place2. **Build order** (each phase shippable):- **Phase 1 — Vendor identity.** `Spree::Vendor` model (see Vendor identity & teams: lifecycle, branding, ToS acceptance, holiday mode), onboarding task registry + core tasks, vendor teams via `RoleUser`/`Invitation` (`resource: vendor`), self-serve application endpoint, core `Spree::VendorMailer` lifecycle emails (see Vendor notifications), product ownership (`products.vendor_id` + approval preference), Admin API Marketplace/vendors endpoints + Store API vendor profiles, vendor CSV import/export on the `Spree::Import` pipeline. No splitting yet.- **Phase 2 — Commission engine.** `CommissionRate` + `CommissionRule` + `CommissionLine`, resolution + calculation services (dimension-grouped matching, min/max clamps, `include_shipping`), commission-tax field, admin UI for rates. Compute-only (attach to single-vendor orders, no split).- - **Phase 3 — Order splitting + fund ledger.** `OrderGroup`, `Carts::SplitByVendor` inside `Carts::Complete`, per-vendor delivery selection at checkout, `PaymentSplit`, derived group status, reversals, the two-level `VendorTransfer` (on-fulfillment) + `VendorPayout` (scheduled sweep) + `PayoutProvider::System` + `vendor.balance(currency)`. **Gated on `6.0-cart-order-split.md` and `6.0-split-adjustments.md` landing first** — and cart-order-split is today a one-page stub: it must be expanded (checkout/delivery-selection/payment flow on Cart) before this phase's design can freeze. Flagging early: the 6.0 headline feature sits downstream of the two biggest unstarted refactors.+ - **Phase 3 — Order splitting + fund ledger.** `OrderGroup`, `Carts::SplitByVendor` inside `Carts::Complete`, per-vendor delivery selection at checkout, `PaymentSplit`, derived group status, reversals, the two-level `VendorTransfer` (on-fulfillment) + `VendorPayout` (scheduled sweep) + `PayoutProvider::System` + `vendor.balance(currency)`. **Gated on `6.0-cart-order-split.md` and `6.0-6.1-split-adjustments.md` landing first** — and cart-order-split is today a one-page stub: it must be expanded (checkout/delivery-selection/payment flow on Cart) before this phase's design can freeze. Flagging early: the 6.0 headline feature sits downstream of the two biggest unstarted refactors.- **Phase 3b — OSS Stripe provider** (after Phase 3, alongside the Stripe gateway pull-in: the payment-sessions-API gateway classes come into the monorepo from the standalone `spree_stripe` repo, likely into `spree/core`, leaving the legacy v2-API/storefront code behind): Express onboarding link in the vendor dashboard, `account.updated` status webhook, `transfer!` on fulfillment with `source_transaction`, payout-schedule mapping + payout webhooks. Ledger-only `reverse!`.- **Phase 4 — Dashboards.** (a) Operator marketplace screens in `@spree/dashboard`: Vendors list/detail (lifecycle actions, branding, commission + payout settings, ledger-derived lifetime revenue/commission), Commission Rates settings page, Payouts review queue (owed balances, itemized payouts, mark-paid), OrderGroup rendering on order screens, and a "needs attention" queue on the dashboard home (vendors `ready_for_review` + pending vendor products — a lightweight unified review inbox). (b) Vendor panel: compose `@spree/dashboard-ui` + `@spree/dashboard-core` into a vendor-scoped panel (per `6.0-admin-spa.md` — the package split exists precisely for this). Permissions via code. Surfaces the vendor's products, orders + fulfillment actions, and the balance + transfer/payout ledger (earned/settled) read-only for OSS.@@ -577,7 +577,7 @@ Even before this lands, work touching adjacent areas should:- **Cart/Order split (`6.0-cart-order-split.md`)**: keep `cart.complete!`/`Spree::Carts::Complete` as the single completion entry point — the vendor split hooks in there. Do not reintroduce an order-level `after_transition` extension surface; multi-vendor must not depend on one. When fleshing out the checkout flow on Cart, design delivery selection **per package** (packages come from order routing) — the multi-vendor checkout needs one delivery choice per vendor package before completion, and payments must be attachable to an `OrderGroup`, not only to an `Order`.- **Rich text sanitization (`6.0-rich-text-descriptions.md`)**: vendors are the marketplace's lower-trust writers, and today they are protected by the 5.x-only Enterprise gem's `Spree::SanitizeConcern` (`sanitize :description, :meta_description, if: -> { vendor_id.present? }`). That gem does not carry into 6.0 — this plan rewrites its functionality as core models — so **core must own the sanitization before vendor-authored content lands here**. Core's `SanitizableRichText` (shipped 5.6.2) sanitizes on write rather than deriving `sanitized_*` on read, which is the stronger form. Three obligations for this plan: (1) apply it to every vendor-writable rich text field (`Vendor#about`, vendor-authored product descriptions); (2) keep vendor-facing write paths — the vendor dashboard, vendor CSV/feed imports, bulk maintenance jobs — on save-backed writers, since the concern is a `before_save` and does not cover `update_columns`/`update_all`/raw SQL (anything that must bypass callbacks calls `Spree::RichTextSanitizer.sanitize` explicitly); (3) do **not** ship a 6.0 allowlist weaker than the Enterprise scrubber vendors have on 5.x — that one prunes `script`/`style` element bodies entirely.-- **Split adjustments (`6.0-split-adjustments.md`)**: `TaxLine` and `Discount` stay strictly line-item- or fulfillment-attached (order-level discounts distribute to line items at application time), so they re-home unambiguously to one child order during the split. `Fee` may additionally be **order-level** (payment surcharge, COD — resolved 2026-07-27); at split, order-level fees prorate across child orders by item totals (largest-remainder), tax lines following the fee. Do **not** add a commission/marketplace `Fee` kind — commission is `Spree::CommissionLine`, off-order (Decision 2); `Fee` stays buyer-facing.+- **Split adjustments (`6.0-6.1-split-adjustments.md`)**: `TaxLine` and `Discount` stay strictly line-item- or fulfillment-attached (order-level discounts distribute to line items at application time), so they re-home unambiguously to one child order during the split. `Fee` may additionally be **order-level** (payment surcharge, COD — resolved 2026-07-27); at split, order-level fees prorate across child orders by item totals (largest-remainder), tax lines following the fee. Do **not** add a commission/marketplace `Fee` kind — commission is `Spree::CommissionLine`, off-order (Decision 2); `Fee` stays buyer-facing.- **Inventory operations (`6.0-inventory-operations.md`)**: the procurement model is `Spree::Supplier` — never reuse `Spree::Vendor` (reserved for marketplace sellers) for purchase-order sources. See `decisions.md` 2026-07-14.- **External-store sync stays Enterprise**: do **not** add external store/resource models, associations, or callbacks to core (no `external_store` on Vendor, no external product/order/category tables, no platform sync hooks). The Shopify/WooCommerce connection layer is an Enterprise concern that decorates core's Vendor from outside; core only needs to stay decorable (events + the onboarding task registry are the seams it plugs into).- **Fulfillment & delivery (`6.0-fulfillment-and-delivery.md`)**: the ledger trigger is defined against Fulfillment ("all fulfillments fulfilled"), and `DeliveryMethod` gets an optional `vendor_id` — keep the fulfillment-status surface queryable per order (child orders fulfill independently) and don't assume one order per checkout in fulfillment UIs.@@ -618,4 +618,4 @@ Even before this lands, work touching adjacent areas should:- Current Enterprise multi-vendor module (private source, actively maintained against Spree 5.4+): source-read for this port — the Vendor lifecycle, per-item commission + commission-VAT formula, parent/child split flow, Stripe transfer ledger + reversal chain, vendor-user permission baseline, and the settlement-statement report. **Internals (file paths, class/table names) are deliberately not cited in this public file** — the Enterprise repository holds the detailed port map. Public behavior cross-checked against the user docs (next bullet).- Surveyed modern open-source marketplace implementations (primary-source survey 2026-07-14; names and the detailed comparison deliberately kept out of this public file): source of the commission rule-engine shape (dimension-grouped matching, `percentage | fixed`, `include_tax`/`include_shipping`), the `OrderGroup` container pattern, and the payout-provider abstraction. **Framework-specific machinery NOT to copy:** big-number jsonb sidecar columns, remote-link join-table indirection (use Rails FKs + `has_many`), and external workflow/step engines (use Spree services + `publish_event`). The leading implementation's payout pipeline creates per-order payouts after capture and keeps no balance ledger and no reversal chain — Spree's two-level ledger is designed from scratch.- Current Enterprise behavior (user docs, spreecommerce.org/docs): `user/vendors/vendor-management` (lifecycle: Invited → Onboarding → Ready for Review → Approved/Rejected/Suspended; branding; onboarding checklist), `user/vendors/commission-rates` (product > vendor > marketplace-default ladder, category-vendor pairing), `user/vendors/vendor-payouts` (schedule intervals incl. bi-weekly + "use marketplace default"), `user/vendors/multi-vendor-checkout` (per-vendor delivery selection, suborder split, per-vendor tracking), `user/settings/marketplace` (default rate copied at invite, vendor ToS), `api-reference/storefront/vendors` (public vendor profile fields).-- Related plans: `6.0-cart-order-split.md`, `6.0-split-adjustments.md`, `6.0-order-routing.md`, `6.0-tax-provider.md`, `6.0-delivery-rate-provider.md`, `6.0-fulfillment-and-delivery.md`, `6.0-returns-exchanges-claims.md`, `6.0-inventory-operations.md` (Supplier disambiguation), `5.4-6.0-eu-legal-compliance.md`, `5.6-admin-spa-csv-import.md`, `6.0-admin-spa.md`, `6.0-admin-api.md`, `6.0-channels-catalogs-b2b.md` (B2B — deferred to 6.1, see `decisions.md`).+- Related plans: `6.0-cart-order-split.md`, `6.0-6.1-split-adjustments.md`, `6.0-order-routing.md`, `6.0-tax-provider.md`, `6.0-delivery-rate-provider.md`, `6.0-fulfillment-and-delivery.md`, `6.0-returns-exchanges-claims.md`, `6.0-inventory-operations.md` (Supplier disambiguation), `5.4-6.0-eu-legal-compliance.md`, `5.6-admin-spa-csv-import.md`, `6.0-admin-spa.md`, `6.0-admin-api.md`, `6.0-channels-catalogs-b2b.md` (B2B — deferred to 6.1, see `decisions.md`).diff --git a/docs/plans/6.0-normalize-state-to-status.md b/docs/plans/6.0-normalize-state-to-status.mdindex 57b36c46e5..2c7d046315 100644--- a/docs/plans/6.0-normalize-state-to-status.md+++ b/docs/plans/6.0-normalize-state-to-status.md@@ -2,7 +2,7 @@**Status:** Design finalized, implementation not started**Target:** Spree 6.0-**Depends on:** Cart/Order split (6.0-cart-order-split.md), Split Adjustments (6.0-split-adjustments.md)+**Depends on:** Cart/Order split (6.0-cart-order-split.md), Split Adjustments (6.0-6.1-split-adjustments.md)**Author:** Damian + Claude**Last updated:** 2026-03-16@@ -113,5 +113,5 @@ None.- CLAUDE.md rule: "State machines: default column `status` (legacy uses `state`)"- Related plan: `6.0-cart-order-split.md` (removes Order.state entirely)-- Related plan: `6.0-split-adjustments.md` (removes Adjustment.state entirely)+- Related plan: `6.0-6.1-split-adjustments.md` (removes Adjustment.state entirely)- Decision log: `docs/plans/decisions.md` (2026-03-16 entry)diff --git a/docs/plans/6.0-returns-exchanges-claims.md b/docs/plans/6.0-returns-exchanges-claims.mdindex a3334252b9..57712e906a 100644--- a/docs/plans/6.0-returns-exchanges-claims.md+++ b/docs/plans/6.0-returns-exchanges-claims.md@@ -2,7 +2,7 @@**Status:** Draft**Target:** Spree 6.0-**Depends on:** Fulfillment & Delivery rework (6.0-fulfillment-and-delivery.md), Split Adjustments (6.0-split-adjustments.md), Normalize state→status (6.0-normalize-state-to-status.md), Service Workflows (6.0-service-workflows.md)+**Depends on:** Fulfillment & Delivery rework (6.0-fulfillment-and-delivery.md), Split Adjustments (6.0-6.1-split-adjustments.md), Normalize state→status (6.0-normalize-state-to-status.md), Service Workflows (6.0-service-workflows.md)**Successor:** 6.1-order-change-substrate.md — the mutation half of these flows moves onto the shared OrderChange substrate in 6.1 (additive; the models and statuses below do not change)**Author:** Damian + Claude**Last updated:** 2026-08-02@@ -897,7 +897,7 @@ None at this time.- Current ReimbursementType hierarchy: `spree/core/app/models/spree/reimbursement_type/`- Related plan: `6.0-service-workflows.md` (the workflow tier; no-state-machines rule)- Related plan: `6.0-fulfillment-and-delivery.md` (FulfillmentItem replaces InventoryUnit, Fulfillment replaces Shipment)-- Related plan: `6.0-split-adjustments.md` (return credits removed from adjustment system)+- Related plan: `6.0-6.1-split-adjustments.md` (return credits removed from adjustment system)- Related plan: `6.0-typed-stock-movements.md` (restock on return creates `received` movement)- Successor plan: `6.1-order-change-substrate.md` (the mutation half moves ontothe shared preview-then-apply substrate; additive)diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.mdindex 34226c52b5..ae9b13da9e 100644--- a/docs/plans/6.0-tax-provider.md+++ b/docs/plans/6.0-tax-provider.md@@ -8,7 +8,7 @@> **Provider registry option (2026-07-30):** `TaxLine.provider_id` stays a plain string registry key (`'internal'`, `'avalara'`) — Medusa's tax lines use the identical field name and semantics (`tp_system` for their built-in engine), so the name is the term of art for the audience 6.0 targets; it is deliberately NOT a table reference, preserving the snapshot property after config changes. When this plan is implemented, consider Medusa's shape for the config side: a minimal registry model per engine (identifier + enabled — no credentials) backing per-market provider selection in the admin, with credentialed connections staying `Spree::Integration`. Tax lines keep stamping the string key regardless.**Target:** Spree 6.0-**Depends on:** Split Adjustments (6.0-split-adjustments.md) for TaxLine model, Channels/Catalogs/B2B (6.0-channels-catalogs-b2b.md) for Company.tax_exempt+**Depends on:** Split Adjustments (6.0-6.1-split-adjustments.md) for TaxLine model, Channels/Catalogs/B2B (6.0-channels-catalogs-b2b.md) for Company.tax_exempt**Author:** Damian + Claude**Last updated:** 2026-07-27@@ -652,7 +652,7 @@ end### Phase 4: Adapt to Split Adjustments-When `6.0-split-adjustments.md` ships:+When `6.0-6.1-split-adjustments.md` ships:- Internal provider writes `TaxLine` records instead of `Adjustment` records (with `tax_rate_id` + `rate`/`label`/`provider_id` snapshots)- External providers also write `TaxLine` records — self-describing, `tax_rate_id` nil, never synthesizing local TaxRate rows- `OrderUpdater` reads totals from `tax_lines` instead of `adjustments.tax`@@ -710,6 +710,6 @@ Tax-side only — shipping keeps Zone untouched (see the Zones section of `6.0-d- Current order updater: `spree/core/app/models/spree/order_updater.rb`- Current zone matching: `spree/core/app/models/spree/zone.rb`- AdjustmentSource concern: `spree/core/app/models/concerns/spree/adjustment_source.rb`-- Related plan: `6.0-split-adjustments.md` (TaxLine model replaces polymorphic Adjustment for tax)+- Related plan: `6.0-6.1-split-adjustments.md` (TaxLine model replaces polymorphic Adjustment for tax)- Related plan: `6.0-channels-catalogs-b2b.md` (Company.tax_exempt, CompanyLocation.tax_exempt)- Related plan: `6.0-returns-exchanges-claims.md` (Return flow triggers provider.refund)diff --git a/docs/plans/6.0-typed-stock-movements.md b/docs/plans/6.0-typed-stock-movements.mdindex 8c399e7054..45ac83b539 100644--- a/docs/plans/6.0-typed-stock-movements.md+++ b/docs/plans/6.0-typed-stock-movements.md@@ -418,4 +418,4 @@ None at this time.- Current shipment unstock: `spree/core/app/models/spree/shipment.rb:491`- Current return restock: `spree/core/app/models/spree/return_item.rb:201`- Related plan: `6.0-stock-reservations.md` (reservations layer on top of availability)-- Related plan: `6.0-split-adjustments.md` (same pattern: replace polymorphic with concrete FKs)+- Related plan: `6.0-6.1-split-adjustments.md` (same pattern: replace polymorphic with concrete FKs)diff --git a/docs/plans/6.1-order-change-substrate.md b/docs/plans/6.1-order-change-substrate.mdindex 16b5cd1c2c..f55867ea31 100644--- a/docs/plans/6.1-order-change-substrate.md+++ b/docs/plans/6.1-order-change-substrate.md@@ -308,5 +308,5 @@ These apply during 6.0, before any of this is implemented:- `docs/plans/6.0-returns-exchanges-claims.md` — first business consumer- `docs/plans/6.0-cart-order-split.md` — post-placement edit path and the`resum_typed_totals!` semantics Confirm reuses-- `docs/plans/6.0-split-adjustments.md` — typed money rows the preview projects+- `docs/plans/6.0-6.1-split-adjustments.md` — typed money rows the preview projects- `decisions.md` 2026-07-27 — typed `kind` + concrete FKs over polymorphismdiff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 5f64c59154..61e1170b90 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,19 @@+## 2026-08-05: v5 developer docs are frozen until the 6.0 release; 6.0 docs land under docs/v6++The pages under `docs/developer/` document the stable 5.x line and stay+untouched until 6.0 ships — even where they describe subsystems 6.0 has+already replaced on main (the polymorphic `Adjustment` model, the+`AdjustmentSource` concern, and similar). Any plan whose remaining work+includes "update developer docs" fulfills it by writing a **v6 variant**+under `docs/v6/developer/` (registered in `docs/docs.json` under the+v6.x version), never by editing the v5 page. First applications: the+typed-adjustments docs (`v6/developer/core-concepts/taxes-discounts-fees.mdx`+already exists; promotions core-concepts and the custom-promotion how-to+get v6 variants). Also renamed `6.0-split-adjustments.md` →+`6.0-6.1-split-adjustments.md`: the implementation shipped for 6.0 and+the remainder (legacy-table drop, promotion stacking) is 6.1 work, so+the plan spans two releases like the other `X.Y-X.Z` plans.+## 2026-08-04: Commerce-behavior globals move to Store preferences; app configuration stays globalA full usage audit of `Spree::Config` (multi-agent trace with adversarial@@ -623,7 +639,7 @@ discount engine is being rewritten there anyway), retargeted to 6.1 the sameday: stacking is **purely additive** — no schema change, no breaking windowneeded — and 6.0 is already the heaviest release in Spree's history. Deferringcosts nothing structurally because the expensive prerequisites ship in 6.0-regardless (`6.0-split-adjustments.md`): typed Discount tables that permit+regardless (`6.0-6.1-split-adjustments.md`): typed Discount tables that permitmultiple rows per adjustable, per-adjustable clamping, andprorate-over-the-remaining-discounted-base (needed for order-leveldistribution either way), with winner-only selection isolated in a singlediff --git a/docs/v6/developer/core-concepts/promotions.mdx b/docs/v6/developer/core-concepts/promotions.mdxnew file mode 100644index 0000000000..de7235fb8d--- /dev/null+++ b/docs/v6/developer/core-concepts/promotions.mdx@@ -0,0 +1,260 @@+---+title: Promotions+description: Build percentage and fixed-amount discounts, free shipping, BOGO offers, and coupon codes with Spree's rule and action-based promotion system.+---++## Overview++Promotions give money off an order — a percentage off, free shipping, or free items added to the cart. A promotion is a campaign definition: **rules** decide when it applies, **actions** decide what it does. When a promotion applies, its actions write [Discount](/v6/developer/core-concepts/taxes-discounts-fees#discounts) rows on the order.++```mermaid+erDiagram+ Promotion {+ string name+ string kind+ string code+ datetime starts_at+ datetime expires_at+ integer usage_limit+ string match_policy+ }++ PromotionRule {+ string type+ text preferences+ }++ PromotionAction {+ string type+ }++ CouponCode {+ string code+ string state+ }++ Discount {+ string label+ string kind+ string code+ string amount+ }++ Promotion ||--o{ PromotionRule : "has many"+ Promotion ||--o{ PromotionAction : "has many"+ Promotion ||--o{ CouponCode : "has many"+ PromotionAction ||--o{ Discount : "writes"+ Order ||--o{ Discount : "has many"+```++Promotions can be activated in two ways:++- **Automatic promotions** — applied on their own when the rules are met (e.g. free shipping on orders over $50)+- **Coupon code promotions** — applied when a customer enters a valid code during checkout++### How discounts are recorded++Each applied promotion becomes one or more Discount rows on the order — on a specific line item or on a fulfillment, never a loose adjustment. Each row keeps a copy of the coupon code and the configured value ("10% off"), so the order still tells the whole story even if the promotion is deleted later.++Two things follow from this design:++- **Only winners are stored.** When several promotions compete for the same item, Spree picks the one that saves the customer the most and writes only that one. Losing candidates are recomputed on every cart change, so a promotion that loses today can win tomorrow without any bookkeeping.+- **A discount on the whole order is shared out across the items.** If a customer later returns one item, Spree knows exactly how much of the discount belonged to it.++## Promotion Attributes++| Attribute | Description | Example |+|-----------|-------------|---------|+| `name` | The name of the promotion | Summer Sale |+| `description` | Brief description (max 255 chars) | 20% off all summer items |+| `kind` | Type: `coupon_code` or `automatic` | `automatic` |+| `starts_at` | When the promotion becomes active | 2026-06-01 00:00:00 |+| `expires_at` | When the promotion expires | 2026-09-01 23:59:59 |+| `usage_limit` | Max times the promotion can be used | 500 |+| `match_policy` | How rules are evaluated: `all` or `any` | `all` |+| `advertise` | Whether to display on storefront | `true` |++### Multi-Code Promotions++For promotions that need unique codes per customer (e.g. influencer campaigns), Spree supports bulk code generation:++| Attribute | Description | Example |+|-----------|-------------|---------|+| `multi_codes` | Enable bulk code generation | `true` |+| `number_of_codes` | How many codes to generate | 1000 |+| `code_prefix` | Prefix for generated codes | `SUMMER` |++Generated codes follow the pattern `{prefix}{random}`, e.g. `SUMMER22A0F62A230BD919`.++## Rules++Rules decide when a promotion is eligible. You can combine multiple rules and configure whether **all** must match or **any** is enough (via `match_policy`).++| Rule | Applies when |+|---|---|+| **FirstOrder** | It's the customer's first order (checked by account and email) |+| **ItemTotal** | The order subtotal is within configured minimum/maximum thresholds |+| **Product** | Specific products are in the order (`any` / `all` / `none` match policy) |+| **Category** | Products from specific categories are in the order — child categories count |+| **OptionValue** | Products with specific option values (size, color) are in the order |+| **User** | The customer is one of the listed accounts |+| **UserLoggedIn** | The customer is logged in |+| **OneUsePerUser** | The customer hasn't used this promotion before |+| **CustomerGroup** | The customer belongs to one of the configured customer groups |+| **Country** | The order ships to a specific country |+| **Currency** | The order is in a specific currency |+| **Channel** | The order was placed through one of the configured [channels](/developer/core-concepts/channels) |+| **Market** | The order belongs to one of the configured [markets](/developer/core-concepts/markets) |++You can also [build your own rules](/v6/developer/how-to/custom-promotion) for business-specific conditions.++## Actions++Actions define what happens when a promotion applies.++### CreateAdjustment++A discount on the whole order. The amount is distributed proportionally across the line items — there is no single order-level row, so per-item reporting and partial returns always know their share.++**Default calculator:** `FlatPercentItemTotal` (percentage off the order). Also available: `FlatRate`, `FlexiRate`, `TieredFlatRate`, `TieredPercent`.++**Use case:** "10% off your order", "$20 off orders over $100".++### CreateItemAdjustments++A discount on individual line items. Only items that match the promotion's rules receive it — if a Category rule says "Electronics", only electronics are discounted.++**Default calculator:** `PercentOnLineItem` (percentage off each item).++**Use case:** "15% off shoes", "Buy 2+ shirts get 10% off each".++### FreeShipping++Writes a discount on each fulfillment covering its delivery cost. The row is kept even when the cost is zero — its presence is what marks the order as having free shipping.++**Use case:** "Free shipping on orders over $75", "Free shipping with code FREESHIP".++### CreateLineItems++Adds specified products to the cart when the promotion is eligible, checking stock first. Items are not removed automatically if eligibility is lost — customers remove them manually.++**Use case:** "Free gift with purchase", "Spend $100 get a free sample".++## Managing Promotions++Create and manage promotions via the [Admin API](/api-reference/admin-api/introduction). Rules and actions can be supplied inline on create — each is a `{ type, preferences }` draft using the rule and action types described above:++<CodeGroup>++```typescript Admin SDK+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://store.example.com',+ secretKey: 'sk_xxx',+})++// "20% off orders over $100 with code SUMMER20"+const promotion = await client.promotions.create({+ name: 'Summer Sale',+ code: 'SUMMER20',+ kind: 'coupon_code',+ rules: [{ type: 'item_total', preferences: { amount_min: 100 } }],+ actions: [+ {+ type: 'create_adjustment',+ calculator: { type: 'flat_percent_item_total', preferences: { flat_percent: 20 } },+ },+ ],+})+```++```bash CLI+spree api post /promotions -d '{+ "name": "Summer Sale",+ "code": "SUMMER20",+ "kind": "coupon_code",+ "rules": [{ "type": "item_total", "preferences": { "amount_min": 100 } }]+}'+```++</CodeGroup>++You can also add rules and actions to an existing promotion, or update and remove the promotion itself:++<CodeGroup>++```typescript Admin SDK+await client.promotions.rules.create('promo_xxx', {+ type: 'first_order',+})+await client.promotions.update('promo_xxx', { expires_at: '2026-09-01T00:00:00Z' })+await client.promotions.delete('promo_xxx')+```++```bash CLI+spree api post /promotions/promo_xxx/promotion_rules -d '{"type": "first_order"}'+spree api patch /promotions/promo_xxx -d '{"expires_at": "2026-09-01T00:00:00Z"}'+```++</CodeGroup>++The available rule and action types — including any custom ones you register — are discoverable at `/api/v3/admin/promotion_rules/types` and `/api/v3/admin/promotion_actions/types`, together with their preference schemas. The dashboard's promotion editor is built on these endpoints, so custom types show up there without any UI work.++<Note>+Deleting a promotion doesn't disturb the orders that used it. Their discount rows stay, keeping the code and value they were created with — only the link back to the promotion is cleared.+</Note>++## Coupon Codes++Coupon codes track promotion usage and can be single-use or multi-use.++- **Single code** — set the `code` attribute on the promotion; `usage_limit` controls how many times it can be redeemed.+- **Multi-code** — bulk-generated codes each track their own state (`unused` / `used`).++Customers apply codes on the cart via the Store API:++<CodeGroup>++```typescript Store SDK+// Apply a discount code to the cart+const cart = await client.carts.discountCodes.apply('cart_abc123', 'SUMMER20', {+ spreeToken: '<token>',+})++// Remove a discount code from the cart+await client.carts.discountCodes.remove('cart_abc123', 'SUMMER20', {+ spreeToken: '<token>',+})+```++```bash cURL+# Apply a coupon code+curl -X POST 'https://api.mystore.com/api/v3/store/carts/cart_abc123/discount_codes' \+ -H 'X-Spree-API-Key: pk_xxx' \+ -H 'X-Spree-Token: <token>' \+ -H 'Content-Type: application/json' \+ -d '{ "code": "SUMMER20" }'+```++</CodeGroup>++The returned cart already carries the updated discounts and totals. If the cart doesn't qualify yet — say the code needs a $100 minimum and the cart holds $80 — the code stays on the cart and the discount activates on its own the moment the cart qualifies.++Automatic promotions need no customer action at all — they are evaluated on every cart change.++## Promotion Flow++1. **Cart change** — every change to a cart (item added, address entered, code applied) triggers a recalculation+2. **Eligibility** — each connected promotion is checked: active dates, usage limits, then rules per `match_policy`+3. **Competition** — candidate discounts are computed for every eligible promotion; per item, per fulfillment, and order-wide, the largest saving wins+4. **Persistence** — winning discounts are written as rows; anything stale from the previous pass is removed; tax is then estimated on the discounted amounts+5. **Placement** — once the order is placed, its discount rows are frozen; usage counts are recorded against the promotion++## Related Documentation++- [Taxes, Discounts & Fees](/v6/developer/core-concepts/taxes-discounts-fees) — the Discount rows promotions write, and manual discounts+- [Build Custom Promotion Rules & Actions](/v6/developer/how-to/custom-promotion) — step-by-step guide to custom rules, actions and adjusters+- [Calculators](/developer/core-concepts/calculators) — promotion calculators+- [Carts](/v6/developer/core-concepts/carts) — the cart lifecycle promotions act on+- [Admin SDK Resources](/developer/sdk/admin/resources) — the `client.promotions.*` resource-client pattern used abovediff --git a/docs/v6/developer/core-concepts/taxes-discounts-fees.mdx b/docs/v6/developer/core-concepts/taxes-discounts-fees.mdxindex 2453f8fa94..33b307aade 100644--- a/docs/v6/developer/core-concepts/taxes-discounts-fees.mdx+++ b/docs/v6/developer/core-concepts/taxes-discounts-fees.mdx@@ -111,7 +111,7 @@ You never create tax lines yourself. They're written whenever the order total is| `promotion_id` | The promotion it came from || `line_item_id` / `fulfillment_id` | What it reduced |-Most discounts come from [Promotions](/developer/core-concepts/promotions) — a customer applies a code and the rows appear. A **manual** discount is one an admin adds directly, for a goodwill gesture or a price match:+Most discounts come from [Promotions](/v6/developer/core-concepts/promotions) — a customer applies a code and the rows appear. A **manual** discount is one an admin adds directly, for a goodwill gesture or a price match:<CodeGroup>@@ -194,6 +194,6 @@ Once an order is placed, the rows stop being regenerated. Editing a placed order## Related- [Taxes](/developer/core-concepts/taxes) — how tax is worked out-- [Promotions](/developer/core-concepts/promotions) — where most discounts come from+- [Promotions](/v6/developer/core-concepts/promotions) — where most discounts come from- [Fulfillments](/v6/developer/core-concepts/fulfillments) — delivery charges- [Orders](/v6/developer/core-concepts/orders) — order totals and statusesdiff --git a/docs/v6/developer/how-to/custom-promotion.mdx b/docs/v6/developer/how-to/custom-promotion.mdxnew file mode 100644index 0000000000..f4031bc5a0--- /dev/null+++ b/docs/v6/developer/how-to/custom-promotion.mdx@@ -0,0 +1,338 @@+---+title: Build Custom Promotion Rules & Actions+description: Step-by-step guide to creating custom promotion rules, discount actions, and adjusters for business-specific eligibility logic and charges.+---++## Overview++Spree's promotion system has three extension points:++- **Rules** — conditions that decide when a promotion applies+- **Actions** — what an applied promotion does, usually writing [Discount](/v6/developer/core-concepts/taxes-discounts-fees#discounts) rows+- **Adjusters** — for discounts and fees that aren't promotions at all (loyalty pricing, gift wrap fees, payment surcharges)++Spree ships with a comprehensive set of [built-in rules and actions](/v6/developer/core-concepts/promotions#rules). This guide shows how to build your own of each kind.++## Custom Promotion Rules++Rules determine whether a promotion is eligible for a given order. Each rule implements `eligible?` which returns `true` or `false`.++### Step 1: Create the Rule Class++Create a new class inheriting from `Spree::PromotionRule`:++```ruby app/models/spree/promotion/rules/minimum_quantity.rb+module Spree+ class Promotion+ module Rules+ class MinimumQuantity < Spree::PromotionRule+ preference :quantity, :integer, default: 5++ def applicable?(promotable)+ promotable.is_a?(Spree::Order) || promotable.is_a?(Spree::Cart)+ end++ def eligible?(order, options = {})+ total_quantity = order.line_items.sum(&:quantity)++ if total_quantity >= preferred_quantity+ true+ else+ eligibility_errors.add(+ :base,+ "Order must contain at least #{preferred_quantity} items"+ )+ false+ end+ end+ end+ end+ end+end+```++#### Key Methods to Implement++| Method | Required | Description |+|--------|----------|-------------|+| `applicable?(promotable)` | Yes | Returns `true` if this rule type can evaluate the promotable — accept both carts and orders (see the note below) |+| `eligible?(promotable, options = {})` | Yes | Returns `true` if the promotable meets this rule's conditions. Add messages to `eligibility_errors` to explain why not. |+| `actionable?(line_item)` | No | Returns `true` if a specific line item should receive the promotion's discount. Defaults to `true`. Override this for rules that target specific items (like product or category rules). |++The `options` hash passed to `eligible?` can include `:user`, `:email`, and other context from the checkout flow.++<Warning>+Accept **both** `Spree::Cart` and `Spree::Order` in `applicable?`. Promotions are evaluated on every cart change, long before the cart becomes an order, and in Spree 6 a cart is its own model rather than an unfinished order. A rule guarding on `Spree::Order` alone silently never applies during checkout — the promotion just appears not to work. Every built-in rule accepts both.+</Warning>++#### Using Preferences++Rules use Spree's preference system for configuration. Each preference creates getter/setter methods automatically:++```ruby+preference :amount, :decimal, default: 100.00+preference :operator, :string, default: 'gte'+preference :category_ids, :array, default: []++# These create:+# preferred_amount / preferred_amount=+# preferred_operator / preferred_operator=+# preferred_category_ids / preferred_category_ids=+```++Available types: `:string`, `:integer`, `:decimal`, `:boolean`, `:array`.++### Step 2: Register the Rule++```ruby config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.promotions.rules << Spree::Promotion::Rules::MinimumQuantity+end+```++Registered rules are discoverable at `/api/v3/admin/promotion_rules/types` together with their preference schema, and the dashboard's promotion editor is built on that endpoint — your rule appears there with a generated preferences form, no UI work needed.++### Step 3: Add Translations++The rule's display name and description in the dashboard come from your locale file:++```yaml config/locales/en.yml+en:+ spree:+ promotion_rule_types:+ minimum_quantity:+ name: Minimum Quantity+ description: Order must contain at least X items+```++### Example: Rule with `actionable?`++When your rule targets specific line items (not the whole order), implement `actionable?` so that item-level actions only discount matching items:++```ruby app/models/spree/promotion/rules/brand.rb+module Spree+ class Promotion+ module Rules+ class Brand < Spree::PromotionRule+ preference :brand_names, :array, default: []++ def applicable?(promotable)+ promotable.is_a?(Spree::Order) || promotable.is_a?(Spree::Cart)+ end++ def eligible?(order, options = {})+ order.line_items.any? { |li| matches_brand?(li) }+ end++ # Only discount line items from matching brands+ def actionable?(line_item)+ matches_brand?(line_item)+ end++ private++ def matches_brand?(line_item)+ brand = line_item.product.get_metafield('details.brand')&.value+ preferred_brand_names.include?(brand)+ end+ end+ end+ end+end+```++## Custom Promotion Actions++Actions define what happens when a promotion is applied. A discount action doesn't write rows itself — it declares **where** its discount belongs and **how much** it is, and Spree's promotion engine does the rest: running the competition between promotions, clamping amounts so nothing goes below zero, writing the winning Discount rows, and removing stale ones on every recalculation.++### Discount Action (with Calculator)++Three declarations make a discount action:++| Method | Description |+|--------|-------------|+| `discount_scope` | Where the discount belongs: `:line_item` (per matching item), `:fulfillment` (per delivery), or `:order` (whole order, distributed proportionally across items) |+| `compute_amount(adjustable)` | The discount for one adjustable — a line item, fulfillment, or the order, matching your scope. Return a **negative** amount, or zero for "no discount". |+| `perform(options = {})` | Called when the promotion is activated. For discount actions, delegate to `apply_via_adjuster(options)`. |++```ruby app/models/spree/promotion/actions/tiered_discount.rb+module Spree+ class Promotion+ module Actions+ class TieredDiscount < Spree::PromotionAction+ include Spree::CalculatedAdjustments++ before_validation -> { self.calculator ||= Calculator::FlatRate.new }++ def discount_scope+ :order+ end++ def perform(options = {})+ apply_via_adjuster(options)+ end++ def compute_amount(order)+ # Tiered discount: $10 off orders over $50, $25 off orders over $100+ discount = case order.item_total+ when 100..Float::INFINITY then 25+ when 50..99.99 then 10+ else 0+ end++ # Negative for discounts, capped at the order total+ [discount, order.item_total].min * -1+ end+ end+ end+ end+end+```++With `discount_scope :order`, the winning amount is shared out proportionally across the line items — you never handle the distribution yourself. With `:line_item`, `compute_amount` is called once per line item, and only items passing your rules' `actionable?` receive rows.++<Note>+There is nothing to clean up either. If the promotion stops being eligible — the cart shrinks below the threshold, the code is removed — the next recalculation deletes its rows. If your action loses to a better promotion, its candidate simply isn't written that round, and it competes again on the next one.+</Note>++### Non-Discount Action++For actions that don't create discounts (awarding points, sending notifications), implement `perform` alone:++```ruby app/models/spree/promotion/actions/add_loyalty_points.rb+module Spree+ class Promotion+ module Actions+ class AddLoyaltyPoints < Spree::PromotionAction+ preference :points, :integer, default: 100++ def perform(options = {})+ order = options[:order]+ return false unless order.user.present?++ order.user.add_loyalty_points(preferred_points, source: promotion)+ true+ end+ end+ end+ end+end+```++`perform` receives `:order` and `:promotion` in its options and should return `true` if the action was applied. Optionally implement `revert(options = {})` to undo side effects when the promotion is deactivated.++### Register and Translate++```ruby config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.promotions.actions << Spree::Promotion::Actions::TieredDiscount+end+```++```yaml config/locales/en.yml+en:+ spree:+ promotion_action_types:+ tiered_discount:+ name: Tiered Discount+ description: Different discount amounts based on order total tiers+```++Like rules, registered actions surface automatically in the dashboard's promotion editor via `/api/v3/admin/promotion_actions/types`.++## Custom Adjusters++Not every charge or reduction is a promotion. A gift wrap fee, a payment surcharge, or loyalty pricing has no rules, no coupon codes, and no competition — it just needs to be on the order whenever it applies. That's an **adjuster**: a class invoked on every recalculation that owns a family of [Fee or Discount](/v6/developer/core-concepts/taxes-discounts-fees) rows.++```ruby app/models/my_app/adjusters/gift_wrap.rb+module MyApp+ module Adjusters+ class GiftWrap < Spree::Adjusters::Base+ def update+ if order.gift_wrap?+ order.fees.find_or_initialize_by(kind: 'gift_wrap').update!(+ amount: 5.99, label: 'Gift wrapping'+ )+ else+ order.fees.where(kind: 'gift_wrap').destroy_all+ end+ end+ end+ end+end+```++```ruby config/initializers/spree.rb+Rails.application.config.after_initialize do+ Spree.adjusters << MyApp::Adjusters::GiftWrap+end+```++The contract is one method: `update`. It runs on every recalculation, so it must be idempotent — write the rows that should exist, remove the ones that shouldn't (that's why the example uses `find_or_initialize_by` keyed by `kind` rather than `create`). The `order` it receives is the cart during checkout and the order after placement, and rows attach to it either way.++There's no totals bookkeeping to do: after all adjusters run, Spree re-sums the typed rows into the order totals and the tax provider estimates tax on the result — a fee you write here gets taxed in the same pass, like any other fee.++Custom discounts work the same way, writing `order.discounts` rows with your own `kind` (e.g. `'loyalty'`). Use a kind other than `'promotion'` — promotion rows belong to the promotion engine, which removes any it didn't write itself.++## Testing++```ruby spec/models/spree/promotion/rules/minimum_quantity_spec.rb+require 'spec_helper'++RSpec.describe Spree::Promotion::Rules::MinimumQuantity do+ let(:rule) { described_class.new(preferred_quantity: 3) }+ let(:order) { create(:order_with_line_items, line_items_count: 1) }++ describe '#eligible?' do+ context 'when order has enough items' do+ before { order.line_items.first.update(quantity: 3) }++ it { expect(rule.eligible?(order)).to be true }+ end++ context 'when order does not have enough items' do+ it { expect(rule.eligible?(order)).to be false }++ it 'sets eligibility error' do+ rule.eligible?(order)+ expect(rule.eligibility_errors.full_messages).to include(+ /at least 3 items/+ )+ end+ end+ end+end+```++```ruby spec/models/spree/promotion/actions/tiered_discount_spec.rb+require 'spec_helper'++RSpec.describe Spree::Promotion::Actions::TieredDiscount do+ let(:promotion) { create(:promotion) }+ let(:action) { described_class.create!(promotion: promotion) }++ describe '#compute_amount' do+ it 'returns -10 for orders over $50' do+ order = build(:order, item_total: 75)+ expect(action.compute_amount(order)).to eq(-10)+ end++ it 'returns -25 for orders over $100' do+ order = build(:order, item_total: 150)+ expect(action.compute_amount(order)).to eq(-25)+ end++ it 'returns 0 for orders under $50' do+ order = build(:order, item_total: 30)+ expect(action.compute_amount(order)).to eq(0)+ end+ end+end+```++## Related Documentation++- [Promotions](/v6/developer/core-concepts/promotions) — promotion architecture and built-in rules and actions+- [Taxes, Discounts & Fees](/v6/developer/core-concepts/taxes-discounts-fees) — the typed rows actions and adjusters write+- [Calculators](/developer/core-concepts/calculators) — available calculator types for promotion actions+- [Events](/developer/core-concepts/events) — subscribe to promotion eventsdiff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 784f9cf7e1..e1e76a4634 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -177,7 +177,7 @@ module Spreehas_many :refunds, through: :payments# Typed adjustment rows owned by this order (line-, fulfillment- and- # order-level). See docs/plans/6.0-split-adjustments.md.+ # order-level). See docs/plans/6.0-6.1-split-adjustments.md.has_many :tax_lines, class_name: 'Spree::TaxLine', dependent: :destroy, inverse_of: :orderhas_many :discounts, class_name: 'Spree::Discount', dependent: :destroy, inverse_of: :orderhas_many :fees, class_name: 'Spree::Fee', dependent: :destroy, inverse_of: :orderdiff --git a/spree/core/lib/tasks/typed_adjustments_migration.rake b/spree/core/lib/tasks/typed_adjustments_migration.rakeindex c53f5df35a..c823c212ce 100644--- a/spree/core/lib/tasks/typed_adjustments_migration.rake+++ b/spree/core/lib/tasks/typed_adjustments_migration.rake@@ -1,7 +1,7 @@# frozen_string_literal: true# 5.6 → 6.0: convert legacy polymorphic spree_adjustments rows into the typed-# TaxLine / Discount / Fee tables (docs/plans/6.0-split-adjustments.md, Wave 7).+# TaxLine / Discount / Fee tables (docs/plans/6.0-6.1-split-adjustments.md, Wave 7).## Contract:# - Legacy rows are READ ONLY — spree_adjustments stays in place through 6.0