Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Add B2B plans for Spree 6.1

Damian Legawiece6e9823b7917
diff --git a/CLAUDE.md b/CLAUDE.md
index 7940fa136e..cfa26dce5f 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -13,6 +13,13 @@ Use `/project:create-plan` and `/project:update-plan` for plan management.
Active plans (6.0 target, work pending):
- `6.0-b2b-storefront-purchasing.md` — Storefront company self-service (account section: members, invitations, address book, company orders; the invitation acceptance page the mailer already links) + company-aware checkout (buying-for picker on cart **and** checkout, company address book replacing the personal one at the address step). **Implemented, in review 2026-08-27** (spree/spree#14498 + spree/storefront#214). **No polymorphic owner on Cart/Order** — a purchase keeps two buyer-side parties (`customer_id` + `company_id`), the industry dual axis; OSS ships plain machinery, the polished buyer portal is Enterprise. Backend grew past the planned one-guard widening: `Spree::HasAddressBook` lets an owner declare where its default slots live (a customer's `bill_address_id` vs a company's `default_bill_address_id`) so `Addresses::Create`/`Update` work for any owner — they silently dropped a company's default flag before; default flags are three-state (claim / give up / say nothing) and released by conditional UPDATE, never read-then-write; `Company#address_book` is the inherited reading list, and reads inherit while writes stay with the owning node. **Constraints now:** never branch on an address owner's class — ask the owner (`has_address_book`); a new owner declares its slots or its defaults silently no-op; nothing storefront-side may branch on a member's "role" (OSS has none — gate on standing).
+- `6.0-catalog-agreement-rework.md` — Implementation of the one-question-per-entity catalog consequences (design finalized 2026-08-30; extracted from the `6.0-b2b-companies-and-catalogs.md` amendment block so its Implemented status stops hiding unbuilt work; **sequence Wave 1 — everything catalog-shaped builds on it**): the binding inversion (`spree_price_lists.catalog_id` replaces `spree_catalogs.price_list_id`; catalogs migration rewritten in place — unreleased edge; generic rule matching skips owned lists by FK, closing the deactivated-catalog leak in `bound_price_list_ids`, which is deleted along with its `Spree::Current` memoization); `PriceRules::CustomerGroupRule`/`UserRule` deprecated (bridge + `spree:upgrade:migrate_audience_price_rules_to_catalogs`; mixed-rule lists are REPORTED for manual review, never auto-converted — a wrong conversion is a silent price change), `ChannelRule` grandfathered; catalog-first dashboard (agreement editor, inline `price_list` payload on catalog create/update, products-with-prices view, detach warning, one-go wizard). **Constraints now:** no new reads of `spree_catalogs.price_list_id` or `bound_price_list_ids`; no new features on the deprecated/grandfathered price rules; catalog-page features (terms, pricing card) mount on the agreement editor, never parallel surfaces.
+- `6.0-b2b-wholesale-shipping.md` — Wholesale/freight shipping (design finalized 2026-08-30, nothing built): **`Spree::PackageType`** — store-scoped packaging vocabulary (`box|envelope|carton|pallet|container`, one default per store Channel-style) absorbing the four `default_package_*` store preferences (one-release bridges; deliberately NOT `Spree::Package` — `Stock::Package` is the in-memory packer); variant packing chain `carton_package_type_id` + `units_per_carton` + `carton_weight` + `cartons_per_pallet` (geometry on the shared carton row, packing facts on the variant; Unit → Carton → Pallet → CBM/weight); unit-aware `Spree::FreightSummary` (units/cartons/pallets/CBM/gross weight, `complete?` flag) built on the currently-unused `Stock::Package#volume` chain via a new `Spree::Measurement` conversion helper; shipment tiers = `DeliveryMethodRules::VolumeRule` (CBM min/max) + `CompanyRule` (`company_presence`) — **no new delivery profile kind** (the same product ships parcel retail and carton wholesale, and a product has one profile); **unpriced rates are first-class** (`unpriced` on Estimate + `spree_delivery_rates`, estimator skips markup, UIs render "quoted after review" — never a $0 rate that displays as Free) returned by `DeliveryRateProvider::Freight`, whose rate `metadata` snapshots the summary + deposit terms (frozen at completion — duties doctrine, never re-derived); **deposits are collected, not displayed**: deposit terms → `Cart#amount_due_at_checkout`, `Carts::Complete` validates payments against the deposit (base = order total at placement), order completes `partially_paid` with the existing `outstanding_balance` (2026-08-30 amendment: the method-level `deposit_percentage` is a *default source* feeding the order's `payment_terms` snapshot — see `6.0-6.1-b2b-payment-terms.md`); the forwarder's quote lands later as `Fee(kind: 'freight')` through `/admin/orders/:id/fees`. **Constraints now:** all volume/CBM math goes through the unit-aware helper (raw dimension-column multiplication is forbidden — the `WeightRule` raw-number shortcut does not extend to volume); no new readers of the `default_package_*` preferences; never model quote-later as a zero-cost priced rate; carton geometry never becomes variant columns; nothing may assume a completed order is paid in full (check `payment_status`/`outstanding_balance`); post-placement freight charges are Fees, never delivery-rate edits.
+- `6.0-b2b-quantity-rules.md` — B2B MOQ + order multiples + purchase unit (design finalized 2026-08-30 under the one-question-per-entity doctrine — decisions.md): variant base columns `minimum_order_quantity`/`order_multiple`/`purchase_unit` (`unit|carton`, display-only vocabulary — stored quantities stay units) binding every cart, enforced as named steps in `Carts::AddItem`/`UpsertItems` on the RESULTING line quantity and re-checked at `Carts::Complete` (staff/admin unrestricted; server refuses invalid quantities naming the nearest valid neighbors — **never silently rounds**); storefront steppers step by the multiple / count cartons ("2 CTNS — 48 units"). **Commercial terms are Catalog data:** the catalog-wide default = `minimum_order_quantity` + `order_multiple` **columns on `spree_catalogs`** (same pair at three levels: variant base → catalog default → override), contextual per-SKU tiers = `spree_catalog_quantity_rules` (catalog_id, variant_id both null: false, one plain unique index — strictly overrides), and the cart-level minimum = `spree_catalog_order_minimums` (per-currency rows, never one amount + a currency column) — **deliberately typed tables per grain, never one generic catalog_rules table or an STI rule family** (hot-path indexed lookups + DB uniqueness; rules are matching predicates, terms are values — typed-adjustments doctrine), all resolved **per-field nearest-agreement-wins** through `Catalog.for_context` (override row → catalog columns → variant base; a channel minimum is just its default catalog's terms; a terms-only catalog with empty assortment is legitimate); serializers expose the buyer's *resolved* rules + the minimum/shortfall. The earlier same-day `ChannelRule` STI family is superseded — access gating (`storefront_access`/`guest_checkout`) stays as Channel preferences because gating binds before identity exists. **Constraints now:** nothing below the cart layer may read quantity rules (stock/allocation/fulfillment stay unit-pure); new item mutations keep routing through `AddItem`/`UpsertItems`; commercial terms are catalog rows/columns resolved per-field — no purchase-term settings on Channel, no term columns on variants beyond the base rules; never move gating onto catalogs.
+- `6.0-price-list-automatic-pricing.md` — Automatic price adjustments (design finalized 2026-08-30): `spree_price_lists.price_adjustment_percentage` (signed decimal, nil = fixed list; `adjust_compare_at` boolean) — the resolver derives base × factor **on read** for variants without an explicit row (explicit amounts override per variant × currency; nil-amount placeholder rows fall through), currency-rounded, currency-agnostic (applies to every base currency), **never materialized** (no refresh jobs, no drift; resolution cache keys must include the base price's version). Combined with `VolumeRule` this gives automatic % volume discounts with zero rows to maintain. Dashboard Pricing card (magnitude + increase/decrease + compare-at switch) on the standalone list page AND embedded on the catalog page for a catalog-owned list. **Constraints now:** no job/rake/import may write price rows computed from an adjustment; price exports/feeds/reports must resolve through the pricing provider once adjustment lists exist; "how numbers are made" lives on PriceList, never Catalog.
+- `6.0-b2b-customer-po-numbers.md` — Buyer PO reference on orders (design finalized 2026-08-30): `po_number` string on cart + order (industry-exact name; copied at completion; staff may correct post-placement as a plain write — it is not money) + optional **`po_document`** private-storage attachment (direct upload, spoofing-protected, blob re-attached to the order at completion — no competitor has order-native PO upload) + **`po_number_required` boolean on `Spree::Company`** (per-company is the market's control granularity; deliberately NOT a catalog term — buyer process ≠ agreement; not governance, so the OSS-companies constraint holds) enforced as a `Carts::Complete` validation (`code: 'po_number_required'`, staff-created orders skip); `po_number` ransackable + the dashboard order search matches number OR PO; surfaced on admin order page, customer order history, confirmation email, and every future order-facing document. The Enterprise quote plan's `customer_reference`/attachment were replaced by these order fields (amended 2026-08-30). **Constraints now:** never model the buyer PO as a payment method or couple it to tender choice; `po_number` (buyer reference) and `Spree::PurchaseOrder` (merchant procurement, inventory-operations) never mix — no shared endpoints/serializers/vocabulary; new order-facing documents/emails render `po_number` when present; post-placement PO edits never route through the order-change substrate.
+- `6.0-draft-order-negotiation-mechanics.md` — Manual line pricing on draft orders + cart→draft copy (design finalized 2026-08-30; OSS half of the quotes tier split — the quote product is Enterprise `b2b-quotes.md`). **6.0:** admin item endpoints accept `price` on incomplete orders, stamping **`price_source: 'manual'`** — the provenance column's first readers land as guards (`Carts::PriceItems` skips manual rows, `LineItem#should_update_price?` false for them) so quantity edits stop silently re-pricing negotiated lines; `'manual'` is a reserved key no pricing provider may register; `price: null` = explicit revert; `price_source` exposed admin-only, never on store serializers; plus fixes — `Orders::Create` stamps `created_by`, and the `payment_pending` docstring corrected (completion yields `payment_status: 'none'`, not `'balance_due'`; a distinct unpaid value is the wholesale-deposit rollup work's call). **6.0, late (retargeted 2026-08-30 so Enterprise quotes need nothing beyond 6.0 GA):** `Spree::Orders::CreateFromCart` copies a customer cart into a fresh draft order leaving the cart untouched (not the completion copier — no money re-pointing, no `cart_id` claim). **Constraints now:** nothing reprices a `manual` line except the explicit revert and new repricing call sites must honor the guard; no post-placement price overrides (fees/discounts until the order-change substrate's `update_item_price` kind); quote lifecycle/statuses/expiry/customer surfaces never grow here (Enterprise plan).
+- `6.0-b2b-company-self-registration.md` — B2B front door, OSS mechanisms only (design finalized 2026-08-30; **retargeted 6.1 → 6.0 the same day**: the Enterprise onboarding product must ship on 6.0 GA and these small additive mechanisms are its only missing input): `POST /store/companies` (authenticated customer — including an existing retail customer — founds a root company + membership in one call; companies **born active**; registration answers → `metadata['registration']`; `company.registered` event, core sends no mail), fourth storefront access posture **`approval_required`** (prices + checkout need a standing over an active company; `prices_hidden` guest-only semantics untouched), **`pricing_access`** reason code beside every nulled price (`login_required` | `company_required` | policy-supplied), and **`Spree::Companies::ActivationPolicy`** (dependency-registered, default: every company active) consulted by `Catalog.for_company`, BOTH `sole_standing_company`s, cart `company_id` writes and the posture. The approval FLOW (pending lifecycle, requirements checklist mirroring seller onboarding, queue, request-more-info) is **Enterprise** (`spree-enterprise-v2/docs/plans/b2b-company-onboarding.md`) via the policy — no competitor ships approval OSS. **Constraints now:** new company-resolving code (visibility/pricing/checkout) consults the policy and the two `sole_standing_company`s stay mirrored; self-service standing never approval-gated; no status columns on `spree_companies`; no interim approval primitives beside it (customer-group membership prices, never approves); prices-hidden surfaces always carry the `pricing_access` code.
- `6.0-multi-vendor-marketplace.md` — Open-source the marketplace core (Seller, OrderGroup-based order splitting, commission engine with EU commission taxation, `SellerTransfer`/`SellerPayout` ledger + pluggable `PayoutProvider`) per spree/spree#13323. 6.0 headline feature; rebuilds the legacy Enterprise multi-seller module as native models on the Cart/Order split. Basic Stripe Connect payouts (Express onboarding + on-fulfillment transfers) ship OSS in the monorepo, alongside the Stripe core gateway pulled in from the standalone `spree_stripe` repo (payment-sessions classes only, likely `spree/core` — decisions.md 2026-07-15); Enterprise keeps refund clawbacks/netting, reconciliation, KYC ops, DAC7 payout reports, facilitator taxes + Shopify/WooCommerce seller apps. **Seller principal + surface (Decision 10, 2026-08-15):** seller staff are `Spree.admin_user_class` (no `SellerUser`; membership by `RoleUser.resource_type`, never `store_id`) on a dedicated `/api/v3/seller` branch — own `seller_api` JWT audience, own `Spree.seller_authentication_strategies` + `/seller/auth/*`, audience-stamped refresh tokens, every endpoint scope-fetched through `current_seller` (store derived from the seller); sellers never call the Admin API and admin controllers are never subclassed into the seller namespace.
- `6.0-seller-onboarding-requirements.md` — Operator-configured seller onboarding checklist (design finalized 2026-08-18): `Spree::SellerRequirement` = store-scoped STI rows (`acts_as_list`, `active`/`required`, per-kind preferences) over developer-written kinds registered in `Spree.seller_requirements` (same `registers_subclasses_via` + `PreferenceSchema` types-discovery pattern as `DeliveryMethodRule`); three completion families — computed from seller data, attested by the seller, verified by the operator/a provider — the last two through one persisted `Spree::SellerRequirementSubmission` (`pending | accepted | rejected | waived`, optional private file attachment; generic `Attestation`/`OperatorReview`/`Document` kinds); evaluated on read by `Spree::Sellers::Requirements` into `SellerRequirementStatus` value objects (`complete | incomplete | pending | rejected`), never denormalized onto sellers. **Exactly two enforcement points:** `Sellers::SubmitForReview` (new; `onboarding → ready_for_review`, `auto_approve_sellers` store preference chains into Approve) and `Sellers::Approve` (refuses unless `override_requirements: true`, recorded on the event); post-approval drift is flagged, never enforced (`sellable?` unchanged, payouts gated by the provider). `Sellers::StartOnboarding` on invitation acceptance, `Sellers::ReopenOnboarding` for send-back. Admin API `/admin/seller_requirements` (+`/types`) under `write_sellers`, `include=onboarding` on sellers, submission accept/reject/waive; seller branch `GET /seller/onboarding`, `POST /seller/onboarding/submit_for_review`, `POST /seller/requirements/:id/submissions`. Defaults provisioned per store (`provision_defaults` + seed); empty = nothing required. **Constraints now:** no `Seller#onboarding_completed?`-style methods or step-done columns on `spree_sellers` — new admission checks are kinds (or `validate` hooks on the seller workflows), per-seller check state is a submission; nothing but the two workflows reads the checklist as a gate.
- `6.0-store-policies.md` — Store + seller policy documents (**implemented 2026-08-27**): the missing back-office surface for `Spree::Policy` — Admin API v3 CRUD (five endpoints, `settings` scope, writes take the plain `body`, sanitized on save) + dashboard Settings → Policies page (MediaRichTextEditor, delete confirm, no reorder) — and extend ownership to sellers: `Seller has_many :policies, as: :owner` (no seeding — stores keep their four seeded defaults, sellers start empty), seller-branch CRUD (`Seller::ResourceController` derives the scope; `scoped_resource :seller_profile`), seller panel Settings → Policies page (plain `RichTextEditor` — media embedding is admin-only), new computed `Spree::SellerRequirements::Policy` kind (**one row per document** — `allow_multiple?`, so the row's own `name` is the policy required and two required policies are two separately-tracked lines; matched case/space-insensitively + non-blank body; no preferences; not in `DEFAULT_KINDS`; status exposes `required_policy_name`), store seller serializer exposes policies behind `?expand=policies`, store policy serializer gains `updated_at` (recorded exception to the no-timestamps rule). **Constraints now:** the leaky `Policy.for_store` override is deleted and must never come back — read policies through the owner association (`store.policies` / `seller.policies`), never a class-level scope (the deletion is a prerequisite for seller policies: the override leaked non-store-owned policies into every store's public endpoint); no `kind` enum, `position` column or fixed policy vocabulary (open set is the design); rich-text writes go to the plain attribute — `body_html` is a read-only reader and the `*_html`-on-write line in `6.0-admin-api.md`/`6.0-rich-text-descriptions.md` was wrong and is corrected; nothing persists checkout consent (that's `5.4-6.0-eu-legal-compliance.md` scope); storefront policy links stay hardcoded until a `store/info`-style endpoint embeds the policy list.
@@ -38,7 +45,7 @@ Active plans (6.0 target, work pending):
- `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-media-library.md` — Store-wide media library over `Spree::Media` (**shipped 2026-08-24**): `store_id` on `spree_media` (backfilled from the viewable's product; upgrade task in the 5.6→6.0 manifest), upload-first unattached rows (`viewable_id: nil`), dashboard library page + picker. **Reuse = blob sharing, never a shared asset entity:** copying to another product duplicates the `Media` row and attaches the same blob (`Media#duplicate_for`; `source_media_id` accepted by BOTH the nested media create and the inline `media:` list on the product — the dashboard Save uses the latter), a copy takes the **target's** store (never the source's — `duplicate_for` leaves `store_id` unset so `SingleStoreResource` reads it from the new owner), bare attachment fields (category/collection/store/seller images) adopt files via the blob's `signed_id` through their unchanged endpoints, and deletion safety rests on the Rails `active_storage_attachments`→blobs FK + `PurgeJob` discard — that FK is load-bearing (the no-FK rule covers Spree tables only), and media paths always `purge_later`, never synchronous `purge`. Rich text editor gains image embedding: Tiptap Image + `img` in `RichTextSanitizer.allowed_tags` land in the SAME change (plain `<img>` URLs to a new non-cropping `embed` rendition; no reference-tracking tables) — `MediaRichTextEditor` is the wired component every description field uses, the bare `RichTextEditor` has no picker. `Spree::Media::Usage` answers "where is this file used" from the blob's attachments plus a best-effort search of `SanitizableRichText.declaring_models`. **Category/Collection are real viewables (2026-08-24):** `Spree.media_viewable_types` = Product | Variant | Category | Collection (engine registry, append from an initializer); their `image`/`square_image` slots reconcile into placements via `Spree::HasLibraryMedia` (slots stay the operational storage; clearing a slot UNPLACES the row, never destroys; `spree:upgrade:backfill_library_media_placements` in the manifest) — until a real category gallery exists, reconciliation owns every placement on those records, so never create Media rows on a category by another path. **Media is its own permission resource** (`read_media`/`write_media`, catalog group): the library endpoints (index/show/update/destroy/usage) require it, while the product-nested gallery routes keep `products` — reaching a file through a product the caller already sees is not the same as enumerating the library (Shopify's split). Every attachment-creating path must check the media key, not just the endpoints. Library `DELETE /admin/media/:id` returns 422 + usage list while the file is in use; `detach=true` runs `Spree::Media::Destroy` (removes it from every placement + plain attachment in its store, then purges) — the dashboard sends it after a confirmation. Only the nested gallery destroy removes a single placement. Sellers/stores stay bare attachments (branding, not merchandising). **Constraints now:** no attachment-style join tables onto `Media` (a new context gets its own row sharing the blob); don't add `img` to the sanitizer ahead of the editor node; a new media write path must accept `source_media_id` or reuse silently drops on it; a new viewable type is appended to `Spree.media_viewable_types` deliberately, never by writing the polymorphic column; embedding is opt-in per editor in the dashboard (`MediaRichTextEditor`), never a server-side model list.
-- `6.0-inventory-operations.md` — StockTransfer lifecycle (draft → ready_to_ship → in_transit → received with partial receive), new `Spree::PurchaseOrder` + `Spree::Supplier` (the procurement source; `Spree::Seller` is the marketplace seller — see decisions.md 2026-07-14 and 2026-08-17) 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-inventory-operations.md` — StockTransfer lifecycle (draft → ready_to_ship → in_transit → received with partial receive), new `Spree::PurchaseOrder` + `Spree::Supplier` (the procurement source; `Spree::Seller` is the marketplace seller — see decisions.md 2026-07-14 and 2026-08-17) replacing today's "external receive" hack, variant + stock-location stock history panels. Consumes the typed-movement primitives from `6.0-typed-stock-movements.md`. **Lot-level inventory added 2026-08-30, targeted 6.1** (scope trim — purely additive, opt-in; full tracking chosen over provenance-only): `Spree::StockLot` = per-(location, variant) quantity bucket (`lot_number`, nullable `expires_at`), opt-in via `lot_tracked` on the variant; lot quantities are a decomposition of `count_on_hand` kept in sync **transactionally** with typed movements (license-pool discipline — movements gain nullable `stock_lot_id`, one row per lot touched); receives assign lots (lot-tracked items refuse receipt without lot data), `allocated` stays lot-agnostic, dispatch picks **FEFO** with per-fulfillment override; no storefront exposure. **Constraint now:** lot numbers live only on `Spree::StockLot` — never as strings on line items/fulfillments/movements, and a lot quantity never changes outside its movement's transaction.
- `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`.
- `6.0-delivery-method-rules.md` — `Spree::DeliveryMethodRule` STI on DeliveryMethod (design finalized 2026-07-29): ItemTotal/Weight rules first (Channel/Market/CustomerGroup later in lockstep with payment-method-rules), enforced solely in `Stock::Estimator`'s method filter so calculator- AND provider-priced methods obey eligibility; replaces the FlatRate-only bound preferences (one-release bridge + data task). **Phase 1 shipped** (rules + Estimator seam + admin nested CRUD/types discovery + dashboard Conditions card). **2026-08-06:** `ExcludedProductsRule` (products via `spree_delivery_method_rule_products` join, Saleor-style method-side exclusion) replaces the dropped `spree_products.excluded_delivery_method_ids` JSON column; rule-reference storage picks by cardinality — small reference sets stay `normalize_id_preference` arrays, catalog-scale (products) gets a join table.
- `6.0-service-workflows.md` — Two-tier services doctrine (2026-07-30). **Tier 1 `app/services/`:** plain `ServiceModule` classes, hand-written `def call(cart:, ...)`, Ruby kwargs as the contract — the permanent default; no DSL, no new `run`-pipelines, no hand-rolled sagas. **Tier 2 `app/workflows/`:** `Spree::Workflow` — named steps inside a plain `def perform(order:, ...)` (the ActiveJob::Continuable shape; bare `super` turns parameters into readers). Vocabulary: `step`/`external_step` (+ `with:`, `on_flow_failure:`), `run_hooks` + class-level `hooks`, `failure`/`halt!`; plain `ApplicationRecord.transaction`/`with_lock`/`rescue`/`publish_event`; every step instrumented as `step.spree_workflow`. Money lives in `Carts::RecalculateTotals` (single totals seam; the completed-order branch is the post-placement re-sum — rows re-summed, never regenerated), statuses in `Orders::UpdateStatuses` (refreshes each fulfillment's state, then rolls up); Order/CartUpdater are 6.1-removed warning shells. Shared Cart/Order surface lives in `Spree::Purchase::*` concerns; completion side effects (newsletter, account creation, risk) run in the sync `OrderPlacedSubscriber` on order.placed. Reserved for flows needing hooks, compensation/external I/O, or replay — currently `Carts::Complete`, `Carts::AddItem`, `Carts::Recalculate`, `Carts::RecalculateTotals` (+ order twins) and `Orders::Cancel` (absorbed `Order#after_cancel`; gateway settlement is an external_step). A service graduates to the workflow tier when it earns a hook, never speculatively — but hooks on flows already in the tier ship deliberately on the 6.0 boundary (2026-08-02), since hook keys are public API and moving one later is breaking. **New models get no state machine** — plain `status` string + inclusion validation, transitions through workflows; gateway I/O never in a save callback. Three hook families, contracts settled 2026-08-02: **lifecycle** (past tense, read-only), **validate** (handler calls `workflow.reject!(message)` to veto), **context** (`set_*_context`/`get_provider_data` — handler returns a hash, `run_hooks` deep-merges all handlers and returns it; last writer wins on collision). Phase 3 **shipped (2026-08-02)**: `run_hooks` returns the merged hash and `Workflow#reject!` is public API; `validate`/context/lifecycle hooks live on AddItem, Complete, Recalculate, RecalculateTotals, Cancel and Resume; `Fulfillments::Create`, `Payments::Capture`/`Refund`, `Payments::HandleWebhook` and `Carts::Merge` moved to `app/workflows/` (seams `fulfillment_create_workflow`, `payment_capture_workflow`, `payment_refund_workflow`, `payments_handle_webhook_workflow`, `cart_merge_workflow`; legacy names readable one release). **Customer registration (2026-08-05):** `Customers::Create` (seam `customer_create_workflow`, hooks `customers.create.validate`/`after_create`) is the single storefront customer-creation flow — self-registration + checkout account box (optional `order:` adopts addresses and links the order); absorbs `Orders::CreateUserAccount` (deprecated shell); admin create stays plain CRUD; token issuance stays in controllers; core sends NO welcome email — signup email is host-app code on `user.created` or the `after_create` hook. **Payment flows live in the workflows (2026-08-18, supersedes “money movement stays in the model”):** `Payments::Capture`/`Void`/`Process` implement capture, void and authorize/purchase inline as named steps — Capture/Process claim atomically BEFORE the gateway (a stale instance must not re-drive money movement), while Void stays gateway-authoritative (no pre-claim — the gateway decides if the authorization can still be released) with a compare-and-swap on the terminal write only; `Spree::Payment` keeps only gateway mechanics (`gateway_options`, `handle_response`, error translation) plus deprecated verb shells (`capture!`, `void_transaction!`, `process!`, `authorize!`, `purchase!`) that delegate to the workflows **until 7.0** (a full major — they have been the public money-movement API since Spree 1 and the replacement is a different shape) — new callers use `Spree.payment_*_workflow`, never the shells. `confirm!` stays on the model by design: it runs inside `settle_payment!`'s lock, where workflows cannot go, and makes no gateway call. No workflows for plain CRUD. Workflow Dependencies seams use `*_workflow` keys; legacy `*_service` names stay settable/readable with warnings until 6.1 but writes are stashed, never applied (old service classes aren't workflow-contract compatible). `Carts::Complete` battery must pass unmodified. **Durability = plain Rails:** long-running background work uses `ActiveJob::Continuable` directly (reference: `Spree::Imports::ProcessJob` — CSV spine with a row-number cursor; `CreateRowsJob`/`ProcessRowsJob` deprecated shells); workflows are synchronous request-cycle flows and are NOT jobs — Workflow-level durable execution ships only if the payout run proves the need.
@@ -64,7 +71,10 @@ Multi-version plans (some phases shipped, some pending):
- `5.6-dashboard-typed-plugin-routes.md` — Plugin file routes compiled into the host's TanStack route tree: `spree.dashboard.routes` marker + virtual-route-config composition in `@spree/dashboard/vite`, `createDashboardRouter` + `<Dashboard router>` ownership inversion, typed cast-free links, cross-package collision pre-flight with package-named errors. Runtime route registry stays for dynamic/in-app cases (catch-all is lowest priority). Implemented; published-tarball spike passed.
Pending design work (drafts, no implementation yet):
-- `6.1-order-change-substrate.md` — `Spree::OrderChange` + `Spree::OrderChangeAction`: one preview-then-apply substrate behind every post-placement mutation (admin order edits, returns, exchanges, claims, draft-order amendments), replacing four per-domain draft models with one `begin → request → confirm → cancel` lifecycle. Actions are typed `kind` + concrete FKs (never polymorphic); **preview is computed in memory and never persisted**; confirm is a workflow with the balance settlement as an `external_step`. Deliberately 6.1 — new schema + new extension API, and 6.0 already carries the Cart/Order split, typed adjustments and the returns rework. **Resolved 2026-08-10:** a change set belongs to one `Order`, never an `OrderGroup` (multi-seller edits = N change sets, each settling against its own order); a pending change set does **not** hold stock (`add_item` takes stock at confirm — reservations are checkout-scoped and would have no expiry trigger here). Phase 3 replaces the **6.0 order edit screen** (`/orders/$orderId/edit`) — quantities as inputs, `x` marks a row removed, Save applies the batch (**reshaped 2026-08-11**, reversing the original immediate-write rule); Phase 3 adds `begin`/preview/`confirm` behind the Save/Discard it already has. 6.0 constraints: don't **persist** a draft/preview model (transient React form state is fine and is the shape the substrate wants), don't compute projected totals client-side to fake a preview, expose post-placement money math through a service returning a value object, and keep line-item mutation on the edit screen rather than the fulfillment card. Known gap: the batch save is not atomic (no bulk endpoint; Phase 3's `Confirm` fixes it in one transaction).
+- `6.0-6.1-b2b-payment-terms.md` — Deposit-style payment terms + bank references (design finalized 2026-08-30; **collect-first OSS, ship-first Enterprise** — Net terms/credit/invoicing/dunning stay Enterprise roadmap): ONE frozen **`payment_terms` jsonb snapshot** on cart/order (`{kind: prepaid|deposit, deposit_percentage, balance_due_label, source}`) resolved quote/order override → company `payment_term_id` (→ `Spree::PaymentTerm` store-scoped presets, `kind` class_attribute Enterprise extends with `net`) → freight-method deposit prefs (demoted to default source — wholesale plan amended) → none; `Cart#amount_due_at_checkout` reads the snapshot; the **payment schedule** (due-now/deposit-state/balance+label) is derived on read — `Orders::UpdateStatuses` untouched; balance-due moment is a LABEL, real due dates are Enterprise. 6.1: `PaymentMethod::BankTransfer` (public-preference account details), stored generated **`reference` on every payment** (structured RF-style, unique, ransackable — the reconciliation identifier), storefront pay-balance route (`POST /store/orders/:id/payments`, capped by `max_amount`). 6.0 fixes: derived `R1001-P1` number removed from ransack whitelist + Stripe `find_by(number:)` corrected (NULL column). **Constraints now:** terms read from the snapshot, never re-resolved post-placement; nothing durable keys on derived payment numbers; no net-terms/credit/due-date machinery in OSS; payment-collecting surfaces respect `amount_due_at_checkout` + `max_amount`.
+- `6.1-order-stages.md` — Merchant-composed order stages (design finalized 2026-08-30; **stages are data, statuses stay code** — the doctrine ruling): store-scoped `Spree::OrderStage` rows (acts_as_list, `customer_visible` flag, optional **auto-enter event binding** from the `Spree.order_stage_events` registry — event-driven labeling, never gating) composed visually in a dashboard settings page; `spree_orders.order_stage_id` (nullable) + `expected_ready_on` (order-level merchant promise — distinct from variant `preorder_ships_at` supply fact and fulfillment `estimated_delivery_at` carrier truth); `Orders::SetStage` is the single writer (manual select or binding subscriber), publishes `order.stage_changed` (automation rides events); store serializer shows the stage only when visible + a progress indicator over the visible ordered subset. **No transition graph ever; stages carry zero commerce semantics** — nothing in checkout/payments/stock/fulfillment may branch on `order_stage_id`; a needed GATE is a code status/workflow validation, never a stage; no per-store vocabularies on `has_status` models (statuses are process-global code); `Order` deliberately NOT migrated to `has_status`. No platform offers composed stages (nearest: display labels pinned to fixed states, or code-config state machines) — OSS first.
+- `6.1-b2b-order-documents.md` — Order Documents area + logistics prints (design finalized 2026-08-30): `Spree::OrderDocument` (order-nested uploads, private storage + spoofing protection, per-document `customer_visible` default false, buyer uploads allowed, `po_document` keeps its dedicated semantic slot) + two client-side HTML prints extending the shipped packing-slip pattern — carton/pallet/CBM **packing list** off the frozen freight summary, **payment-instructions sheet** off the terms schedule + bank reference. **No invoice vocabulary in OSS** (no model/number/document named invoice, no PDF stack — numbered proforma/commercial docs are Enterprise invoicing); order-facing files go through `OrderDocument` or a dedicated semantic slot, never loose attachments; prints render `po_number` + payment reference when present.
+- `6.1-order-change-substrate.md` — `Spree::OrderChange` + `Spree::OrderChangeAction`: one preview-then-apply substrate behind every post-placement mutation (admin order edits, returns, exchanges, claims — **draft orders excluded**: Phase 5 superseded 2026-08-30, the substrate is strictly post-placement; drafts are directly mutable with no balance to settle, and edit screens may share components but only placed orders create OrderChange rows), replacing four per-domain draft models with one `begin → request → confirm → cancel` lifecycle. Actions are typed `kind` + concrete FKs (never polymorphic); **preview is computed in memory and never persisted**; confirm is a workflow with the balance settlement as an `external_step`. Deliberately 6.1 — new schema + new extension API, and 6.0 already carries the Cart/Order split, typed adjustments and the returns rework. **Resolved 2026-08-10:** a change set belongs to one `Order`, never an `OrderGroup` (multi-seller edits = N change sets, each settling against its own order); a pending change set does **not** hold stock (`add_item` takes stock at confirm — reservations are checkout-scoped and would have no expiry trigger here). Phase 3 replaces the **6.0 order edit screen** (`/orders/$orderId/edit`) — quantities as inputs, `x` marks a row removed, Save applies the batch (**reshaped 2026-08-11**, reversing the original immediate-write rule); Phase 3 adds `begin`/preview/`confirm` behind the Save/Discard it already has. 6.0 constraints: don't **persist** a draft/preview model (transient React form state is fine and is the shape the substrate wants), don't compute projected totals client-side to fake a preview, expose post-placement money math through a service returning a value object, and keep line-item mutation on the edit screen rather than the fulfillment card. Known gap: the batch save is not atomic (no bulk endpoint; Phase 3's `Confirm` fixes it in one transaction). **Applier rulings (2026-08-30):** appliers never derive unit prices (a `price_source: 'manual'` line comes through an amendment untouched); a post-placement price change is its own future action kind (`update_item_price`), never a discount abused as one.
- `6.0-payment-method-rules.md` — `Spree::PaymentMethodRule` STI on PaymentMethod (Channel / Market / OrderTotal / CustomerGroup rules), mirroring the PromotionRule/PriceRule/OrderRoutingRule pattern. Enforced solely through `Order#collect_frontend_payment_methods` (listing + `Payments::Create` + payment sessions all flow through it); admin/backoffice bypasses; no rules = available everywhere. Dashboard-only management (nested Admin API CRUD + `/payment_method_rules/types` discovery). Supersedes the "no distribution concept" rationale in `5.6-6.0-single-store-promotions-payment-methods.md`; per-channel provider credentials (multiple Stripe accounts, multi-entity setups) explicitly deferred for grooming — see decisions.md 2026-07-23.
- `6.0-channel-delivery.md` — **Implemented in PR #14404 (2026-08-09).** Optional Channel→StockLocations allowlist (`spree_channel_stock_locations`, empty = all): constrains which fulfillment origins serve a channel's traffic, enforced origin-side (Coordinator allocation + pickup discovery intersect `Channel#serves_location?`) — never on profiles/groups (channel constraint composes from outside; Medusa-shaped transitive delivery). `preferred_stock_location_id` must be a served location. **Per-channel rates** are a separate axis: `DeliveryMethodRules::ChannelRule` (STI, beside ItemTotal/Weight/ExcludedProducts) gates which methods a channel is *offered* from origins it already reaches — origins decide whether a channel can be served, rules decide what it sees.
- `6.0-channel-markets.md` — Optional Channel→Markets allowlist (`spree_channel_markets` join, empty = all markets). Enforced in market resolution (`set_market_from_country` + channel-aware `Spree::Current.market` fallback), channel-filtered Store API `/store/markets`, and order-level `market must be served by channel` validation. Composes with `MarketRule` from the payment-method-rules plan.
@@ -76,7 +86,7 @@ Pending design work (drafts, no implementation yet):
- `6.1-exchange-rates.md` — `Spree::ExchangeRate` + `ExchangeRateProvider` (ECB feed as the credential-free default, registry copied from `tax_providers`/`delivery_rate_providers`, keyed providers via `Spree::Integration`). **Rates fill fields, they never price anything** — a merchant gets editable suggestions for the other currencies and what persists is a plain number they own; Spree's "one explicit amount per currency, no FX" stance is unchanged. Never at charge time: EU VAT Directive Art. 91 pins the rate to the instant VAT becomes chargeable, so a commission invoice's VAT figure must be frozen with its rate/date/source or the platform cannot reproduce its own filed documents (Shopify converts at capture and is the wrong pattern here; Vendure/Medusa/Saleor never convert in core). Rates are stored historically and looked up **most-recent-on-or-before**, never exact-date (the ECB skips weekends); cross-currency derives through the base per Art. 91, never stored as a third row; rate precision is NOT money's `decimal(_,2)`. **Constraints now:** never set `Money.default_bank` or call `exchange_to` (the empty rate store raising `UnknownRate` is correct); new money configuration is born per currency, never one amount + a currency column; no conversion endpoint on any API. Also records two live promotion bugs found while researching it — `Calculator::FlatRate` silently discounts **zero** on a currency mismatch, and `Promotion::Rules::ItemTotal` stores a bare threshold with no currency — both independent of this feature.
Shipped plans:
-- `6.0-b2b-companies-and-catalogs.md` — B2B companies as a **multi-level organization tree** + Catalogs pulled into 6.0 (**implemented 2026-08-25**; replaced the unreleased Company→CompanyLocation→CompanyContact prototype outright — migrations rewritten in place, no bridges). One `spree_companies` table: self-referential `parent_id`, `kind` = `company` (legal entity) | `division`, depth capped at `MAX_DEPTH` (5), roots must be `company`; **`#legal_entity` (nearest self-or-ancestor company node) is the single tax anchor** — TaxIdentifier/TaxExemptionCertificate refuse division owners, and purchases read `company_legal_entity`, never the node. `CompanyAddress` (owned rows, labeled, one default per kind via Channel-style demotion + partial index), `CompanyMembership` (always customer-backed; standing = node + subtree, checked via `Customer#standing_for?`/`company_standing(store:)` — never node equality), `CompanyInvitation` (plaintext token, 30-day expiry, pending-scoped uniqueness; mail in `spree/emails`, acceptance via `CompanyInvitations::Accept` running `Customers::Create`; both member-adding surfaces converge on `Companies::AddMember` by email). Carts/orders carry `company_id` (any node; cart-side standing validation, sole-membership resolution in `resolved_company`, frozen at completion). **Catalogs:** `Catalog` (assortment + optional PriceList) + `CatalogProduct` (membership only — **no position**: a catalog decides what a buyer sees, never the order they see it in; category/collection membership stays positioned) + polymorphic `CatalogAssignment` (CustomerGroup|Company — buyer audiences only, company assignments cover the subtree; narrowed 2026-08-28 from the original four: Channel/Market were write-only — a channel's catalog is `spree_channels.default_catalog_id`, a market catalog returns only with a designed regional-assortment reader); visibility = `Products::ForContext` (union of effective catalogs, wired into the store products listing), pricing = catalog price lists nearest-node-first in `Pricing::Resolver` (catalog-bound lists excluded from generic rule matching — a rule-less list must not leak to everyone). Store API self-service (`/store/account/companies`, `/store/companies/*`, unauthenticated invitation lookup/accept, writable cart `company_id`) authorizes by **standing + `Storefront::AccessPolicy`** (company branch answers yes for any member — OSS has no company roles; Enterprise narrows via the policy class + checkout hooks). Dashboard: lazy tree list, node page (sub-units/members+invitations/address book; tax cards hidden on divisions), catalogs pages; slots renamed `company_membership.*`, `company.form_*` only. **Constraints:** never reference the deleted location/contact models; no governance fields on OSS models; `kind` stays the fixed two (divergence = STI, never a second table); catalog/company lookups store-scoped including incidental ids.
+- `6.0-b2b-companies-and-catalogs.md` — B2B companies as a **multi-level organization tree** + Catalogs pulled into 6.0 (**implemented 2026-08-25**; replaced the unreleased Company→CompanyLocation→CompanyContact prototype outright — migrations rewritten in place, no bridges). One `spree_companies` table: self-referential `parent_id`, `kind` = `company` (legal entity) | `division`, depth capped at `MAX_DEPTH` (5), roots must be `company`; **`#legal_entity` (nearest self-or-ancestor company node) is the single tax anchor** — TaxIdentifier/TaxExemptionCertificate refuse division owners, and purchases read `company_legal_entity`, never the node. `CompanyAddress` (owned rows, labeled, one default per kind via Channel-style demotion + partial index), `CompanyMembership` (always customer-backed; standing = node + subtree, checked via `Customer#standing_for?`/`company_standing(store:)` — never node equality), `CompanyInvitation` (plaintext token, 30-day expiry, pending-scoped uniqueness; mail in `spree/emails`, acceptance via `CompanyInvitations::Accept` running `Customers::Create`; both member-adding surfaces converge on `Companies::AddMember` by email). Carts/orders carry `company_id` (any node; cart-side standing validation, sole-membership resolution in `resolved_company`, frozen at completion). **Catalogs:** `Catalog` (assortment + optional PriceList) + `CatalogProduct` (membership only — **no position**: a catalog decides what a buyer sees, never the order they see it in; category/collection membership stays positioned) + polymorphic `CatalogAssignment` (CustomerGroup|Company — buyer audiences only, company assignments cover the subtree; narrowed 2026-08-28 from the original four: Channel/Market were write-only — a channel's catalog is `spree_channels.default_catalog_id`, a market catalog returns only with a designed regional-assortment reader); visibility = `Products::ForContext` (union of effective catalogs, wired into the store products listing), pricing = catalog price lists nearest-node-first in `Pricing::Resolver` (catalog-bound lists excluded from generic rule matching — a rule-less list must not leak to everyone). Store API self-service (`/store/account/companies`, `/store/companies/*`, unauthenticated invitation lookup/accept, writable cart `company_id`) authorizes by **standing + `Storefront::AccessPolicy`** (company branch answers yes for any member — OSS has no company roles; Enterprise narrows via the policy class + checkout hooks). Dashboard: lazy tree list, node page (sub-units/members+invitations/address book; tax cards hidden on divisions), catalogs pages; slots renamed `company_membership.*`, `company.form_*` only. **Constraints:** never reference the deleted location/contact models; no governance fields on OSS models; `kind` stays the fixed two (divergence = STI, never a second table); catalog/company lookups store-scoped including incidental ids. **Amended 2026-08-30 (one-question-per-entity doctrine — decisions.md):** the Catalog is the **commercial agreement** — it grows commercial terms (catalog-level `minimum_order_quantity`/`order_multiple` columns + per-variant override rows + per-currency order minimums, owned by `6.0-b2b-quantity-rules.md`); the list binding **inverts** to `spree_price_lists.catalog_id` (a list is standalone or owned by ONE catalog; generic rule matching skips owned lists by FK — the shipped active-catalogs-only derived set leaked a deactivated catalog's rule-less list to the whole store); `PriceRules::CustomerGroupRule`/`UserRule` deprecated (bridge + data task → assortment-less catalogs), `PriceRules::ChannelRule` grandfathered (kept working, nothing new builds on it — forward path is the channel's default catalog); dashboard goes catalog-first with one-go setup (inline `price_list` payload on catalog create/update, products-with-prices view). Implementation extracted to `6.0-catalog-agreement-rework.md` (Draft).
- `5.4-store-api-bridges.md` — Bridge 6.0 naming into 5.4 Store API (PR #13782)
- `5.4-spree-starter-and-create-spree-app.md` — Replace monorepo server/ with spree-starter template repo
- `5.4-option-type-enhancements.md` — `kind` (dropdown/color_swatch/buttons) on OptionType + `color_code` on OptionValue
diff --git a/docs/plans/6.0-6.1-b2b-payment-terms.md b/docs/plans/6.0-6.1-b2b-payment-terms.md
new file mode 100644
index 0000000000..839ae0a81f
--- /dev/null
+++ b/docs/plans/6.0-6.1-b2b-payment-terms.md
@@ -0,0 +1,143 @@
+# B2B Payment Terms, Deposits Schedule & Bank Transfer References
+
+**Status:** Draft — design finalized 2026-08-30, nothing built
+**Target:** Spree 6.0 (terms snapshot + fixes, riding the wholesale deposit work) / 6.1 (named terms, company assignment, bank transfer method, pay-balance)
+**Depends on:** B2B Wholesale Shipping (6.0-b2b-wholesale-shipping.md — deposit collection, amended 2026-08-30), B2B Companies (6.0-b2b-companies-and-catalogs.md), Customer PO Numbers (6.0-b2b-customer-po-numbers.md), Document Numbers (6.0-document-numbers.md)
+**Author:** Damian + Claude
+**Last updated:** 2026-08-30
+
+## Summary
+
+Spree already understands order total, payment total and outstanding balance —
+and multiple partial payments against one order work today (each capped at the
+outstanding balance, `partially_paid` derived automatically, the dashboard
+add-payment dialog is the "record the wire" UI). What's missing is the
+commercial layer: *how much is due now*, *what the agreed terms are*, and a
+*reconciliation-grade payment reference* for bank transfers. This plan adds
+**deposit-style payment terms** (collect-first: 100% prepayment, N% deposit +
+balance-before-X) as a frozen order snapshot resolved from layered sources, a
+derived **payment schedule** ("Deposit due $8,000 → Deposit paid ✓ → Balance
+$12,000 — due before shipping"), a real **`PaymentMethod::BankTransfer`** with
+structured, stored, searchable **payment references** (no commerce platform
+generates these natively — only one PSP does), and the storefront
+**pay-the-balance** route. Ship-first terms (Net 7/30/60, credit accounts,
+invoicing, due dates, dunning) remain **Enterprise roadmap item #1** — the
+tier line is risk: collecting before shipping is OSS mechanics, extending
+credit is the commercial instrument (decided 2026-08-30).
+
+## Key Decisions (do not deviate without discussion)
+
+- **One `payment_terms` snapshot on the order, layered sources**
+ (2026-08-30, interactive review — amends the wholesale plan): the cart
+ resolves `{kind, deposit_percentage, balance_due_label, source}` from
+ **quote/order override → company terms → the freight method's deposit
+ preferences → none (pay in full)** and the order freezes the copy at
+ placement — agreed terms survive later changes to the company default,
+ exactly like negotiated prices. The wholesale plan's method-level
+ `deposit_percentage` is demoted from anchor to *default source*;
+ `Cart#amount_due_at_checkout` now reads the snapshot. Same resolution
+ shape as `capture_method`.
+- **`Spree::PaymentTerm` is a store-scoped named preset** (6.1): `name`
+ ("40% Deposit / 60% Before Shipping"), `kind` (`prepaid | deposit` — a
+ `class_attribute` vocabulary Enterprise extends with `net`),
+ `deposit_percentage`, `balance_due_label`. Companies reference one
+ (`payment_term_id`, nullable); the order snapshot copies **values, never
+ the reference** — a renamed preset must not rewrite history.
+- **The balance-due moment is a label, not automation** (the merchant's own
+ framing): `balance_due_label` ("Before shipping", "Before dispatch") is
+ recorded and displayed; real due *dates* arrive with Enterprise net
+ terms. OSS derives the **payment schedule** on read — due-now amount,
+ deposit state (due / paid), outstanding balance, the label — exposed on
+ store + admin serializers; nothing persisted, `Orders::UpdateStatuses`
+ stays untouched (its `partially_paid` already tells the ledger truth;
+ the schedule tells the commercial truth).
+- **`PaymentMethod::BankTransfer` joins core** (6.1) beside
+ `PaymentMethod::Check`: an offline method whose account details and
+ instruction lines are public preferences (the `public_preference_keys`
+ mechanism — labels configurable because banking fields differ by
+ country), shown at checkout, in order mails and on the
+ payment-instructions print.
+- **Every payment gets a stored, generated `reference`** (6.1): unique,
+ ransackable, created with the payment (structured creditor-reference
+ style — RF/ISO 11649 check-digits over the payment's prefixed id — so a
+ bank statement line matches exactly one payment). This is deliberately a
+ **stored column**, never the derived `R1001-P1` number: derived numbers
+ shift when a sibling is destroyed (the code's own idempotency warning)
+ and their column is NULL on 6.0 rows — which is also why the derived
+ number quietly broke search and the Stripe gateway's `find_by(number:)`
+ lookup. **6.0 fixes**: the misleading `number` ransack whitelist entry
+ is removed and the gateway lookup corrected; 6.1's `reference` becomes
+ the reconciliation identifier the dashboard searches alongside order
+ and PO numbers.
+- **Storefront pay-balance** (6.1): `POST /store/orders/:id/payments` /
+ payment sessions on a placed order, owner-authorized, amount capped by
+ the existing `max_amount` validation — resolves the wholesale plan's
+ open question 1. The deprecated `Payments::Create` service is not
+ touched (nothing calls it; removed in 7.0).
+- **PO and terms stay separate** (merchant point 10, already our stance):
+ a PO authorizes the purchase buyer-side; terms say when the merchant
+ requires payment. No coupling anywhere.
+
+## Design Details
+
+- Snapshot storage: `payment_terms` jsonb on `spree_carts` +
+ `spree_orders` (nil = pay in full — today's behavior); resolved by the
+ cart, copied at completion with the purchase fields. Serializers expose
+ the snapshot and the derived schedule
+ (`{amount_due_now, deposit_amount, deposit_paid, outstanding_balance,
+ balance_due_label}`).
+- `Carts::Complete` validates payments against `amount_due_at_checkout`
+ (already the wholesale design — unchanged, just re-sourced); the
+ invoice-later `payment_pending:` path composes as before.
+- Company: `payment_term_id` on `spree_companies` (admin form + serializer);
+ Enterprise's quote flow writes the order-level override
+ (`b2b-quotes.md` shows terms on the quotation and acceptance freezes
+ them via placement — no quote-side fields).
+- Bank reference surfaces: checkout confirmation + order mails ("Amount to
+ pay now: $8,000 · Reference: RF71-…"), the payment-instructions print
+ (`6.1-b2b-order-documents.md`), dashboard payment rows + the combined
+ reference search (order number / PO number / payment reference).
+
+## Migration Path
+
+1. **6.0** (with wholesale phase 7): `payment_terms` jsonb + resolution
+ (method source only), `amount_due_at_checkout` re-sourced, schedule
+ value object + serializers; the `number` ransack/Stripe lookup fixes.
+2. **6.1**: `Spree::PaymentTerm` + company assignment + dashboard settings
+ page; snapshot source layering completed; `PaymentMethod::BankTransfer`;
+ payment `reference` column + generation + search; store pay-balance
+ route + storefront balance UI.
+
+## Constraints on Current Work
+
+- **Terms are read from the order snapshot, never re-resolved** from
+ company/method after placement.
+- **Nothing durable keys on the derived payment number** (`R1001-P1` is
+ display + gateway `order_id` only); reconciliation identifiers are the
+ stored `reference`.
+- **No net-terms/credit/due-date machinery in OSS** — `kind` values beyond
+ `prepaid | deposit` and anything invoice-shaped belong to the Enterprise
+ terms plan.
+- New payment-collecting surfaces must respect `amount_due_at_checkout`
+ vs. full total per the snapshot, and the existing `max_amount` cap.
+
+## Open Questions
+
+1. **Progress payments** (30/30/40 three-stage schedules) — the payment
+ model supports arbitrary partials already; whether the *terms*
+ vocabulary grows multi-stage schedules is deferred until real demand
+ (Enterprise terms likely owns it).
+
+## References
+
+- Merchant feedback, 2026-08 (terms by company; deposit calculation;
+ balance-due label; terms frozen on order; bank/TT references;
+ multiple payments; payment due status; net terms; PO separation).
+- `docs/plans/6.0-b2b-wholesale-shipping.md` — deposit collection
+ (amended: method deposit is now a source).
+- `spree-enterprise-v2/docs/plans/b2b-companies.md` — terms/invoicing
+ roadmap (the `net` kind's home); `b2b-quotes.md` — terms on quotations.
+- Payments machinery: `spree/core/app/models/spree/payment.rb`
+ (`max_amount`), `app/services/spree/orders/update_statuses.rb`
+ (`partially_paid`), `payment/gateway_options.rb` (derived-number
+ warning), `payment_method/check.rb` (offline method precedent).
diff --git a/docs/plans/6.0-b2b-companies-and-catalogs.md b/docs/plans/6.0-b2b-companies-and-catalogs.md
index 7a730b41ff..31acf487b1 100644
--- a/docs/plans/6.0-b2b-companies-and-catalogs.md
+++ b/docs/plans/6.0-b2b-companies-and-catalogs.md
@@ -4,7 +4,59 @@
**Target:** Spree 6.0
**Depends on:** `6.0-channels-catalogs-b2b.md` Phase 1 (Channels, shipped 5.5) + Phase 1.5 (gated storefront access, shipped 5.6); `6.0-tax-provider.md` Phases 3–7 (tax identifiers, exemption certificates, `ResolveExemptions` — shipped); PriceList system (existing)
**Author:** Damian + Claude
-**Last updated:** 2026-08-25
+**Last updated:** 2026-08-30
+
+> **Amendment (2026-08-30) — the Catalog is the commercial agreement.**
+> *Implementation of consequences 2–4 is tracked in its own plan,
+> `6.0-catalog-agreement-rework.md` (Draft) — extracted 2026-08-30 so this
+> plan's Implemented status stops hiding unbuilt work.* The
+> one-question-per-entity doctrine (decisions.md 2026-08-30) settles how the
+> three targeting entities relate: **Channel answers where the buyer is
+> shopping** (publications, key binding, routing, stock allowlist, access
+> gating — gating stays as Channel preferences because it must bind before
+> identity exists), **Catalog answers what this buyer's agreement is**, and
+> **PriceList answers what the numbers are**. Four consequences amend this
+> plan:
+>
+> 1. **Catalog grows commercial terms** — catalog-level
+> `minimum_order_quantity` + `order_multiple` columns with per-variant
+> override rows, and per-currency order minimums, resolved per-field
+> nearest-agreement-wins through `Catalog.for_context`; a terms-only
+> catalog (empty assortment, no list) is legitimate. Owned by
+> `6.0-b2b-quantity-rules.md`.
+> 2. **The list binding inverts: `spree_price_lists.catalog_id` replaces
+> `spree_catalogs.price_list_id`.** A price list is standalone
+> (rule-matched) or owned by exactly one catalog; generic matching skips
+> owned lists by the FK, which closes a leak in the shipped derived-set
+> approach — `Catalog.bound_price_list_ids` reads **active** catalogs
+> only, so deactivating a catalog dropped its (typically rule-less) list
+> back into generic matching for the whole store. Detaching becomes an
+> explicit act with a dashboard warning. One catalog serving several
+> audiences via assignments replaces the lost list-sharing-across-catalogs.
+> 3. **Audience-shaped price rules are deprecated**:
+> `PriceRules::CustomerGroupRule` and `PriceRules::UserRule` duplicate
+> catalog assignment with different precedence; 6.0 deprecates them with
+> the standard one-release bridge and a data task that converts each such
+> list into an assortment-less catalog (assigned to the group; a `UserRule`
+> list maps to a single-member customer group) owning the list.
+> `PriceRules::ChannelRule` is **grandfathered** — kept working, nothing
+> new builds on it; a channel's pricing story is its default catalog
+> (which may own an assortment-less list). `MarketRule` and `VolumeRule`
+> are context-shaped and stay first-class.
+> 4. **The dashboard flow inverts to catalog-first, and setup is one go.**
+> The catalog page becomes the agreement editor: audience assignments,
+> assortment, pricing card (its owned list inline — fixed rows or the
+> automatic ±% adjustment from `6.0-price-list-automatic-pricing.md`),
+> and terms; plus a products-with-prices view that shows, per product,
+> assortment membership and the resolved price with its source
+> (explicit / automatic / base) — making assortment↔pricing divergence
+> visible instead of discoverable-by-accident. Creating a catalog
+> creates its price list in the same flow — the New catalog form takes
+> name, audience, assortment, and a pricing choice (base prices / ±%
+> adjustment / fixed prices), and the admin catalogs create/update
+> endpoints accept an inline `price_list` payload for the owned list so
+> the whole agreement is one submission; merchants never visit the
+> price-lists page to stand up a catalog.
## Summary
diff --git a/docs/plans/6.0-b2b-company-self-registration.md b/docs/plans/6.0-b2b-company-self-registration.md
new file mode 100644
index 0000000000..1efa54782e
--- /dev/null
+++ b/docs/plans/6.0-b2b-company-self-registration.md
@@ -0,0 +1,176 @@
+# B2B Company Self-Registration & Activation Mechanisms
+
+**Status:** Draft — design finalized 2026-08-30, nothing built
+**Target:** Spree 6.0 (retargeted 2026-08-30, sequencing review — originally 6.1 on the additive test, pulled forward because the Enterprise onboarding product must ship on 6.0 GA and these mechanisms are its only missing input; every piece remains additive and small)
+**Depends on:** B2B Companies & Catalogs (6.0-b2b-companies-and-catalogs.md), B2B Quantity Rules (6.0-b2b-quantity-rules.md — catalog terms), gated storefront access (shipped 5.6)
+**Author:** Damian + Claude
+**Last updated:** 2026-08-30
+
+## Summary
+
+The B2B flow has no front door: there is no storefront way for a business to
+register itself (`/store/companies` is show + update only), and no way for a
+merchant to gate pricing on having a commercial relationship. This plan adds
+the **open-source mechanisms**: storefront company self-registration, an
+`approval_required` storefront access posture ("prices and checkout require
+an active company standing"), a machine-readable `pricing_access` reason
+code beside hidden prices, and a registered **company activation policy**
+consulted everywhere a company's commercial standing matters. In OSS the
+default policy activates every company, so registration is instant and the
+posture means "company members only" — a useful trade-store feature on its
+own. The merchant-approval *flow* (pending applications, verification
+requirements, review queue, request-more-information) is the Enterprise
+onboarding product built on these mechanisms (tier split decided 2026-08-30
+— see `spree-enterprise-v2/docs/plans/b2b-company-onboarding.md`; no
+competitor ships approval in open source, and everyone who has it charges
+for it).
+
+## Key Decisions (do not deviate without discussion)
+
+- **Registration is OSS and companies are born active** (2026-08-30, tier
+ split): `POST /api/v3/store/companies` lets an authenticated customer —
+ including an existing retail customer — create a root company (kind
+ `company`) plus their own membership in one call; a guest storefront
+ chains `POST /store/customers` first so the UX is one flow. Free-form
+ registration answers land in `metadata['registration']`. Rate-limited
+ like customer registration. Core publishes `company.registered` and sends
+ no mail.
+- **`Spree::Companies::ActivationPolicy` is the single seam** (2026-08-30):
+ a dependency-registered class
+ (`Spree::Dependencies.company_activation_policy_class`, mirroring
+ `storefront_access_policy_class`) answering `active?(company)` and
+ `pricing_access_code(user:, store:)`. The OSS default answers active for
+ every company. Every place that resolves a company for **visibility,
+ pricing, or checkout** consults it: `Catalog.for_company`, both
+ `sole_standing_company` implementations (`Purchase::Company` and
+ `Products::ForContext` — mirrored, by existing constraint), the cart
+ `company_id` write validation, and the `approval_required` posture.
+ Subtree semantics (a suspended parent covering its divisions) are the
+ policy implementation's job, which is why the seam takes the node.
+- **No status column on `spree_companies` in OSS.** The lifecycle
+ (pending / review / approved / rejected / suspended, the requirements
+ checklist, the queue) lives on an Enterprise-owned application record
+ referencing the company — OSS tables never reference Enterprise models,
+ and OSS behavior flows entirely through the policy. This supersedes the
+ same-day draft that put five statuses on Company.
+- **A fourth storefront access posture: `approval_required`** (2026-08-30):
+ beside `public | prices_hidden | login_required`. Guests and
+ authenticated buyers without a standing over a policy-active company
+ browse the catalog with prices null and checkout refused; `prices_hidden`
+ keeps its shipped guest-only semantics untouched. Under the default
+ policy this reads as "prices for company members only"; under the
+ Enterprise policy it becomes "prices for approved companies only".
+- **A reason code travels with hidden prices.** Serializers today null
+ prices with no explanation. The gating concern computes `pricing_access`
+ — `null` (visible) | `login_required` | `company_required` | codes the
+ registered policy supplies (Enterprise adds `approval_pending`) —
+ surfaced wherever prices are nulled, following the checkout-requirements
+ `code:` convention; the channel serializer also exposes
+ `storefront_access`. Storefronts render "Awaiting approval" / "Register
+ your business" from the code, never by interpreting bare nulls.
+- **Checkout is gated by a requirement, standing is not gated at all.** A
+ new checkout requirement (`company_activation_required` code) refuses
+ customer-initiated completion on `approval_required` channels without a
+ policy-active cart company — same shape as `guest_checkout_not_allowed`.
+ Self-service standing (`standing_for?`, `company_standing`,
+ `Storefront::AccessPolicy`) never consults the policy: members of an
+ inactive company keep their company pages, address book, members and
+ invitations — that is the pre-approval workspace the Enterprise flow
+ needs.
+- **Customer-group membership is never an activation mechanism** — groups
+ price (catalog assignments), the policy activates. The seeded Wholesale
+ group's "approval primitive" comment is retired with this plan.
+
+## Design Details
+
+### Registration
+
+`Companies::Register` workflow (`hooks :validate, :after_register`):
+builds the root node + membership in one transaction, stamps
+`metadata['registration']`, publishes `company.registered`. The `validate`
+hook is the screening point (domain rules, fraud checks — host or
+Enterprise handlers); it does NOT fire on `CompanyInvitations::Accept`
+(joining an existing company is not founding one), while `Customers::Create`
+hooks keep firing on both paths as today. Controller:
+`POST /store/companies` (authenticated, rate-limited); the account
+companies index and company serializer are unchanged except where the
+policy adds codes.
+
+One open guard: at most one self-registered root per customer per store
+(validation in `Register`) — keeps duplicate applications out without a
+uniqueness constraint on names.
+
+### Activation policy
+
+```ruby
+class Spree::Companies::ActivationPolicy
+ # Whether the company may act commercially (catalogs, pricing, checkout).
+ def active?(_company) = true
+
+ # The pricing_access code for a viewer lacking prices, or nil.
+ def pricing_access_code(user:, store:)
+ return 'login_required' if user.blank?
+ 'company_required' unless user.company_standing(store: store).any? { |c| active?(c) }
+ end
+end
+```
+
+Consulted (all existing call sites, no new resolution paths):
+`Catalog.for_company` (assignments of active companies only), both
+`sole_standing_company`s (memberships of active companies only),
+`customer_has_standing_over_company` (cart write gains a distinct
+`:not_active` error), the posture + checkout requirement. Completed orders
+answer from their stamped `company_id`, untouched.
+
+### Gating
+
+`Channel::Gating::STOREFRONT_ACCESS += ['approval_required']`; store-level
+fallback validation updated. `hide_prices?` becomes posture-aware; the
+`pricing_access` code rides `serializer_params` beside `hide_prices` and is
+exposed on the payloads that null prices.
+
+## Migration Path
+
+1. `ActivationPolicy` + dependency registration + the resolution call-site
+ consultations (behavior-neutral under the default policy — specs assert
+ that explicitly; shared-concern battery runs against Cart AND Order).
+2. `approval_required` posture + `pricing_access` code + checkout
+ requirement + serializer exposure.
+3. `Companies::Register` + `POST /store/companies` + SDK types + docs.
+4. Storefront reference: registration page + code-driven price labels.
+5. Retire the Wholesale-group seed comment.
+
+Nothing to migrate; every change is additive and inert until a merchant
+selects the posture or registers a policy.
+
+## Constraints on Current Work
+
+- **Any new code resolving a company for visibility, pricing, or checkout
+ consults the activation policy** — and the two `sole_standing_company`
+ implementations stay mirrored.
+- **Never approval-gate self-service standing.**
+- **New prices-hidden surfaces carry the `pricing_access` code** — no bare
+ nulls.
+- **No status/approval columns on `spree_companies`** — lifecycle state is
+ the Enterprise application record's; OSS asks the policy.
+- **Don't build interim approval primitives beside this mechanism** (customer-group
+ membership, boolean flags); anything approval-shaped waits for this
+ mechanism.
+
+## Open Questions
+
+None for the OSS scope. The flow-side questions (statuses, requirements,
+queue) belong to the Enterprise plan.
+
+## References
+
+- Merchant feedback, 2026-08 (register → browse "awaiting approval" →
+ verify → assign the agreement → ordering enabled).
+- Tier split + rationale: `docs/plans/decisions.md` 2026-08-30;
+ `spree-enterprise-v2/docs/plans/b2b-company-onboarding.md` (the flow).
+- `docs/plans/6.0-b2b-companies-and-catalogs.md` — tree, memberships,
+ self-service, `Catalog.for_context`.
+- Gating: `spree/core/app/models/spree/channel/gating.rb`,
+ `spree/api/app/controllers/concerns/spree/api/v3/storefront_gating.rb`.
+- Registration hook precedent:
+ `spree/core/app/workflows/spree/customers/create.rb`.
diff --git a/docs/plans/6.0-b2b-customer-po-numbers.md b/docs/plans/6.0-b2b-customer-po-numbers.md
new file mode 100644
index 0000000000..2ea750c692
--- /dev/null
+++ b/docs/plans/6.0-b2b-customer-po-numbers.md
@@ -0,0 +1,138 @@
+# B2B Customer PO Numbers
+
+**Status:** Draft — design finalized 2026-08-30, nothing built
+**Target:** Spree 6.0
+**Depends on:** Cart/Order split (6.0-cart-order-split.md), B2B Companies & Catalogs (6.0-b2b-companies-and-catalogs.md), Service Workflows (6.0-service-workflows.md — `Carts::Complete` validations)
+**Author:** Damian + Claude
+**Last updated:** 2026-08-30
+
+## Summary
+
+For corporate buyers their own purchase-order number is as important as the
+merchant's order number — it is how their accounting reconciles the order,
+the invoice and the payment years later. Spree doesn't need a procurement
+system for this; it needs to treat the buyer's PO as a first-class,
+permanent, searchable reference on the order. This plan adds `po_number` on
+cart + order (offered at B2B checkout and on draft orders, carried
+everywhere the order goes), an **optional PO document upload** (no platform
+ships this natively on orders — the only native attachment precedents
+anywhere are on quotes), and a per-company **required** flag. The field
+follows the market's best shape: always available and optional at B2B
+checkout (the biggest platform's approach — theirs has no configuration at
+all and can't even be made required natively), with requiredness hung on
+the **company** (the granularity both platforms that control it use), never
+on a payment method (two platforms tie the PO to an offline payment method,
+which couples a reference to a tender choice — deliberately not copied).
+
+Not to be confused with `Spree::PurchaseOrder` from
+`6.0-inventory-operations.md` — that is the merchant's *procurement* PO to
+suppliers, the opposite direction, its own model. The buyer's reference is
+a column named `po_number`, the industry-exact field name.
+
+## Key Decisions (do not deviate without discussion)
+
+- **`po_number` is a plain column on cart and order** (2026-08-30) —
+ copied at completion like the other purchase fields, exposed under the
+ same name on store and admin serializers (read/write symmetry). Never a
+ metafield, never payment-method data. The buyer sets it pre-completion;
+ **staff may set or correct it after placement** (a plain attribute write
+ — it is not money, and "the buyer forgot" is the common case both
+ reference platforms allow for).
+- **The field is always offered on B2B carts, optional by default**;
+ **`po_number_required` is a boolean on `Spree::Company`** (2026-08-30,
+ interactive review, after the platform research): where the market
+ controls this at all it does so per company, it is the merchant's
+ literal ask, and it is a property of the buyer's own procurement
+ process, not of the commercial agreement — so it is deliberately NOT a
+ catalog term. Not a governance field (it gates order data, not member
+ powers), so the no-governance-on-OSS-companies constraint holds.
+ Enforced in `Carts::Complete` as a validation (`code:
+ 'po_number_required'`) for customer-initiated checkouts; staff-created
+ orders skip it.
+- **PO document upload is optional and order-native** — `po_document` as a
+ private-storage attachment on cart + order (direct upload via signed
+ blob; spoofing-protected content-type validation per the
+ seller-submission precedent), the same blob re-attached to the order at
+ completion (blob sharing, the media-library precedent). A genuine
+ first — no competitor has it outside quote attachments.
+- **Searchable everywhere a reference is looked up.** `po_number` joins
+ the order's ransackable attributes, and the dashboard's order search
+ matches order number OR PO number — an accountant holding either
+ reference finds the same transaction. Surfacing: admin order page,
+ customer order history, order confirmation email (a line when present —
+ cheap differentiation: the biggest platform's own emails can't show it),
+ and every future order-facing document (invoices, packing lists) must
+ render it when present.
+- **Quotes read this field, not their own.** The Enterprise quote plan's
+ `customer_reference` and quote-level attachment are replaced by the
+ underlying draft order's `po_number` + `po_document` (amended
+ 2026-08-30) — one reference, no duplication, and "quotation → buyer
+ issues PO → order" is just filling the field before acceptance.
+- **Buyer-side PO permissions are Enterprise governance** — "only an
+ authorised buyer may submit the company's PO" is a capability on company
+ roles, the existing Enterprise plan's territory; nothing here prepares
+ or blocks it. Invoice-number linkage rides the Enterprise
+ terms/invoicing roadmap; OSS delivers the searchable reference and the
+ order↔payment linkage that already exists.
+
+## Design Details
+
+- Schema: `po_number` string on `spree_carts` + `spree_orders`;
+ `po_number_required` boolean (default false, null: false) on
+ `spree_companies`; Active Storage attachments (no Spree columns).
+- Writes: store cart update permits `po_number` + `po_document` (signed
+ blob id); admin order create/update permit both (draft orders — "a PO
+ arrives by email and the merchant keys the order in" is just the
+ existing draft flow plus these fields); admin company form + serializer
+ gain the flag.
+- Completion: `po_number` copies with the purchase fields;
+ `create_draft_order!`'s copy attaches the cart's blob to the order.
+ The `Carts::Complete` validation reads `resolved_company`.
+- Dashboard: PO field on the draft-order create form and order page
+ (editable, showing both references side by side; document
+ download/replace); orders list gains a PO column option + the combined
+ number-or-PO search; company page gets the requiredness toggle.
+- Storefront reference: PO input (+ optional file) at checkout for B2B
+ carts, marked required when the company demands it; order history shows
+ the reference.
+
+## Migration Path
+
+1. Schema + model (columns, attachment, validation, ransackable).
+2. API surfaces (store cart, admin orders, admin companies) + SDK types.
+3. `Carts::Complete` validation + email line.
+4. Dashboard + storefront surfaces.
+
+No data migration; empty fields are today's behavior.
+
+## Constraints on Current Work
+
+- **Never model the buyer's PO as a payment method** or couple it to
+ tender choice.
+- **`po_number` (buyer reference) and `Spree::PurchaseOrder` (merchant
+ procurement) never mix** — no shared endpoints, serializers, or UI
+ vocabulary between them.
+- Any new order-facing document or email renders `po_number` when
+ present.
+- Post-placement edits to `po_number` are staff-only plain writes — never
+ route them through the order-change substrate, and never let them touch
+ money.
+
+## Open Questions
+
+None for this scope. (Per-channel/store requiredness defaults can arrive
+later as a nullable tri-state on the company if merchants ask; noted, not
+built.)
+
+## References
+
+- Merchant feedback, 2026-08 (PO number + optional document, per-company
+ required flag, audit-trail searchability, PO-starts-an-order).
+- Platform research 2026-08-30 (field granularity, per-company control,
+ the payment-method anti-pattern, the upload gap) — private, not in this
+ repo.
+- `docs/plans/6.0-inventory-operations.md` — the *other* purchase order.
+- `spree-enterprise-v2/docs/plans/b2b-quotes.md` — amended to consume this
+ field.
+- Attachment precedents: seller requirement submissions (spoofing
+ protection), media library (blob sharing).
diff --git a/docs/plans/6.0-b2b-quantity-rules.md b/docs/plans/6.0-b2b-quantity-rules.md
new file mode 100644
index 0000000000..6a089af76b
--- /dev/null
+++ b/docs/plans/6.0-b2b-quantity-rules.md
@@ -0,0 +1,266 @@
+# B2B Quantity Rules (MOQ, Order Multiples, Purchase Unit)
+
+**Status:** Draft — design finalized 2026-08-30 (one-question-per-entity doctrine, decisions.md 2026-08-30), nothing built
+**Target:** Spree 6.0
+**Depends on:** B2B Wholesale Shipping (6.0-b2b-wholesale-shipping.md — packing chain on variants), B2B Companies & Catalogs (6.0-b2b-companies-and-catalogs.md), Extendable Validations (6.0-extendable-validations.md), Service Workflows (6.0-service-workflows.md)
+**Author:** Damian + Claude
+**Last updated:** 2026-08-30
+
+## Summary
+
+Wholesale products can't be purchased in arbitrary quantities. Two distinct
+rules govern how many units a buyer may order: a **minimum order quantity**
+(MOQ — the least a buyer may purchase) and an **order multiple** (the
+increment orders must land on, because the product is packed in multiples).
+MOQ 48 with multiple 24 means 48 / 72 / 96 / 120 are valid and 50 or 100 are
+not. On top of that, wholesale buyers think in **cartons, not units** — a
+merchant sells the SKU internally by unit but commercially by carton, so the
+storefront should offer "2 CTNS — 48 units / 3 CTNS — 72 units" rather than a
+1-2-3 stepper. Finally, merchants often require a **minimum for the whole B2B
+order** (an amount, e.g. $500) independent of any single SKU.
+
+This plan adds those rules as a purchasing layer over unchanged inventory:
+stock stays in units, `Stock::Quantifier` and availability are untouched, and
+the rules are enforced where quantities enter the cart — the `Carts::AddItem`
+/ `Carts::UpsertItems` workflows that already own item validation. It builds
+directly on the packing chain the wholesale-shipping plan puts on variants
+(`units_per_carton`, `cartons_per_pallet`), completing SKU → MOQ → Order
+Multiple → Carton → Pallet.
+
+## Key Decisions (do not deviate without discussion)
+
+- **Commercial terms live on the Catalog** (2026-08-30, one-question-per-
+ entity doctrine — decisions.md): the Catalog is the buyer's commercial
+ agreement (assortment + attached price list + terms), so both the
+ contextual quantity tiers (retail 1/1, small business 24/12, wholesale
+ 48/24, distributor 480/240 on the same SKU) and the cart-level order
+ minimum are **catalog data**, resolved through the existing
+ `Catalog.for_context` chain (nearest company node → customer groups →
+ the channel's default catalog). The channel-level minimum falls out for
+ free: the wholesale channel's *default catalog* carries the $500
+ minimum — no channel mechanism needed. Variant columns stay the base
+ rule for buyers who resolve no catalog terms.
+- **Catalog terms are typed tables per grain, never one generic
+ `catalog_rules` table or an STI rule family** (2026-08-30, review):
+ quantity rules are `(catalog, variant?) → integers` on the add-to-cart
+ hot path (indexed typed lookups, catalog-scale cardinality); minimums
+ are `(catalog, currency) → money` checked at completion with
+ DB-enforced per-currency uniqueness. One munged table is the polymorphic
+ `Adjustment` mistake the typed-adjustments split un-made; an STI rule
+ family is the wrong category — rules are matching *predicates* stored
+ as low-cardinality preference blobs (unindexable for the hot path, no
+ DB uniqueness), and giving catalogs a rules engine would reopen the
+ two-mechanisms ambiguity the one-question-per-entity doctrine closed.
+ A future term kind gets its own typed table under the same catalog
+ Terms surface.
+- **The catalog-wide default is a pair of columns on the catalog itself**
+ (2026-08-30, follow-up review — supersedes the same-day NULL-variant-row
+ sketch): `spree_catalogs` gains `minimum_order_quantity` +
+ `order_multiple`, and `spree_catalog_quantity_rules` is strictly the
+ per-variant override (`variant_id null: false`, one plain unique index —
+ no partial indexes, no MySQL fallback). Three-level symmetry, same
+ column pair at each level: variant base → catalog default → catalog ×
+ variant override; the catalog default costs no extra query (resolved
+ catalogs are request-memoized), and the dashboard edits it as ordinary
+ catalog form fields.
+- **Terms resolve per-field, nearest-agreement-wins** (2026-08-30): the
+ first catalog in resolution order that *defines* a field (a quantity row
+ for the variant, a minimum for the currency) wins that field; catalogs
+ that are silent on a field pass through. All-or-nothing resolution was
+ rejected — a distributor catalog with no stated minimum must not
+ silently waive the channel default's $500.
+- **No `ChannelRule` family — superseded same day** (2026-08-30): an
+ earlier draft of this plan introduced an STI rule family on Channel for
+ minimums and access gating. Dropped: with terms on the catalog, nothing
+ purchase-shaped is left for it, and access gating (`storefront_access`,
+ `guest_checkout`) **stays as the existing Channel preferences** — gating
+ must bind before the buyer has an identity, and catalogs resolve *from*
+ identity, so gating can never be catalog data. Order minimums are
+ **born per currency** (one row per currency on the catalog, per the
+ recorded no-FX constraint — never one amount plus a currency column).
+- **Inventory is never restated.** Quantities are stored, reserved, moved and
+ counted in units everywhere; cartons and pallets are a purchasing and
+ display vocabulary. No code below the cart layer may read these rules.
+- **Enforcement lives in the item workflows.** `Carts::AddItem` and
+ `Carts::UpsertItems` gain a quantity-rules validation as a named step (core
+ behavior, not a hook — hooks remain the host-app extension surface).
+ Storefront violations render the standard validation error naming the
+ nearest valid quantities; the admin order twin is unrestricted (staff can
+ always key in what the customer actually negotiated).
+- **The storefront rounds up, the server refuses.** The quantity selector
+ starts at the MOQ and steps by the multiple (or by cartons when the
+ purchase unit is carton); the API never silently rounds a submitted
+ quantity — an invalid quantity is a 422 with the valid neighbors in the
+ message. Silent rounding on a wholesale order is a five-figure surprise.
+- **Purchase unit is display vocabulary.** `purchase_unit` ∈ `unit | carton`
+ on the variant changes what the storefront and line-item serializers
+ present ("2 CTNS — 48 units"); the stored line-item quantity remains
+ units. Requires `units_per_carton`; validated together.
+- **Cart-level minimum is enforced at completion, not add-to-cart** — a
+ buyer must be able to build the order below the threshold and see how far
+ they are from it ("$180 to reach the $500 minimum"), so the check is a
+ `Carts::Complete` validation plus a computed shortfall the cart serializer
+ exposes.
+
+## Design Details
+
+### Variant rules
+
+```ruby
+# spree_variants gains:
+# minimum_order_quantity integer # nil = 1
+# order_multiple integer # nil = 1
+# purchase_unit string # 'unit' (nil) | 'carton'
+
+class Spree::Variant
+ def valid_order_quantity?(quantity)
+ quantity >= (minimum_order_quantity || 1) &&
+ (quantity % (order_multiple || 1)).zero?
+ end
+
+ def nearest_valid_quantities(quantity)
+ # the two neighbors used in the validation message and the stepper
+ end
+end
+```
+
+Validations on the variant: `order_multiple` must divide evenly into a
+declared `units_per_carton` when both are present (a multiple of 24 with
+20-unit cartons is a data error the merchant should hear about at edit time,
+not discover in a customer complaint); `purchase_unit: 'carton'` requires
+`units_per_carton`.
+
+The base columns bind every cart; the dual-audience SKU (retail 1/1,
+wholesale 48/24) is solved by catalog quantity rules (below).
+
+### Workflow enforcement
+
+- `Carts::AddItem` / `Carts::UpsertItems`: a `validate_quantity_rules` step
+ checks the *resulting* line quantity (an add of 24 onto an existing 24 is
+ 48 — valid), so increments compose. Rejections carry
+ `ActiveModel::Errors` per the extendable-validations contract; on the
+ storefront bulk path they ride the existing partial-success `warnings`
+ channel.
+- `Carts::Complete`: validates every line once more (rules may have changed
+ since the item was added) plus the cart-level minimum. Staff-created and
+ admin-completed orders skip both (same `created_by` pattern as return
+ eligibility).
+
+### Storefront quantity UX
+
+- The store variant serializer exposes the rules
+ (`minimum_order_quantity`, `order_multiple`, `purchase_unit`,
+ `units_per_carton`, `cartons_per_pallet`) so any storefront can build the
+ right selector without extra calls.
+- Reference storefront: +/- stepper stepping by the multiple, starting at
+ the MOQ; when `purchase_unit` is `carton`, the selector counts cartons and
+ shows the unit equivalent ("3 CTNS — 72 units"); line items display both.
+- Cart page shows the shortfall banner when a cart-level minimum applies and
+ is not yet met.
+
+### Catalog commercial terms
+
+```ruby
+# spree_catalogs gains the catalog-wide default (2026-08-30 follow-up):
+# minimum_order_quantity integer # nil = no catalog-wide rule
+# order_multiple integer
+#
+# spree_catalog_quantity_rules — strictly the per-variant overrides:
+# catalog_id bigint null: false
+# variant_id bigint null: false
+# minimum_order_quantity integer
+# order_multiple integer
+# unique index on (catalog_id, variant_id)
+
+# spree_catalog_order_minimums — the cart-level minimum:
+# catalog_id bigint null: false
+# currency string null: false
+# amount decimal(10,2), null: false
+# unique index on (catalog_id, currency)
+```
+
+- **Resolution — per-field, nearest-agreement-wins.** For a variant's
+ quantity rules: walk the cart's resolved catalogs in `Catalog.for_context`
+ order; within each catalog the variant override row beats the catalog's
+ own default columns; the first catalog defining the field wins; nothing
+ anywhere → the variant base columns. Same pair of column names at all
+ three levels. For the order minimum: the
+ first resolved catalog with a row for the cart's currency; none → no
+ minimum. A retail buyer resolves no catalogs and gets base behavior
+ untouched.
+- The resolution readers live beside the existing catalog machinery
+ (`Catalog.for_context` is already request-memoized via
+ `Spree::Current`), exposed as `Cart#quantity_rules_for(variant)` and
+ `Cart#order_minimum` / `#below_order_minimum?` /
+ `#order_minimum_shortfall` — computed, never stored.
+- `Carts::Complete` validates the minimum for customer-initiated checkouts;
+ staff-created orders skip it. Store cart serializer exposes the minimum,
+ whether it is met, and the shortfall; the store variant serializer
+ exposes the buyer's *resolved* quantity rules (base or catalog override)
+ so storefronts render the right stepper without knowing the mechanism.
+- **A terms-only catalog is legitimate**: empty assortment (which the
+ resolver already treats as "no visibility narrowing"), no price list,
+ just terms rows — that is how a channel's default catalog carries a
+ minimum without touching what anyone sees or pays.
+- Dashboard: the catalog page gains a Commercial terms card (per-currency
+ minimums + a paginated per-product quantity-override table); channel
+ gating settings are untouched.
+
+## Migration Path
+
+1. **Schema** — the three columns on `spree_variants` +
+ `spree_catalog_quantity_rules` + `spree_catalog_order_minimums`.
+2. **Variant model + validations**, serializer exposure (store + admin),
+ the three-write-paths permit for the new variant attributes
+ (duties-plan constraint).
+3. **Catalog terms** — the two term models, per-field resolution readers on
+ the cart, admin CRUD nested under `/admin/catalogs/:id`.
+4. **Workflow steps** — item workflows + completion checks (resolved
+ quantity rules + order minimum).
+5. **Dashboard** — a "B2B ordering" section beside the Carton section on the
+ variant sheet + bulk spreadsheet; catalog Commercial terms card.
+6. **Storefront** — selector, carton display, shortfall banner.
+
+Nothing to migrate: all columns start empty and empty means today's
+behavior (MOQ 1, multiple 1, unit display).
+
+## Constraints on Current Work
+
+- **Never read quantity rules below the cart layer** — no stock, allocation,
+ or fulfillment code may branch on MOQ/multiple/purchase-unit.
+- **Never silently round a submitted quantity** — refuse with the valid
+ neighbors.
+- **New item mutations keep routing through `AddItem`/`UpsertItems`**
+ (existing extendable-validations constraint) — that is what makes the
+ enforcement complete.
+- Carton/pallet packing data is owned by `6.0-b2b-wholesale-shipping.md`;
+ this plan reads it, never redefines it.
+- **Commercial terms are catalog data.** No purchase-term settings on
+ `Spree::Channel` (a surface's terms are its default catalog's) and no new
+ term columns on variants beyond the base rules — a new kind of term
+ starts as catalog rows resolved per-field through `Catalog.for_context`.
+- **Access gating stays on Channel** (`storefront_access`,
+ `guest_checkout`) — never move it to catalogs; gating binds before
+ identity exists.
+
+## Open Questions
+
+1. **Carton-denominated minimums** ("minimum 10 cartons per order") —
+ deferred; the amount minimum covers the common case, and a carton-count
+ minimum needs the freight summary at completion time anyway. (The
+ catalog/price-list ownership question this plan previously carried was
+ resolved 2026-08-30 by the one-question-per-entity doctrine —
+ decisions.md.)
+
+## References
+
+- Merchant feedback, 2026-08 (MOQ + order multiple; carton as the commercial
+ purchase unit; pallet quantities; per-catalog rule tiers; minimum B2B
+ order value).
+- `docs/plans/6.0-b2b-wholesale-shipping.md` — packing chain
+ (`units_per_carton`, `carton_weight`, `cartons_per_pallet`,
+ `PackageType`).
+- `docs/plans/6.0-extendable-validations.md` — `UpsertItems` contract,
+ partial-success warnings, `ActiveModel::Errors` rejections.
+- `docs/plans/6.0-b2b-companies-and-catalogs.md` — catalogs,
+ `Products::ForContext`, company on cart.
diff --git a/docs/plans/6.0-b2b-wholesale-shipping.md b/docs/plans/6.0-b2b-wholesale-shipping.md
new file mode 100644
index 0000000000..c9e23feb10
--- /dev/null
+++ b/docs/plans/6.0-b2b-wholesale-shipping.md
@@ -0,0 +1,433 @@
+# B2B Wholesale Shipping (Cartons, Pallets, Containers)
+
+**Status:** Draft — design finalized 2026-08-30, nothing built
+**Target:** Spree 6.0
+**Depends on:** Delivery Profiles (6.0-delivery-profiles.md), Delivery Method Rules (6.0-delivery-method-rules.md), Delivery Rate Provider (6.0-delivery-rate-provider.md), B2B Companies & Catalogs (6.0-b2b-companies-and-catalogs.md), Duties & Custom Fees (6.0-duties-and-custom-fees.md), Service Workflows (6.0-service-workflows.md)
+**Author:** Damian + Claude
+**Last updated:** 2026-08-30
+
+## Summary
+
+Wholesale orders don't ship like retail orders. A B2B purchase leaves the
+warehouse as cartons, a pallet, or a container — chosen by the total volume of
+the order — and for international freight the shipping price is usually quoted
+by a forwarder *after* the merchant reviews the order, not calculated at
+checkout. What the platform must do is different from parcel shipping: know how
+products pack into cartons, roll a cart up into logistics numbers (carton
+count, cubic meters, gross weight), classify the shipment into the right
+merchant-configured tier, let checkout complete without a shipping price, and
+collect the deposit the merchant's terms require for that shipment type.
+
+This plan adds that layer without touching retail shipping, so one catalog can
+serve both retail and wholesale buyers: a store-scoped **`Spree::PackageType`**
+model (boxes, cartons, pallets, containers — absorbing the four
+`default_package_*` store preferences), per-variant **carton details** (a
+reference to a carton-kind `PackageType` plus `units_per_carton` and packed
+gross weight), a **freight summary** rollup computed on the existing (currently
+unused) `Stock::Package#volume` chain, a **`DeliveryMethodRules::VolumeRule`**
+so shipment tiers are configuration on delivery methods rather than code,
+**unpriced delivery rates** — a first-class "freight quoted after review" rate
+carrying the logistics summary instead of a price — and **deposit collection at
+checkout**: a freight method can require an N% deposit, the buyer pays exactly
+that at completion, and the order tracks the outstanding balance until the
+merchant settles it (including the freight `Fee` added once the forwarder
+quotes).
+
+## Key Decisions (do not deviate without discussion)
+
+- **`Spree::PackageType` is the packaging vocabulary** (2026-08-30):
+ store-scoped rows, `kind` ∈ `box | envelope | carton | pallet | container`,
+ geometry (length/width/height + `dimensions_unit`), `max_weight`. It
+ replaces the four `default_package_*` store preferences — the store's
+ default shipping box becomes the store's default `PackageType` row (one
+ default per store), read through the existing single access point
+ (`Stock::Package#weight`/`#dimensions`), with the preferences kept as
+ deprecated one-release bridges. The name is deliberately NOT
+ `Spree::Package`: `Spree::Stock::Package` is the in-memory packing unit at
+ the heart of the estimator, and a persisted sibling with the same name
+ would be permanently confusing.
+- **Carton details live on a `PackageType` reference, not loose columns**
+ (2026-08-30, interactive review): `spree_variants` gains
+ `carton_package_type_id` + `units_per_carton` + `carton_weight`. Geometry
+ belongs to the shared carton row (merchants reuse standard carton sizes;
+ one edit fixes every product packed in that carton); packing facts that
+ vary per product — how many units fit, what a packed carton weighs — stay
+ on the variant. Accepted cost: the product editors need a carton picker
+ with inline create, and CSV/spreadsheet paths resolve cartons by name.
+- **Tier classification is a rule, not a calculator or a provider branch.**
+ `DeliveryMethodRules::VolumeRule` (min/max volume in CBM) drops in beside
+ `WeightRule`/`ItemTotalRule`; each shipment type (carton / pallet / 20ft /
+ 40ft) is an ordinary `DeliveryMethod` whose volume rule defines its range.
+ Eligibility hooks only in the Estimator filter chain, per
+ `6.0-delivery-method-rules.md`.
+- **No new delivery profile kind.** The same product ships parcel to a
+ consumer and carton to a wholesale buyer, and a product has exactly one
+ profile — so freight methods live on the regular shipping profile, gated by
+ buyer context (`ChannelRule`, and the new `CompanyRule`), not by product.
+- **Unpriced rates are first-class** (2026-08-30, interactive review):
+ `Estimate` and `DeliveryRate` gain an `unpriced` boolean; the estimator
+ skips markup for them and serializers/UIs render "quoted after review"
+ copy instead of a price. A zero-cost rate rendering as "Free" is a
+ merchant-facing lie, and 6.0 is the window to model this properly instead
+ of blessing the placeholder-rate workaround.
+- **Deposits are collected, not just displayed** (2026-08-30, interactive
+ review — the ambitious option, chosen deliberately): a freight method's
+ `deposit_percentage` changes what checkout charges. The buyer pays exactly
+ the deposit at completion; the order completes with an outstanding balance
+ and a partial payment status. This opens a partial-payment surface on
+ orders — scoped below to the minimum that makes deposits real (deposit
+ math in `Carts::Complete`, balance tracking via the existing
+ `outstanding_balance`, settlement through existing payment endpoints).
+ Anything beyond that (installment schedules, automatic balance capture,
+ dunning) is explicitly out of scope.
+- **Deposit base = the order total at placement.** That total cannot include
+ the freight charge (it isn't quoted yet); the later freight `Fee` simply
+ increases the outstanding balance. One base, no second "deposit-eligible
+ subtotal" vocabulary; revisit only if real merchants need a
+ goods-only base.
+- **Volume math is unit-aware from day one.** CBM derived from inch
+ dimensions differs from centimeter math by a factor of ~16 — the
+ raw-number shortcut `WeightRule` was allowed
+ (`6.0-delivery-method-rules.md`, resolved question 1) is not available
+ here. A small conversion helper normalizes dimensions to centimeters
+ before multiplying.
+- **The freight summary on a completed order is frozen, never re-derived.**
+ The summary the provider computes at estimate time is persisted in the
+ selected `DeliveryRate#metadata` (jsonb, already exists); order-facing
+ reads come from there. Carts compute live. Same doctrine as the duty
+ snapshot in `6.0-duties-and-custom-fees.md` — never re-derive logistics
+ from the live catalog on an existing order.
+- **The quoted freight charge is a `Fee`.** After the merchant gets the
+ forwarder's quote, the amount goes onto the order through the existing
+ `/admin/orders/:id/fees` endpoint (kind `freight`) — no retroactive
+ editing of the delivery rate, no new money path.
+- **Lot numbers are not this plan.** Recording which lot/pallet a unit came
+ from is an inventory concern and lives in `6.0-inventory-operations.md`
+ (lot-level inventory added there 2026-08-30).
+
+## Design Details
+
+### Spree::PackageType
+
+```ruby
+class Spree::PackageType < Spree.base_class
+ include Spree::SingleStoreResource
+ include Spree::Metadata
+
+ KINDS = %w[box envelope carton pallet container].freeze
+
+ belongs_to :store, class_name: 'Spree::Store'
+ has_many :variants, class_name: 'Spree::Variant',
+ foreign_key: :carton_package_type_id, dependent: :restrict_with_error
+
+ validates :name, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }
+ validates :kind, inclusion: { in: KINDS }
+ # length/width/height decimal(8,2), dimensions_unit, max_weight decimal(10,2),
+ # weight_unit, default boolean
+
+ def volume
+ Spree::Measurement.cubic_meters(length, width, height, unit: dimensions_unit)
+ end
+end
+```
+
+- One `default` per store (the shipping box), demoted Channel-style
+ (conditional UPDATE, partial index) — the same pattern as `CompanyAddress`
+ defaults. `Stock::Package#weight` (tare) and `#dimensions` read the default
+ row instead of the four store preferences, so the EasyPost parcel path is
+ unchanged in shape; the preferences become deprecated one-release bridges
+ reading through the row.
+- A backfill task creates the default row per store from the current
+ preference values (skipping stores still on the seeded zeros).
+- `carton` rows are what variants reference (below). `pallet`/`container`
+ rows are merchant vocabulary and reference data (and the natural anchor for
+ future label/BOL work); nothing in the tier math depends on them — tiers
+ are volume ranges on rules, so a merchant can configure tiers without ever
+ defining a pallet row.
+- Admin API: `/api/v3/admin/package_types` CRUD under the `settings` scope;
+ dashboard page under Settings → Shipping.
+
+### Variant carton details
+
+```ruby
+# spree_variants gains:
+# carton_package_type_id bigint # a PackageType with kind 'carton'
+# units_per_carton integer
+# carton_weight decimal(8,2) # gross weight of one PACKED carton
+# cartons_per_pallet integer # optional third packing level
+
+class Spree::Variant
+ belongs_to :carton_package_type, class_name: 'Spree::PackageType', optional: true
+
+ def carton_volume
+ carton_package_type&.volume
+ end
+
+ def cartons_for(quantity)
+ return nil if units_per_carton.blank? || units_per_carton.zero?
+
+ (quantity / units_per_carton.to_f).ceil
+ end
+
+ def units_per_pallet
+ return nil if units_per_carton.blank? || cartons_per_pallet.blank?
+
+ units_per_carton * cartons_per_pallet
+ end
+end
+```
+
+Geometry comes from the shared carton row; `units_per_carton`,
+`carton_weight` and `cartons_per_pallet` are the per-product packing facts.
+Together they form the packing chain **Unit → Carton → Pallet → CBM /
+Weight**: the freight summary reports pallet counts wherever
+`cartons_per_pallet` is present, and the same data feeds the quantity-rules
+plan (`6.0-b2b-quantity-rules.md`) — a buyer ordering 5 pallets is ordering
+200 cartons is ordering 4,800 units, and Spree knows all three numbers from
+one place. Pallet geometry stays on `pallet`-kind `PackageType` rows; the
+variant only records how it stacks. A validation refuses a
+reference to a non-`carton` kind, and cross-store references must be
+impossible by construction (the association is resolved through
+`current_store` in every controller, per the scope-fetching rule).
+
+Editing: the variant sheet and the bulk spreadsheet both get a Carton section
+— a carton picker (with inline "new carton size" create, since merchants
+discover carton sizes while cataloguing) plus the two numeric fields. CSV
+import/export and the spreadsheet resolve the carton by `PackageType#name`
+within the store. The three new variant attributes must be permitted in all
+three variant write paths (`6.0-duties-and-custom-fees.md` constraint: the
+nested variants controller, the inline `variants: [...]` list on the products
+controller, and the permitted-attribute declaration).
+
+`Spree::Measurement` is a tiny stateless conversion module (`in`/`ft`/`mm`/
+`cm` → cm for dimensions, `g`/`kg`/`lb`/`oz` → kg for weight) — the one
+genuinely new primitive this plan needs. Two module functions with unit
+tables, not a value-object zoo.
+
+### Freight summary
+
+```ruby
+# Value object (ActiveModel::Model + Attributes, per conventions — no Struct)
+Spree::FreightSummary.build(contents, store:)
+# => total_units, total_cartons, total_pallets (nil unless every carton-bearing
+# line declares cartons_per_pallet), total_volume (CBM), total_weight (kg),
+# complete? (false when any line lacks carton data), lines[]
+```
+
+Per line: cartons = `variant.cartons_for(quantity)`, volume = cartons ×
+`carton_volume`, weight = cartons × `carton_weight`. Lines without carton
+data fall back to unit volume/weight × quantity and mark the summary
+incomplete — the numbers stay useful, and the flag tells the merchant why
+they're partial.
+
+`Stock::Package#volume` is redefined through the same unit-aware math (its
+current raw `contents.sum(&:volume)` has no consumers, so this is safe); the
+deliberate "item dimensions are not summed" stance of `Package#dimensions`
+stays untouched — freight aggregates *carton* volume, which does stack.
+
+### VolumeRule and CompanyRule
+
+```ruby
+class Spree::DeliveryMethodRules::VolumeRule < Spree::DeliveryMethodRule
+ preference :minimum_volume, :decimal, default: nil, nullable: true # CBM
+ preference :maximum_volume, :decimal, default: nil, nullable: true
+
+ def eligible?(package)
+ volume = package.freight_summary.total_volume
+ return false if preferred_minimum_volume.present? && volume < preferred_minimum_volume
+ return false if preferred_maximum_volume.present? && volume > preferred_maximum_volume
+ true
+ end
+end
+```
+
+Same shape and fail-open convention as `WeightRule`, but the compared value is
+always CBM (unit-aware), never a raw column sum. Registered in the engine +
+i18n + dashboard Conditions card like the existing rules.
+
+`DeliveryMethodRules::CompanyRule` gates by buyer context: `preference
+:company_presence, :string` (`required` | `absent`). `required` on freight
+methods hides them from retail carts; `absent` on parcel methods hides those
+from B2B carts where a merchant wants a hard split. It reads
+`package.owner.b2b?` (company resolution already lives on the cart).
+Per-company narrowing stays Enterprise territory — OSS gates on presence
+only, consistent with the no-company-roles stance.
+
+The wholesale tier table is then pure configuration: four delivery methods
+("Carton shipping", "Pallet", "20ft container", "40ft container"), each with
+a `VolumeRule` range + `CompanyRule`(required), on the freight rate provider.
+
+### Unpriced rates and the freight rate provider
+
+- `Spree::DeliveryRateProvider::Freight` ships in core beside `Internal`.
+ `estimates(package)` returns one `Estimate` with `unpriced: true`, `cost:
+ 0`, the method's name, and `metadata` = the freight summary plus the
+ method's deposit terms (below).
+- `Estimate` gains `unpriced` (boolean attribute); `spree_delivery_rates`
+ gains an `unpriced` boolean column (default false). The estimator skips
+ markup for unpriced estimates and keeps its cheapest-first sort (cost is
+ 0, so unpriced rates naturally sort first among freight-only sets; mixed
+ priced/unpriced offerings are a merchant configuration choice).
+- Store + admin rate serializers expose `unpriced`; the storefront and
+ dashboard render "Quoted after review" (i18n) instead of a price. Order
+ totals charge zero shipping at placement.
+- Completion snapshot: the winning rate row already persists `metadata`, so
+ the frozen summary rides for free.
+
+### Deposits and the outstanding balance
+
+> **Amended 2026-08-30 (later the same day, payment-terms work):** the
+> method-level deposit preferences below are demoted from anchor to
+> **default source**. The order carries ONE resolved `payment_terms`
+> snapshot (quote/order override → company terms → these method
+> preferences → none), and `Cart#amount_due_at_checkout` reads the
+> snapshot — see `6.0-6.1-b2b-payment-terms.md`. The collection mechanics
+> in this section (completion validation, `partially_paid`,
+> `outstanding_balance`) are unchanged; only where the percentage comes
+> from is layered. Open question 1 (storefront balance payment) is
+> resolved there too (6.1 pay-balance route).
+
+Freight methods (via the provider) declare terms:
+
+```ruby
+preference :deposit_percentage, :decimal, default: nil, nullable: true # nil = pay in full
+preference :payment_instructions, :string # "Bank / TT Transfer"
+```
+
+Mechanics, scoped to the minimum that makes deposits real:
+
+- **`Cart#amount_due_at_checkout`** — the order total, unless the selected
+ delivery rate carries a `deposit_percentage`, in which case it is
+ `total × deposit_percentage / 100` (rounded with the currency). Computed,
+ never stored on the cart.
+- **`Carts::Complete` charges the deposit.** The payment-sufficiency check in
+ the completion pipeline validates payments against
+ `amount_due_at_checkout` instead of the full total; the deposit terms
+ (percentage, base amount, instructions) are stamped into the selected
+ rate's metadata alongside the freight summary. The existing
+ `payment_pending:` (invoice-later) path is unchanged and composes — a
+ merchant can require a deposit online or invoice the whole thing.
+- **Balance = the existing `Order#outstanding_balance`** (total minus
+ payments net of refunds — already how the returns rework left it). The
+ freight `Fee` added after quoting increases the total and therefore the
+ balance. No new balance column.
+- **Payment status**: the `Orders::UpdateStatuses` rollup derives a partial
+ state (`partially_paid`) when payments cover more than zero but less than
+ the total. Dashboard order list + page surface it with the balance.
+- **Settling the balance** happens through the payment surfaces that already
+ exist: the admin records/captures further payments on the order; the
+ balance invoice/email and a storefront "pay the balance" flow are follow-up
+ work (open question 1).
+- **Explicitly out of scope**: installment schedules, automatic capture at a
+ later date, dunning, deposit forfeiture rules. `capture_method` semantics
+ are untouched — a deposit payment is an ordinary payment for a smaller
+ amount.
+
+### Where the money happens, end to end
+
+1. Buyer completes checkout on an unpriced freight rate, paying the deposit
+ (or nothing, on the invoice-later path).
+2. Merchant reviews the order — the dashboard order page shows a Logistics
+ card (shipment type, units, cartons, CBM, gross weight, deposit terms,
+ outstanding balance) read from the rate metadata + order money.
+3. Merchant gets the forwarder's quote and adds it as a `Fee` (kind
+ `freight`) via `/admin/orders/:id/fees`; totals recompute through the
+ existing typed-adjustments path; the balance grows accordingly.
+4. Merchant collects the balance per the method's payment instructions and
+ records/captures it; `Orders::UpdateStatuses` rolls the order to paid.
+
+### API surface
+
+- Admin: `package_types` CRUD; variant carton attributes on the existing
+ product/variant writes; delivery method rules types discovery picks up the
+ two new rules automatically; order serializer exposes
+ `outstanding_balance` (if not already) + the partial payment status.
+- Store: cart and order serializers gain a `freight_summary` object
+ (nullable — null when no line carries carton data) and the cart exposes
+ `amount_due_at_checkout`; summaries are computed live on carts and read
+ from the selected rate's metadata on orders. Delivery rate serializer
+ gains `unpriced` and carries deposit terms in metadata.
+
+## Migration Path
+
+1. **Unit groundwork** — `Spree::Measurement`; `Variant#dimensions_unit`
+ store fallback (mirror of the existing `weight_unit` fallback).
+2. **Schema** — `spree_package_types`; `carton_package_type_id` +
+ `units_per_carton` + `carton_weight` + `cartons_per_pallet` on
+ `spree_variants`; `unpriced` on `spree_delivery_rates`.
+3. **PackageType** — model, backfill task (`spree:package_types:backfill`)
+ creating default rows from the store preferences, `Stock::Package`
+ reading through the default row, preference deprecation bridges.
+4. **Rollups** — `FreightSummary`, unit-aware `Stock::Package#volume`.
+5. **Rules** — `VolumeRule` + `CompanyRule` (+ engine registration, i18n,
+ dashboard Conditions card).
+6. **Freight provider + unpriced rates** — provider, estimator handling,
+ serializers.
+7. **Deposits** — `amount_due_at_checkout`, the `Carts::Complete`
+ payment-sufficiency change, `partially_paid` in the status rollup,
+ admin balance surfaces.
+8. **Dashboard** — package types settings page, variant carton section
+ (sheet + spreadsheet + CSV), order Logistics card with balance,
+ "quoted after review" rendering.
+9. **Storefront** — freight summary on cart/checkout, unpriced rate copy,
+ deposit line at payment ("Due now: $X (40% deposit) · Balance: $Y").
+
+No data migration beyond the package-type backfill: carton fields start
+empty, and nothing changes for stores that never fill them.
+
+## Constraints on Current Work
+
+- **Never compute volume by multiplying raw dimension columns.** All
+ volume/CBM math goes through the unit-aware helper; the raw-number
+ shortcut recorded for `WeightRule` does not extend to volume.
+- **No new readers of the `default_package_*` store preferences.** Package
+ dimensions are read through `Stock::Package#weight`/`#dimensions` (today)
+ and the default `PackageType` row (after phase 3).
+- **Don't build "freight quoted later" as a zero-cost priced rate.** The
+ `unpriced` flag is the mechanism; a $0 rate renders as free shipping.
+- **Don't add carton dimension columns to `spree_variants`.** Carton
+ geometry lives on the referenced `PackageType`; only packing facts
+ (`units_per_carton`, `carton_weight`) sit on the variant.
+- **Nothing may assume payments cover the order total at completion.** Code
+ that reads "completed ⇒ paid in full" is wrong once deposits land; check
+ `payment_status` / `outstanding_balance`, not completion.
+- **Post-placement freight charges are Fees**, never delivery-rate edits or
+ ad-hoc money columns.
+- **A new variant attribute must be permitted in all three write paths** or
+ it silently drops on the dashboard's product Save (duties-plan lesson).
+- Tier/eligibility logic hooks only in the Estimator filter chain via rules
+ (existing `6.0-delivery-method-rules.md` constraint).
+
+## Open Questions
+
+1. **Storefront balance payment.** Should 6.0 ship a customer-facing "pay
+ the remaining balance" flow (account order page + payment session on the
+ balance), or is admin-recorded settlement enough for the first release?
+ Unblocked by: implementing phase 7 and seeing what the B2B storefront
+ purchasing work (spree/storefront#214 line) needs.
+2. **Deposit rounding + tiny balances.** Currency rounding of
+ `total × percentage` can strand a cent of balance; decide the rounding
+ rule (round deposit up, absorb remainder into balance) during phase 7.
+
+## References
+
+- Merchant feedback, 2026-08 (wholesale carton/pallet/container shipping
+ with freight quoted after review; logistics summary as the checkout
+ output; deposit percentage per shipment type).
+- `docs/plans/6.0-delivery-method-rules.md` — rules pattern + Estimator-only
+ eligibility constraint.
+- `docs/plans/6.0-delivery-rate-provider.md` — provider contract the freight
+ provider implements.
+- `docs/plans/6.0-duties-and-custom-fees.md` — Fee substrate + snapshot
+ doctrine + the three-places variant attribute constraint.
+- `docs/plans/6.0-b2b-companies-and-catalogs.md` — company on cart,
+ `#b2b?` / `resolved_company`.
+- `docs/plans/6.0-service-workflows.md` — `Carts::Complete` pipeline the
+ deposit check slots into.
+- `docs/plans/6.0-b2b-quantity-rules.md` — MOQ / order multiples / purchase
+ unit built on the same packing chain.
+- `docs/plans/6.0-inventory-operations.md` — lot-level inventory (out of
+ scope here).
+- Existing volume chain: `spree/core/app/models/spree/variant.rb`
+ (`#volume`), `.../stock/content_item.rb`, `.../stock/package.rb`.
+- Store default package preferences: `spree/core/app/models/spree/store.rb`.
diff --git a/docs/plans/6.0-catalog-agreement-rework.md b/docs/plans/6.0-catalog-agreement-rework.md
new file mode 100644
index 0000000000..28018b1b7a
--- /dev/null
+++ b/docs/plans/6.0-catalog-agreement-rework.md
@@ -0,0 +1,133 @@
+# Catalog Agreement Rework (Binding Inversion + Audience-Rule Retirement)
+
+**Status:** Draft — design finalized 2026-08-30 (extracted 2026-08-30 from the amendment block in `6.0-b2b-companies-and-catalogs.md`, whose Implemented status was hiding this unbuilt work), nothing built
+**Target:** Spree 6.0 — sequence Wave 1: everything catalog-shaped builds on the inverted binding, and the leak fix touches unreleased code
+**Depends on:** B2B Companies & Catalogs (6.0-b2b-companies-and-catalogs.md — the shipped catalogs this reworks), PriceList system (released)
+**Author:** Damian + Claude
+**Last updated:** 2026-08-30
+
+## Summary
+
+The implementation half of the one-question-per-entity doctrine (decisions.md
+2026-08-30): the Catalog becomes the **commercial agreement** — the one
+object answering "what does this buyer see, pay, and buy on" — and the
+Catalog ↔ PriceList relationship is reshaped accordingly. The binding
+inverts (`spree_price_lists.catalog_id` replaces
+`spree_catalogs.price_list_id`), which closes a real leak in the shipped
+unreleased design; the audience-shaped price rules
+(`PriceRules::CustomerGroupRule`, `UserRule`) are retired in favor of
+catalog assignment; and the dashboard flips to **catalog-first, one-go
+setup**. The related term/pricing features build on this: the quantity
+plan's catalog terms (`6.0-b2b-quantity-rules.md`) and the automatic ±%
+pricing card (`6.0-price-list-automatic-pricing.md`) both land on the
+catalog page this rework establishes.
+
+## Key Decisions (do not deviate without discussion)
+
+- **The binding inverts: a price list is standalone or owned by exactly one
+ catalog** (2026-08-30, interactive review). `spree_price_lists.catalog_id`
+ (nullable) replaces `spree_catalogs.price_list_id`; generic rule matching
+ simply skips owned lists (`WHERE catalog_id IS NULL`). This closes the
+ leak: the shipped derived exclusion set (`Catalog.bound_price_list_ids`)
+ reads **active** catalogs only, so deactivating a catalog dropped its —
+ typically rule-less — list back into generic matching, pricing the whole
+ store. With the FK, a deactivated catalog's list goes dormant; detaching
+ a list is an explicit act behind a dashboard warning ("this list will
+ start matching by its own rules"). Sharing one list across catalogs is
+ lost — one catalog serving many audiences through assignments is the
+ replacement.
+- **Audience price rules retire; context rules stay.**
+ `PriceRules::CustomerGroupRule` and `PriceRules::UserRule` duplicated
+ catalog assignment with different, silent precedence — deprecated in 6.0
+ with the standard one-release bridge and a data task converting each such
+ list into an assortment-less catalog assigned to the audience and owning
+ the list (a `UserRule` list maps to a single-member customer group).
+ `PriceRules::ChannelRule` is **grandfathered**: kept working, nothing new
+ builds on it, the forward path is the channel's default catalog owning an
+ assortment-less list. `MarketRule` (carries VAT restatement) and
+ `VolumeRule` are context-shaped and stay first-class.
+- **Because catalogs are unreleased (6.0 edge), the catalogs side rewrites
+ in place** — the create-catalogs migration drops its `price_list_id`
+ reference, no bridge, per the companies-plan precedent. The
+ `spree_price_lists` side is a **released** table and gets an ordinary
+ additive migration for `catalog_id`.
+- **The dashboard flips to catalog-first, and setup is one go.** The
+ catalog page becomes the agreement editor — audience assignments,
+ assortment, an inline pricing card for its owned list, terms — plus a
+ **products-with-prices view** showing, per product, assortment membership
+ and the resolved price with its source (explicit / automatic / base), so
+ assortment↔pricing divergence is visible instead of
+ discoverable-by-accident. The New catalog flow takes name, audience,
+ assortment, and a pricing choice (base prices / ±% adjustment / fixed
+ prices); the admin catalog create/update endpoints accept an inline
+ `price_list` payload for the owned list, so standing up an agreement
+ never requires visiting the price-lists page.
+
+## Design Details
+
+- Associations flip: `PriceList belongs_to :catalog (optional)` /
+ `Catalog has_one :price_list`; `Catalog.bound_price_list_ids` and its
+ `Spree::Current` memoization are deleted — the resolver's
+ `applicable_price_lists` filters `catalog_id: nil` in SQL, and
+ `catalog_price_lists` reads the association. Only **active** catalogs
+ still claim their list in the resolution walk (unchanged semantics,
+ now leak-free on the exclusion side).
+- Deprecation bridges: creating a new `CustomerGroupRule`/`UserRule` warns
+ (removed 6.1); existing rows keep matching through the bridge release so
+ un-migrated stores don't lose pricing mid-upgrade.
+- Data task (`spree:upgrade:migrate_audience_price_rules_to_catalogs`, in
+ the 6.0 manifest): audience-only lists convert cleanly; a list mixing
+ audience and context rules (or `match_policy: all` across both) is
+ reported for manual review rather than guessed at — a wrong automatic
+ conversion here is a silent price change.
+- Admin API: catalogs create/update accept `price_list: {...}` (create or
+ update the owned list inline); the price-lists endpoints keep working for
+ standalone lists; detach = `price_list: null`-style explicit action.
+- Dashboard: catalog page (agreement editor + products-with-prices view +
+ detach warning), New catalog wizard, price-list page banner for owned
+ lists linking to their catalog.
+
+## Migration Path
+
+1. **Schema** — rewrite the catalogs migration in place (drop
+ `price_list_id`); additive `catalog_id` on `spree_price_lists`; edge
+ worktrees rebuild the template DB.
+2. **Model + resolver** — association flip, SQL-level owned-list exclusion,
+ delete the derived set + memoization; specs pin the leak (a deactivated
+ catalog's rule-less list prices nobody).
+3. **Rule retirement** — deprecation warnings + bridge, the data task,
+ types-discovery marking.
+4. **API + dashboard** — inline `price_list` payload, agreement editor,
+ products-with-prices view, wizard, detach warning. (The pricing card's
+ ±% controls and the Terms card arrive with their own plans on this
+ surface.)
+
+## Constraints on Current Work
+
+- **No new code reads `spree_catalogs.price_list_id`** or
+ `Catalog.bound_price_list_ids` — the FK on the list is the one binding.
+- **No new features build on `PriceRules::CustomerGroupRule`/`UserRule`**
+ (deprecated) **or `ChannelRule`** (grandfathered) — audience targeting is
+ catalog assignment; channel pricing is the default catalog.
+- Catalog-page features (terms, pricing card) mount on the agreement
+ editor this plan establishes — no parallel catalog editing surfaces.
+
+## Open Questions
+
+None — the design questions were resolved in the 2026-08-30 entity review
+(decisions.md). The mixed-rule-list conversion policy (report, don't guess)
+is deliberate, not open.
+
+## References
+
+- decisions.md 2026-08-30 — "One question per entity" (doctrine +
+ rejected alternatives).
+- `docs/plans/6.0-b2b-companies-and-catalogs.md` — the shipped catalogs +
+ the amendment block this plan was extracted from.
+- `docs/plans/6.0-b2b-quantity-rules.md` (terms on this surface),
+ `docs/plans/6.0-price-list-automatic-pricing.md` (±% card on this
+ surface).
+- Leak mechanics: `spree/core/app/models/spree/catalog.rb`
+ (`bound_price_list_ids`),
+ `spree/core/app/models/spree/pricing_provider/internal.rb`
+ (`applicable_price_lists`).
diff --git a/docs/plans/6.0-draft-order-negotiation-mechanics.md b/docs/plans/6.0-draft-order-negotiation-mechanics.md
new file mode 100644
index 0000000000..7759816de3
--- /dev/null
+++ b/docs/plans/6.0-draft-order-negotiation-mechanics.md
@@ -0,0 +1,146 @@
+# Draft Order Negotiation Mechanics (Manual Line Pricing + Cart Copy)
+
+**Status:** Draft — design finalized 2026-08-30, nothing built
+**Target:** Spree 6.0 (retargeted 2026-08-30: the cart→draft copy moved from 6.1 into 6.0 so the Enterprise quotes product needs nothing beyond 6.0 GA)
+**Depends on:** Cart/Order split (6.0-cart-order-split.md), Third-Party Pricing (6.0-third-party-pricing-inventory.md — `price_source`), Service Workflows (6.0-service-workflows.md)
+**Author:** Damian + Claude
+**Last updated:** 2026-08-30
+
+## Summary
+
+Draft orders (staff-created `Spree::Order` rows, `status: 'draft'`,
+`cart_id: nil`) already carry most of a negotiation engine: items,
+addresses, manual fees and discounts that survive recalculation and freeze
+at placement, notes, and invoice-later conversion. What's missing is the
+one thing every negotiated B2B deal needs — **setting a unit price** ("10,000
+units @ $7.20 for this order only, without touching the customer's price
+list") — plus the machinery to start a negotiation from a customer's cart
+without consuming it. This plan ships those **open-source mechanics**; the
+customer-facing quotation product (lifecycle, send/accept, expiry, portal)
+is Enterprise (`spree-enterprise-v2/docs/plans/b2b-quotes.md`; tier split
+decided 2026-08-30 — same shape as company registration: OSS mechanisms,
+Enterprise flow). Manual pricing is deliberately 6.0: it polishes the
+brand-new draft-order surface (phone orders need it too) and rides with two
+fixes in the same area; the copy service lands late in 6.0 so its Enterprise
+consumer (quotes) needs nothing beyond 6.0 GA (retargeted 2026-08-30).
+
+## Key Decisions (do not deviate without discussion)
+
+- **`price_source: 'manual'` is the negotiated-price marker** (2026-08-30):
+ the existing write-only provenance column gains its first reader.
+ Setting a line's price through the admin API stamps `'manual'`; the two
+ repricing paths gain guards — `Carts::PriceItems` skips manual rows, and
+ `LineItem#should_update_price?` answers false for them — so a quantity
+ change no longer silently re-prices a negotiated line from the pricing
+ provider. `'manual'` is a **reserved key**: no pricing provider may
+ register it.
+- **Explicit revert, never silent.** `price: null` on the item update is
+ the "back to catalog price" gesture — clears the marker and re-prices
+ through the resolver. Nothing else may overwrite a manual price.
+- **Price overrides are pre-placement only.** Once placed, money edits stay
+ what they are today — fees and discounts — until the 6.1 order-change
+ substrate owns post-placement amendments. Overrides answer "what is the
+ agreed unit price", discounts answer "what concession is itemized on top";
+ both freeze at placement through the existing paths.
+- **`price_source` is admin-only surface.** Exposed on the admin line-item
+ serializer (the dashboard marks negotiated lines and offers the revert);
+ never on the store serializer — provenance is operational.
+- **`Orders::Create` stamps `created_by`** (bug fix): the column and
+ association exist but were never written, leaving staff drafts
+ identifiable only by `cart_id IS NULL`.
+- **The `payment_pending` docstring is corrected** (bug fix): it promises
+ `payment_status: 'balance_due'`, but the status rollup has no such branch
+ and produces `'none'`. The docstring now tells the truth; whether an
+ unpaid placed order deserves a distinct rollup value is decided inside
+ the wholesale-deposit work (`6.0-b2b-wholesale-shipping.md` phase 7),
+ which is already reshaping that rollup — not here, and not twice.
+- **`Spree::Orders::CreateFromCart` (6.0, late)** copies a customer's cart into a
+ fresh draft order — line items with prices and `price_source` as they
+ stand, addresses, customer/company, notes, metadata — **leaving the cart
+ untouched** (a buyer who requests a quote keeps shopping). No money
+ records, no fulfillments: those are rebuilt by the draft's own lifecycle.
+ Deliberately a new service, not a reuse of `Carts::Complete`'s private
+ copy helpers — that copy re-points money records and is one-shot by
+ unique index; this one is an independent duplicate.
+
+## Design Details
+
+### Manual pricing (6.0)
+
+- Admin surface: `price` accepted on `POST/PATCH
+ /admin/orders/:id/items` (and the inline `items:` list on order create);
+ `Orders::UpdateItem` gains a `price:` keyword. Guarded to incomplete
+ orders.
+- Model: setting a price through these paths assigns `price_source:
+ 'manual'`. Guards:
+
+```ruby
+# Carts::PriceItems#call — before resolving a row:
+next if line_item.price_source == 'manual'
+
+# LineItem#should_update_price?
+!owner.completed? && price_source != 'manual'
+```
+
+- Dashboard: the draft-order items table's unit price becomes an editable
+ input; a negotiated line shows a marker + "reset to catalog price"
+ action; the order create form keeps quantity-only (override on the edit
+ page, where the resolved price is visible to compare against).
+- Specs pin the contract: a manual price survives quantity changes,
+ recalculation, an external-pricing store's `confirm_prices`, and
+ placement; revert re-prices; a provider registering key `'manual'`
+ raises.
+
+### Fixes (6.0)
+
+`created_by` stamped from the authenticated admin in `Orders::Create`;
+`payment_pending` docstring corrected to `payment_status: 'none'` with the
+cross-reference to the deposit rollup work.
+
+### Cart → draft order copy (6.0, late)
+
+`Spree::Orders::CreateFromCart.call(cart:, created_by: nil, customer: nil)`
+→ draft `Spree::Order` (no `cart_id` — it is NOT the completion copy and
+must not claim the one-shot slot). Consumers: the Enterprise
+request-a-quote flow (buyer-initiated), and plain admin "start a draft from
+this cart".
+
+## Migration Path
+
+1. **6.0** — guards + admin `price` params + `'manual'` stamping + reserved
+ key; `created_by`; docstring fix; dashboard editable price; admin
+ serializer `price_source`.
+2. **6.0, late** — `Orders::CreateFromCart` + specs; consumed by the Enterprise
+ quote plan.
+
+No data migration; every existing line has a provider or nil
+`price_source` and behaves exactly as today.
+
+## Constraints on Current Work
+
+- **Nothing may reprice a `price_source: 'manual'` line** except the
+ explicit revert; any new repricing call site must honor the guard.
+- **`'manual'` never becomes a pricing-provider key.**
+- **No post-placement price overrides** — placed-order money edits remain
+ fees/discounts until the order-change substrate.
+- **Store serializers never expose `price_source`.**
+- Quote lifecycle, statuses, expiry, customer surfaces: Enterprise plan —
+ don't grow them here.
+
+## Open Questions
+
+None for this scope. (Whether unpaid placed orders get a distinct
+payment-status value is owned by the wholesale-deposit rollup work.)
+
+## References
+
+- Merchant feedback, 2026-08 (extend draft orders into quotations;
+ negotiated line-item pricing that must not touch the price list).
+- Tier split: `docs/plans/decisions.md` 2026-08-30;
+ `spree-enterprise-v2/docs/plans/b2b-quotes.md` (the flow).
+- Repricing contract: `spree/core/app/services/spree/carts/price_items.rb`,
+ `spree/core/app/models/spree/line_item.rb` (`should_update_price?`,
+ `update_adjustments`).
+- Draft-order path: `spree/core/app/services/spree/orders/create.rb`,
+ `app/workflows/spree/orders/complete.rb` (`payment_pending`),
+ `app/workflows/spree/carts/complete.rb` (`complete_draft_order`).
diff --git a/docs/plans/6.0-inventory-operations.md b/docs/plans/6.0-inventory-operations.md
index 20a4e6a072..c271707f6e 100644
--- a/docs/plans/6.0-inventory-operations.md
+++ b/docs/plans/6.0-inventory-operations.md
@@ -1,10 +1,10 @@
-# Inventory Operations (Transfers + Purchase Orders + Variant History)
+# Inventory Operations (Transfers + Purchase Orders + Lots + Variant History)
**Status:** Draft
-**Target:** Spree 6.0
+**Target:** Spree 6.0 (transfers, purchase orders, history) / 6.1 (lot tracking — deferred 2026-08-30 scope review: purely additive, opt-in, nothing in 6.0 or Enterprise depends on it)
**Depends on:** Typed Stock Movements (6.0-typed-stock-movements.md), Fulfillment & Delivery (6.0-fulfillment-and-delivery.md), Stock Reservations (6.0-stock-reservations.md)
**Author:** Damian + Claude
-**Last updated:** 2026-07-14
+**Last updated:** 2026-08-30
> **Naming note (2026-07-14):** the procurement-source model this plan introduces is **`Spree::Supplier`** (`spree_suppliers`, prefix `sup_`, `/api/v3/admin/suppliers`). An earlier draft called it `Spree::Seller`, which collided with the marketplace seller model of `6.0-multi-vendor-marketplace.md` — `Spree::Seller` is reserved for marketplace sellers (see `decisions.md` 2026-07-14). "Supplier" also matches Shopify's purchase-order vocabulary.
@@ -15,6 +15,7 @@ Lift inventory operations from "atomic decrement + log" to a first-class workflo
1. **`Spree::StockTransfer` gains a lifecycle.** Today a transfer is one-shot — source decrements and destination increments in the same transaction. After this plan: `draft → ready_to_ship → in_transit → received` (with `cancelled` as a terminal escape hatch), plus line items, partial receive support, and a discrepancy column. Source units leave on `mark_in_transit`, destination units land on `receive` — not at the same instant.
2. **New `Spree::PurchaseOrder` model** for supplier receives. Today's "external receive" hack (a `StockTransfer` with `source_location_id: nil`) is replaced by a proper `PurchaseOrder` with `supplier`, `expected_at`, `line_items[]` with `unit_cost`, and the same receive flow as transfers.
3. **Variant + Location stock history.** Surfaces the audit feed introduced by `6.0-typed-stock-movements.md` as inline timelines in the admin SPA — answering "why is on-hand 47?" in the place users always ask: on a SKU or a warehouse.
+4. **Lot-level inventory** (added 2026-08-30, interactive review — full lot tracking chosen over provenance-only; **6.1** per the same-day scope trim). New `Spree::StockLot` decomposes a lot-tracked variant's on-hand quantity per location into lots (`lot_number`, optional `expires_at`); receives assign lots, dispatch picks them FEFO, and every stock movement on a lot-tracked variant names its lot — so a merchant can answer "which LOT/pallet went into this shipment" and "what expires next", the two questions wholesale and regulated-goods merchants actually ask.
This plan is the **UX surface** for inventory ops. The data primitives (typed `StockMovement`, `kind`, concrete FKs to Order/Fulfillment/Return/Exchange/StockTransfer/PurchaseOrder) come from `6.0-typed-stock-movements.md` and the Fulfillment rename. Those two plans must land first.
@@ -73,6 +74,39 @@ Once `6.0-typed-stock-movements.md` lands, every change to `count_on_hand` carri
- **`PurchaseOrderItem` has `unit_cost` (Money) and `quantity_ordered` / `quantity_received`.** Currency comes from the PO's `currency` column (defaults to the store's). Receiving units writes typed `received` stock movements with `purchase_order_id`.
- **PO does not affect `count_on_hand` until receive.** Ordered units are visible to the merchant as "on order" (computed: `SUM(quantity_ordered - quantity_received)` per variant), but never count toward availability.
+### Lot tracking (added 2026-08-30 · targeted 6.1)
+
+- **Lots are opt-in per variant** (`lot_tracked` boolean). Untracked variants — the vast majority — see zero behavior change; no lot rows, no lot columns on their movements.
+- **A lot is a per-location quantity bucket, not a global batch record.** `Spree::StockLot` belongs to a variant + stock location and carries `lot_number`, `quantity`, `expires_at` (nullable), `received_at`, and optional provenance FKs (`purchase_order_id` / `stock_transfer_id`). Uniqueness on `(stock_location_id, variant_id, lot_number)`. The same physical batch split across two warehouses is two rows sharing a `lot_number` — receiving reconciles by number.
+- **Lot quantities are a decomposition of `count_on_hand`, kept in sync transactionally.** For a lot-tracked variant, `SUM(stock_lots.quantity)` must equal the stock level's `count_on_hand` at that location — the same invariant discipline as the license-pool count sync in `6.0-digital-assets.md`. Every movement that changes `count_on_hand` on a lot-tracked variant adjusts a lot in the same transaction; drift is a bug, never reconciled lazily.
+- **Movements name their lot.** `spree_stock_movements` gains a nullable `stock_lot_id`; a physical quantity change spanning several lots is several movement rows, one per lot. This keeps the typed-movements doctrine intact — `count_on_hand` still only ever changes through movements; lots add *which shelf section*, not a second write path.
+- **Receiving assigns lots.** PO and transfer receive payloads accept per-item lot allocations (`[{ lot_number, expires_at, quantity }]`); receiving finds-or-creates the destination lot and writes the `received` movements against it. A lot-tracked item received without lot data is refused — the receive screen is the one moment the information exists.
+- **Allocation stays lot-agnostic; dispatch picks lots.** Per `6.0-typed-stock-movements.md`, stock leaves the shelf at fulfillment: `allocated` movements (order placement) carry no lot — an allocation is a promise, not a physical pick. The `shipped` movements written at dispatch pick lots **FEFO** (earliest `expires_at`, then oldest `received_at`), with a per-fulfillment override so the warehouse can record what was actually grabbed. The fulfillment's movements are the record of which lots shipped, surfaced on the fulfillment page and in the variant history (`+200 received · PO-42 · LOT 2026-113`).
+- **Returns and adjustments are lot-aware** for tracked variants: a return receive lands in the lot it shipped from when known (else a merchant-chosen lot), and manual adjustments name the lot they correct.
+- **No storefront exposure in 6.0.** Lots are back-office data; nothing in the Store API reads them.
+
+```ruby
+class Spree::StockLot < Spree.base_class
+ has_prefix_id :lot
+
+ belongs_to :variant, class_name: 'Spree::Variant'
+ belongs_to :stock_location, class_name: 'Spree::StockLocation'
+ belongs_to :purchase_order, class_name: 'Spree::PurchaseOrder', optional: true
+ belongs_to :stock_transfer, class_name: 'Spree::StockTransfer', optional: true
+
+ has_many :stock_movements, class_name: 'Spree::StockMovement', inverse_of: :stock_lot
+
+ validates :lot_number, presence: true,
+ uniqueness: { scope: [:stock_location_id, :variant_id, *spree_base_uniqueness_scope] }
+ validates :quantity, numericality: { greater_than_or_equal_to: 0, only_integer: true }
+
+ scope :available, -> { where('quantity > 0') }
+ scope :fefo, -> { order(Arel.sql('expires_at IS NULL, expires_at ASC, received_at ASC')) }
+end
+```
+
+Admin surface: lots listed on the variant Inventory tab and the stock-location Activity view (with expiry badges); lot filter on the movement history; per-lot adjustment from the lot row. API: `GET /api/v3/admin/stock_lots` (Ransack-filterable by variant/location/expiry) + lot allocations embedded in the existing receive/adjustment payloads — no standalone lot mutation endpoints beyond adjustment, since lots change through receives and picks.
+
### Typed Stock Movements wiring
These additions live in `6.0-typed-stock-movements.md`; this plan only consumes them.
@@ -499,6 +533,28 @@ class AddInventoryOperations < ActiveRecord::Migration[7.2]
# Typed-movements extension
add_column :spree_stock_movements, :purchase_order_id, :bigint
add_index :spree_stock_movements, :purchase_order_id
+
+ # Lot tracking
+ add_column :spree_variants, :lot_tracked, :boolean, default: false, null: false
+
+ create_table :spree_stock_lots do |t|
+ t.references :variant, null: false
+ t.references :stock_location, null: false
+ t.references :purchase_order
+ t.references :stock_transfer
+ t.string :lot_number, null: false
+ t.integer :quantity, null: false, default: 0
+ t.date :expires_at
+ t.datetime :received_at
+ t.timestamps
+ end
+ add_index :spree_stock_lots,
+ [:stock_location_id, :variant_id, :lot_number],
+ unique: true,
+ name: 'idx_stock_lots_unique'
+
+ add_column :spree_stock_movements, :stock_lot_id, :bigint
+ add_index :spree_stock_movements, :stock_lot_id
end
end
```
@@ -557,6 +613,7 @@ All other existing transfers (with a real source location) become `status: 'rece
- **Don't add receive flows to `StockTransfer` without `source_location_id`.** Supplier receives move to `PurchaseOrder`. If a 5.5 feature needs to record a supplier receive, scope it minimally and flag it for migration.
- **Don't create a separate "Stock Movements" admin SPA page.** Movement history is always inline on variant + stock location.
- **Don't fold cost data onto `StockTransfer`.** Transfers don't have a unit cost — they move existing inventory between owned locations. Cost lives on `PurchaseOrderItem.unit_cost`.
+- **Don't put lot numbers anywhere but `Spree::StockLot`.** No `lot_number` strings on line items, fulfillments, or movements-as-text — a movement references its lot by FK, and everything else reads through the movement. A lot quantity never changes outside the transaction that writes its movement.
## Open Questions
@@ -564,6 +621,8 @@ All other existing transfers (with a real source location) become `status: 'rece
2. **Suppliers shared across stores?** Today the plan scopes them per-store. Some merchants run multiple storefronts off one supplier base. Could promote to a `Spree::Supplier` with a M2M to stores in a follow-up. Defer.
3. **Average / weighted-average cost on Variant?** A PO's `unit_cost` enables margin reporting. The natural extension is `Variant.average_cost` (rolling avg of received unit costs) for COGS. Likely worth a separate plan — call it out, don't scope it here.
4. **Pickup transfers (ship-to-store).** `6.0-fulfillment-and-delivery.md` mentions `pickup_stock_policy: 'any'` as enabling ship-to-store. The natural implementation is auto-creating a `StockTransfer` when a pickup order's items aren't local at the chosen pickup location. Mechanism is straightforward; UX (does the customer see "ready in 3 days" instead of "ready in 2 hours"?) needs a separate decision. Defer.
+5. **Expired lots and sellability.** Should a lot past `expires_at` be excluded from FEFO picking (forcing a manual override), and should expiring stock reduce the availability `Stock::Quantifier` reports? Leaning: warn-and-skip in FEFO, no availability change in 6.0 — availability semantics touch checkout and deserve their own decision. Unblocked by: implementing the receive/pick flows and seeing what merchants on lot-tracked catalogs report.
+6. **Turning `lot_tracked` on for a variant with existing stock.** The existing `count_on_hand` has no lot decomposition; the flag flip likely requires an opening "untracked" lot holding the current quantity (adjusted into real lots by the merchant). Decide during implementation.
## References
diff --git a/docs/plans/6.0-price-list-automatic-pricing.md b/docs/plans/6.0-price-list-automatic-pricing.md
new file mode 100644
index 0000000000..e3cf79e14f
--- /dev/null
+++ b/docs/plans/6.0-price-list-automatic-pricing.md
@@ -0,0 +1,154 @@
+# Price List Automatic Pricing (Percentage Adjustments)
+
+**Status:** Draft — design finalized 2026-08-30, nothing built
+**Target:** Spree 6.0
+**Depends on:** B2B Companies & Catalogs (6.0-b2b-companies-and-catalogs.md — catalog-bound lists), one-question-per-entity doctrine (decisions.md 2026-08-30)
+**Author:** Damian + Claude
+**Last updated:** 2026-08-30
+
+## Summary
+
+Today a price list is only as good as the rows someone typed into it: a
+"wholesale −5%" list means manually maintaining a derived copy of the whole
+base price book, and every base-price change silently strands the list. This
+plan adds **automatic pricing**: a price list can declare a percentage
+adjustment off base prices ("5% decrease", "10% increase"), and the resolver
+derives the price at lookup time for any variant the list doesn't price
+explicitly. Explicit rows stay as per-variant overrides. Combined with the
+existing rule matching, this makes the common cases one-field configuration:
+a wholesale catalog's list at −15%, or automatic volume pricing (a list with
+a `VolumeRule` `min_quantity: 10` and a −5% adjustment) — with zero rows to
+maintain and no drift when base prices move.
+
+## Key Decisions (do not deviate without discussion)
+
+- **Derived prices are computed on read, never materialized** (2026-08-30,
+ interactive review): `PricingProvider::Internal` builds an in-memory
+ price from the base price at resolution time. Base-price changes
+ propagate instantly — which is the point — and there are no refresh jobs
+ and no drift window. Accepted cost: adjusted prices are not inspectable
+ as rows, so exports, feeds and reports must read through the resolver for
+ adjustment lists.
+- **Plain currency rounding** (2026-08-30): derived amounts round to the
+ currency's minor unit, nothing else. Charm/psychological endings (.99)
+ are a possible later additive option — and because nothing is stored,
+ adding them later rewrites no data.
+- **The percentage is currency-agnostic** (2026-08-30): it applies to every
+ currency the variant has a base price in. No per-list currency column
+ (money configuration is born per currency — the no-FX constraint);
+ a per-variant × currency explicit row overrides the adjustment for that
+ currency only.
+- **Explicit rows beat the adjustment; placeholder rows do not.** A row
+ with an amount is a deliberate override. A nil-amount placeholder row
+ (the `add_products` shape) falls through to the computed value — same
+ skip the resolver already performs.
+- **The adjustment lives on the PriceList, not the Catalog.** Under the
+ one-question-per-entity doctrine the catalog is the agreement and the
+ price list is the numbers; "how the numbers are produced" is a price-list
+ concern. A catalog gets automatic pricing by attaching an adjustment
+ list.
+- **Signed storage, directional UI.** One `price_adjustment_percentage`
+ decimal column (negative = decrease, positive = increase); the dashboard
+ renders magnitude + an increase/decrease select. No separate direction
+ column to fall out of sync.
+
+## Design Details
+
+### Schema + model
+
+```ruby
+# spree_price_lists gains:
+# price_adjustment_percentage decimal(6,3) # nil = fixed-price list (today's behavior)
+# adjust_compare_at boolean, default: false, null: false
+
+class Spree::PriceList
+ validates :price_adjustment_percentage,
+ numericality: { greater_than: -100 }, allow_nil: true
+
+ def automatic_pricing?
+ price_adjustment_percentage.present?
+ end
+
+ def adjustment_factor
+ 1 + (price_adjustment_percentage / 100)
+ end
+end
+```
+
+`adjust_compare_at: true` derives the compare-at from the base compare-at by
+the same factor; `false` means derived prices carry no compare-at. (An
+explicit row's own `compare_at_amount` is authoritative for that row either
+way.)
+
+### Resolution
+
+`Spree::PricingProvider::Internal#find_price_for_list` becomes:
+
+1. Explicit row with an amount → use it (unchanged).
+2. Otherwise, if the list is `automatic_pricing?`: read the variant's base
+ price for the context currency; none → the list yields nothing (falls
+ through to the next list / base price, unchanged semantics). Otherwise
+ build an **unsaved** `Spree::Price` with `amount = base.amount ×
+ adjustment_factor` (currency-rounded), `price_list` set so
+ `price_source` stamping and line-item write-back (`price_list_id`)
+ behave exactly as for a stored row.
+
+Nothing else in the walk changes: adjustment lists are ordinary lists —
+rule-matched by position, or catalog-bound with catalog precedence, dates
+and status honored. The resolution cache key must incorporate the base
+price's version for adjustment lists (a computed price changes when the
+base row changes, not when the list does).
+
+### API + dashboard
+
+- Admin price list endpoints accept the two new attributes; serializers
+ expose them (admin only — the storefront just sees prices).
+- Dashboard: a Pricing card — magnitude input + increase/decrease select +
+ "also adjust compare-at" switch — on the standalone price list page, and
+ the same card embedded on the **catalog page** for a catalog-owned list
+ (the binding is `spree_price_lists.catalog_id` per
+ `6.0-catalog-agreement-rework.md`; the catalog page is the agreement
+ editor that plan establishes). The products table shows computed prices grayed as
+ "automatic" with the explicit-row override editable per variant (clearing
+ the override returns the variant to automatic).
+- CSV export of an adjustment list exports resolved amounts flagged
+ `automatic`, so a re-import doesn't accidentally freeze computed values
+ into explicit rows.
+
+## Migration Path
+
+1. Schema (two columns) + model.
+2. Resolver branch + cache-key change + specs on the walk (explicit
+ override, placeholder fall-through, missing base currency, catalog-bound
+ and rule-matched variants of each).
+3. Admin API attributes + dashboard Pricing card + export flagging.
+
+Nothing to migrate — every existing list has a nil percentage and behaves
+exactly as today.
+
+## Constraints on Current Work
+
+- **Never materialize derived rows** — no job, rake task, or import path
+ may write price rows computed from an adjustment; the override path is a
+ merchant typing an explicit amount.
+- Price exports/feeds/reports touching lists must resolve through the
+ pricing provider rather than reading `spree_prices` raw once adjustment
+ lists exist.
+- New price-producing features put "how numbers are made" on the price
+ list, never on the catalog.
+
+## Open Questions
+
+None remaining for the 6.0 scope. Deferred, recorded: charm-rounding styles
+(additive later), per-variant percentage overrides (explicit rows already
+cover the need).
+
+## References
+
+- Merchant feedback, 2026-08 (manual price-list maintenance pain; requested
+ automatic % volume discounts).
+- One-question-per-entity doctrine + audience price-rule deprecation:
+ `docs/plans/decisions.md` (2026-08-30).
+- Resolver walk: `spree/core/app/models/spree/pricing_provider/internal.rb`.
+- Price list + rules: `spree/core/app/models/spree/price_list.rb`,
+ `spree/core/app/models/spree/price_rules/`.
diff --git a/docs/plans/6.1-b2b-order-documents.md b/docs/plans/6.1-b2b-order-documents.md
new file mode 100644
index 0000000000..c76bcc11da
--- /dev/null
+++ b/docs/plans/6.1-b2b-order-documents.md
@@ -0,0 +1,108 @@
+# B2B Order Documents (Documents Area + Logistics Prints)
+
+**Status:** Draft — design finalized 2026-08-30, nothing built
+**Target:** Spree 6.1
+**Depends on:** Customer PO Numbers (6.0-b2b-customer-po-numbers.md — `po_document`, the first order attachment), B2B Wholesale Shipping (6.0-b2b-wholesale-shipping.md — freight summary feeds the packing list), B2B Payment Terms (6.0-6.1-b2b-payment-terms.md — schedule + bank reference feed the payment sheet)
+**Author:** Damian + Claude
+**Last updated:** 2026-08-30
+
+## Summary
+
+A B2B order accumulates paperwork — the buyer's PO, the quotation, packing
+lists, shipping documents — and today the only place it can live is email
+threads. This plan adds an order **Documents area** (uploaded files, private
+storage, per-document customer visibility, listed in the buyer's order view)
+and extends the dashboard's existing client-side print path with two
+generated documents the data already supports: a **carton-level packing
+list** (units / cartons / pallets / gross weight / CBM from the freight
+summary, plus PO and order numbers) and a **payment-instructions sheet**
+(order + PO references, terms snapshot, amount due now, bank transfer
+details + payment reference). Real *invoices* — numbered proforma and
+commercial documents with PDF generation and legal numbering — are
+deliberately NOT here: they are the Enterprise terms/invoicing product
+(tier decided 2026-08-30; no OSS competitor generates them either, and
+legal numbering is exactly what the document-numbers plan says core never
+promises).
+
+## Key Decisions (do not deviate without discussion)
+
+- **`Spree::OrderDocument` is an uploaded-file row, not a generation
+ pipeline**: `order_id`, `label`, `customer_visible` (default false),
+ private-storage attachment (spoofing-protected, the
+ seller-submission/tax-certificate precedent), `uploaded_by`
+ (staff or the customer — buyers can add their own paperwork through the
+ account order view). The planned `po_document` keeps its dedicated slot
+ (it has semantics — the requiredness check); the Documents area lists it
+ alongside the generic rows.
+- **Generated documents stay client-side HTML prints** in 6.1, extending
+ the shipped packing-slip pattern (deliberately a print window, not an
+ admin route; everything needed is already loaded on the order screen).
+ The packing list adds the carton/pallet/CBM block from the frozen
+ freight summary; the payment-instructions sheet renders the terms
+ schedule + bank preferences + payment reference. Neither claims to be
+ an invoice, carries no invoice number, and creates no stored artifact.
+- **No PDF stack in core.** The day server-side rendering is needed, it
+ arrives with the Enterprise invoicing product; OSS prints and OSS
+ uploads never grow a PDF dependency.
+- **Customer visibility is per document, default private** — internal
+ paperwork stays internal; the buyer's order view lists visible documents
+ with expiring signed URLs (the private-storage read pattern).
+
+## Design Details
+
+```ruby
+class Spree::OrderDocument < Spree.base_class
+ belongs_to :order, class_name: 'Spree::Order'
+ belongs_to :uploaded_by, polymorphic: true, optional: true
+
+ has_one_attached :file, service: Spree.private_storage_service_name
+
+ validates :label, presence: true
+ # customer_visible boolean, default false, null: false
+end
+```
+
+- Admin API: nested `/admin/orders/:id/documents` CRUD (direct upload via
+ signed blob); store API: documents index on the account order view
+ (visible only) + create (buyer uploads, always visible to themselves,
+ flagged as buyer-supplied for staff).
+- Dashboard: a Documents card on the order page (upload, visibility
+ toggle, download, delete-with-confirm); print actions beside the
+ existing packing slip.
+- Storefront: documents list on the order page — completing the buyer
+ view: stage + expected date (`6.1-order-stages.md`), payment schedule
+ (`6.0-6.1-b2b-payment-terms.md`), shipment/freight summary, documents.
+
+## Migration Path
+
+1. Schema + model + admin nested CRUD + dashboard card.
+2. Store surfaces (list + buyer upload).
+3. The two prints (packing list block, payment sheet).
+
+Nothing to migrate.
+
+## Constraints on Current Work
+
+- **Order-facing files go through `OrderDocument` or a dedicated
+ semantic slot** (like `po_document`) — never loose attachments on other
+ models.
+- **No invoice vocabulary in OSS** — no model, number, or document may be
+ called an invoice; the payment sheet is "payment instructions".
+- Prints render `po_number` and the payment reference when present (the
+ PO plan's document constraint applies).
+
+## Open Questions
+
+None for this scope. (Auto-attaching generated prints as stored documents
+is deliberately not done — a print is a view of live data; a stored
+artifact is an invoicing feature.)
+
+## References
+
+- Merchant feedback, 2026-08 (documents area; proforma/packing
+ list/commercial invoice; customer visibility).
+- Print precedent: `packages/dashboard/src/lib/packing-slip.ts`.
+- Attachment precedents: `Spree::TaxExemptionCertificate#document`,
+ `Spree::SellerRequirementSubmission#file`.
+- Enterprise invoicing: `spree-enterprise-v2/docs/plans/b2b-companies.md`
+ roadmap item 1.
diff --git a/docs/plans/6.1-order-change-substrate.md b/docs/plans/6.1-order-change-substrate.md
index 293d61fbad..6bc40ec54c 100644
--- a/docs/plans/6.1-order-change-substrate.md
+++ b/docs/plans/6.1-order-change-substrate.md
@@ -4,7 +4,7 @@
**Target:** Spree 6.1
**Depends on:** 6.0-service-workflows.md (workflow tier), 6.0-returns-exchanges-claims.md (first consumer), 6.0-cart-order-split.md (Order is immutable-by-default after placement)
**Author:** Damian + Claude
-**Last updated:** 2026-08-10
+**Last updated:** 2026-08-30 (Phase 5 superseded — substrate is strictly post-placement; applier pricing rulings added)
## Summary
@@ -177,6 +177,19 @@ Each `kind` has a known applier — a plain method on the confirm workflow, not
a class hierarchy. Extensions add kinds through the `register_action_kind`
seam (see Extension surface).
+Two rulings from the negotiated-pricing work (2026-08-30,
+`6.0-draft-order-negotiation-mechanics.md`):
+
+- **Appliers never derive unit prices.** An `update_item` quantity applier
+ applies the quantity; the line's price is data — in particular a
+ `price_source: 'manual'` (negotiated) line must come through an amendment
+ untouched.
+- **A post-placement price change is its own action kind** —
+ `update_item_price` (stamping `price_source: 'manual'`), registered when
+ the first consumer needs it. It is the sanctioned "we agreed a new unit
+ price after placement" gesture; discounts stay itemized concessions,
+ never price-change vehicles.
+
### Preview
```ruby
@@ -333,8 +346,20 @@ returns keep working with `order_change_id` null.
### Phase 5 — draft orders
-Amending a draft order becomes an OrderChange, so draft-order editing and
-placed-order editing share one implementation.
+~~Amending a draft order becomes an OrderChange, so draft-order editing and
+placed-order editing share one implementation.~~
+
+**Superseded (2026-08-30, quote-work review):** the substrate is strictly
+**post-placement**. A draft order (`status: 'draft'`, `cart_id: nil`) is
+directly mutable, carries no payments and therefore no balance to settle —
+the confirm spine (settle at the gateway, re-derive statuses) is meaningless
+for it, and forcing drafts through preview-then-apply is pure ceremony. This
+is also what keeps B2B quotations thin
+(`spree-enterprise-v2/docs/plans/b2b-quotes.md`): pre-acceptance negotiation
+edits the mutable draft directly and needs no change-set; only
+post-conversion amendments ride OrderChange. The admin edit screen may share
+components across drafts and placed orders, but only placed orders create
+`OrderChange` rows.
## Constraints on Current Work
diff --git a/docs/plans/6.1-order-stages.md b/docs/plans/6.1-order-stages.md
new file mode 100644
index 0000000000..046d364e23
--- /dev/null
+++ b/docs/plans/6.1-order-stages.md
@@ -0,0 +1,150 @@
+# Merchant-Composed Order Stages
+
+**Status:** Draft — design finalized 2026-08-30, nothing built
+**Target:** Spree 6.1
+**Depends on:** Service Workflows (6.0-service-workflows.md — statuses doctrine), B2B Wholesale Shipping (6.0-b2b-wholesale-shipping.md — the orders this serves), Events system
+**Author:** Damian + Claude
+**Last updated:** 2026-08-30
+
+## Summary
+
+A B2B order can be commercially active for weeks while nothing sits in a
+warehouse: confirmed → in production → quality control → ready for shipment.
+Today that lifecycle has no home — order `status` is a frozen three-value
+constant (`draft | placed | canceled`) written only by workflows, and rightly
+so. This plan gives merchants a **parallel, per-store stage axis they compose
+visually in the dashboard**: ordered stage definitions, a current-stage
+pointer on the order, per-stage customer visibility, an order-level expected
+ready date, and events on every stage change for automation and mail. No
+commerce platform offers this (2026-08-30 research): the closest is
+merchant-created status *labels* pinned to fixed states that never
+participate in the workflow, or fully custom state machines that are
+code-config only — while a paid-app economy on the biggest platform proves
+the demand. The design is the two-axis shape the codebase already uses
+(fulfillment `status` vs `tracking_status`) and the one the ERP world
+converged on: **stages are process tracking and presentation; semantic
+statuses stay code-owned**.
+
+## Key Decisions (do not deviate without discussion)
+
+- **Stages are data; statuses stay code** (2026-08-30, interactive review):
+ `Spree::OrderStage` rows are store-scoped, ordered (`acts_as_list` →
+ drag-reorder per dashboard convention), named, translatable, with a
+ `customer_visible` flag. The order gains a nullable `order_stage_id`.
+ Semantic statuses (`Order::STATUSES`, payment/fulfillment rollups) remain
+ code-defined and workflow-written — a merchant must never be able to
+ break checkout, money, or stock from a settings screen. `Order` is
+ deliberately NOT migrated to `has_status` for this; the stage axis is
+ the answer to extensibility, and `add_status` remains the code-level
+ path for models that have it.
+- **No transition graph, ever.** Any stage can follow any stage; staff move
+ orders freely (`Spree::Orders::SetStage` — a plain service, the single
+ writer, publishing `order.stage_changed`). Validating transitions
+ centrally would be a state machine by another name — the exact thing 6.0
+ removed. Automation (mails, webhooks, external systems) rides the event.
+- **Auto-enter bindings are event-driven labeling, never gating**
+ (2026-08-30, follow-up discussion): a stage may optionally declare
+ `auto_enter_on` — an event name picked from a curated dropdown backed by
+ the `Spree.order_stage_events` registry (`order.placed`, the payment
+ schedule's deposit-covered / balance-paid moments,
+ `fulfillment.fulfilled`, `fulfillment.delivered`, …; extensions register
+ their own events, which is how a developer's custom status feeds a
+ merchant's stage). A subscriber reacts to the bound event by calling
+ `SetStage` — the binding only ever moves the pointer *after* something
+ already happened; it can veto nothing. One stage per event per store
+ (validated). This is what makes the composer a flow, not a label list —
+ and it stays doctrine-safe because reaction is not enforcement. A
+ merchant can compose either presentation: true stages beside the derived
+ payment/fulfillment axes, or one linear timeline where those milestones
+ appear as bound stages.
+- **Stages carry zero commerce semantics.** Nothing in checkout, payments,
+ stock, fulfillment, tax, or pricing may read the stage. The one designed
+ touchpoint is display composition: the customer order view shows the
+ stage (when visible) beside the payment schedule and fulfillment state.
+- **`expected_ready_on` is an order-level merchant promise** (nullable
+ date) — distinct by design from the variant's `preorder_ships_at` (a
+ supply fact) and the fulfillment's `estimated_delivery_at` (carrier
+ truth). Set by staff, shown to the customer, never derived.
+- **Deleting a stage definition nils the pointer** (`dependent: :nullify`
+ + a dashboard confirm listing affected order counts); order history
+ keeps the trail through the emitted events, not through the row.
+
+## Design Details
+
+```ruby
+class Spree::OrderStage < Spree.base_class
+ include Spree::SingleStoreResource
+ include Spree::Metadata
+
+ acts_as_list scope: :store_id
+
+ belongs_to :store, class_name: 'Spree::Store'
+ has_many :orders, class_name: 'Spree::Order', dependent: :nullify
+
+ validates :name, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }
+ # customer_visible boolean, default false
+ # auto_enter_on string, nullable — an event name from Spree.order_stage_events;
+ # one stage per event per store (validated)
+end
+```
+
+- `spree_orders.order_stage_id` (nullable — nil is "no stage", today's
+ behavior) + `spree_orders.expected_ready_on` (date, nullable).
+- `Orders::SetStage.call(order:, stage:, actor:)` — staff surfaces only;
+ publishes `order.stage_changed` with old/new stage in the payload.
+- Admin API: `/admin/order_stages` CRUD (settings scope, reorder via
+ `position`), `order_stage_id` + `expected_ready_on` on order update;
+ ransackable `order_stage_id` for list filtering.
+- Store API: order serializer exposes `stage` (name only, when the stage
+ is `customer_visible`) and `expected_ready_on` — composing the buyer
+ view the merchant sketched: stage + expected date + payment schedule +
+ shipment summary + documents. Because stages are ordered and
+ visibility-flagged, the serializer can also expose the visible subset's
+ position ("step 3 of 6") for a storefront progress indicator.
+- A stage-binding subscriber listens to registered events and calls
+ `SetStage`; `Spree.order_stage_events` is the curated registry the
+ composer's dropdown reads (core lifecycle events seeded; extensions
+ append).
+- Dashboard: a Settings → Order stages composer (drag to order, visibility
+ toggle per stage — the visual composition that is the differentiator), a
+ stage select on the order page, a list column + filter.
+
+## Migration Path
+
+1. Schema + model + `SetStage` + event.
+2. Admin API + dashboard composer + order-page select.
+3. Store serializer + storefront display.
+
+Nothing to migrate; no stages defined = no change anywhere.
+
+## Constraints on Current Work
+
+- **Nothing in commerce logic may branch on `order_stage_id`** — stages
+ are tracking/presentation; a feature needing a real gate needs a real
+ status or workflow validation.
+- **No transition rules on stages** — not in core, not via extension
+ points; automation belongs on the `order.stage_changed` event.
+- **Don't add per-store status vocabularies to `has_status` models** —
+ statuses stay process-global code; per-store process expression is this
+ stage axis.
+
+## Open Questions
+
+1. **Per-channel or per-flow stage sets** (retail orders shouldn't show a
+ "Production" stage) — deferred; v1 is one set per store and the
+ customer-visible flag covers most of it. Unblocked by: merchant
+ feedback after 6.1.
+
+## References
+
+- Merchant feedback, 2026-08 (configurable pre-shipment stages; production
+ lead time; customer visibility) + the maintainer's status-composer
+ question.
+- Landscape research 2026-08-30 (no platform offers composed stages;
+ label-on-state and code-config precedents; app-economy demand) —
+ private, not in this repo.
+- Two-axis precedent: `spree/core/app/models/spree/fulfillment.rb`
+ (`status` vs `tracking_status`).
+- Statuses doctrine: `spree/core/app/models/concerns/spree/has_status.rb`
+ ("validating transitions centrally would be a state machine by another
+ name").
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 8e9a378ae8..42e3264c89 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -4064,3 +4064,350 @@ does this context pay*. No cleanup migration: any pre-release rows of the
dropped kinds were always inert (the inclusion validation runs on the
assignment row, which nothing re-saves), so they are left to lie. Plan
amended: `6.0-b2b-companies-and-catalogs.md`.
+
+## 2026-08-30 — Wholesale shipping ships in 6.0: PackageType, unpriced rates, collected deposits; lot-level inventory joins inventory-operations
+
+Merchant feedback (wholesale carton/pallet/container shipping) turned into
+two new plans plus an inventory-operations extension. The decisions other
+plans need to know about:
+
+**`Spree::PackageType` is the packaging vocabulary and replaces the four
+`default_package_*` store preferences.** Store-scoped rows (`box | envelope
+| carton | pallet | container`, one default per store, Channel-style
+demotion); the default row is what `Stock::Package#weight`/`#dimensions`
+and the EasyPost parcel path read, with the preferences kept as deprecated
+one-release bridges. The name is deliberately not `Spree::Package` —
+`Spree::Stock::Package` is the in-memory packing unit and a persisted
+sibling with that name would be permanently confusing. Variant carton data
+is a **reference to a carton-kind row** (`carton_package_type_id`) plus
+per-variant packing facts (`units_per_carton`, `carton_weight`,
+`cartons_per_pallet`) — geometry is shared, packing facts are not.
+
+**Unpriced delivery rates are first-class.** `Estimate` and
+`spree_delivery_rates` gain `unpriced`; the estimator skips markup and
+serializers/UIs render "quoted after review". A zero-cost rate displaying
+as "Free" was rejected as the mechanism. Volume math behind the CBM tier
+rules is **unit-aware from day one** (a new conversion helper) — the
+raw-number shortcut recorded for `WeightRule` (2026-07-29) explicitly does
+not extend to volume, where cm-vs-in is a 16× error.
+
+**Deposits are collected, not just displayed** — the ambitious option,
+chosen deliberately in review. A freight method's `deposit_percentage`
+changes what `Carts::Complete` requires payments to cover
+(`Cart#amount_due_at_checkout`; base = the order total at placement);
+orders complete `partially_paid` against the existing
+`outstanding_balance`. Consequence for all order code: **completed no
+longer implies paid in full**. The later freight quote is a
+`Fee(kind: 'freight')` through the existing admin fees endpoint, never a
+delivery-rate edit. *[Amended same day — the method-level deposit became a
+default source feeding the order's `payment_terms` snapshot; see the
+payment-terms entry below.]*
+
+**Quantity rules (MOQ / order multiple / purchase unit) are a purchasing
+layer, never inventory.** Stock stays in units everywhere; enforcement
+lives in the item workflows and completion, the server refuses invalid
+quantities rather than rounding. Contextual tiers (the same SKU at retail
+1/1 and wholesale 48/24) were committed with the owner entity initially
+unresolved. *[Resolved same day — the tiers live on the Catalog; see the
+one-question-per-entity entry below.]*
+
+**`Spree::ChannelRule` is the home for channel-scoped gates.**
+*[Superseded same day — see the one-question-per-entity entry below: the
+family is dropped; terms went to the Catalog and gating stayed as Channel
+preferences.]*
+
+**Lot-level inventory (full tracking, not provenance-only) joins
+`6.0-inventory-operations.md`.** `Spree::StockLot` decomposes a
+lot-tracked variant's `count_on_hand` per location, kept in sync
+transactionally with typed movements (`stock_lot_id` on movements);
+receives assign lots, dispatch picks FEFO, allocation stays lot-agnostic.
+Lot numbers live only on `StockLot` rows.
+
+Plans: `6.0-b2b-wholesale-shipping.md`, `6.0-b2b-quantity-rules.md`,
+`6.0-inventory-operations.md`.
+
+## 2026-08-30 — One question per entity: Channel is the surface, Catalog is the agreement, PriceList is the numbers
+
+A stop-and-analyze pass over Channel (live), PriceList (live), and Catalog
+(unreleased) — triggered by the question of whether channel purchase rules
+duplicate catalog terms (they do) — settled the doctrine each of the three
+entities lives by. Each answers exactly one question with exactly one
+targeting mechanism:
+
+**Channel answers "where is the buyer shopping."** Publications, publishable-
+key binding, order routing, the stock-location allowlist, and access gating.
+Gating (`storefront_access`, `guest_checkout`) **stays as Channel
+preferences and never moves to catalogs**: it must bind before the buyer has
+an identity, and catalogs resolve *from* identity — a catalog cannot gate
+the door to the thing that determines the catalog. The `ChannelRule` STI
+family proposed earlier the same day is dropped; nothing purchase-shaped
+remains for it.
+
+**Catalog answers "what is this buyer's agreement."** Assortment (optional),
+its price list (optional), and — new — commercial terms: catalog-level
+`minimum_order_quantity`/`order_multiple` columns with per-variant override
+rows, and per-currency order minimums, resolved **per-field,
+nearest-agreement-wins** through the existing `Catalog.for_context` chain
+(nearest company node → customer groups → the channel's default catalog).
+All-or-nothing resolution was rejected — an agreement silent on a field
+passes it through rather than waiving it. The channel-level minimum falls
+out for free: it is the terms on the channel's *default catalog*, so no
+second mechanism exists. A terms-only catalog (empty assortment, no list)
+is legitimate. Terms are typed tables/columns per grain — never one
+generic `catalog_rules` table or an STI rule family (rules are matching
+predicates; terms are values on the hot path needing indexed lookups and
+DB uniqueness — the typed-adjustments doctrine).
+
+**PriceList answers "what are the numbers."** Price rows, dates, status,
+and *context* rules only. The audience-shaped rules duplicated catalog
+assignment with different precedence and are removed from the vocabulary:
+`PriceRules::CustomerGroupRule` and `PriceRules::UserRule` are **deprecated
+in 6.0** (one-release bridge + a data task converting each such list into
+an assortment-less catalog assigned to the audience and owning the list).
+`PriceRules::ChannelRule` is **grandfathered** — kept working, nothing new
+builds on it, the forward path being the channel's default catalog.
+`MarketRule` (carries VAT restatement) and `VolumeRule` are context-shaped
+and stay first-class. Price lists also gain **automatic pricing**
+(`6.0-price-list-automatic-pricing.md`): a signed percentage adjustment off
+base prices, computed on read (never materialized), currency-rounded,
+currency-agnostic, with explicit rows as per-variant overrides.
+
+**The list binding inverts: `spree_price_lists.catalog_id` replaces
+`spree_catalogs.price_list_id`.** A list is standalone (rule-matched) or
+owned by exactly one catalog, and generic matching skips owned lists by
+FK. This closes a live leak in the unreleased derived-set design:
+`Catalog.bound_price_list_ids` excluded only lists bound to **active**
+catalogs, so deactivating a catalog dropped its typically rule-less list
+into generic matching — pricing the entire store. Detaching a list is now
+an explicit act (dashboard warns that the list will start matching by its
+rules). Sharing one list across catalogs is lost; one catalog serving many
+audiences through assignments is the replacement.
+
+**Setup is catalog-first and one go.** The catalog page is the agreement
+editor (audiences, assortment, inline pricing card for the owned list,
+terms, and a products-with-prices view exposing assortment↔pricing
+divergence); the create flow takes the pricing choice (base / ±% / fixed)
+and the admin catalog endpoints accept an inline `price_list` payload, so
+standing up an agreement never requires visiting the price-lists page.
+
+Rejected alternatives, for the record: merging Catalog and PriceList (forces
+assignment-targeting and rule-matching into one entity — the ambiguity the
+2026-08-28 narrowing removed — and rewrites a released surface); killing
+Catalog (renames the merge); audience price rules kept alongside catalog
+assignment (two mechanisms, silent precedence). Supersedes the `ChannelRule`
+paragraph and resolves the "tier owner unresolved" clause of the earlier
+2026-08-30 entry. Plans amended: `6.0-b2b-companies-and-catalogs.md`
+(amendment block), `6.0-b2b-quantity-rules.md` (design finalized),
+`6.0-price-list-automatic-pricing.md` (new).
+
+## 2026-08-30 — Company registration is OSS 6.1 mechanisms; the approval flow is Enterprise onboarding
+
+The B2B front door splits along the recorded boundary. **OSS 6.1**
+(`6.0-b2b-company-self-registration.md`) ships the mechanisms: storefront
+company self-registration (`POST /store/companies` — an authenticated
+customer, including an existing retail customer, founds a root company +
+their membership in one call; companies are **born active**), a fourth
+storefront access posture **`approval_required`** (prices + checkout
+require a standing over an active company; shipped `prices_hidden`
+semantics untouched), a machine-readable **`pricing_access`** code beside
+every nulled price (no more bare nulls a client must interpret), and a
+dependency-registered **`Companies::ActivationPolicy`** consulted by every
+company-resolving call site (catalog resolution, both
+`sole_standing_company`s, cart company writes, the posture) — OSS default:
+every company is active, so the posture reads "company members only".
+Deliberately 6.1: every piece is additive, nothing needs the 6.0 breaking
+window, and 6.0 work must not build interim approval primitives in the
+meantime.
+
+**Enterprise** (`spree-enterprise-v2/docs/plans/b2b-company-onboarding.md`)
+registers the policy and owns the flow: an application record (FK → the
+OSS company; `spree_companies` stays status-free — this supersedes the
+same-day draft that put five statuses on Company), the seller-onboarding
+shape reused deliberately — requirements + submissions + evaluated-on-read
+statuses + exactly two enforcement points, reopen-with-note as the
+request-more-information move — plus the review queue, mails, and
+`approval_pending` pricing codes. Rationale: no modern platform ships
+registration approval in open source and everyone who has it charges for
+it, while the OSS side keeps a real free feature (instant self-registration
+— open-starter parity) and the funnel shape holds: registration works free,
+verification is the upgrade trigger. Two approval concepts stay distinct
+forever: account verification (merchant ↔ company, this split) vs order
+approvals/spend limits (company-internal governance, the existing
+Enterprise plan).
+
+**Constraints now (OSS):** any new code resolving a company for
+visibility, pricing, or checkout consults the activation policy (and the
+two `sole_standing_company` implementations stay mirrored); self-service
+standing is never approval-gated; new prices-hidden surfaces carry the
+`pricing_access` code; no status/approval columns on `spree_companies`;
+customer-group membership is never an activation mechanism.
+
+## 2026-08-30 — Quotes: OSS ships the negotiation mechanics, Enterprise the quote product; the OrderChange substrate is strictly post-placement
+
+Merchant feedback proposed building B2B quotations by extending draft
+orders, and the code audit confirmed the instinct: a 6.0 draft order
+(`Spree::Order`, `status: 'draft'`, `cart_id: nil`) already carries the
+editing engine — items, addresses, manual fees/discounts that survive
+recalculation and freeze at placement, notes, invoice-later conversion via
+`payment_pending`. Four things were missing: a customer-facing surface,
+negotiated unit prices, a lifecycle, and a cart-copy service. The tier
+split mirrors company registration:
+
+**OSS (`6.0-draft-order-negotiation-mechanics.md`)** ships the
+mechanics that are features in their own right. In 6.0: **manual line-item
+pricing** — admin item endpoints accept `price`, stamping
+`price_source: 'manual'`, and the provenance column gains its first
+readers as guards (`Carts::PriceItems` skips manual rows;
+`LineItem#should_update_price?` answers false for them) so a quantity edit
+no longer silently re-prices a negotiated line; `'manual'` is a reserved
+key no pricing provider may register; `price: null` is the explicit
+revert; overrides are pre-placement only and `price_source` stays off
+store serializers. Plus two fixes: `Orders::Create` stamps `created_by`
+(never written despite the column), and the `payment_pending` docstring
+lied — completion yields `payment_status: 'none'`, not `'balance_due'`
+(whether unpaid-placed deserves a distinct value belongs to the
+wholesale-deposit rollup work, decided once). In 6.1:
+`Orders::CreateFromCart` — copy a customer's cart into a fresh draft order
+leaving the cart untouched (deliberately not the completion copier, which
+re-points money records and is one-shot).
+
+**Enterprise (`spree-enterprise-v2/docs/plans/b2b-quotes.md`)** owns the
+quote product: a thin `Quote` row over the draft order (own model → clean
+`Q` numbers from the per-resource sequence; one quote per draft), statuses
+`draft → sent → accepted → converted` (+ `changes_requested`, `expired`
+evaluated on read against `valid_until`, `canceled`), buyer PO
+reference via the order's fields, `/store/quotes` view + accept (runs
+`payment_pending` completion; placement freezing is the price lock) +
+request-changes, mails. The quote never duplicates order data.
+
+**The OrderChange substrate narrows (Phase 5 superseded).** The 6.1 plan
+had draft-order amendments becoming OrderChanges "so draft-order editing
+and placed-order editing share one implementation" — wrong in the split
+world: a draft is directly mutable with no payments and no balance to
+settle, so preview-then-apply is ceremony there, and pre-acceptance quote
+negotiation needs no change-set (unlike the competitor whose draft is
+placed-like). The substrate is strictly post-placement; edit screens may
+share components, but only placed orders create OrderChange rows. Two
+applier rulings recorded with it: **appliers never derive unit prices** (a
+manual price comes through an amendment untouched), and a post-placement
+price change is its own future action kind (`update_item_price`), never a
+discount abused as one.
+
+## 2026-08-30 — Buyer PO numbers: a plain order reference, required per company, never a payment method
+
+Merchant feedback asked for the customer's purchase-order number as a
+permanent order reference, and the platform research settled the shape.
+The market: the largest platform's `poNumber` is a first-class, always-on,
+optional field at B2B checkout with no configuration surface at all (staff
+can edit it post-placement; their own emails cannot even render it); the
+two platforms that control PO behavior at all hang it **per company**; two
+platforms tie the number to an offline "Purchase Order" payment method —
+an anti-pattern we explicitly reject (a reconciliation reference must not
+depend on tender choice); nobody ships PO **document upload** on orders
+(native attachments exist only on quotes).
+
+Spree 6.0 ships (`6.0-b2b-customer-po-numbers.md`): `po_number` on cart +
+order (copied at completion, staff-correctable after placement as a plain
+write), optional `po_document` private-storage attachment (an order-native
+first), and `po_number_required` on `Spree::Company` — per-company per the
+market and the merchant ask, deliberately NOT a catalog term (a PO
+requirement is the buyer's procurement process, not the commercial
+agreement, and no platform models it on the assortment/pricing side) —
+enforced in `Carts::Complete` for customer checkouts. `po_number` is
+ransackable and the dashboard order search matches order number OR PO
+number. The Enterprise quote plan drops its own `customer_reference` +
+attachment in favor of the order's fields. Naming guard: `po_number` (the
+buyer's reference) and `Spree::PurchaseOrder` (the merchant's procurement
+document, `6.0-inventory-operations.md`) are opposite directions and never
+share endpoints, serializers, or vocabulary. "Only an authorised buyer may
+submit the company's PO" is Enterprise governance (company-role
+capability), untouched here.
+
+## 2026-08-30 — Payment terms split on the risk line; stages are data, statuses stay code; documents without invoices
+
+The deposits/terms/documents feedback plus the maintainer's status-composer
+question resolved into three plans and one doctrine ruling.
+
+**Payment terms split where the risk flips** (`6.0-6.1-b2b-payment-terms.md`):
+collect-first terms (prepaid, N% deposit + a balance-due *label* — the
+merchant's own "configurable label rather than automating every workflow")
+are OSS; ship-first terms (Net N, due dates, credit, invoicing, dunning)
+stay Enterprise roadmap item #1. The order carries **one frozen
+`payment_terms` snapshot** resolved from layered sources — quote/order
+override → company's `PaymentTerm` preset → the freight method's deposit
+preferences (demoted same-day from anchor to default source; wholesale plan
+amended) → none. The derived payment **schedule** (due-now, deposit state,
+balance + label) is computed on read; `Orders::UpdateStatuses` is untouched
+— `partially_paid` is the ledger truth, the schedule is the commercial
+truth. `PaymentMethod::BankTransfer` joins core with public-preference
+account details, and every payment gains a stored, generated, ransackable
+**`reference`** (structured, RF-style) — deliberately never the derived
+`R1001-P1` number, whose NULL column had silently broken ransack search and
+the Stripe `find_by(number:)` lookup (6.0 fixes recorded). Storefront
+pay-balance lands 6.1 and resolves the wholesale plan's open question 1.
+
+**Stages are data; statuses stay code** (`6.1-order-stages.md`): merchants
+compose a per-store, ordered, customer-visibility-flagged stage axis in the
+dashboard (`Spree::OrderStage` + nullable `order_stage_id` +
+`expected_ready_on` on orders; `Orders::SetStage` publishing
+`order.stage_changed`; optional auto-enter event bindings from the
+`Spree.order_stage_events` registry — event-driven labeling, never
+gating), while semantic statuses remain code-defined and workflow-written.
+**No transition graph, no commerce semantics on stages, ever** — nothing
+in checkout/payments/stock may branch on a stage; a needed gate is a code
+status/workflow validation; per-store status vocabularies on `has_status`
+models are forbidden (statuses are process-global code; per-store process
+expression is this axis). `Order` is deliberately not migrated to
+`has_status`. Landscape: no platform offers composed stages
+(label-on-fixed-state and code-config-machine are the closest), so this is
+an OSS first with a proven app-economy demand.
+
+**Documents without invoices** (`6.1-b2b-order-documents.md`):
+`Spree::OrderDocument` = uploaded files on orders (private storage,
+per-document customer visibility, buyer uploads allowed), and two
+client-side prints extending the shipped packing-slip pattern — a
+carton/pallet/CBM packing list off the frozen freight summary and a
+payment-instructions sheet off the terms schedule + bank reference. **No
+invoice vocabulary in OSS** — no model, number, or document called an
+invoice, no PDF stack in core; numbered proforma/commercial documents are
+the Enterprise invoicing product. `expected_ready_on` is an order-level
+merchant promise, deliberately distinct from the variant's
+`preorder_ships_at` (supply fact) and the fulfillment's
+`estimated_delivery_at` (carrier truth).
+
+## 2026-08-30 — Enterprise B2B ships on 6.0 GA: registration mechanisms and the cart→draft copy pulled forward
+
+Sequencing the whole plan set exposed a commercial inversion: both designed
+Enterprise B2B products (company onboarding, quotes) depended on OSS pieces
+scheduled for 6.1 — deferred there purely on the additive test, not
+necessity — leaving Enterprise revenue features gated behind a release that
+does not exist yet. Retargeted the same day:
+`6.0-b2b-company-self-registration.md` (renamed from 6.1 — the activation
+policy, `approval_required` posture, `pricing_access` codes and the
+registration endpoint are small, additive, and exist *for* Enterprise to
+build on) and the `Orders::CreateFromCart` phase of
+`6.0-draft-order-negotiation-mechanics.md` (renamed from 6.0-6.1) both land
+late in 6.0. This supersedes the "deliberately 6.1" clauses in the two
+earlier entries above. Consequence: **onboarding starts after the 6.0
+front-door wave, quotes after 6.0 wave 1 — every designed Enterprise B2B
+product needs nothing beyond 6.0 GA.** Track C (credit terms/invoicing)
+deliberately stays behind OSS 6.1 wave 6: it is roadmap-stage, and it can
+begin earlier on the 6.0 `payment_terms` snapshot if needed (the `kind`
+vocabulary is extensible and Enterprise may assign terms from its own
+tables), adopting the OSS `PaymentTerm` presets, bank-transfer method and
+payment references when they land.
+
+## 2026-08-30 — Scope trim: lot tracking defers to 6.1
+
+The counterpart of the same day's pull-forwards: limiting 6.0 scope. Lot
+tracking is the biggest additive chunk in the new set (new table, FEFO
+picking, receive/pick integration, admin surfaces), opt-in per variant, and
+nothing in 6.0 or the Enterprise GA products depends on it — so it moves to
+6.1 within `6.0-inventory-operations.md` (the plan keeps both halves:
+transfers/POs 6.0, lots 6.1). Flagged alongside: the transfer lifecycle's
+removal of the one-shot `StockTransfer.transfer` API is that plan's one
+breaking piece — it either uses the 6.0 window or ships in 6.1 behind the
+standard deprecation bridges; decided when inventory-operations is groomed.
+Further optional trims, in order, if 6.0 needs more relief: the one-go
+catalog wizard polish, the wholesale storefront surfaces, automatic pricing
+(last resort — the catalog wizard's ±% option wants it).