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.

198 KB
Raw Blame

Multi-Vendor Marketplace (Open Source Core)

Status: In Progress — design complete (2026-08-15, auth/API surface + the last blocking questions settled). Phase 0 (admin-branch hardening), Phase 1 (seller identity, teams, lifecycle workflows, mail, the seller API branch), Phase 1b (the shared catalog — Decision 11), Phase 2 (commission engine), Phase 3 (order splitting — OrderGroup, PaymentSplit, the split inside Carts::Complete, 2026-08-20), Phase 3a (the two-level fund ledger, 2026-08-22) and Phase 3b (OSS Stripe Connect payouts, 2026-08-22) implemented; Phase 4 (dashboards) remains, along with the seller-facing onboarding screens Target: Spree 6.0 (the "Marketplace" release) Depends on: 6.0-cart-order-split.md (Cart/Order split + dual-FK LineItem owner (cart_id/order_id, #owner method) — expanded 2026-07-27; Phase 3 design can now freeze against it), 6.0-6.1-split-adjustments.md (TaxLine/Discount/Fee replace polymorphic Adjustment), 6.0-order-routing.md (per-seller stock location), 6.0-fulfillment-and-delivery.md (Fulfillment/DeliveryMethod vocabulary, per-seller delivery selection), 6.0-admin-spa.md (seller panel composition), 6.0-admin-api.md (Marketplace endpoints), 6.0-platform-auth.md (Spree::AdminUser is the seller principal; strategy registries + JWT audiences — shipped in PR #14380), 6.0-admin-rbac.md (permission catalog, RoleUser resource typing, seller audience direction — shipped in PR #14412) Author: Damian + Claude Last updated: 2026-09-16

Summary

Open-source the core of Spree's multi-vendor marketplace into Spree 6.0, per spree/spree#13323. Today multi-vendor lives in the paid Enterprise module as a decorator-heavy monkey-patch of core (dozens of prepended core classes, a parent order mutated into a line-item-less "splitted" state). 6.0 brings the Seller identity, per-seller order splitting, the commission engine, and the payout ledger into core as first-class models — built natively on the 6.0 Cart/Order split rather than retrofitted onto the legacy Order-only model.

What stays paid (Enterprise — boundary amended 2026-07-15 and 2026-10-27, see decisions.md): ledger⇄provider reconciliation, KYC/account-health operations, payout reports (incl. DAC7), marketplace-facilitator taxes, Shopify/WooCommerce sales-channel apps, the category mapper. Basic Stripe Connect execution — Express onboarding + on-fulfillment transfers — ships open-source in the monorepo, alongside the Stripe core gateway being pulled in from the standalone spree_stripe repo (the payment-sessions-API classes only; the legacy v2-API/storefront code stays behind — likely home: spree/core). Core runs the happy path end-to-end (onboard, sell, get paid); Enterprise operates the unhappy paths and compliance at scale.

This plan covers the four subsystems: (A) seller identity & teams, (B) order splitting, (C) the commission engine, and (D) the payout/fund-transfer ledger. It is informed by a source-level port review of the current Enterprise multi-vendor module (private source — internals deliberately not cited here), the Enterprise behavior documented in the public user docs, and a survey of modern open-source marketplace implementations — see References (competitor names and the detailed comparison are likewise kept out of this public file).

Key Decisions (do not deviate without discussion)

Scope split (OSS 6.0 vs Enterprise) — per #13323, amended 2026-07-15 (basic Stripe execution → OSS; see decisions.md)

OSS core (this plan) Enterprise (stays paid)
Spree::Seller identity + invitation and self-serve application onboarding state machine + seller teams (reusing Role/RoleUser/Invitation) KYC/account-health operations (requirements monitoring, restricted-account workflows)
Seller admin dashboard (composed from @spree/dashboard-*) + operator marketplace screens Refund clawbacks — moved to OSS 2026-10-27: the Stripe provider reverses the transfer on refund
Basic Stripe Connect payouts (Express onboarding link + on-fulfillment transfers — ships with the monorepo Stripe gateway) Ledger⇄Stripe reconciliation
Commission engine (seller- + product- + category-level rules, commission taxation) Payout reports (incl. EU DAC7 seller-income reporting)
Order splitting + payment split Shopify white-label Sales Channel app
Fund ledger — SellerTransfer (on-fulfillment earnings) + SellerPayout (scheduled settlement) + balance, lifecycle, reversals WooCommerce integration
Seller CSV import/export (rides the Spree::Import/Spree::Export pipeline) Category mapper (external category → Spree taxon)
Sellers API endpoints (Admin + Store) + lifecycle webhooks/events + onboarding task registry (core tasks) Enterprise onboarding tasks registered into the core checklist (Stripe KYC, Shopify/Woo store connection)
Merchandising + permissions (via code) "Automatic taxes" (marketplace-facilitator remittance)

The boundary is operational depth: you can run a marketplace for free end-to-end — sellers onboard to Stripe Express through a hosted link and get paid automatically on fulfillment — and core records what each seller is owed (the payout ledger). The moment you need the money operations — ledger⇄Stripe reconciliation, KYC workflows, regulatory reporting, tax remittance — that's Enterprise (Decision 9).

The OSS payout story is execution-capable, not just record-keeping (amended 2026-07-15): the monorepo's Stripe gateway ships a basic PayoutProvider::StripeConnect — Express onboarding + on-fulfillment transfers — so the free tier demos money movement end-to-end, at parity with the surveyed OSS competition. PayoutProvider stays a public interface, so community providers (PayPal Payouts, Wise, SEPA batch files) are first-class. Enterprise differentiates on the operations around the money, not on whether money moves.

Spree::Seller name ownership (RESOLVED 2026-07-14; renamed 2026-08-17)

Spree::Seller (prefix sel_, table spree_sellers) is the marketplace seller — this plan's model. The purchase-order procurement source is Spree::Supplier (sup_, spree_suppliers, /api/v3/admin/suppliers). They are different lifecycles: a supplier is an address-book entry the merchant buys stock from; a seller is an onboarded selling party with users, commission, and payouts.

Both models were originally called Spree::Vendor — a hard collision resolved on 2026-07-14 by giving the marketplace the Vendor name and renaming the procurement source. The split stood; the naming was reversed on 2026-08-17 once the two reasons for it expired (the user docs are being rewritten for 6.0 stable, and there is no Enterprise production data to keep ven_ continuity with). vendor was the wrong word for the marketplace side precisely because this schema also holds the supplier: Amazon's Vendor Central buys from suppliers while Seller Central hosts third parties, so vendor_id reads as the procurement relationship to anyone with Amazon experience. Seller is also what Gartner, Forrester, VTEX, Marketplacer, Amazon and Mercur all use for this entity. Full rationale in decisions.md 2026-08-17.

1. Split happens at cart completion, into N child Orders under one parent — never seller-tagged flat line items

The legacy module and current industry implementations agree on the shape, and it maps cleanly onto 6.0-cart-order-split.md:

  • One mixed Spree::Cart through the entire shopping + checkout flow (a customer adds items from many sellers to one cart — no per-seller cart fragmentation).
  • At cart.complete! (the Spree::Carts::Complete service from the cart/order-split plan), partition cart line items by the denormalized line_item.seller_id snapshot (set from product.seller at add-to-cart; revalidated at completion — see Order splitting) and, when the cart spans more than one partition (first-party items, seller_id: nil, count as their own partition), fan out into N child Spree::Orders, one per partition, all owned by one Spree::OrderGroup that holds customer/payment/address context. Single-partition carts complete as a bare order — no group (see the Trigger & gate bullet).
  • The parent↔child relationship is an explicit FK via a dedicated Spree::OrderGroup, not the legacy state == 'splitted' string hack and not a join-table indirection. See Design Details and Decision 8.

This is the single most important integration point with the rest of 6.0: the split is a consumer of the Cart/Order split, implemented inside the completion service, not a state-machine after_transition callback bolted onto a monolithic Order (which is how the legacy module did it). The 6.0 cart/order plan removes the order-level state machine entirely, so the legacy trigger cannot survive — splitting must be invoked explicitly from Carts::Complete.

2. Commission is a frozen snapshot line attached to the order line item, computed once at placement

Mirror the core insight from both the legacy module and the industry references: commission is denormalized and frozen at sale time, never recomputed on read. This matches Spree's existing EU Omnibus "frozen at sale" precedent (5.4-6.0-eu-legal-compliance.md PriceHistory).

  • New model Spree::CommissionLine (NOT a revival of the legacy commission table, NOT a polymorphic Adjustment). One row per commissioned line item — plus one per fulfillment when the rate commissions delivery revenue (include_shipping, Decision 4) — storing a snapshot of rate, amount, and the resolved rule's identity.
  • Written by a service during/after cart.complete!, once. A later rate change does not touch existing lines.
  • Frozen, not re-derived (corroborated 2026-08-17). A source review of the leading surveyed OSS engine found it re-resolves commission from current rate configuration on every refresh (order edit, return received, claim created), deleting and reinserting the lines — so editing a rate there retroactively changes what a seller was already charged on past orders. Its own documentation claims the opposite, which is worth knowing if it is ever used as a reference. Ours are a snapshot written once, the same rule the duties work settled ("never re-derive from the live catalog on an existing order").
  • Commission is NOT a Spree::Fee. 6.0-6.1-split-adjustments.md's Fee is a buyer-facing charge — it rolls into order.fee_total and the order total the customer pays. Commission is a platform ↔ seller settlement line the customer never sees; it must never touch order totals. CommissionLine is therefore its own off-order ledger table that merely follows the same typed-line design (concrete FKs, no polymorphic source, no state machine) as the split-adjustments family. The only real split-adjustments dependency is that tax lines / discounts / fees are line-item-attached, so they re-home cleanly to the child order during the split. (A buyer-facing marketplace service fee — StockX-style — would be a Spree::Fee with a kind; possible later, out of scope here.)

3. Commission taxation is a first-class field — this is the OSS differentiator

This is the one place where the legacy Enterprise module is ahead of the surveyed industry implementations and the reason #13323 calls out "commission taxation which is essential for European marketplaces." The common industry pattern uses an include_tax toggle that only decides whether the seller's item tax inflates the commission base; it charges no tax on the marketplace fee itself. The legacy module already charges VAT on the commission at a configurable per-seller rate (fee_total = fee_amount + fee_amount × tax_rate, half-up rounding). The marketplace's commission is itself a taxable B2B service the platform renders to the seller. 6.0 must model:

  • amount — the commission (the fee the platform charges the seller),
  • tax_amount — VAT/tax on that commission, at a configurable commission tax rate,
  • tax_rate — the rate that produced it, so the row explains its own figure,
  • taxability_reason + country_code/state_code — how the fee was treated and where, in Spree::TaxLine's vocabulary (see below),
  • total — amount + tax_amount.

One tax or several? → one, on the line (RESOLVED 2026-08-17). The fee's tax stays a scalar on CommissionLine — tax_amount plus the tax_rate it was charged at — rather than becoming child rows. A marketplace fee is a single supply to a single business, which is the EU case this plan exists for.

Reusing Spree::TaxLine was considered and rejected, and the reason is worth recording because the model genuinely fits: it already carries rate, amount, treatment, jurisdiction and provider. What does not fit is its scope. A tax line's owner is the cart or order because it is the buyer's tax: Carts::RecalculateTotals sums order.tax_lines straight into additional_tax_total, so a commission row stored there would inflate what the shopper pays — the one thing Decision 2 forbids — and /orders/:id/tax_lines returns them wholesale, so seller fee arrangements would become visible to any holder of read_orders. Both are fixable with a WHERE commission_line_id IS NULL, and that is exactly the cost: every future reader of tax_lines would have to remember, with an overcharged customer or leaked settlement data as the failure. Same shape, opposite side of the ledger.

What is borrowed instead is the vocabulary. The line carries taxability_reason validated against Spree::TaxLine.taxability_reasons — one list, so a provider registering a treatment registers it once — plus country_code/state_code through has_iso_geography, holding the seller's jurisdiction rather than the shopper's. Spree::CommissionTax is the ephemeral value object the resolver returns, carrying rate and treatment together; only the tax engine sets a jurisdiction, since an operator override or a store default is a number somebody typed and knows no country. Should a fee ever attract two levies at once, these are the columns that move to child rows, and they will already be named as TaxLine names them.

EU base (RESOLVED 2026-06-25): commission is computed on the seller's net (ex-VAT) item price, and tax_amount is applied on top of the commission — the marketplace fee is a separate taxable supply from the consumer's item sale, so the two VATs never mix. That base toggle stays available for non-EU/edge merchants who want a gross base (shipped as tax_inclusive), but the EU default is net-base + fee-VAT. The tax-on-the-fee field is mandatory and is the headline EU feature. The commission tax rate is resolved through 6.0-tax-provider.md (per-Market TaxProvider) rather than a bare platform_fee_tax_rate column on the seller (RESOLVED — see Resolved Decisions).

4. Commission rate resolution: layered rules, first match wins in operator order — generalize the legacy flat rate

The legacy module resolves a single flat percentage with a two-level fallback: the product's platform-fee override if set, else the seller's default rate. That is "very simplified" — percentage only; no categories, no caps, no currency scoping. The industry pattern generalizes this into a proper CommissionRate + CommissionRule engine (operator-ordered, first-match-wins, dimension-grouped targeting rules, percentage | fixed, min_amount floor, currency gate, no-rules = global default).

6.0 adopts the rule-engine shape but keeps the legacy fallback as the default ladder. New models Spree::CommissionRate (position, kind, value, currency, commission tax handling) + Spree::CommissionRule (polymorphic subject → Product / Category / Seller / global). Resolution walks enabled rates in list order, first match wins. Seed a marketplace-wide rate at the bottom of the list so narrower rates an operator adds resolve ahead of it.

Rule matching: every rule must hold, and a rule naming several records means any of them. A rate carries typed rules (Product / Category / Seller / value band / …); the rate matches a line item when every one of them says yes, and a rule holding several ids is satisfied by any of them. A category rule naming Electronics and Cameras beside a seller rule naming X reads "(Electronics OR Cameras) AND seller X" — which expresses plain lists and the seller × category pairing today's Enterprise sells (user docs: "per seller, per category-seller pairing, or per individual product") with no match_policy knob at all. The leading surveyed OSS engine uses the same semantics, so the model is proven; where we differ deliberately is precedence — an explicit operator-ordered list instead of implicit most-specific-wins, which is more predictable (already RESOLVED below).

Rule shape evidence (survey 2026-08-17). Read against the enterprise platform's own published API contract, our (subject_type, subject_id) rule is the weakest of the three models surveyed. There, a rule carries a typed configuration block — seller ids, channel codes, brands, condition codes — plus a validity period and an applicability ceiling, and its rate is a list of tiered thresholds rather than one number. Every dimension we currently cannot express without a migration (price band, channel, validity window, product attribute) is a field there. The other OSS engine shares our shape and is equally stuck: five hardcoded dimensions behind a switch with no extension point, and it removed its own minimum-amount cap rather than generalising it. The conclusion is that a commission rule needs its own configuration, not merely a pointer to a record — which is what the STI rule pattern already used by Spree::PriceRule and Spree::DeliveryMethodRule provides (see Resolved Decisions).

Two specifics worth copying rather than inventing. Tiering is expressed as thresholds carrying only a lower bound, so bands are contiguous by construction and can neither overlap nor leave a gap — safer than storing min/max pairs and validating the relationship. And precedence there is likewise an explicit operator-declared ranking (a per-category ordered list), not inferred specificity: both surveyed platforms independently concluded the merchant must be able to state which rule wins.

Precedence evidence (source review 2026-08-17). That engine is worth reading on this point because it has now tried both of the alternatives we rejected. It shipped a priority integer, then dropped it in a later migration in favour of most-specific-wins — scoring a rate by how many distinct dimensions it names, tie-broken by creation date. Two failure modes follow from that scoring and are visible in its current source: dimensions are unranked, so a product-specific rate and a seller-wide rate both score 1 and the older one wins; and creation order therefore becomes load-bearing configuration a merchant can neither see nor change. Our ordered list is the third option and answers both — the ladder is explicit, visible, and reorderable. The same review found that engine also removed its min_amount cap, and has no notion of tax on the commission at all, so our floor/cap and the EU fee-VAT have no prior art there to copy.

include_shipping on the rate (default false): when the resolved rate has it, the same calculation also runs against the seller order's delivery amounts, persisting a fulfillment-scoped CommissionLine. The surveyed OSS competitor commissions shipping via a global-rate-only flag, and Amazon-style referral fees include it; the legacy module was items-only (its order-level "reverse fee" only prorates item commission on whole-order refunds — shipping is excluded from its base). Ours is per-rate — strictly more flexible than a global-only flag, and off by default so legacy behavior is preserved.

Percentage only (RESOLVED 2026-08-17, shipped). A flat fee cannot charge delivery. A percentage answers "what share of this money is ours?", and postage is money; a flat fee answers "what do we charge for handling this?", and the parcel is part of the sale already being charged for — so a £5 rate on a three-item order was billing £20. The flag is refused on a fixed rate and the toggle is hidden for one, matching the surveyed OSS engine, which reads its shipping flag off the percentage default only. A marketplace wanting a flat charge on delivery states it as its own rate, which composes correctly because rates resolve independently.

Flat fees multiply by quantity (RESOLVED 2026-08-17, shipped). A flat fee is charged per unit sold, not once per line — three cameras in one line earn the same as three bought one at a time. Charging per line would have let the shopper set the fee through cart grouping alone, and would have made quantity matter under a percentage but not under a flat fee, so switching a rate between the two kinds silently changed more than the number. No per-line/per-order toggle, for two reasons. Per-unit is what merchants assume — the large marketplaces state their flat charges as "per unit" and "per item", and that is the industry vocabulary. And a per-order mode has no coherent answer in this engine, because rates resolve per line: a basket with a camera at 8% and a book at £2 has no single rate to charge the order with. The enterprise platform reviewed for this reaches the same conclusion structurally — its per-order charges are a separate seller-fee concept in its ledger, never a mode of its commission engine, whose order-level total is documented only as the sum of its lines. A per-order platform charge, if wanted later, is its own entity rather than a flag here. The floor and cap still apply per line, to the multiplied total — which is the first time they do useful work on a flat rate, since one could not previously exceed itself.

Per-currency amounts (RESOLVED 2026-08-17, shipped). Every amount a rate states is per currency, held in spree_commission_rate_values one row per currency: a flat fee's amount, and a percentage's min_amount floor and max_amount cap. The rate itself carries no currency column at all. This replaced a single currency on the rate, which had meant a dollar-priced rate silently not applying to a euro sale — a seller's fee depended on how the buyer paid — and then, briefly, left the floor and cap on that one column while the flat fee had moved on, so one form asked the same question two different ways. Nothing is ever converted: a converted figure would drift daily against a fee the seller agreed to, and a cap that moves is not a cap. Follows Spree::Price and the delivery calculators' amounts hash, and the repo's standing "one explicit amount per currency, no FX" decision.

The two kinds differ in what an unstated currency means, and the difference is deliberate. A flat fee is skipped entirely for a currency it names no amount in, and the sale falls to the next rate — a fee with no number is not a fee. A percentage always applies, since a ratio needs no currency; only its bounds stay behind, so a euro sale under a dollar-capped rate is charged unbounded rather than skipped. Skipping would read "we capped our dollar fees" as "we want no commission on euro sales", which no marketplace means. Amounts and bounds share a row but are written by separate fields (amounts= / bounds=), and neither write may erase the other — a row carrying bounds survives being dropped from the flat fee, and clearing a bound retires the row only if no amount is left on it. Four specs pin those crossings, since sharing a row is exactly where a wholesale-replace writer silently deletes someone else's data.

Precedence (RESOLVED 2026-06-25; reshaped 2026-08-17 — acts_as_list, shipped): an ordered list, not a fixed ladder. Rates carry position via acts_as_list scope: :store_id and are walked top-down, first match wins — so the order an operator sees in the table is the precedence, and reordering is dragging a row rather than reasoning about an integer. New rates are created at the top (add_new_at: :top): a rate exists to say something more specific than what is already there, and appending would file it behind the catch-all that matches everything. Seeds put a disabled marketplace-wide rate at the bottom, which makes the product-then-category-then-seller order merchants asked for fall out for free without hardcoding it. Ordering is deliberately not derived from how specific a rate's rules look: a rate may name a product, a category and a seller at once, so there is no single dimension to sort on, and "narrowest wins" guesses at an intent the operator can simply state.

The failure mode this model has, and which every change near it must be checked against: a rate that matches everything makes every rate below it unreachable, and the mistakes that produce one are all silent widenings — a rate charging more sales than anybody asked it to, with a 200 saying it worked. Three separate instances surfaced while building this, each needing a deliberate refusal rather than a sensible default: a rules payload naming an unreachable record used to drop that rule (leaving a narrow rate global), an unregistered rule kind used to be skipped by assign_typed_association (same result), and the seeded catch-all was created at the top of the list by add_new_at: :top (shadowing every targeted rate on a store that already had some, once enabled). CommissionRate#global? exists so the condition is at least visible — the admin marks such a rate — and any future work on rules, ordering or seeding should ask what happens when its input is wrong in the widening direction.

5. One payment, recorded as a per-seller split — adopt the explicit split-payment record

The customer makes one payment (one gateway charge against the order group). Do not create N gateway charges. The split is bookkeeping:

Two patterns exist in the wild: (a) link one payment collection to all child orders and split captures proportionally into per-order transaction rows computed on read; or (b) an explicit split-payment record per child order (authorized_amount, captured_amount, refunded_amount).

6.0 adopts the explicit per-seller payment record (pattern b) rather than proportion-on-read, because a marketplace needs a durable per-seller audit trail for partial captures, partial refunds, and payouts. This is also what the legacy module effectively did by creating real Spree::Payment rows on each seller sub-order — but 6.0 does not clone Payment rows: the gateway object stays singular.

Concretely: Spree::Payment gains a nullable order_group_id — a grouped checkout's payment attaches to the group (its order_id is nil); a plain ungrouped order keeps payment.order as today. The per-seller bookkeeping is a new Spree::PaymentSplit row per child order (payment_id, order_id, authorized_amount / captured_amount / refunded_amount, currency) — sketched in Design Details. A partial refund on one seller's order updates that child's split, never the siblings'.

6. Per-seller totals are computed independently, not prorated

Confirmed by the references and the legacy module (its split moves line items, adjustments, inventory units, and shipments wholesale to the child order, then recomputes). Taxes/discounts/shipping travel with whichever line item or shipment they were attached to, into exactly one seller's order; each child order recomputes its own totals. No cart-level total proration (the one exception is the single payment capture, Decision 5, and store-credit allocation, which the references and the legacy module prorate per item).

7. Native models, not decorators

The legacy module is a large decorator layer prepending ~35 core classes. 6.0 brings this into core as real models, associations, and services — Spree::Seller, Spree::OrderGroup, Spree::PaymentSplit, Spree::CommissionLine, Spree::CommissionRate, Spree::CommissionRule, Spree::SellerTransfer, Spree::SellerPayout, and a Spree::Carts::SplitBySeller (or folded into Carts::Complete) service. No prepend. Follow CLAUDE.md model conventions (Spree.base_class, prefixed IDs, class_name/dependent on every association, string status columns, paranoia where needed).

Deliberately not new models: seller team membership and invitations reuse the existing polymorphic rails — Spree::RoleUser (resource: seller) and Spree::Invitation (resource: seller; its resource docstring already names Seller as an intended type). The legacy admin's current_seller hooks (spree/admin base_controller.rb:155, resource_controller.rb:249) exist only for the Enterprise module's legacy-admin panel and die with the legacy admin; the 6.0 equivalent is current_seller scope-fetching on a dedicated Seller API branch (Decision 10 — not ability-level scoping, which the RBAC catalog cannot express).

8. The parent is a dedicated Spree::OrderGroup, not Order#parent_id (RESOLVED 2026-06-16)

The container is a separate Spree::OrderGroup model, not the legacy "an Order that is secretly a parent" (Order#parent_id + state == 'splitted').

Crucially, OrderGroup is a domain-neutral primitive, not a marketplace concept. It means "N orders placed together as one customer transaction" — multi-vendor is merely its first consumer. The same primitive is reused, without a second container model, for: split-by-fulfillment-location (one checkout → per-warehouse orders), split-by-availability (in-stock + pre-order/backorder in one cart), and B2B split-by-company-location (6.0-channels-catalogs-b2b.md → 6.1). Naming it OrderGroup (not SellerOrderSet) keeps it reusable across all of these. The seller relationship lives on the child Order (order.seller), never on the group — the group stays seller-agnostic.

Why a dedicated model beats parent_id:

  • No ambiguity / no empty parent orders. A parent Order with parent_id: nil and zero line items (the legacy shape) breaks every "an order has line items" assumption and forces a family of union-association and "is this really a parent?" workarounds. OrderGroup simply has many orders.
  • Clean composition with the Cart/Order split: Cart (one, mixed) → on completion → one OrderGroup owning N child Orders. The group is the natural home for the single payment, the customer, and the shared addresses; children own their own line items, shipments, totals.
  • Future-proof: when split-by-location or B2B needs the same fan-out, they reuse OrderGroup rather than overloading Order again.

This requires an Enterprise-side data backfill (not core — existing OSS stores have no sellers). The Enterprise module must ship a one-time migration that, for every legacy splitted parent order, creates an OrderGroup, attaches its parent_id-children as the group's orders, and migrates the legacy commission rows into spree_commission_lines. The backfill lives in Enterprise because only Enterprise customers have legacy marketplace data; core ships clean. Tracked as a hard dependency for the Enterprise 6.0 upgrade. See Migration Path.

9. Two-level fund ledger — SellerTransfer (on-fulfillment) + SellerPayout (on-interval), generic in core + a pluggable provider that executes it (RESOLVED 2026-06-25)

Transfer and payout are two distinct events — the legacy module conflated them, and an earlier draft of this plan repeated the mistake. They must be separate models:

  • Spree::SellerTransfer — the per-order fund movement, triggered on-fulfillment. When a seller's order is fully fulfilled (shipped; digital fulfills instantly after payment), the seller earns sale − commission; that credits their balance. One transfer per fulfilled seller order. This is what the legacy Stripe transfer ledger actually modeled (it fires when the seller sub-order's shipments are all shipped).
  • Spree::SellerPayout — the scheduled settlement, triggered on-interval (daily/weekly/biweekly/monthly). It sweeps the seller's accumulated unpaid transfers, batches them into one bank settlement, and debits the balance. One payout per interval per seller (per currency).

The legacy module only models the transfer and outsources payouts to Stripe (it just configures Stripe's native connected-account payout schedule — there is no Payout record; its "payouts" screens are reports aggregating transfers, not a ledger). That's fine for Stripe-only Enterprise but wrong for OSS core: a system-provider marketplace has no Stripe to schedule settlements, so it needs its own payout records.

Spree::SellerTransfer   (one per fulfilled seller order, on-fulfillment) → credits seller balance
      ↓ accumulate                                                   (sale − commission)
Spree::SellerPayout     (one per interval per seller, scheduled)  → debits balance, settles to bank
      ↑ has_many transfers (each SellerTransfer.payout_id)           (batches N transfers; amount = Σ them)

seller.balance = Σ(completed transfers) − Σ(completed payouts)   # derived bridge between the two levels

Payout ⇄ Transfer link (RESOLVED): transfers belong_to a payout. Each SellerTransfer carries a nullable payout_id. The scheduled job sweeps all unpaid completed transfers for a seller, creates one SellerPayout, and stamps them with its id; payout.amount = SUM(its transfers). Every payout itemizes exactly which order-transfers it settled — auditable, and robust to mid-period reversals (a refund after a transfer was already paid out becomes the next period's negative transfer rather than corrupting a closed payout). This is the seller-balance ledger the surveyed industry references documented but never implemented — Spree ships it properly.

Both levels are generic in core + provider-executed, mirroring 6.0-tax-provider.md / 6.0-delivery-rate-provider.md:

  • Core ships both ledger models + a Spree::PayoutProvider::Base strategy with a system default: it records transfers (on-fulfillment) and payouts (on-interval) but moves no money — the OSS operator sees the per-seller balance and the itemized payout records, and settles offline (marking the payout complete). This is what #13323 means by core knowing "what's owed."
  • The monorepo ships the basic Spree::PayoutProvider::StripeConnect (boundary amendment 2026-07-15), alongside the Stripe core gateway being pulled in from the standalone spree_stripe repo — only the payment-sessions-API gateway classes come over (likely into spree/core); the legacy v2-API/storefront code stays behind. The provider: Express-account creation + hosted onboarding link surfaced in the seller dashboard + account.updated webhook → payout-account status on the seller. transfer! executes an on-fulfillment Stripe::Transfer tied to the charge via source_transaction (gated on the account being payouts-enabled); pay! maps payouts_schedule_interval onto Stripe's native connected-account payout schedule and records SellerPayout rows from payout webhooks.
  • Enterprise extends that provider with the money operations: KYC/account-health workflows beyond the hosted flow, and ledger⇄Stripe reconciliation + payout reports. The paid tier operates the unhappy paths.

OSS funds flow — two modes. (a) system (no gateway objects): the customer's single charge settles in full to the operator's own gateway account as a plain payment; the split is pure bookkeeping (PaymentSplit + this ledger); disbursement happens outside the gateway — on the payout schedule the operator pays each seller by bank (SEPA/ACH/wire), guided by the itemized SellerPayout, and marks it complete, or automates it (seller_payout.due webhook → banking API → POST /seller_payouts/:id/complete). The platform is merchant of record for the full transaction and carries seller payables on its own books. (b) stripe_connect basic (the monorepo Stripe gateway): sellers onboard as Express accounts through Stripe's hosted link; on fulfillment the provider executes a real transfer — money moves automatically. A refund writes the ledger reversal in every tier, and since 2026-10-27 OSS mode (b) also reverses the seller's share of the Stripe transfer; a seller already paid out carries a negative Stripe balance that their next earnings make up. Reconciliation stays Enterprise. Note the hard coupling that shapes this seam: a Stripe::Transfer requires a connected account, so basic Connect onboarding necessarily ships together with OSS transfer execution; what Enterprise keeps is not onboarding itself but the KYC operations around it.

Transfer amount basis (ports the legacy allowed-transfer-amount rule, generalized per the resolved store-credit decision): the seller's sale value minus commission, payment-source-agnostic (store credit / gift card is the platform's funding concern, not the seller's):

transfer.amount = seller_order.total − seller_order.commission_lines.sum(:total)

seller_order.total is the child order's grand total — items + its delivery + its taxes − its discounts. The deduction is CommissionLine#total, i.e. commission including the VAT on the commission (the platform invoices the seller commission + VAT; the seller reclaims that VAT as input tax). The seller is merchant of record for their child order in v1: consumer tax and shipping revenue are theirs. A marketplace-facilitator / deemed-supplier mode — where the platform withholds consumer tax and the basis becomes total − tax_total − commission — is selected per seller by spree_sellers.tax_remittance (seller | platform, default seller; RESOLVED 2026-08-15): core owns both branches of the math so the ledger stays provider-independent, while deciding that a seller is platform-remitted (nexus, deemed-supplier rules) is Enterprise "automatic taxes" territory (see the scope table).

Reversals (ports the legacy reversal chain): a refund on a shipped order writes a negative SellerTransfer linked to the original via reversed_from, so the seller's net earned is always Σ(seller_transfers). If the original was already settled in a closed payout, the reversal lands as a negative transfer in the next payout period. Ties into 6.0-returns-exchanges-claims.md. The reversible-amount rule — original minus already-reversed, floored at zero — carries over as a model method on SellerTransfer.

Scheduling (RESOLVED 2026-09-09). SellerPayouts::SweepDueJob is what turns the intervals below into payouts, and it is scheduled by the host app — core ships no cron. Until 6.0 nothing scheduled it and no payout was ever created, for any seller on any interval; docs/developer/deployment/background_jobs.mdx now carries the daily entry a marketplace must add. A seller on manual is skipped there by design and settled from the operator's Sellers screen, which sweeps them by hand (POST /admin/sellers/:id/payouts).

Triggers (RESOLVED): seller_transfer.due fires on-fulfillment (all the seller order's fulfillments fulfilled); seller_payout.due fires on the seller's payouts_schedule_interval (daily/weekly/biweekly/monthly/manual, nil ⇒ store default — the "Use marketplace default interval" semantics in today's Enterprise settings, carried over). Core implements all of them — SweepSellerJob resolves each seller's interval and decides who is due, and manual means the operator settles by hand from the Sellers screen. Corrected 2026-09-09: this line previously gave the scheduled intervals to Enterprise, which was never true of the shipped code; what Enterprise adds is the money operations around a payout (reconciliation), not deciding when one is due.

Naming & scope (RESOLVED 2026-06-25): the models keep the Seller prefix and belongs_to :seller — they are deliberately not generalized to bare Transfer/Payout. Rationale: (1) "transfer" and "payout" are heavily overloaded payment terms (gateway ACH/wire transfers, Stripe payout objects) — the Seller prefix is what keeps these ledger records unambiguous and avoids re-introducing the very namespace confusion that made the legacy gateway-namespaced transfer model unclear; (2) the reusability that a dealership / B2B revenue-share scenario would want comes from an abstract payee (belongs_to :payee, polymorphic), not from a generic model name — and we have no second consumer yet, so per YAGNI we bind to Seller now. If a concrete non-seller payee requirement lands later, the migration path is to make payee polymorphic (Seller + e.g. CompanyLocation) — a localized schema change — rather than a rename. This mirrors OrderGroup's seller-agnostic structure, but the inverse conclusion is correct here: the container is generic because the seller lives on its children, whereas these ledger rows are intrinsically a payment to one specific payee.

10. Seller users are Spree::AdminUser, on a dedicated /api/v3/seller API branch with its own JWT audience and login registry (RESOLVED 2026-08-15)

Two questions were re-examined against the shipped auth (PR #14380) and RBAC (PR #14412) work — should seller staff be a separate user model, and should they use the Admin API with narrower permissions or their own routes. Both settled the same way: reuse the principal, separate the surface.

Principal — Spree.admin_user_class, no SellerUser model. The platform is two-principal after #14380: Customer buys, AdminUser operates a back office — and a seller's team operates a back office. That one class now carries the entire auth stack (has_secure_password, lockout, password policy, generates_token_for :password_reset, UserIdentity SSO linking, invitation acceptance, refresh-token cookie flow); a third principal would duplicate every one of those (and every future MFA/passkey improvement) as a second security surface. The RBAC rails already assume it: RoleUser (user: Spree.admin_user_class, resource: seller, store binding derived from the seller), Invitation (resource: seller), and Spree::Ability#staff_roles deliberately excluding seller-resourced assignments as belonging to "their own panel's ability". One human, one login, several hats: an AdminUser may hold a store role and a seller role at once (the operator's own first-party seller; a merchant selling on two marketplaces run on two stores). A seller member is not store staff — membership is by resource type, never by store_id.

Surface — a third v3 branch, /api/v3/seller/…, beside store and admin. The plan's earlier line ("seller users hit the same admin API with seller-scoped abilities — no separate seller routes") is superseded: it relied on PermissionSets::SellerUser with seller_id: user.seller_ids hash conditions, and #14412 removed permission sets with no bridge — the catalog is flat read_*/write_* keys with no conditions, and the RBAC plan already re-decided on 2026-08-08 that "seller-panel endpoints scope-fetch through current_seller exactly as admin endpoints scope through current_store". Reusing the ~300 admin endpoints would mean per-principal forks in every scope/find_resource/incidental lookup (stock_location_id, reason_id, variant_id on line-item writes) — each miss a cross-seller read or write inside the same store — plus per-principal field masking in serializers. A seller branch is ~20 controllers, each written scope-first (current_seller.products, current_seller.orders, …): IDOR by construction, the same way store isolation works on the admin branch today (controller scoping only — the ability layer has no tenancy conditions). What a seller may not do (publish to channels, edit orders, take payments, approve itself, create stock locations) is an endpoint that does not exist, not an ability rule. (Amended 2026-09-03 — refund was in that list and should not have been: the legacy module granted vendors Refund, Reimbursement, CustomerReturn and ReturnAuthorization on their own orders, so a seller refunding their own return is behavior being opened up, not new latitude. See 6.0-seller-order-management.md Decision 1; the group's Payment stays the operator's.) Do not subclass admin controllers into the seller namespace — inherited current_store.* lookups are precisely the leak; share workflows and permitted-param lists, never controllers.

Isolation is enforced at the token layer, not only at membership. Three requirements, all mandatory (they answer the two concrete objections to a shared model — "staff must be SSO-only while sellers use passwords" and "what happens when a seller token hits the Admin API"):

  1. Own JWT audience — JWT_AUDIENCE_VENDOR = 'seller_api' beside store_api/admin_api. The admin branch rejects a seller token at decode_jwt (verify_aud) with 401 before any store resolution, membership check, or ability is built, and the seller branch rejects admin tokens symmetrically. Fail-closed at the outermost layer; the resource_type filters below remain defense in depth.
  2. Own login surface — Spree.seller_authentication_strategies (default: :email only) + /api/v3/seller/auth/{login,refresh,logout,password_reset}. Login policy is per surface, not per class: an SSO-only store keeps Spree.admin_authentication_strategies.remove(:email) while sellers sign in with passwords, against the same AdminUser table. The seller login refuses anyone with no seller membership (role_users on resource: seller), the same "unprovisioned subject is rejected" rule the admin SSO callback applies — so a staff-only account cannot mint a token here, and a token it could mint carries the seller audience anyway.
  3. Refresh tokens carry the audience — spree_refresh_tokens.audience (string), written at mint and enforced on refresh, with a separate cookie name/path for the seller panel. Today's RefreshToken has no audience, so without this a seller-minted refresh token could be presented to the admin refresh endpoint and exchanged for an admin_api JWT.

Accepted trade-offs: password policy and lockout stay model-level and therefore shared between staff and sellers (desired — a seller account locks out too; a stricter staff-only policy is a per-surface login concern, like MFA later). Thin controllers are duplicated across the admin and seller branches; that duplication is the price of an auditable tenancy boundary.

Cross-plan obligation (admin branch, ship ahead of Phase 1): AdminAuthentication#current_user_member_of_store? matches role_users.exists?(store: current_store), which a seller-resourced assignment passes (its store is the seller's store) — the Ability then yields no keys so scoped endpoints 403, but the scope-exempt ones (/admin/tags, /admin/store show, exports/imports index, translation batches) are reachable. Tighten to resource_type: 'Spree::Store', mirroring Ability#staff_roles and RoleGrantGuard, with a regression spec.

11. Several sellers may sell the same item: the seller lives on the variant, not on a separate offer record (RESOLVED 2026-08-16, shipped)

Until now this plan assumed one product belongs to one seller (products.seller_id), so two sellers of the same physical item produced two unrelated products and two storefront listings. That is the right shape for unique goods and the wrong one for commodities — the same book, phone or part sold by several sellers. Supporting both is the single most requested capability the legacy module could not deliver, so 6.0 must get the grain right; retrofitting it after the split and commission engine are built on one-owner assumptions is the expensive path.

The seller is an attribute of the variant. spree_variants.seller_id (nullable) alongside the existing spree_products.seller_id. The column is the variant's override: blank defers to the product, so a seller who owns a whole listing is named once on the product and every variant inherits them, and only a variant blank on both is first-party. Every consumer — the split's partition key, SKU uniqueness, the buy box — reads that one resolved answer rather than the raw column. One product may therefore hold variants from several sellers: a new unit from the marketplace's own warehouse and a refurbished one from a seller, on one product page. Condition (new / used / refurbished) is an OptionType, so it splits the variant like any other axis and inherits the option machinery already there — presentation kinds, positions, storefront pickers and facets.

Why not a separate Offer record. The surveyed implementations that model this all introduce one, but they share a constraint Spree does not have: each is built on top of a commerce engine or a merchant's existing catalog, so they cannot put a seller on the variant and cannot re-key inventory. Their offer row is a variant they were not allowed to write. Spree owns the variant, and an offer would duplicate almost all of it — seller, sku, price, stock, condition, delivery config. Modelling it separately would mean a second pricing pipeline, a stock anchor migration (spree_stock_items is uniquely keyed on (variant, stock_location)), a new line_items.offer_id with the cart's variant-keyed deduplication reworked around it, and offer-relative rewrites of ~67 purchasability call sites. On the variant, all of that is already true by construction: two sellers are two variant rows, so two stock rows, prices resolve unchanged, and line_item.variant.seller_id gives per-line seller attribution — which is precisely what the split in Decision 1 partitions on.

"Offer" remains the right word for the storefront ("3 offers from 2 sellers"). Presentation vocabulary need not be a table.

Consequences that must ship with it:

  • Buy box. Product-level answers (purchasable?, in_stock?, headline price, default_variant) become buy-box-relative: a selection service groups a product's sibling variants and picks a featured one, and the existing rollups then answer about the winner. Selection is computed, never a stored winner column — it depends on price, stock and delivery, all of which move constantly — and pluggable from the start, since ranking is marketplace policy. Real implementations weight landed price and delivery speed, gate on seller performance, and rotate among near-equals rather than crowning one; losing sellers stay visible. Because condition is an option, the buy box is keyed on (product, option combination), which gives the industry's "a new buy box and a used buy box" behaviour for free.
  • default_variant prefers first-party. The product's public identity — headline price, SKU, and the EU Omnibus prior_price, which is a compliance claim — should be the operator's own listing where one exists, not whichever seller sorts first.
  • Delivery profile gains a variant-level override. It is product-level today, and Stock::Splitter::DeliveryProfile memoises one profile per product_id, so sellers sharing a product would share whichever profile resolved first — packing and pricing one seller's goods with another's shipping config. A nullable delivery_profile_id on the variant falling back to the product follows Variant#tax_category exactly. This is worth having regardless of marketplaces: a merchant selling a poster and its framed print under one listing cannot express that today.
  • Writes never destroy another seller's variants — enforced at the seller branch, not the model. Product#variants= is full-replacement — variants absent from the payload are destroyed — and the dashboard round-trips the whole array on every save. That is correct for the operator's write path, and it is deliberately not narrowed by seller there: marketplace staff see and write every seller's variants on a master product (that is what running a marketplace means), and on an owned product all variants are one seller's anyway. The danger is only a seller's write path handed a full-replacement setter with a narrowed read. So the obligation sits where Decision 10 already puts every seller-branch concern: the seller products controller (Phase 3) scope-fetches through current_seller and must never pass a whole-product variants: payload through — it writes its own rows through the nested variants endpoint, where a row belonging to another seller is a 404 by scope. No model-level bound (an earlier writing_seller was cut as over-engineered — it solved Phase 3's problem in the wrong layer).
  • Option filtering must match within one variant. with_option_value_ids issues a separate subquery per option type against product_id, so "Blue AND XL" matches a product with a Blue variant and a different XL variant. This is a pre-existing storefront bug that sharing a product across sellers makes worse; the fix is to require one variant to satisfy every value.
  • Search documents are per-product with a single scalar price and a single boolean stock. They describe the buy-box winner, and a seller's write must not silently rewrite a rival's listing facts.

Operators see everything; sellers see their own. Marketplace staff manage every variant on a product, including other sellers' — they run the marketplace. Seller isolation is the /api/v3/seller branch scope-fetching through current_seller (Decision 10), not a narrowing of the admin surface.

Both shapes coexist with no mode switch. A store selling only its own goods has seller_id: nil everywhere and notices none of this. Unique goods keep one seller per product. A commodity gets sibling variants from several sellers. Promoting an exclusive listing to a shared one is a data change, not a migration. What this deliberately does not solve in 6.0 is catalog matching — deciding that two sellers' submissions are the same item. Every surveyed platform treats that as hard and several sell it separately; core should ship exact matching on a typed identifier (the identifier's namespace stored explicitly, never inferred from its shape) and leave fuzzy matching to an extension.

Supersedes: the "SKU uniqueness relaxes to per-seller scope" line under Product ownership & approval, which assumed duplicate product rows per seller.

12. A seller's addresses are a stock location and a business identity — not two loose Address rows (RESOLVED 2026-08-20)

spree_sellers carries billing_address_id and returns_address_id, both plain Spree::Address. Two problems follow, and the legacy module had the shape of both answers already.

The returns address is a stock location wearing a different hat. 6.0 routes returns through Spree::Return, and a received return has to restock somewhere — spree_stock_movements is anchored to a StockLevel, which is anchored to a StockLocation. An address the inventory system cannot restock into is a dead end: the shopper is told where to post the parcel, and the goods arrive somewhere the catalog does not believe in. The legacy module reached the same conclusion from the other direction — it gave every vendor stock locations and created a default one at vendor creation.

So returns_address is dropped and a seller's returns route to a stock location. spree_stock_locations.seller_id (nullable, per the model sketch this plan already carried), a default one provisioned when the seller is created, and Seller#returns_address becomes a method reading that location. Sellers manage their locations from the panel — the same records the operator's inventory screens already understand, so seller stock is not a parallel universe.

Two things about StockLocation have to move for this to be true, and neither is marketplace-specific:

  • Spree::UniqueName scopes location names to the store, so two sellers could not both call a location "Warehouse". Names become unique per (store, seller) — an operator location and a seller's may share a name, which is what a marketplace looks like.
  • ensure_one_default unsets every other default in the store. A seller saving their default would silently demote the operator's. The default flag becomes per-owner: one default among the operator's locations, one among each seller's.

Billing is a business identity, and most of it is not an address. A commission invoice needs the seller's legal name, their registration number and — for EU B2B reverse charge on the fee (Decision 3) — a verified VAT number with the evidence retained, because a registry only ever answers "valid now" while an invoice must stay defensible for years. A vat_number string cannot carry a verdict, a timestamp or evidence.

Core already models exactly this. Spree::TaxIdentifier (from 6.0-tax-provider.md Phase 7) has kind / value / validation_status / validated_at / validation_evidence and a validator registry. The seller becomes another owner — and, since a fifth owner is what showed the per-owner-FK shape had outlived its rationale, the owner became polymorphic in the same pass (decisions.md 2026-08-22), so the seller costs no column at all and seller VAT inherits validation for free. legal_name and registration_number go on spree_sellers; billing_address is a Spree::BusinessAddress.

No per-seller tax rate. Adding one is the legacy platform_fee_tax_rate column this plan already rejected (Resolved Decisions, 2026-06-16): the seller supplies tax identity, and the commission tax rate resolves through CommissionRate + the TaxProvider so it stays jurisdiction-correct.

One Address subclass, sharing the table. The legacy module subclassed BillingAddress/ReturnsAddress to override require_name? (a company address has no first and last name) and show_company_address_field?. Returns no longer need an address subclass at all — they route to a stock location — so only the billing half survives, as Spree::BusinessAddress. It is not STI: spree_addresses has no type column and gains none. STI was implemented and reverted (decisions.md 2026-08-23) — checkout copies address attributes, not records (update_or_create_address ends at Spree::Address.create), so the class never survives the copy that was the whole argument for it; keeping type significant for dedup would stop a B2B buyer's address book from ever matching; and the tax decision reads the owner (company_location_id, then Company) and never the address class. The base Address has carried a company column and preference-driven require_company? all along. The subclass reads the same rows and overrides the three predicates (require_name? false, require_company? true, show_company_address_field? true), which is where those rules belong — the alternative tried first was a before_validation flag on the seller, and a validation rule that has to be switched on per record is a class.

Supersedes the belongs_to :returns_address line in the Seller model sketch below, and the Spree::SellerRequirements::ReturnsAddress checklist kind becomes "has a returns location".

13. Seller delivery: the marketplace owns the profiles, the seller owns their methods (RESOLVED 2026-09-01, implemented 2026-09-01)

A marketplace has two different delivery questions, and they get two different owners.

"What kind of goods is this?" is the marketplace's question. A DeliveryProfile (parcel, digital, pallet, …) is the hub the zones, origin groups and methods hang off, so a shared vocabulary of profiles is what keeps a buyer's shipping options readable across sellers and lets the operator reason about the store as one. Profiles, zones and origin groups stay operator-owned and store-scoped — none of them gets a seller_id, ever. A seller assigns a profile to their product (directly, or through a product type whose template stamps one at creation — shipped 2026-09-01) and never creates one.

"Who ships it, how, and at what price?" is the seller's question. DeliveryMethod gains a nullable seller_id. A seller creates, prices and retires their own methods against the marketplace's profiles and zones; the operator's methods stay seller_id: nil. This is what the Seller API surface and the Order splitting section have assumed since 2026-08-15, and what Carts::SplitBySeller#divide_delivery_cost names as the real answer to per-seller quoting — it was never built, and it is now designed:

  • Eligibility is one rule in one place. A package's seller is its stock location's (stock_location.seller_id) — the derivation the legacy module used, and still correct: a seller's goods only ever sit in that seller's locations. A seller's package is offered that seller's own methods plus any marketplace method the operator has marked available_to_sellers (new boolean on spree_delivery_methods, default false); a first-party package is offered marketplace methods only. Enforced in Stock::Estimator#filter_delivery_methods beside the existing audience/address/location/rule filters, so calculator- and provider-priced methods obey it alike. The one boolean covers both marketplace shapes: an operator who runs shipping for everyone shares their methods and sellers create none; an operator who lets each seller quote shares nothing.
  • Origins need no new layer. A seller method belongs to a profile and optionally a zone from the marketplace's list, and takes the profile's default origin group like any other method. Which packages it may quote is settled by the seller filter above, so no per-seller origin group exists. The one change is to coverage: DeliveryOriginGroup#covers_location? answers true for any seller-owned location, because a group's member list narrows the operator's warehouses ("pallets ship from Warehouse B") and says nothing about where a seller keeps stock. Today a narrowed group silently makes every seller's stock unallocatable — a defect this design fixes.
  • Carriers stay the operator's in 6.0. A seller method prices through the internal rate provider (flat or calculated rates, plus DeliveryMethodRules) and fulfils through the manual provider with the hand-entered tracking number a seller already supplies today; a validation refuses any other rate_provider or fulfillment_provider on a row carrying seller_id, because carrier credentials live on the store-scoped Spree::Integration. Neither marketplace platform we studied lets a seller register a carrier account in-platform either — both hand that to the seller's own tools. A seller-owned integration is a later, purely additive step (Open Question 3). Pickup at a seller's own counter follows the same shape (a seller method on the Pickup provider whose pickup locations are the seller's) and is not in the first cut.
  • Checkout is already per package. Packages come out per stock location, so with seller methods a seller's goods are quoted by that seller's methods from the start, and the buyer picks one rate per package through store/carts/:id/fulfillments exactly as today. SplitBySeller#divide_delivery_cost stays as the fallback for the one case that still spans sellers — a first-party location holding several sellers' variants.
  • "At least one way to ship" is an onboarding requirement, not a gate. Spree::SellerRequirements::DeliveryMethod, a computed kind in DEFAULT_KINDS: complete when the seller has an active method of their own or the store shares at least one active method with sellers. Read only by the two enforcement points 6.0-seller-onboarding-requirements.md allows — a seller who later retires their last method is flagged, never blocked.
  • Permission: DeliveryMethod, DeliveryMethodRule and DeliveryMethodService leave settings for a delivery_methods catalog resource (read_delivery_methods/write_delivery_methods, group settings, seller-grantable) — settings is never seller-grantable, and per 6.0-admin-rbac.md a capability a new audience holds gets its own entry. Unreleased edge, so no bridge: operator roles are data and the seeded admin role is a super-role.
  • Surface: /api/v3/seller/delivery_methods CRUD rooted in current_seller.delivery_methods (nested rules and services in the same payload shape the operator's endpoint takes), read-only GET /seller/delivery_zones?delivery_profile_id= for the zone picker, and the seller panel gains Settings → Fulfillment → Delivery methods beside Stock locations. The operator's delivery-method form gains one switch, "Available to sellers", and the operator's list shows which seller owns a method. The Enterprise Shopify/WooCommerce seller apps may write a seller's shipping setup into these rows; core provides the rows only.

Phases (all shipped 2026-09-01): (1) spree_delivery_methods.seller_id + available_to_sellers, the estimator filter, the provider validations and the origin-group coverage fix; (2) /api/v3/seller/delivery_methods (CRUD + calculators + rule_types) and read-only /seller/delivery_zones, the Spree::SellerRequirements::DeliveryMethod kind in DEFAULT_KINDS, and the delivery_methods permission resource split out of settings; (3) the seller panel's Settings → Fulfillment → Delivery methods page beside Stock locations, plus the operator's "Available to sellers" switch and owner badges; (4) verified against a live cart — a package from a seller's warehouse quotes that seller's own methods, gains the operator's when one is shared, and a first-party package sees marketplace methods only.

Two details settled during implementation. The eligibility filter runs in Ruby over the loaded methods rather than as a merged scope, because Package#eligible_delivery_methods is stubbed with a plain array in a good deal of existing coverage. And the seller's rule vocabulary is a subset of the operator's — channel rules segment the marketplace's own traffic and the excluded-products rule wants a catalog picker the panel does not have — with a kind outside that subset refused rather than dropped, so a seller is never told a condition saved that did not.

Cross-reference (2026-09-08, 6.0-seller-package-types.md). Packaging joins the seller's side of this split: Spree::PackageType gains a nullable seller_id with the same first_party / for_seller scopes and the same dependent: nil reasoning as delivery methods, a seller's package is quoted with their own default box, and a computed PackageType onboarding requirement asks each seller for it. Unlike methods there is no available_to_sellers flag — the marketplace's cartons carry no price, so every seller may read and pack into them.

Design Details

Seller identity & teams

The headline model. Ports the Enterprise module's seller model — renamed to Spree::Seller with prefix sel_ (2026-08-17), so the Enterprise backfill re-stamps ids rather than carrying ven_ over — and adopts the lifecycle already shipped in the Enterprise admin (user docs: Invited → Onboarding → Ready for Review → Approved / Rejected / Suspended). The external-store subsystem is not ported — none of it, ever: the external store/product/order/category resource family, the per-platform Shopify/WooCommerce connections and sync workers, the category mapper, and the seller-side hooks that reach into them (external-store shipping-method pulls, external-store-derived settings) all remain Enterprise. Core's Seller carries no external-store associations, columns, or callbacks — the Enterprise module layers its connection models onto core's Seller from the outside:

class Spree::Seller < Spree.base_class
  has_prefix_id :ven
  include Spree::SingleStoreResource
  include Spree::UserManagement   # roles, role_users, users, invitations — the team
  include Spree::HasCustomFields  # Metafields is a 6.1-removed shell
  include Spree::Metadata
  include Spree::TranslatableResource   # about/description translate like Product
  acts_as_paranoid
  publishes_lifecycle_events

  belongs_to :store, class_name: 'Spree::Store'
  belongs_to :billing_address, class_name: 'Spree::Address', optional: true  # on the commission invoice (EU)
  # No returns_address: returns route to a stock location, so the goods land
  # somewhere inventory can restock into (Decision 12).

  has_many :products,        class_name: 'Spree::Product',       dependent: :nullify
  has_many :stock_locations, class_name: 'Spree::StockLocation', dependent: :nullify
  has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', as: :owner  # VAT etc — Decision 12
  has_many :orders,          class_name: 'Spree::Order'           # child (seller) orders
  has_many :commission_lines, class_name: 'Spree::CommissionLine'
  has_many :seller_transfers, class_name: 'Spree::SellerTransfer'
  has_many :seller_payouts,   class_name: 'Spree::SellerPayout'
  # Teams come from Spree::UserManagement above, not hand-rolled: after the
  # RBAC refactor a RoleUser has no resource of its own, so a seller's team is
  # whoever holds a role the seller owns (`roles` → `role_users` → `users`).

  # name, slug (unique per store), contact_email, billing_email
  # about          : rich text (sanitized HTML column per 6.0-rich-text-descriptions.md)
  # NO denormalized sales_total/commission_total counters (legacy has them) — lifetime
  # revenue & commission derive from commission_lines / seller_transfers (we have a ledger now)
  # NO encrypted name/contact columns (legacy encrypts for its multi-tenant SaaS; core stays plain)
  # logo / square_logo / cover_photo : ActiveStorage attachments (storefront-facing branding)
  # terms_accepted_at : datetime — seller ToS acceptance (store-configured rich-text ToS)
  # holiday_mode_until : datetime, nullable — paused storefront presence ("holiday mode")
  # payouts_schedule_interval : string, nullable — 'daily'|'weekly'|'biweekly'|'monthly'|'manual';
  #                             nil ⇒ store default (store preference), matching today's
  #                             "Use marketplace default interval" semantics
  # minimum_payout_amount : decimal, nullable — sub-threshold balances carry to the next period;
  #                         nil ⇒ store preference default_minimum_payout_amount (RESOLVED 2026-08-15)
  # tax_remittance : string — 'seller' (default) | 'platform'; selects the transfer basis (Decision 9;
  #                  RESOLVED 2026-08-15). Enterprise 'automatic taxes' sets it; core only reads it

  # Ports the legacy lifecycle (status column renamed from `state` per
  # 6.0-normalize-state-to-status.md), but NOT its state machine: approving
  # sends mail and provisions payouts, which is exactly the work
  # 6.0-service-workflows.md keeps out of save callbacks. Transitions are
  # workflows (Spree::Sellers::Invite, ::Approve, ::Suspend, …); the model
  # only declares the values.
  #
  #   pending → invited → onboarding → ready_for_review → approved
  #
  # `approve` also lifts a suspension and revives a rejected seller, so the
  # reachable set is wider than that line — which is the permissiveness the
  # legacy machine had, now expressed as workflow guards rather than a graph.
  include Spree::HasStatus
  has_status :pending, :invited, :canceled, :onboarding, :ready_for_review,
             :approved, :rejected, :suspended, default: :pending

  validates :name, presence: true
  # Scoped to the store: spree_base_uniqueness_scope is empty, so naming it
  # explicitly is what makes two marketplaces able to share a slug.
  validates :slug, presence: true, uniqueness: { scope: [*spree_base_uniqueness_scope, :store_id] }
end
  • Two entry paths, one lifecycle. (a) Invitation: operator creates a pending seller and invites → Spree::Invitation (resource: seller, seller-role) → acceptance creates the RoleUser and fires start_onboarding. (b) Self-serve application — a public "become a seller" flow: a Store API endpoint creates a pending seller + application; the operator admits into onboarding or rejects. Same state machine, no second flow.
  • Teams = Spree::RoleUser rows with resource: seller and user: Spree.admin_user_class. Seller admins invite teammates through the same Invitation rail the store admin uses. No new membership model.
  • Authorization (rewritten 2026-08-15 for the shipped RBAC — Decision 10): seller users are Spree.admin_user_class and sign in through the seller login surface (own strategy registry, own seller_api JWT audience). Authorization on the Seller API branch is the same two-axis model the admin branch uses:
    • Tenancy is controller scoping — every seller endpoint scope-fetches through current_seller (resolved from X-Spree-Seller-Id + a role_users membership check on resource: seller; current_store is derived from current_seller.store, never taken from a header). Writes are force-stamped seller_id. Nothing tenancy-related lives in the ability.
    • Capability is the permission catalog — the same read_*/write_* vocabulary, through the same ScopedAuthorization key gate. Adopts the RBAC plan's settled direction: Role#audience (staff | seller); a seller-grantable catalog subset marked at register_scope (products, orders, fulfillments, stock, returns, exports/imports, analytics — never settings, staff, api_keys, commissions); the roles editor filters its grid by audience; assignment and invitation guards pair audience with resource type. Seller roles are defined by the operator (role names are globally unique — sellers assign their people to tiers, they do not define roles). Two seller-only catalog resources: seller_profile (own profile, branding, addresses, onboarding tasks) and read-only payouts (the seller's ledger view). Spree::Ability gains a resource: option (default the store) so the seller branch builds its ability from role_users where resource: current_seller — the "seller-side ability" the RBAC plan deferred here.
    • The legacy PermissionSets::SellerUser baseline survives only as the seeded default seller role's key set (write_products, write_orders, write_fulfillments, write_stock, write_returns, write_exports, write_seller_profile, read_payouts). "No commission management / no channel publication / no self-approve / no stock-location create" are endpoints that do not exist on the seller branch, not ability rules. #13323's "manage permissions (via code)" = seeds or the roles API, per the RBAC plan.
    • Spree::UserRoles gains has_many :sellers, through: :role_users, source: :resource, source_type: 'Spree::Seller' beside stores; the seller branch's /me returns the seller memberships so a panel can pick its context. AdminUserMethods#can_be_deleted? reasons about Store.current.users — the seller branch needs its own "last owner of this seller" rule.
  • Onboarding checklist — superseded 2026-08-18 by 6.0-seller-onboarding-requirements.md. The "lightweight task registry" below became an operator-configured model (Spree::SellerRequirement rows over registered kinds, persisted SellerRequirementSubmission for attested/verified checks, Sellers::SubmitForReview + Approve as the only gates); the paragraph is kept for the intent it records. Original text: Onboarding checklist — the registry is core, Enterprise contributes tasks. Core ships a lightweight task registry (task key + completion check + required flag) and the core tasks: accept ToS, complete profile/branding, billing + returns addresses, at least one delivery method, at least one product. submit_for_review requires all required tasks complete (ports the legacy onboarding_completed? guard — without a checklist the guard has nothing to check, and sellers can't see what's missing). Extensions register additional tasks into the same registry: the monorepo Stripe gateway adds "connect your Stripe account" (Express onboarding); Enterprise adds KYC verification follow-through and Shopify/Woo store connection — the paid value is in those tasks, not in the tracker. The seller dashboard and the operator's onboarding-progress view (the n/m column in today's Enterprise) both render from the registry.
  • Storefront visibility: only approved sellers (and their products) are exposed; holiday_mode_until in the future hides the seller's products from sale (purchasability gate, not catalog deletion).

Columns added to existing tables (the complete list — everything else in this plan is new tables):

Table Column Why
spree_products seller_id (nullable) listing ownership — a seller's own product; nil on a shared one
spree_variants seller_id (nullable), delivery_profile_id (nullable) which seller sells this variant, and how they ship it (Decision 11)
spree_stock_locations seller_id (nullable) seller-owned stock, feeds order routing
spree_orders seller_id (nullable), order_group_id (nullable) child-order identity
spree_line_items seller_id (nullable, denormalized) split partition + seller scoping without 3-join hops
spree_payments order_group_id (nullable) the single shared payment (Decision 5)
spree_delivery_methods seller_id (nullable) optional seller-scoped delivery options (see Order splitting)

Legacy seller scoping deliberately not carried over: spree_payments.seller_id and spree_shipments.seller_id (both derivable — PaymentSplit/fulfillment reach the seller through the child order), and seller_id on reports + webhook subscribers (seller-scoped reports and seller-owned webhook subscriptions are post-6.0 dashboard/API work, not v1 schema).

Order splitting

Spree::Cart (one, mixed)
  └─ line_items (owner: cart_id set, order_id nil)   ← 6.0-cart-order-split.md

   cart.complete!  →  Spree::Carts::Complete  →  splits by seller
        │
        ▼
Spree::OrderGroup (the transaction container — customer, single payment, shared addresses)
  ├─ Spree::Order (seller A)  belongs_to :order_group, belongs_to :seller
  │     ├─ line_items (owner = this order)   — seller A's items
  │     ├─ fulfillments                       — seller A's fulfillment (Shipment pre-rename)
  │     ├─ commission_lines                   — frozen at split
  │     ├─ seller_transfer                    — seller A's earning, on-fulfillment (level-1 ledger)
  │     └─ payment_split                      — seller A's share of the single payment
  ├─ Spree::Order (seller B)  …
  └─ …

The OrderGroup owns the customer + single payment + shared addresses; each child Order owns its own line items, fulfillments, and totals. The group carries no seller reference — seller lives on the child order (Decision 8). Vocabulary follows 6.0-fulfillment-and-delivery.md throughout: Fulfillment (né Shipment), DeliveryMethod (né ShippingMethod), and the ledger trigger is on-fulfillment — which also covers digital/instant fulfillment types (a digital seller order fulfills, and therefore earns, immediately after payment).

  • Trigger & gate: explicit call inside Spree::Carts::Complete, after payment authorization. The gate is more than one fulfillment partition — line items partition by the seller_id snapshot, with nil (the operator's own first-party items) forming its own partition, and the split + OrderGroup happen only when ≥ 2 partitions exist. A mixed cart of seller A + first-party items splits into two child orders (one with seller_id: nil). A single-partition cart — all first-party, or all one seller — completes as a bare order exactly as today: no group, no PaymentSplit; when that partition is a seller's, the order still carries seller_id and commission + ledger apply unchanged (Phase 2's compute-only mode is exactly this). Not a state-machine callback — and not the legacy shape either: the legacy module splits ~30 seconds after checkout in a background job, leaving a window where the parent order exists un-split. 6.0 splits synchronously inside completion, so the checkout response already returns the finished OrderGroup and no splitted-pending state ever exists.
  • Partition key: line_item.seller_id, denormalized from variant.seller — the variant the customer actually chose, falling back to variant.product.seller for a product whose seller owns the whole listing (Decision 11). Denormalization is load-bearing, not an optimization: the split, seller ability scoping, and seller order lists all key on it, and on a shared product the product cannot answer which seller was bought from. Because ownership can change while an item sits in a cart, Carts::Complete revalidates each line's seller_id before partitioning and refreshes stale lines (re-running package/delivery validation) — the same cart-revalidation class as price or availability drift.
  • Per-seller delivery selection happens at checkout, before the split. Today's Enterprise checkout already groups packages by seller and lets the customer pick a delivery method per seller package (user docs: multi-vendor-checkout); 6.0 keeps that UX. The cart's packages come from 6.0-order-routing.md (for_allocation — seller items allocate from that seller's stock location), delivery options per package come from 6.0-delivery-rate-provider.md filtered to the package's seller: a DeliveryMethod with seller_id is offered only on that seller's packages; seller_id: nil methods are marketplace-wide. The chosen method + rate travel with the package into that seller's child order at split. This is a hard requirement on the cart/order-split checkout design (see Constraints).
  • Move semantics: line items, their tax lines / discounts / fees (6.0-6.1-split-adjustments.md), fulfillment items, and fulfillments are assigned to the correct child Order (created from the cart partition); the owner FK on every typed line is rewritten to the child order. Order-level Fee rows (both adjustable FKs nil — e.g. a payment surcharge; allowed per split-adjustments 2026-07-27) prorate across child orders by item totals using the same largest-remainder rule as order-level discount distribution, their tax lines following the fee. Stock location per child comes from the routing strategy, not a bare detect.
  • Group status: derived, not a column. The OrderGroup is "fully fulfilled" when all its orders are, "partially canceled" when some are, etc. — computed across order_group.orders, replacing the legacy all_shipments/splitted?/cancel_parent_order workarounds (which existed only because the legacy parent was itself an Order).

OrderGroup model

# Transaction container — N orders placed together as one customer checkout.
# Domain-neutral (Decision 8): multi-vendor is its first consumer, but it's
# reused for split-by-location, split-by-availability, B2B split-by-company-location.
class Spree::OrderGroup < Spree.base_class
  include Spree::Metadata
  has_prefix_id :ogrp
  publishes_lifecycle_events

  belongs_to :store, class_name: 'Spree::Store'
  belongs_to :customer, class_name: Spree.customer_class.to_s, optional: true  # guest groups allowed

  has_many :orders, class_name: 'Spree::Order', dependent: :restrict_with_error  # never cascade-delete completed orders
  has_many :payments, class_name: 'Spree::Payment'                          # the single shared payment(s)
  has_many :payment_splits, class_name: 'Spree::PaymentSplit', through: :payments
  belongs_to :ship_address, class_name: 'Spree::Address', optional: true
  belongs_to :bill_address, class_name: 'Spree::Address', optional: true

  # number (human-facing, e.g. the cart-derived order number), currency
  # email — guest checkouts have no customer; the group carries the contact email

  # Status is DERIVED across orders, never a column:
  def fulfillment_status; ...; end  # all fulfilled / partial / pending
  def payment_status;     ...; end  # paid / partial / void, aggregated from the shared payment
end

The child Order gains belongs_to :order_group (optional — a plain single-seller / single-fulfillment order has no group) and belongs_to :seller (optional — non-marketplace orders have no seller). No parent_id, no splitted status.

Split payment record (Decision 5)

# Per-child-order bookkeeping of the ONE gateway payment. No cloned Payment rows.
class Spree::PaymentSplit < Spree.base_class
  has_prefix_id :paysp

  belongs_to :payment, class_name: 'Spree::Payment'   # the group's single gateway payment
  belongs_to :order,   class_name: 'Spree::Order'     # the child (seller) order

  # authorized_amount / captured_amount / refunded_amount : decimal
  # currency : string

  extend Spree::DisplayMoney
  money_methods :authorized_amount, :captured_amount, :refunded_amount
end

Created at split, one per child order, with a unique index on (payment_id, order_id). authorized_amount is the child's share of that payment — store-credit and gift-card payments are group payments too and get their own PaymentSplit rows, prorated by child totals with the same largest-remainder rule (RESOLVED 2026-08-15), so a mixed store-credit checkout never overstates the gateway exposure: each child's splits across all group payments sum to child.total. Captures on partial fulfillment and refunds on a child order update that child's split only. Spree::Refund against a grouped payment always carries the child-order context so the split, the commission reversal, and the transfer reversal reconcile against the same order (see Reversals).

Commission models

# Snapshot line — one per commissioned line item, frozen at placement
class Spree::CommissionLine < Spree.base_class
  include Spree::Metadata
  has_prefix_id :comln

  belongs_to :order,       class_name: 'Spree::Order'
  belongs_to :line_item,   class_name: 'Spree::LineItem',   optional: true  # the commissioned item…
  belongs_to :fulfillment, class_name: 'Spree::Fulfillment', optional: true # …or the commissioned delivery (include_shipping)
  belongs_to :seller,      class_name: 'Spree::Seller'
  belongs_to :commission_rate, class_name: 'Spree::CommissionRate', optional: true  # nullable: rule may be deleted later

  # exactly one of line_item / fulfillment is set (same pattern as TaxLine's adjustable),
  # enforced by a model validation AND a DB CHECK constraint (num_nonnulls-style XOR)
  validate :exactly_one_of_line_item_or_fulfillment

  # snapshot fields (frozen — never recomputed)
  # rate        : decimal  — the % or flat value applied, as resolved at sale time
  # kind        : string   — 'percentage' | 'fixed'
  # amount      : decimal  — commission charged to the seller (the platform's fee)
  # tax_amount  : decimal  — VAT/tax ON the commission (EU) — Decision 3
  # total       : decimal  — amount + tax_amount
  # currency    : string

  extend Spree::DisplayMoney
  money_methods :amount, :tax_amount, :total
end

# Rate definition (mutable config) — rule-engine resolution, legacy-style defaults
class Spree::CommissionRate < Spree.base_class
  has_prefix_id :comrt
  include Spree::SingleStoreResource
  acts_as_paranoid

  belongs_to :store, class_name: 'Spree::Store'
  has_many :commission_rules, class_name: 'Spree::CommissionRule', dependent: :destroy
  # Every amount this rate states, one row per currency (RESOLVED 2026-08-17).
  has_many :commission_rate_values, class_name: 'Spree::CommissionRateValue', dependent: :destroy

  # name, code (unique per store), enabled (bool), position (int, acts_as_list)
  # kind             : string  — 'percentage' | 'fixed'
  # value            : decimal — the percentage; a flat fee states amounts instead
  # tax_inclusive    : bool    — commission base is the item's gross vs net price
  #                              (EU default: net — Decision 3). Named to match
  #                              Market#tax_inclusive, not the industry's include_tax.
  # include_shipping : bool    — also commission the seller order's delivery amounts
  #                              (Decision 4); percentage rates only
  # commission tax: resolved via 6.0-tax-provider, not a flat column (Decision 3)
  #
  # NO currency / min_amount / max_amount column — an amount means nothing
  # without saying what of, so all three live per currency on the value rows.

  validates :code, uniqueness: { scope: spree_base_uniqueness_scope }
  validate  :fixed_rate_states_an_amount   # a flat fee charging nowhere is skipped everywhere
end

# What a rate charges in one currency, and the bounds it charges within.
# Nothing is ever converted between them (RESOLVED 2026-08-17).
class Spree::CommissionRateValue < Spree.base_class
  belongs_to :commission_rate, class_name: 'Spree::CommissionRate'

  # currency   : string  — unique per rate among live rows
  # amount     : decimal — what a flat fee charges here, per unit sold
  # min_amount : decimal — nullable floor, holds only in this currency
  # max_amount : decimal — nullable cap (NEW — neither reference has this; EU/fairness)

  validate :max_amount_above_min_amount
end

# Targeting rule — typed, like Spree::PriceRule and Spree::DeliveryMethodRule
# (RESHAPED 2026-08-17, shipped). Every rule must hold; a rule naming several
# records means any of them, so the OR lives inside a rule and there is no
# match_policy knob.
class Spree::CommissionRule < Spree.base_class
  include Spree::PreferenceSchema
  belongs_to :commission_rate, class_name: 'Spree::CommissionRate'
  registers_subclasses_via { Spree.commission_rules }

  def applicable?(context); end   # Spree::Commissions::Context
end

# Core kinds: SellerRule, CategoryRule (matches descendants), ProductRule
# (join table — catalog scale), ItemTotalRule (a value band, the kind that
# could not exist while a rule could only name a record).

Resolution (Spree::Commissions::ResolveRate service): load enabled CommissionRates for the store in list order (position ASC) — the currency gate applies only to fixed rates (a flat fee must state an amount in the order's currency; a percentage is a ratio and always passes, its floor and cap simply not applying outside the currencies they were written in) — and return the first whose rules match the line item: rules grouped by subject_type, every present group needs ≥1 match (Decision 4). A rate with no rules is the global default (CommissionRate#global?) — and because resolution stops at the first match, one placed above a targeted rate makes it unreachable, which is why the seeded default sits at the bottom and the admin surfaces the flag. Spree::Seeds::CommissionRates seeds exactly one such rate, disabled and at zero: a marketplace that has not set its terms should charge nothing rather than a number core invented. This also untangles the three legacy meanings of platform_fee (store preference / seller column / product override) into one model.

Calculation (Spree::Commissions::CalculateLine service) — ports the legacy per-item fee calculation, generalized:

item_net   = discounted item amount, ex-VAT     # price − discounts, tax excluded (EU default base)
item_gross = discounted item amount, incl. VAT  # price − discounts, tax included
base       = tax_inclusive ? item_gross_per_unit : item_net_per_unit
per_unit   = kind == 'percentage' ? (base * rate / 100) : amount_for(currency)
amount     = per_unit * quantity                                     # both kinds scale with quantity
amount     = clamp(amount, min_amount_for(currency),
                           max_amount_for(currency))                 # NEW: max cap, per currency
tax_amount = amount * commission_tax_rate / 100                      # Decision 3 — the EU piece
total      = amount + tax_amount

The base is payment-source-agnostic: store credit / gift cards are how the customer paid, not a price component — they never reduce the commission base (consistent with the resolved transfer-basis decision; the legacy implementation subtracted a store-credit share from the base, and that behavior is deliberately dropped). "Net" here means net of VAT; discounts are always subtracted first in both bases (the seller's commission is charged on what the customer actually paid for the item — promotions are seller-funded in v1, see Open Questions).

Commission tax rate source (the contract CalculateLine consumes): precedence is (1) an explicit commission_tax_rate override on the CommissionRate, else (2) the store's TaxProvider asked for the platform-service rate against the seller's billing address (commission is a B2B supply to the seller — not the consumer's ship address), else (3) a store-preference default, else 0. Missing/erroring provider lookups fall through to (3) — commission lines are written inside the split transaction and must never block checkout on a tax-service outage.

Rounding: every persisted money field rounds half-up to the currency's minor unit (2 dp for most currencies, using the currency exponent — matching legacy behavior): per_unit after the percentage step, amount after quantity × clamp, tax_amount after the tax step; total is the sum of the two rounded parts, so Σ CommissionLine amounts always reconcile with balances and payouts to the cent.

Persist one CommissionLine per line item on the child order, inside the split transaction. When the resolved rate has include_shipping, run the same calculation against the seller order's delivery amount and persist a fulfillment-scoped CommissionLine alongside.

Fund ledger — two levels (Decision 9)

# Level 1 — PER-ORDER, on-fulfillment. Credits the seller's balance with what they earned.
# CORE; provider-agnostic. The `system` provider records only; StripeConnect executes.
class Spree::SellerTransfer < Spree.base_class
  has_prefix_id :vtr
  include Spree::RansackableAttributes

  belongs_to :seller, class_name: 'Spree::Seller'
  belongs_to :order,  class_name: 'Spree::Order'                       # the child (seller) order
  belongs_to :payout, class_name: 'Spree::SellerPayout', optional: true  # nil until settled (Decision 9 link)
  belongs_to :reversed_from, class_name: 'Spree::SellerTransfer', optional: true
  has_many   :reversals, class_name: 'Spree::SellerTransfer', foreign_key: :reversed_from_id

  # amount   : decimal — seller_order.total − commission_lines.sum(:total) (payment-source-agnostic)
  # currency : string
  # kind     : string  — 'earning' | 'refund_reversal'
  # provider : string  — 'system' | 'stripe_connect'
  # reference: string  — provider txn id (Stripe transfer id); nil for manual

  state_machine :status, initial: :pending do
    event(:process)  { transition pending: :processing }
    event(:complete) { transition [:pending, :processing] => :completed }   # earned/confirmed
    event(:fail)     { transition [:pending, :processing] => :failed }
  end

  scope :completed,  -> { where(status: 'completed') }
  scope :unsettled,  -> { completed.where(payout_id: nil) }              # awaiting the next payout sweep

  extend Spree::DisplayMoney
  money_methods :amount

  # original minus already-reversed, floored at zero (ports the legacy rule)
  def reversible_amount; ...; end
end
# Level 2 — PER-INTERVAL, scheduled. Batches the seller's unsettled transfers into one
# bank settlement and debits the balance. CORE; the `system` provider records the
# settlement, StripeConnect performs it.
class Spree::SellerPayout < Spree.base_class
  has_prefix_id :vpo
  include Spree::RansackableAttributes

  belongs_to :seller, class_name: 'Spree::Seller'
  has_many   :transfers, class_name: 'Spree::SellerTransfer'           # the transfers this payout settles

  # amount   : decimal — SUM(transfers.amount); set when the payout is assembled
  # currency : string
  # period_start / period_end : datetime — the interval this payout covers
  # provider : string  — 'system' | 'stripe_connect'
  # reference: string  — provider payout id; nil for manual

  state_machine :status, initial: :pending do
    event(:process)  { transition pending: :processing }
    event(:complete) { transition [:pending, :processing] => :completed }   # manual mark-paid OR provider webhook
    event(:fail)     { transition [:pending, :processing] => :failed }
  end

  scope :owed,      -> { where(status: %w[pending processing]) }
  scope :completed, -> { where(status: 'completed') }

  extend Spree::DisplayMoney
  money_methods :amount
end

Spree::Seller exposes the derived bridge:

# seller.rb — per currency; every ledger row carries `currency`, so a multi-currency
# store accrues separate balances and the payout sweep runs per (seller, currency).
# Answered in the SETTLEMENT currency (2026-09-14): what a payout can actually send.
def balance(currency)   # what we still owe the seller, in a currency they can be paid in
  earnings = seller_transfers.completed.settling_in(currency)

  earnings.sum(&:settlement_amount) -
    earnings.select { |t| t.payout&.completed? }.sum(&:settlement_amount)
end

Earned and settled are two figures (RESOLVED 2026-09-14, shipped). A transfer is denominated in the order's currency, because that is what the customer paid; a connected account settles in its own, and the provider converts on the way in. With only one figure the ledger accrued money the account could never pay out — a GB seller on a US marketplace was owed USD against an account holding only GBP, so available_payout answered zero and the sweep halted forever. spree_seller_transfers therefore carries settled_amount / settled_currency alongside amount / currency, written by the provider from what it reports actually arrived (Transfer.destination_payment.balance_transaction for Stripe). Both are nullable: nil means no provider has reported a settlement, and the earned figures stand in — which is right for PayoutProvider::System, where the operator settles offline in the order's currency. Payouts are swept, summed and denominated in the settled currency, since that is the only money the account can move; a reversal prorates from its earning's settled figure so a clawback comes back at the rate the money went out at, and lands in the batch that pays the earning it cancels. A balance is one position per (sale currency, settlement currency) pair, showing both sides.

This is not a retreat from "nothing is ever converted". Spree still holds no exchange rates and performs no conversion. It records a conversion the provider performed and reported, as a fact, beside the original — two actuals, never added together. The standing no-FX rule (per-currency commission values, per-currency balances, reporting totals never summed across currencies) is untouched.

# Pluggable execution strategy — CORE base + system no-op; basic StripeConnect ships
# with the monorepo Stripe gateway (2026-07-15 amendment); Enterprise extends it.
# Mirrors 6.0-tax-provider.md / 6.0-delivery-rate-provider.md. Two verbs, one per level.
class Spree::PayoutProvider::Base
  def transfer!(seller_transfer); raise NotImplementedError; end   # on-fulfillment (level 1)
  def pay!(seller_payout);        raise NotImplementedError; end   # on-interval (level 2)
  def reverse!(seller_transfer);  raise NotImplementedError; end   # refund → reverse transfer
end

# CORE default — records both ledgers, moves no money (manual/offline settlement).
class Spree::PayoutProvider::System < Spree::PayoutProvider::Base
  def transfer!(seller_transfer) = seller_transfer.complete!   # earned → credits balance
  def pay!(seller_payout)        = seller_payout               # no-op; admin marks complete manually
  def reverse!(seller_transfer)  = seller_transfer
end

# OSS — ships with the monorepo Stripe gateway (pulled in from the standalone
# spree_stripe repo; payment-sessions classes only, likely spree/core): BASIC Stripe Connect.
#   Spree::PayoutProvider::StripeConnect — Express-account onboarding link + account
#   status webhook; transfer! → Stripe::Transfer with source_transaction on fulfillment
#   (ports the legacy transfer creation); pay! → Stripe's native connected-account
#   payout schedule (ports the legacy schedule mapping) + SellerPayout rows from payout
#   webhooks; reverse! → ledger-only (records the reversal, moves no money back).
#
# ENTERPRISE — extends the OSS provider with the money OPERATIONS (not in this repo):
#   reverse! → prorated Stripe transfer reversals (ports the legacy reversal logic) +
#   negative-balance netting against future transfers; KYC/account-health workflows;
#   ledger⇄Stripe reconciliation + payout reports. Credentials live on its
#   Spree::Integration record, same convention as external tax providers.

Settlement sweep (level 2): the scheduled job runs per (seller, currency) pair on the seller's payouts_schedule_interval: it collects that pair's unsettled transfers, creates one SellerPayout with amount = Σ, stamps each transfer's payout_id, and invokes provider.pay!. system leaves it pending for manual completion; stripe_connect settles and a webhook completes it.

Claim & idempotency contract: creating the payout and stamping its transfers' payout_id happen in one transaction — that stamp is the claim; a re-run sweep only ever sees payout_id IS NULL transfers, so a batch can never be swept twice. provider.pay! must be idempotent, keyed on the payout's prefixed ID (Stripe idempotency key), so a crashed/retried invocation cannot double-pay. Failure paths: pay! raising → payout.fail! with its transfers still stamped — retry means re-invoking pay! on the same payout (never re-sweeping into a new one); a payout stuck in processing past a timeout is surfaced in the operator payouts queue for manual resolution (webhook lost vs. provider-side failure), never auto-recreated.

The same contract applies to level 1. One earning transfer per seller order — enforced by a partial unique index on (order_id) WHERE kind = 'earning' — so a re-fired fulfillment event finds the existing row instead of double-crediting. provider.transfer! is idempotent keyed on the transfer's prefixed ID, and the provider reference (Stripe transfer id) is unique when present: if transfer! succeeded externally but the record never reached completed (crash between API call and commit), the retry's idempotency key returns the same external transfer and the recovery path re-syncs reference + status rather than creating a second money movement. Ambiguous/timed-out attempts park the record in processing for the operator queue, same as payouts.

OSS settlement statements come free. The ledger is exportable through the standard Spree::Export pipeline — a per-seller CSV of transfers/payouts (sales − commission − commission VAT = net, plus reversals) is just an export of these tables, replacing the legacy Spree::Reports::SellersPayout report. What stays Enterprise under "payout reports" is provider reconciliation (ledger ⇄ Stripe) and regulatory reporting (DAC7) — not the raw statement.

Reversals (refunds)

The legacy module writes reverse commission rows when items are refunded (per returned item, plus an order-scoped prorated row for whole-order refunds) and reverse transfers. 6.0 keeps both, symmetric — but reversals are always per line (a whole-order refund reverses each line's commission exactly; the legacy order-level proration and its rounding fuzz are not carried over):

  • A refund writes a negative/reversed CommissionLine (net commission = sum(commission_lines)).
  • A refund writes a refund_reversal SellerTransfer linked via reversed_from (net earned = sum(seller_transfers)). If the original transfer was already settled in a completed payout, the reversal lands in the next payout period (Decision 9).

The hook point is Spree::Refund. 6.0-returns-exchanges-claims.md funnels Return, Exchange, and Claim money movement through Spree::Refund — so a single subscriber on the refund event covers all three flows: it updates the child order's PaymentSplit.refunded_amount, writes the reverse CommissionLines for the refunded items, and writes the reversal SellerTransfer.

Product ownership & approval

  • Products carry seller_id (nullable — the operator's own first-party products have none). Seller users only see/manage their own (ability tenancy condition).
  • Approval reuses the product status workflow — no new approval model. Seller-created products default to draft; a store preference seller_products_require_approval (default true) controls whether sellers may activate their own products or an operator must. This covers the seller product-approval workflow competing marketplaces ship, with zero new machinery, and #13323's "merchandise Seller's products" stays intact — the operator retains full edit rights over seller products (naming, taxons, publication to channels).
  • Seller bulk product CSV import/export rides the existing Spree::Import / Spree::Export pipeline (see 5.6-admin-spa-csv-import.md) with the seller context stamped on created records — no marketplace-specific importer.
  • SKU uniqueness relaxes to per-seller scope. Two sellers legitimately sell the same manufacturer SKU (the legacy module disables SKU validation outright); 6.0 scopes the uniqueness check by the variant's seller_id instead of dropping it (Decision 11 — sellers share a product, so scoping by the product's owner would not separate them). Note today's scope is spree_base_uniqueness_scope, which is empty: SKUs are unique across the whole installation, not even per store.
  • "Shop by seller" curated pages come from a seller-subject CollectionRule kind (6.0-replace-taxons-with-categories.md), replacing the legacy Spree::TaxonRules::Seller.

Seller notifications

Seller notifications are event-driven, with OSS mailers included — split along the existing mailer boundary:

  • Back-office emails to sellers and admins live in core, next to the existing back-office mailers (Spree::ExportMailer, Spree::ImportMailer, Spree::InvitationMailer, Spree::ReportMailer): a Spree::SellerMailer ports the legacy set — seller approved/rejected/suspended (to the seller's team), onboarding started/submitted-for-review (to store admins), new seller order, payout completed — wired as subscribers to the lifecycle events below. Seller invitations need nothing new: they already ride core's InvitationMailer via the Invitation rail. Core-resident means seller email works in every installation, regardless of gems.
  • Consumer-facing emails (e.g. the per-seller shipment tracking emails customers receive) belong to spree/emails (rebuilt + modernized in 5.6, optional) — or to the storefront's own email stack via webhooks, for headless setups that own transactional email.
  • The purchase confirmation is sent once, from the group: order_group.completed → Spree::OrderGroupEmailSubscriber → Spree::OrderGroupMailer, with every child order placing silently. It describes the whole purchase and counts its deliveries from fulfillments rather than from child orders — see the Resolved Decisions entry for why those differ. A checkout that does not split keeps the plain Spree::OrderMailer path untouched.

Either way the events are the seam — subscribers/webhooks feed n8n/Slack/custom stacks, including OSS payout automation: seller_payout.due → webhook → operator's banking flow → POST /seller_payouts/:id/complete.

Events (via publishes_lifecycle_events + explicit publishes): seller.created/updated/approved/rejected/suspended, order_group.completed, per-child order.placed (existing), commission_line.created, seller_transfer.completed/reversed, seller_payout.due/completed/failed.

Store API surface

Mirrors what the legacy v2 storefront already exposed for Enterprise (/api/v2/storefront/sellers), rebuilt on v3:

  • GET /api/v3/store/sellers + GET /api/v3/store/sellers/:slug — public profile: name, slug, about, logo, square_logo, cover_photo. Only approved, non-holiday sellers. No timestamps, no contact email, no financials (store-serializer rules).
  • Product serializers gain a seller { id, name, slug } object (nil for first-party products); product listing accepts q[seller_id_eq] — that plus the seller profile endpoint is a complete seller storefront page. Seller becomes a search facet through the existing SearchProvider filter registry.
  • POST /api/v3/store/seller_applications — the self-serve "become a seller" application (name, contact email, message) creating a pending seller + owner invitation for operator review. Rate-limited, no auth required.
  • Checkout completion of a cart that split returns the order group: { order_group: { id, number, orders: [...] } }; carts that don't split (a single partition — all one seller, or all first-party) keep returning the bare order. Customer account history lists groups with nested per-seller orders + per-order fulfillment tracking (today's "separate tracking per seller" UX).

Admin API surface

Endpoint list lives in 6.0-admin-api.md → "Marketplace (new in 6.0)": sellers CRUD + invite/approve/reject/suspend (approve also un-suspends, matching the legacy machine), commission rates CRUD (nested rules: [], PriceList-style), read-only commission_lines + seller_transfers, seller_payouts + POST :id/complete (manual settlement), read-only order_groups. API key scopes: read_sellers/write_sellers, read_commissions/write_commissions, read_payouts/write_payouts. This is the operator's surface only — seller users never call it (Decision 10; the 2026-07-14 "collapse into ability scoping" wording is superseded).

Seller API surface (new 2026-08-15 — Decision 10)

A third v3 branch, /api/v3/seller/…, anchored by Spree::Api::V3::Seller::BaseController / Seller::ResourceController (mirroring the admin pair; concerns added to one must be added to the other):

  • Auth & context: POST /seller/auth/login|refresh|logout, password reset — Spree.seller_authentication_strategies, seller_api JWT audience, audience-stamped refresh token + own cookie. X-Spree-Seller-Id selects the seller; membership = role_users on resource: seller; a header naming a seller the caller does not belong to is 403; Spree::Current.store is set from current_seller.store. GET /seller/me — user + seller memberships + permission_keys for the selected seller. Invitation acceptance stays on the existing /admin/invitation_acceptances (it is store-agnostic and already handles resource: seller).
  • Own resources: GET/PATCH /seller/profile (name, about, branding uploads, billing/returns addresses, payouts_schedule_interval, ToS acceptance, holiday mode), GET /seller/onboarding_tasks + POST /seller/onboarding/submit_for_review, GET /seller/team + team invitations (RoleGrantGuard-bounded to seller-audience roles), GET /seller/balance, GET /seller/transfers, GET /seller/payouts (read-only ledger).
  • Catalog: products (+ nested variants, prices, media, stock items) — every lookup through current_seller.products; create force-stamps seller_id; approval state per the store's seller-product preference. No channel publication, and no categories/collections/tags at all — filing a listing is the operator's, done at review (2026-08-26). A seller does assign a product type and a delivery profile (2026-09-01): the type is what hands them option types and the profile template, the profile is what makes their goods quotable, and read-only GET /seller/product_types and GET /seller/delivery_profiles back the two pickers.
  • Orders: the seller's child orders (current_seller.orders), fulfillments with Fulfillments::Fulfill/Cancel/UpdateTracking, returns/exchanges/claims on those orders — including refunding their own return (amended 2026-09-03; the legacy module allowed it, and the amount is bounded three times over: by Return#refundable_total, by Refund#order_is_covered_by_payment, and by Refunds::Create#refundable_share, which caps a grouped payment at this child's captured share). No order edits, approvals, payments or delivery confirmation — the seller sees its payment_split, never the group's Payment, and marking goods received is the buyer's word, not the sender's. Full surface: 6.0-seller-order-management.md.
  • Delivery: profiles are read-only vocabulary (shipped 2026-09-01); the seller's own delivery methods (seller_id = self) with read-only zones under a profile, and shared marketplace methods listed read-only with editable: false — Decision 13, shipped 2026-09-01.
  • Exports/imports: the seller's own runs on the Spree::Export/Import pipeline, scoped by seller_id.
  • Serializers: Spree::Api::V3::Seller::*Serializer < V3::*Serializer (the store serializer) plus an explicit list of operational fields — never a subclass of the admin serializer, so nothing leaks by inheritance. Own typelizer output and a generated docs/api-reference/seller.yaml from spree/api/spec/integration/spree/api/v3/seller/.
  • Tripwires: the branch enters Spree::StoreScopeGuard's coverage, and Phase 1 adds a seller-scope guard on the same pattern (flag store-scoped-but-not-seller-scoped scans on seller-owned tables under /seller).
  • Later, not 6.0: seller-bound secret API keys (Enterprise Shopify/Woo apps acting as the seller) — safe only on this branch, because its base scope is current_seller; a store-bound admin key is can :manage, :all.
  • SDK packaging (a @spree/seller-sdk vs a seller namespace in the admin SDK) is decided with Phase 4; the API decision does not depend on it.

Migration Path

This is new OSS code, not a rename of existing core — there is no in-place data migration for existing Spree stores (they have no sellers). The "migration" is twofold:

  1. From the Enterprise module to core, for existing marketplace customers. A one-time backfill rake task (shipped in Enterprise — only Enterprise has legacy data) must:

    • For each legacy splitted parent order, create a Spree::OrderGroup and attach its parent_id children as the group's orders.
    • Migrate the legacy per-item commission rows → spree_commission_lines. Sign convention flips: the legacy module stores order-level fee totals negative (load-bearing in its payout math); CommissionLine amounts are positive, reversals are their own negative/reversed rows.
    • Decrypt the legacy encrypted seller contact columns (ActiveRecord encryption — a multi-tenant SaaS choice) into core's plain columns.
    • Migrate the legacy Stripe transfer ledger → spree_seller_transfers (the per-order, on-fulfillment level) with provider: 'stripe_connect' and the Stripe transfer id in reference. The legacy module has no payout records (it delegated scheduling to Stripe), so there is nothing to backfill into spree_seller_payouts — historical Stripe payouts can optionally be reconstructed from Stripe's API, or simply start fresh from the cutover. The Enterprise module then becomes a thin layer on top of core's new models, deleting its splitting + commission + transfer decorators. The basic Spree::PayoutProvider::StripeConnect ships in the monorepo with the pulled-in Stripe gateway (2026-07-15 amendment); Enterprise extends it (KYC ops, reconciliation) and keeps Shopify/WooCommerce.
  2. Build order (each phase shippable):

    • Phase 0 — admin-branch hardening (ships first, no Seller model needed). IMPLEMENTED 2026-08-16. Tighten AdminAuthentication#current_user_member_of_store? to resource_type: 'Spree::Store' + regression spec; spree_refresh_tokens.audience written at mint and enforced on refresh (admin + store surfaces stamp their own); Role#audience + the audience marker on register_scope (Decision 10 / RBAC plan). Shipped as: audience on refresh tokens (nullable; for_audience scope narrowing every refresh and logout lookup on both surfaces — ending a session belongs to the surface that started it; legacy NULL-audience rows match no surface and are rejected on refresh, costing their holders one login) and on roles (null: false, backfilled staff, immutable after create, Spree::Role::AUDIENCES the vocabulary); the catalog takes audiences: naming every audience a scope is grantable to — the store's own back office is :store, and the default when none is named, so a scope shared with sellers says %i[store seller] and one for sellers alone says %i[seller], with grantable_keys(audience) (unknown audience ⇒ empty, never raises) — a generalization of the originally-planned seller_grantable boolean, so a third panel needs no schema change (decisions.md 2026-08-16); orders/fulfillments/products/stock/dashboard opened to seller. Roles became store-owned (spree_roles.store_id, null: false, via SingleStoreResource): they were global reference data, so two stores could never each define a "Manager" and the marketplace would have inherited that. Names are unique per (store, name, audience) — Spree::UniqueName's global uniqueness is deliberately not used on Role — so one store holds a staff "Manager" beside a seller "Manager", and another store holds its own. admin is now one immutable role per store (default_admin_role(store); Seeds::Roles moved after Seeds::Stores, since a role cannot exist before its store). The upgrade fans every existing role out per store and re-points assignments and invitations at the copy for the store they already named, so no grant changes hands. The audience bound is enforced twice: Spree::Role validates it on write, and Spree::Ability re-filters through grantable_keys(role.audience) at activation, since a catalog that changes after the role was saved would otherwise leave stale keys live. The staff surface is closed to foreign-audience roles at both ends — Admin::RolesController#scope lists only Spree::Role.staff, and RoleGrantGuard rejects assigning a non-staff role to store staff (invitations + admin_users). Spree::Ability takes resource: (defaults to the store) and reads role_users on it — the admin super-role and the implicit-admin fallback apply only on a store resource, and the staff baseline narrows read Spree::Store to the one store a non-store panel operates under. The ability answers capability, never tenancy: a seller holding write_orders gets can :manage, Spree::Order on the model class exactly as an admin does; which records it may touch is current_seller scope-fetching in the controller, so a seller-branch controller that authorizes without scope-fetching reads store-wide.
    • Phase 1 — Seller identity. Spree::Seller model (see Seller identity & teams: lifecycle, branding, ToS acceptance, holiday mode), onboarding task registry + core tasks, seller teams via RoleUser/Invitation (resource: seller) + UserRoles#sellers, self-serve application endpoint, core Spree::SellerMailer lifecycle emails (see Seller notifications), product ownership (products.seller_id + approval preference), Admin API Marketplace/sellers endpoints + Store API seller profiles, seller CSV import/export on the Spree::Import pipeline. Phase 1b — the shared catalog (Decision 11). IMPLEMENTED 2026-08-16: variants.seller_id + variants.delivery_profile_id, condition as an OptionType, the ownership filter on Product#variants=, first-party default_variant priority, the same-variant fix to option filtering, and the buy-box selection service the product rollups then answer through — see the Resolved Decisions entry for what shipped. Sequenced here rather than later because the split's partition key (Phase 3) and the commission line's identity (Phase 2) both read the seller off a line item, and on a shared product only the variant can answer. The Seller API branch anchor (Seller::BaseController/ResourceController, seller_api audience, Spree.seller_authentication_strategies, /seller/auth/*, /seller/me, /seller/profile, onboarding, team, seller-scope guard, Spree::Ability resource: option) + the seeded default seller role. Products/orders/fulfillments on the seller branch follow as each domain lands (products in Phase 1, orders/fulfillments/ledger reads in Phase 3). No splitting yet.
    • Phase 2 — Commission engine. CommissionRate + CommissionRule + CommissionLine, resolution + calculation services (dimension-grouped matching, min/max clamps, include_shipping), commission-tax field, admin UI for rates. Compute-only (attach to single-seller orders, no split).
    • Phase 3 — Order splitting. IMPLEMENTED 2026-08-20 (the fund ledger follows as Phase 3a). Spree::OrderGroup + Spree::PaymentSplit, the split as named steps inside Carts::Complete (Carts::PartitionBySeller → Carts::SplitBySeller → OrderGroups::AllocatePayments), derived group status, per-child refund attribution. What shipped and why it took the shape it did: the split runs in FINALIZE, after payment, and adopts the paid draft order as the group's first child rather than building N fresh orders and discarding it — that order is what the payment was taken against and what carries the unique cart_id replay anchor, so destroying it would orphan money and break resumption; the remaining partitions become siblings and the rows are moved, never re-copied (every line item, fulfillment and typed money row was costed once inside the completion lock — re-deriving would ask the pricing and tax engines a question already answered). The group takes the order's number and children suffix off it (R1001-1, R1001-2), so a customer keeps the reference they saw at checkout. completion_result is now cart.order_group || cart.order and the workflow returns whichever exists. A parcel split between sellers divides its delivery cost by the value each half carries (largest-remainder) — cloning the fulfillment kept the full cost on both halves and charged the customer twice, caught by a totals spec; order-level fees prorate the same way with their tax lines following. Per-seller commission needed no commission-engine change at all: each child publishes its own order.placed, which OrderCommissionSubscriber already answers, and the service already skips nil-seller lines so the first-party child is correctly uncommissioned. Payments moved up to the group (payments.order_group_id, order_id nil; Payment#owner extended, exactly_one_owner now three-way) with one PaymentSplit per (payment, child) prorated by child totals — so a mixed store-credit checkout never overstates gateway exposure on one seller's order. Consequences that had to ship with it: Orders::UpdateStatuses reads a grouped child's money from its splits rather than order.payments (which is empty there); capture-on-dispatch draws from the group's payments bounded by that child's remaining share, so the first seller to ship cannot capture the whole basket; spree_refunds.order_id names which child a refund puts right (Refund#order falls back to the payment, Order#refunds resolves either shape) and PaymentSplitRefundSubscriber recomputes only that child's refunded_amount; Spree::OrderGroup answers the payment-owner contract (payment_total, store credits, addresses via Purchase::Addresses) and counts as a purchase in Storefront::AccessPolicy so a guest can see what they bought. API: the Store completion response returns the group with orders nested (the customer sees one purchase, not three), the gateway-race retry resolves a group id, and read-only GET /admin/order_groups ships with OrderGroup/PaymentSplit added to the orders/payments catalog subjects.
    • Phase 3a — fund ledger. IMPLEMENTED 2026-08-22. The two-level SellerTransfer (on-fulfillment) + SellerPayout (scheduled sweep) + PayoutProvider::System + seller.balance(currency), sequenced after the split because the transfer basis needs child orders to exist. What shipped and why it took the shape it did: a seller earns on fulfilment, not payment — SellerTransferSubscriber answers order.fulfilled (only; the legacy order.shipped is deliberately not subscribed) and SellerTransfers::Create writes order.total − commission_lines.sum(:total), less additional_tax_total when the seller is platform-remitted, floored at zero. Its guards are the interesting part: an order with no fulfillments reads as fully_fulfilled? (vacuously true), so the emptiness is checked explicitly, and a seller whose provider requires_payout_account? but who holds none is skipped rather than credited money nothing can send. A refund writes a reversal row (kind: 'refund_reversal', linked by reversed_from) bounded by reversible_amount, so a twice-refunded order can never claw back more than was credited; the earning row is never edited. A partial unique index on (order_id) WHERE kind = 'earning' makes double-crediting a database error rather than a race (MySQL takes a CASE WHEN generated column instead). SellerPayouts::Sweep claims unsettled transfers by stamping them inside one transaction, so two concurrent runs cannot batch the same earning, and restates its own amount if it claimed fewer rows than it counted; it refuses a batch below the seller's minimum or one a reversal has pushed negative. SellerPayouts::Complete is the only thing that debits a balance, because a settlement is a claim about the outside world — an operator says the bank transfer went out, or a provider's webhook says the money landed. Admin API: read-only /admin/seller_transfers and /admin/seller_payouts plus PATCH /seller_payouts/:id/complete, under a new payouts permission resource (separate from commissions — they are opposite directions of the same relationship, and a finance operator often needs one without the other; closed to the seller audience).
    • Note for the second splitting consumer (recorded 2026-08-20). Carts::SplitBySeller is seller-specific in exactly three lines — the seller_id stamped on the adopted order and on each sibling, and the line_items.where(seller_id:) that selects a partition's rows. Everything else (group construction, number suffixing, parcel division and its delivery-cost apportionment, typed-line re-homing, order-level fee proration, the resum_only re-total) is partition-agnostic. When split-by-location or B2B split-by-company-location lands, the move is to lift those three lines into a registered splitter (Spree.order_splitters, following Spree.stock_splitters/Spree.adjusters) and rename the rest to Orders::Split, not to copy the file. Deliberately not done now, per the standing rule that a flow generalizes when it has a second consumer rather than speculatively — but the analysis is recorded so the second consumer does not have to redo it.
    • Phase 3b — OSS Stripe Connect provider. IMPLEMENTED 2026-08-22 in spree/providers/stripe. SpreeStripe::PayoutProvider transfers on fulfilment naming the customer's own charge as source_transaction (so the money settles with that charge rather than out of the platform's balance — a marketplace should not have to float its sellers), with an idempotency key derived from the ledger row. pay! creates a real Stripe::Payout on the connected account and the payout.paid webhook confirms it, exactly as the built-in provider's is confirmed by an operator. The connected account is deliberately created with settings: { payouts: { schedule: { interval: 'manual' } } } — Spree decides when a seller is settled, and two clocks on one relationship would leave the seller's own interval doing nothing. Corrected 2026-09-09: this line previously said pay! sends nothing and that Stripe settles on its own schedule, which was an earlier design. reverse! is ledger-only in OSS. Connect settings live on the Stripe payment method, not in an integration of their own — it is the same Stripe account either way, and a transfer signed with a different key than the charge cannot name that charge as its funding source, so a second copy of the credentials could only drift out of agreement with the first. Two webhook endpoints, and this is not a detail. Stripe's connect flag is a scope selector, not an additive one: an endpoint receives events from the platform's own account or from its connected accounts, never both. Adding account.updated to the payment endpoint would not widen it — it would switch it over, and the payment webhooks would silently stop arriving. So a marketplace registers a second endpoint with its own signing secret, served by a new provider-agnostic POST /api/v3/webhooks/payouts/:payment_method_id route beside the payments one, and it is registered only once the store actually has sellers. account.updated writes payouts_enabled_at — and clears it when Stripe withdraws the capability, since a seller whose documents expire stops being payable and the ledger must stop crediting them. Not yet built: the Express onboarding UI (create_connect_account_link exists and is specced; the seller-facing screen belongs with the onboarding work) and payout-schedule mapping onto the connected account.
    • Phase 4 — Dashboards. The ledger surfaces landed 2026-09-09 — see 6.0-seller-ledger-ui.md, which owns the seller panel's balance/earnings/payouts screens, the payment share on a seller's order, and the operator's transfers list, payouts review queue with mark-paid, seller balance card and grouped-order payments card. It also adds the seller_earnings permission key; a seller reads their own ledger through that, never through payouts. The order surfaces landed early with Phase 3 (2026-08-21), since a split checkout is unreadable without them: the orders table gained optional seller and order_group columns (both default: false, so a store selling only its own goods never sees them) with Ransack filters behind them, and the order page gained a marketplace card naming the seller — linked to their profile — and, when the order was one of several, the purchase it belonged to with a link back to the list filtered to its siblings. The card renders nothing on an ordinary order. Deliberately no order-group screen of its own: the group is the shared payment and the identity of the purchase, and what an operator acts on is always an order, so the group appears as a filter and a link rather than a page. orders.seller_id/order_group_id joined the Ransack allowlist (without which a filter silently matches nothing); the serializer carries ids only, with the seller's name coming from ?expand=seller requested by the column while it is visible — a denormalized seller_name was tried and dropped as a second copy of something the association already answers. The order group is deliberately not expandable from an order: its serializer renders the orders it holds, so expanding it from one of them would render that order inside itself, and a client wanting the group has /order_groups/:id. Remaining: a "needs attention" queue on the dashboard home (sellers ready_for_review + pending seller products — a lightweight unified review inbox). Everything else in this phase has shipped: the operator's Sellers list/detail with lifecycle actions, branding and settlement settings, the Commission Rates settings page, and — per 6.0-seller-ledger-ui.md (2026-09-09) — the payouts review queue with owed balances, itemized settlements and mark-paid, the seller balance card, and the seller panel's own balance/earnings/payouts screens. The seller panel itself is composed from @spree/dashboard-ui + @spree/dashboard-core against the Seller API branch, with roles assigned from the operator's Sellers detail screen.

    Phases 1–2 have no dependency on the Cart/Order split — they can be built (even shipped behind a preview flag in a 5.x release) while the split refactor lands, de-risking the 6.0 timeline.

Constraints on Current Work

Even before this lands, work touching adjacent areas should:

  • Cart/Order split (6.0-cart-order-split.md): seller attribution hooks into Spree::Orders::Complete, the one finalize home both entry points share — not into Carts::Complete, which admin and B2B drafts never reach (amended 2026-09-17, V-3643; this line previously named Carts::Complete and that is what let an admin-raised order be commissioned while the ledger could never credit anyone). Do not reintroduce an order-level after_transition extension surface; multi-vendor must not depend on one. When fleshing out the checkout flow on Cart, design delivery selection per package (packages come from order routing) — the multi-vendor checkout needs one delivery choice per seller package before completion, and payments must be attachable to an OrderGroup, not only to an Order.
  • Rich text sanitization (6.0-rich-text-descriptions.md): sellers are the marketplace's lower-trust writers, and today they are protected by the 5.x-only Enterprise gem's Spree::SanitizeConcern (sanitize :description, :meta_description, if: -> { seller_id.present? }). That gem does not carry into 6.0 — this plan rewrites its functionality as core models — so core must own the sanitization before seller-authored content lands here. Core's SanitizableRichText (shipped 5.6.2) sanitizes on write rather than deriving sanitized_* on read, which is the stronger form. Three obligations for this plan: (1) apply it to every seller-writable rich text field (Seller#about, seller-authored product descriptions); (2) keep seller-facing write paths — the seller dashboard, seller CSV/feed imports, bulk maintenance jobs — on save-backed writers, since the concern is a before_save and does not cover update_columns/update_all/raw SQL (anything that must bypass callbacks calls Spree::RichTextSanitizer.sanitize explicitly); (3) do not ship a 6.0 allowlist weaker than the Enterprise scrubber sellers have on 5.x — that one prunes script/style element bodies entirely.
  • Split adjustments (6.0-6.1-split-adjustments.md): TaxLine and Discount stay strictly line-item- or fulfillment-attached (order-level discounts distribute to line items at application time), so they re-home unambiguously to one child order during the split. Fee may additionally be order-level (payment surcharge, COD — resolved 2026-07-27); at split, order-level fees prorate across child orders by item totals (largest-remainder), tax lines following the fee. Do not add a commission/marketplace Fee kind — commission is Spree::CommissionLine, off-order (Decision 2); Fee stays buyer-facing.
  • Inventory operations (6.0-inventory-operations.md): the procurement model is Spree::Supplier — never reuse Spree::Seller (reserved for marketplace sellers) for purchase-order sources. See decisions.md 2026-07-14.
  • External-store sync stays Enterprise: do not add external store/resource models, associations, or callbacks to core (no external_store on Seller, no external product/order/category tables, no platform sync hooks). The Shopify/WooCommerce connection layer is an Enterprise concern that decorates core's Seller from outside; core only needs to stay decorable (events + the onboarding task registry are the seams it plugs into).
  • Fulfillment & delivery (6.0-fulfillment-and-delivery.md): the ledger trigger is defined against Fulfillment ("all fulfillments fulfilled"), and DeliveryMethod gets an optional seller_id — keep the fulfillment-status surface queryable per order (child orders fulfill independently) and don't assume one order per checkout in fulfillment UIs.
  • Seller delivery (Decision 13): never give DeliveryProfile, DeliveryZone or DeliveryOriginGroup a seller_id — the seller's row is the method; which methods a seller's package sees is decided in Stock::Estimator#filter_delivery_methods and nowhere else (no seller checks in serializers, splitters or the storefront); code reading DeliveryOriginGroup#covers_location? must not assume its member list says anything about seller-owned locations; a seller product's product_type_id and delivery_profile_id are the seller's to assign, so nothing may treat them as operator-only again; and a seller's product form never offers categories, collections or tags. Spree::DeliveryMethod, DeliveryMethodRule and DeliveryMethodService are gated by the delivery_methods permission resource, not settings — a new delivery-method endpoint on either branch declares that resource, and nothing seller-facing may be gated on settings.
  • Order routing (6.0-order-routing.md): the per-child stock-location decision must come from the routing strategy, so a seller's items allocate from that seller's stock location. Keep for_allocation seller-aware-friendly (it already takes order:).
  • Tax provider (6.0-tax-provider.md) and Delivery rate provider (6.0-delivery-rate-provider.md): the PayoutProvider follows the same pluggable-strategy shape — keep the provider-registration convention consistent so all three (tax, delivery rate, payout) register and resolve the same way.
  • Admin API (6.0-admin-api.md): the Seller prefix is sel_. The "Marketplace (new in 6.0)" endpoint group there is the operator's API surface — keep it in sync. Seller users never call the Admin API (Decision 10).
  • Auth + RBAC (6.0-platform-auth.md, 6.0-admin-rbac.md): no third principal — never add a SellerUser/Spree.seller_user_class; seller staff are Spree.admin_user_class. Never derive back-office membership from store_id alone — match RoleUser.resource_type (Ability#staff_roles and RoleGrantGuard already do; the membership check must follow). New login surfaces get their own strategy registry and JWT audience; refresh tokens must carry the audience they were minted for. Catalog resources that sellers may hold must be marked seller-grantable at register_scope; settings/staff/api_keys never are. Seller-branch controllers scope-fetch through current_seller and never subclass admin controllers.
  • Seller addresses (Decision 12): do not add a returns_address back, and do not give a seller a tax rate column — identity (legal_name, registration_number, a TaxIdentifier) is the seller's, the rate is CommissionRate + TaxProvider. A billing address is a Spree::BusinessAddress (table-sharing subclass, never STI — before proposing a type column again, read decisions.md 2026-08-23: update_or_create_address and find_existing_address are what decide it). Code reading a seller's returns destination goes through Seller#returns_location, never a stored address FK. StockLocation name-uniqueness and its default flag are per-owner, so new code must not assume one default per store.
  • Do not revive the legacy commission model's shape (label-based rows + denormalized fee totals on the order), do not model commission as a polymorphic Adjustment, and do not write commission as a Spree::Fee (fees are buyer-facing and roll into order totals — Decision 2) — 6.0 uses the off-order Spree::CommissionLine ledger. Do not put the fund ledger in a payment-gateway namespace (the legacy gateway-namespaced-transfer mistake) nor collapse transfer and payout into one model — Spree::SellerTransfer (on-fulfillment) and Spree::SellerPayout (scheduled) are both core and provider-agnostic.

Resolved Decisions

  • One purchase, one confirmation — sent from the group, not its first child (RESOLVED 2026-09-16, shipped). A split checkout was already deliberate about sending a single confirmation, and wrong about which one: complete_orders silenced every child but the first, so the customer received that child's own email — its number, its items, its delivery, its total — with nothing in it to say the rest of the purchase existed. On a mixed basket the first-party child sorts first, so a $374.97 purchase of three items confirmed $50.67 and one item, and the $324.30 it did not mention included both sellers' goods. The email now hangs off the order_group.completed event this plan already named as the seam and which nothing had ever subscribed to: every child places silently, Spree::OrderGroupEmailSubscriber answers the group, and Spree::OrderGroupMailer renders the whole purchase — the number the customer saw at checkout (R1001, not R1001-1), every item, and the total actually paid. The email counts deliveries from fulfillments, never from child orders, because the two are not the same number. Where one warehouse serves several sellers the packer builds one package and the split divides its single quote between the children (see "Splitting a parcel between sellers divides everything hanging off it"), so three orders ship as one parcel; where sellers hold their own stock, three orders are three parcels each keeping its own untouched quote. Spree::FulfillmentGroup collapses divided halves back together on [stock_location_id, delivery_method_id] — the pair clone_fulfillment preserves, and one the packer cannot produce twice on its own, since it builds one package per location per order — so the customer is told how many times a courier will call rather than how many sellers they bought from. The delivery method alone will not answer it: available_to_sellers lets two warehouses be quoted on one shared marketplace method, and keying on the method would merge two real parcels. Two things had to ship with it. The store-owner notification moved to the group as well — it rode inside the first child's confirmation, so silencing the children would have removed it entirely — and the admin resend on a grouped child re-sends the group's email, or that back door would put the partial one back. Idempotency is a pair of delivered flags on spree_order_groups mirroring the order's, because replay re-publishes the group event. Grouped cancellation is deliberately untouched: it is opt-in per child (Orders::Cancel defaults notify_customer: false), so it is not misfiring on its own.
  • Seller delivery → marketplace-owned profiles, seller-owned methods (RESOLVED 2026-09-01, implemented 2026-09-01). Decision 13: profiles, zones and origin groups never carry a seller_id; DeliveryMethod gains a nullable seller_id and an available_to_sellers switch; a package's seller is its stock location's and its eligible methods are decided in the estimator alone; seller methods are internal-rate and manual-fulfillment only, carrier accounts staying the operator's; DeliveryOriginGroup#covers_location? is true for seller locations; "at least one way to ship" is a computed onboarding requirement; delivery_methods becomes its own seller-grantable catalog resource. Replaces the bare seller_id promise the Seller API and Order splitting sections carried since 2026-08-15.
  • A seller assigns their product's type and delivery profile; the operator files it (RESOLVED 2026-09-01, shipped). Partly reverses the 2026-08-26 change that took the whole Categorization card off the seller branch. A product type is not filing — it is the template that hands a seller their option types and delivery profile — and the profile is what makes their goods quotable at all: every seller product was landing on the store default, so nothing a seller sold could be digital or oversized. product_type_id and delivery_profile_id are readable and writable on /seller/products, resolved against the seller's store (a foreign id is a 404), backed by read-only GET /seller/product_types (under read_product_types, the key 6.0-seller-product-submission.md minted for exactly this) and GET /seller/delivery_profiles (under read_products — the vocabulary a product form fills in, not a setting a seller holds a key on). Categories, collections and tags stay off the branch: filing a listing is the operator's, done at review.
  • The split adopts the paid order rather than replacing it, and moves rows rather than copying them (RESOLVED 2026-08-20, shipped). Completion builds one draft order holding the whole basket so it can be paid as one; the split then makes that order the group's first child and hands the other partitions' rows to new siblings. The alternative — build N fresh orders and destroy the original — was written first and rejected on two counts: the original is the record the payment was taken against and the row carrying the unique cart_id that makes completion replayable, so destroying it orphans money and breaks resumption. Rows move (update_all on the owner FK) rather than being re-copied from the cart, because everything was costed once inside the completion lock and re-deriving would ask the pricing and tax engines a question already answered — possibly getting a different one. The group takes the order's number so the customer keeps the reference they saw at checkout, and children suffix off it (R1001-1), following the same reads-its-parent shape as fulfillment and payment numbers.
  • Splitting a parcel between sellers divides everything hanging off it (RESOLVED 2026-08-20, shipped). A fulfillment holding two sellers' goods becomes two, and the cost the customer was quoted is apportioned between them by the value each half carries (largest-remainder), never copied onto both. The first implementation cloned the fulfillment wholesale and charged delivery twice — the group totalled more than the customer paid, caught by a totals spec rather than by review. The honest reading is that one quote for one parcel no longer describes two; a marketplace wanting each seller quoted separately gets that by giving sellers their own delivery methods, which packs their goods separately from the start and leaves nothing to divide. Three things divide with it, each missed on the first pass because a divided parcel is the only case where a row's owner keeps its id while its contents change: the parcel's own tax lines, discounts and fees (re-pointing by fulfillment_id finds nothing for the clone, so the source kept tax on a charge it no longer bore and the sibling shipped untaxed), the selected delivery rate (a fulfillment restates its cost from its rate whenever amounts refresh, so leaving the rate whole quietly restored the full charge on both halves the next time anything touched them), and the stock reservations on the moving line items (scoped by order_id at release, so one child would have released everyone's and each sibling none).
  • Per-seller commission needed no commission-engine change (RESOLVED 2026-08-20, verified). Each child order publishes its own order.placed, which OrderCommissionSubscriber already answers, and Commissions::CommissionOrder already partitions by line_item.seller_id and skips nil-seller lines — so the seller children are commissioned and the first-party child correctly is not, with no marketplace branch anywhere in the engine. This is the payoff of the Phase 2 decision to key commission on the line item's own seller snapshot rather than on the order.
  • A promotion is redeemed by a checkout, not by an order (RESOLVED 2026-08-21, shipped). Promotion#credits_count counted distinct order_ids carrying its discount rows, so a split checkout — which leaves a row on every child — spent a usage_limit two or three times over on one customer's single redemption, and a promotion capped at 100 uses ran out early for everyone. Counting now collapses on COALESCE(orders.order_group_id, orders.id), so a group's children are one use between them and an ungrouped order is itself; adjusted_credits_count and used_by? exclude the asking order's whole group rather than just the order, via Order#sibling_order_ids ([id] when ungrouped). Coupon codes and the one-use-per-customer rule were checked and need nothing — a code's used flag lives on the code, and used_by? answers a boolean. The adjacent lesson: anything counting "how many times has this been used" must ask what a use is, because the split turned one of them into several without changing any of those call sites.
  • Seller attribution belongs to the one finalize home, so an admin-raised order divides like a checkout (RESOLVED 2026-09-17, shipped). The stamp and the split lived in Carts::Complete alone, while commission is charged off order.placed — published by Orders::Complete, which both entry points share. An order raised in the back office therefore came out commissioned against a seller by name with orders.seller_id NULL, so SellerTransfers::Create could never credit them and their own order list never showed the sale; a mixed basket commissioned two sellers and divided into nothing. This is the same oversight as the single-seller checkout entry below, one level up: that one fixed the case, not the cause. Orders::Complete now owns the division outright — partition, then stamp one seller or divide into a group, apportion the payment and place the siblings — running it after payment and before placement. Carts::Complete divides nothing: FINALIZE makes one call and reads the group back, losing two steps and its per-child loop. Carts::SplitBySeller takes cart: as optional, since build_group was its only cart-coupled method and the order carries every fact it reads. The admin completion endpoint answers with the group when one was made, as the Store API already did, and the dashboard redirects to the orders list filtered to it rather than leaving the operator on a page that is now one seller's fragment of what they completed. Refusing multi-seller admin orders was considered and rejected: a customer asking a merchant to place an order across sellers is ordinary, and refusing would have left them hand-raising one order per seller. The grouped-order money paths the entry below this one records — bounded dispatch capture, per-child refunds, cancellation, the status rollup — are keyed on order_group_id and not on how the group was made, so an admin-raised group inherits all of them.
  • A single-seller checkout stamps its order with the seller (RESOLVED 2026-08-21, shipped). The split gate returns early on one partition, which was right about not making a group and wrong about doing nothing: the line items carried seller_id (so commission worked) while orders.seller_id stayed null — and that column is what Seller#orders and the seller branch's current_seller.orders read, so a seller's own order list would have been empty for every basket bought only from them. The single-partition path now stamps the order before returning.
  • The seller is asked about through a concern, so the container stays neutral (RESOLVED 2026-08-20, shipped). OrderGroup#sellers, #seller_count and #includes_first_party? live in Spree::Marketplace::OrderGroup, included into the model rather than written on it, and PaymentSplit carries no seller reader at all (its order answers). Decision 8 says the group is a domain-neutral primitive whose other three planned consumers — split-by-location, split-by-availability, B2B split-by-company-location — have no seller, and "first party" means nothing to any of them. The readers are genuinely useful to a marketplace operator and the admin serializer renders them; keeping them in a concern is what lets both be true. Worth doing on the boundary rather than later, since the moment those fields ship they are client-visible API.
  • The split must say "re-sum, don't regenerate" explicitly (RESOLVED 2026-08-20, shipped). Carts::RecalculateTotals takes resum_only:, and the split passes it. The freeze was previously inferred from completed?, which is completed_at.present? — and the children are still drafts when they are re-summed, so the guard did not fire: the promotion adjuster deleted the discounts just moved onto each child and re-tested one seller's subset against a threshold the whole basket met, and the tax provider deleted the moved tax lines and re-derived them from today's rates. The service's own docstring claimed it was avoiding exactly this. A lifecycle predicate was the wrong instrument for an intent the caller knows and the record does not; the parameter states it. Pinned by a spec asserting an order-level £6 promotion survives the split intact (£3 per child, group total equal to what was charged) — the failure was silent and money-visible, and only a totals assertion catches it.
  • A shared payment is bounded, re-allocated and refunded per child — never voided wholesale (RESOLVED 2026-08-20, shipped). Four consequences of one payment covering several orders, each of which fails silently in a different direction: a partial capture forks the payment (split_uncaptured_amount), so the remainder must carry the uncaptured shares with it or the sellers who have not shipped point at an authorization that no longer holds their money; Orders::Cancel on a grouped child refunds that child's captured share instead of voiding the payment, since voiding would release the siblings' authorization and un-pay sellers still shipping; Payment#owner being an OrderGroup means gateway_options asks it for ship_total/additional_tax_total/discount_total/last_ip_address, so the group answers all of them by roll-up (without which every post-placement gateway call on a split checkout raised); and every refund now carries order_id (stamped from the payment when it can answer, named by the caller when it cannot), which is what lets Order#refunds stay one plain association and the admin refunds endpoint keep working.
  • Every post-placement money path needs its own grouped case, and each one fails silently without it (RESOLVED 2026-08-21, shipped). The split itself was well covered while the paths that run after it were not, and that is where the defects clustered — six of them, none raising at checkout. Dispatch capture claims the share before the gateway, inside its lock (claiming after meant a partial capture forked the payment while the share still read uncaptured, carried the full amount onto the remainder, and let the same order capture twice); Carts::Complete's pre-payment compensation refuses to run once a group exists (its guards read order.payments, which a split has moved to the group, so it would have destroyed a paid order); Orders::Cancel honours refund_payments on the grouped path exactly as on the plain one (it had refunded unconditionally, so an operator cancelling with the default got a live gateway refund they never asked for) and reads what the order was paid from its shares; Refunds::Create bounds a refund by the named order's share, so refunding one seller cannot spend a sibling's captured money; payment.paid publishes order.paid per settled child, since a grouped payment has no single order and the event is public webhook API (this one did not actually work until 2026-08-21 — see the shared-payment entry above: it read a captured figure that the subscriber had not yet written); split_uncaptured_amount uses a bang, since a silent failure would leave the group holding more money than was charged; and Refund#update_order re-sums the order the refund names rather than the payment's (nil on a shared payment, so every refund on a split checkout raised). Two of these were found only by writing the specs — the grouped dispatch and grouped refund batteries each failed on their first run against code that had already passed review. The lesson for Phase 3a: a ledger built on captured shares must be specced against dispatch, refund and cancellation of a grouped order, not only against the split, and the bound on what one order may take must count the rows rather than trust a figure a subscriber updates after the fact.
  • A share records what it reserved separately from what the gateway took (RESOLVED 2026-08-21, shipped). spree_payment_splits.claimed_amount beside captured_amount: a parcel reserves what it is about to draw before charging, so two parcels cannot reach for the same money, and that reservation becomes captured only once the charge lands. undrawn_amount (authorized − captured − claimed) is what a parcel may take, and capture_in_flight? is a plain read of the row. Cancellation refuses to settle a share mid-charge, reporting it for manual resolution rather than releasing an authorization about to be drawn or refunding money nobody took. Two earlier attempts got this wrong, and both are the reason the column exists. Overloading captured_amount for the claim meant carry_splits_to — which runs during the capture — saw the claim as taken and carried the full share onto the remainder payment, paying that order twice. Inferring the in-flight state from the payment failed twice over: payment.captured_amount sums capture events, which a checkout-captured payment never writes (so every ordinary order looked mid-capture), and payment.completed? is set by whichever sibling captured first, so a second seller's genuine in-flight claim looked settled and was refunded. The rule for Phase 3a: the split row is the only thing that knows the difference between reserved and confirmed — a transfer or payout sweep must read captured_amount, never authorized_amount minus arithmetic, and never ask the shared payment.
  • A shared payment breaks every reader that assumed one payment means one order (RESOLVED 2026-08-21, shipped). A review pass over the split found thirteen such readers, each verified against the code before being believed, and every one real. The instructive ones: order.paid never fired for a split checkout — it publishes from the payment's own after_commit, which runs before payment.completed reaches the subscriber that marks the shares captured, so the figure it read was always zero (an earlier note in this plan asserted the opposite ordering and was wrong; the trace is what settled it). Public webhook API, silently dead for marketplace orders. Several payments each re-divided the whole basket and each rounded, so three children owed 33.33/33.33/33.34 were credited 33.34/33.32/33.34 — the group's sum correct and two children's wrong; payments now draw down what is left. A parcel whose halves are both worth nothing kept the full delivery charge on each, the same double-charge fixed earlier surviving in the zero-weight path. And a grouped child's payment_total was summed from payments it does not own, persisting nothing paid. The pattern worth carrying into Phase 3a: anything that reaches an order through payment.order, or a total through order.payments, is wrong on a grouped order — and none of these failed loudly.
  • A grouped child order's money is read from its payment splits, not its payments (RESOLVED 2026-08-20, shipped). Such an order owns no payments — the customer paid once, against the group — so Orders::UpdateStatuses reads captured/authorised/refunded from payment_splits, capture-on-dispatch draws from the group's payments bounded by that child's remaining share (without the bound the first seller to ship captures the whole basket), and spree_refunds.order_id names which child a refund puts right so PaymentSplitRefundSubscriber can recompute that share alone. Refund#order falls back to the payment and Order#refunds resolves either shape, so nothing outside a split checkout changes. This is the concrete argument for storing shares rather than computing proportions on read: once one seller has shipped and been captured while another has not, no proportion of the group's totals describes either.
  • The share rows keep a grouped child's payment_total true, rather than any writer remembering to (RESOLVED 2026-09-17, shipped). The entry above records a grouped child's payment_total as one of the thirteen readers found and fixed; it was fixed only halfway, and V-3649 is what the other half looked like. Carts::SplitBySeller re-sums each child before OrderGroups::AllocatePayments writes the shares, so every child persisted nothing paid; refresh_payment_total! — the only other writer, and the one every payment event reaches — sums spree_payments by order_id and would have written the same zero had it ever run, which on a grouped child it does not, because payment.owner is the group. The result was an order reading Payment total 0.00 and its whole total outstanding beside a Paid badge on the admin summary panel, the seller panel and the customer's own order payload, with the Payments card next to it showing the correct share — the badge derives from the shares, the money did not. Spree::Order now overrides the concern's private settled_payments_arel so a grouped order sums captured_amount − refunded_amount over its shares, in the same single scalar subquery the plain path uses, and Spree::PaymentSplit refreshes its order's total on save and on destroy. Deliberately one hook on the row rather than a call at each writer: allocation at checkout, capture on dispatch, an authorisation settling afterwards, a refund and a payment being torn down all move a share, and the pattern this plan already warns about — none of these failing loudly — is exactly what a fifth call site eventually forgotten looks like. Synchronous rather than after_commit, because the checkout response is rendered from the orders the allocation leaves behind. Fixing the column rather than the readers is what makes outstanding_balance, amount_due, paid?, all three order serializers and any Ransack filter or report over the column right at once; net_captured_total stays the live read for callers about to move money, since the column trails the rows by one refresh. No backfill ships with it: order grouping is 6.0 work still in development, so there is no released data carrying the wrong figure.
  • The shared catalog ships as variant attributes plus one selection service (RESOLVED 2026-08-16, shipped — Decision 11's Phase 1b). spree_variants.seller_id and spree_variants.delivery_profile_id, both nullable, and two modes that never mix: on an owned product (products.seller_id set) every variant is that seller's and ships as the product does — no other seller can create a variant there, so the variant's own columns carry no meaning and are kept blank by a normalizer; on a master product (products.seller_id nil, the shared catalog) each seller's row names its own seller and how it ships, falling back to the master's profile. The resolved answer is a plain read on the model (resolved_seller, resolved_delivery_profile — product's if owned, else the row's; no memo, no inheritance chain), and the API carries one field each (seller_id, delivery_profile_id), read resolved and written to the column, so a storefront never learns which mode it is in and a read-then-write round trip on an owned product changes nothing (the write is a no-op there). This deliberately departs from Variant#tax_category's override-the-reader shape, and supersedes an earlier cut that modelled the seller as an inheritance-with-override and grew a second own_* name on the API to keep the round-trip safe — the domain has no override to model, so it needed neither. Variant#digital? moved onto the variant's own profile with it, which is what lets a download and its printed edition sit on one product. Condition is an OptionType shipped as sample data, not a seed (db/sample_data/options.rb, beside color; values new/refurbished/used): nothing in core keys on the word — the buy box groups by whatever option values it is given — so it is a merchant's choice, not an install prerequisite, and a store that sells only new goods never finds it on a fresh install, so it splits a product the way any axis does and the buy box keys on the option combination — a new buy box and a used one, at no extra cost. The buy box is Spree::Products::SelectBuyBox behind Spree.product_buy_box_service: computed on every read and never stored (it turns on price, stock and who is selling today, none of which hold still), ranking first-party ahead of sellers then cheapest, refusing to feature a seller who is suspended, onboarding or away, and still naming a variant when nothing is buyable so the page has a price to render. purchasable?/in_stock?/backorderable? now answer through the winner rather than variants.any? — a product is not purchasable because a suspended seller happens to hold stock — and default_variant prefers a first-party listing, since the headline price, SKU and the Omnibus prior_price are compliance claims about the operator's own pricing. SKU uniqueness is scoped to the resolved seller via a hand-written validation rather than a scope: option, because Rails' uniqueness validator reads the raw column and would have merged two sellers who each own a whole product into the nil scope. Cross-store binding is refused on the model (seller/delivery_profile must belong to the product's store), matching the pair already on Product. Three pre-existing faults were fixed with it, each with a regression spec proven against the old code: Product#variants='s full-replacement delete was left as-is on the operator's path — the operator writes every seller's variants on a master — and the guard against a seller wiping a rival's rows lives at the seller branch, not the model (see "Writes never destroy another seller's variants" above), Stock::Splitter::DeliveryProfile and Stock::Coordinator re-keyed their memoisation off product_id, and with_option_value_ids now requires one variant to satisfy every axis (a HAVING COUNT(DISTINCT option_type_id) over one grouped subquery) instead of asking the product about each axis separately — "Blue AND XL" had matched a product selling a blue small beside a red XL, a live storefront bug independent of marketplaces. Both search providers were fixed together, since a filter's meaning is part of the provider contract and fixing one would have made results change when an operator installs the search gem: the Meilisearch document is per product, so its option values are a union across variants that cannot answer a per-variant question — the presenter now also emits option_value_combination_ids (one token per combination of values seen on the same variant) and a multi-axis filter asks for a whole combination, with single-axis filters and the disjunctive-facet queries unchanged. Whole combinations rather than pairs, because every pair holding on some variant is not the same as one variant holding them all — three variants (blue, XL, used), (blue, S, new) and (red, XL, new) satisfy each pair of "blue AND XL AND new" while none carries all three. Token count is exponential in the axis count, so it is capped (MAX_COMBINATION_AXES) and filters naming more axes fall back to the pairwise approximation. The upgrade needs a reindex — existing documents lack the field, so a multi-axis filter matches nothing until then; search_reindex is in the 5.6→6.0 manifest for exactly this and is a no-op on the database provider.
  • Seller lifecycle → four workflows, never a writable status (RESOLVED 2026-08-16, shipped). Spree::Sellers::Invite / Approve / Suspend / Reject (seams seller_invite_workflow and siblings), each with validate + after_* hooks and its own seller.* event. The Admin API exposes them as member actions (POST invite, PATCH approve|suspend|reject) and deliberately omits status from permitted_params — a PATCH that moved a seller would skip the mail, the payout provisioning and the extension hooks, which is exactly what 6.0-service-workflows.md keeps out of a column write. Guards admit more than the linear path: Approve also lifts a suspension (clearing holiday mode with it) and revives a rejected applicant; Suspend is for a seller already on the marketplace while Reject is for one that never traded, so rejecting an approved seller is refused. Suspension and rejection reasons live in metadata rather than columns — each is a note about one event, and the next one has its own. Creation stays plain CRUD (it is not a lifecycle transition), so the default status is applied in an after_initialize on the model, as on Spree::Fulfillment.
  • Lifecycle emails are seller-facing, event-driven, and skip the invitation (RESOLVED 2026-08-16, shipped). Spree::SellerMailer (approved/suspended/rejected) in spree_emails, fired by Spree::SellerEmailSubscriber off the seller.* events the workflows already publish — nothing mails from a workflow step, so mail is one listener among several rather than something a transition waits on. Three departures from the legacy module: no seller.invited email (inviting creates an Invitation, which already mails the invitee — a second message would be the same news to the same address), no marketplace-staff copies (the legacy module mailed every store admin on approval and onboarding; staff read status in the dashboard, and per-admin fan-out across many sellers is the kind of noise merchants switch off — staff notifications ride the event/webhook surface), and suspension/rejection reasons never appear in the email (the operator's note is an internal record; the seller is asked to get in touch). Gated on a new send_seller_transactional_emails Store preference rather than the consumer one — sellers are a different audience, and silencing customer receipts must not silence seller mail. Onboarding started/completed emails wait for the onboarding task registry.
  • The seller panel is a path, not a subdomain (RESOLVED 2026-08-18). Served at /sellers by spree_dashboard, exactly as the operator's dashboard is served at /dashboard — same engine, same SPA controller (generalised to Spree::Dashboard::SpaController, which a subclass points at a bundle), SPREE_SELLER_PANEL_DIST_PATH beside SPREE_DASHBOARD_DIST_PATH. Nothing forced a second hostname: the two panels' refresh cookies are already isolated by name and path (/api/v3/admin/auth vs /api/v3/seller/auth), so sharing an origin costs nothing in isolation and saves every deployment a hostname, a certificate and a CORS allowlist entry. SPREE_SELLER_PANEL_URL remains for marketplaces that do want sellers on their own domain, and Sellers::PanelUrl now resolves the /sellers mount before falling back to the dashboard. The dev-time sellers.<branch> host stays — two Vite servers cannot share an origin root, which is why admin.<branch> exists too. Constraint: a link the panel builds from a path must resolve against BASE_URL, never window.location.origin alone, or it misses the mount.
  • The seller panel is customisable the way the dashboard is — same registries, same facade (RESOLVED 2026-08-18). Reversing the first cut's "reference/throwaway, no extension points": the seller panel is the part of a marketplace most often shaped to fit, and shaping it should mean adding and removing, not rewriting. @spree/seller-dashboard re-exports @spree/dashboard-core/plugin, so one defineDashboardPlugin({ nav, slots, tables }) extends either panel; the built-in sidebar entries register into the shared nav registry (a marketplace nav.remove('team')s the built-in), and the built-in screens expose named slots (seller.team.actions, seller.team.after). Two core changes made this a reuse rather than a fork: useNavItems(tenantId) lifts the sidebar's registry composition (tenant prefixing + if gates + permission filtering) out of AppSidebar so a panel scoped by seller id composes the same registry, and useOptionalStore() lets shared code run in a panel that mounts no StoreProvider. The chrome moved onto the real Sidebar/NavMain primitives with it. Two more things a second consumer surfaced: the seller /me sent only permission keys, so <Can> — which reads CanCanCan rules — answered false for everything on the panel, silently (fixed: PermissionSerialization concern shared by both /mes); and Seller::ResourceController had no subclass and no spec — Seller::ProductsController is now its first consumer, with the tenancy proofs (another seller's id 404s on show/update/destroy, seller_id in a create payload is ignored, a member without write_products gets 403). The seller product serializer extends the store one, not admin's, so nested variants/media inherit no operator data; the seller SDK writer emits the store-level types a seller serializer nests rather than an empty twin per type.
  • A seller sees their own checklist, one page, no wizard (RESOLVED 2026-08-20). The seller-facing half of 6.0-seller-onboarding-requirements.md: GET /seller/onboarding answers {status, progress, requirements} off the same Spree::Sellers::Requirements evaluator the operator reads, so the two can never disagree about what is outstanding; submitting for review and submitting against one requirement are the existing workflows, called rather than reimplemented. Accepting terms is a profile write (accept_terms: true) rather than an endpoint of its own, and is one-way — the stamp records that it happened. One page, not a wizard: the checklist is not ordered by dependency, a seller does these in any order, and several mean going away and coming back (a document to find, an account to open) — a wizard would trap them at step two. The legacy extension's shape carries over: progress bar, accordion, first outstanding line open. Kind → panel route is a map in the panel, not action_url: the server has no idea how this panel routes, and a kind it does not recognise still renders its name, description and any action_url — which is what makes a provider gem's kind (Stripe payouts, Phase 3b) useful before the panel knows it exists. Submission downloads are served per request through the seller's own scope, never a storage URL: these are identity documents.
  • Team management mirrors the operator's staff page (RESOLVED 2026-08-18). Members in a table, pending offers in their own card, one invite dialog — the same layout, components and row actions as Settings → Staff, because it is the same job seen from the other side. Pending invitations were the gap that made the first cut feel broken: inviting someone changed nothing visible, since team#index lists accepted members only. A seller now gets /seller/invitations (index/destroy + PATCH resend), matching the admin surface, and the seller invitation serializer carries acceptance_url so a colleague who never got the email can be handed the link. Deliberately a separate controller from team: sending an invitation is hiring, chasing or withdrawing one is bookkeeping on the offer. Roles stay single — everyone holds the seller's seeded role, so inviting asks only for an address; narrower seller roles need seller-scoped role management first and are a design of their own. One framework lesson: the panel must extend @spree/dashboard-core/lib/i18n rather than call init() itself, or shared components render raw keys (admin.row_actions.menu_label) — a second init() wins the race and drops the framework's own copy.
  • An invitation opens the app it is an invitation to (RESOLVED 2026-08-17). The admin_invitation_acceptance route branches on invitation.resource: onto a Spree::Seller it resolves Spree::Sellers::PanelUrl (the seller_panel_url preference / SPREE_SELLER_PANEL_URL), everything else keeps the dashboard origin. Not cosmetic — the dashboard's acceptance page authenticates through the Admin API, which no seller may call, so a seller sent there could read the invitation and never accept it. The panel gets its own acceptance page and the seller API its own auth/invitations/:id/{lookup,accept}, parallel to the admin pair rather than subclassing it: what differs is the audience issued and the invitations it will touch, and both are the point — accepting a staff invitation here is refused as not_found, since it carries no seller membership and would mint a seller token for someone who runs no seller. With no panel deployed the link falls back to the dashboard; a marketplace that never onboards sellers by email need configure nothing.
  • The seller panel is its own app and its own SDK (RESOLVED 2026-08-17). @spree/seller-sdk beside @spree/sdk and @spree/admin-sdk, and packages/seller-dashboard (shell) + packages/seller-dashboard-starter (host) beside their dashboard counterparts — not a mode of the admin app. The credentials differ in kind, not degree: a seller JWT only (no secret-key equivalent exists), X-Spree-Seller-Id rather than X-Spree-Store-Id (the store is derived from the seller), and a refresh cookie whose name and path are deliberately not shared. Typing those as optional-but-meaningless on one client is how a panel ends up able to call the wrong API. @spree/dashboard-core generalizes rather than forks: it exported an adminClient singleton built from createAdminClient, so any host reusing the framework got the Admin API — the one thing Decision 10 forbids. Core now takes a registered client (setApiClient/getApiClient) that each host installs at boot; adminClient survives as a deprecated alias. Two further admin assumptions came out with it: the Tailwind source list hardcoded @spree/dashboard (so a second panel's own components were never scanned) and the store switcher built a typed /$storeId link that cannot compile against a router without that route. @spree/dashboard-ui is already headless and needed no change. One framework, two hosts — a fork would mean every registry and provider fix landing twice.
  • The storefront sees a seller's profile, never their operational state (RESOLVED 2026-08-16, shipped). Spree::Api::V3::SellerSerializer carries name, slug, about/about_html and the three image URLs — and nothing else. status and sellable are excluded on purpose (a seller a shopper can reach is sellable by definition), along with settlement/tax configuration, contact and billing addresses, team size and every timestamp; a spec asserts the exact key set so nothing leaks in later. The admin serializer extends this one rather than duplicating it, per the house rule. Store endpoints are read-only index/show scoped to sellable — a seller onboarding, suspended or away is neither listed nor fetchable (404), since listing them would advertise products nobody can buy — and resolve by slug or prefixed id so a storefront can route /sellers/<slug>. Products expose seller_id on both APIs without an expand (so a storefront can group or link by seller cheaply) plus one :seller behind ?expand=seller; the admin serializer additionally carries seller_name for its list column. Spree::Product gains seller_id and seller to its ransack allowlists — without them the products-table filter silently matches nothing.
  • Seller management is staff-only, on its own catalog scope (RESOLVED 2026-08-16, shipped). register_scope(:sellers, …) mints read_sellers/write_sellers with Spree::Seller as its resource, and is deliberately not offered to the seller audience — a seller administering other sellers is the one thing the seller key must never allow. seller_profile (the seller's own record, on the seller branch) therefore claims no subject, so the subject→resource lookup stays unambiguous.
  • Seller principal → Spree::AdminUser (Spree.admin_user_class), no SellerUser model (RESOLVED 2026-08-15). Reuse the whole shipped auth stack and the RBAC rails (RoleUser/Invitation on resource: seller); membership is by resource type, never store_id. Isolation guaranteed at the token layer: own seller_api JWT audience, own Spree.seller_authentication_strategies + /seller/auth/* (so staff can be SSO-only while sellers use passwords; the seller login refuses non-members), spree_refresh_tokens.audience. See Decision 10 + decisions.md 2026-08-15.
  • Seller API → dedicated /api/v3/seller branch, current_seller scope-fetching; sellers never call the Admin API (RESOLVED 2026-08-15). Supersedes the 2026-07-14 "seller users hit the same admin API with seller-scoped abilities" wording — permission sets with tenancy conditions no longer exist (RBAC, PR #14412), and the RBAC plan's 2026-08-08 direction already named current_seller endpoints. Own serializer branch off the store serializers, own OpenAPI spec, no subclassing of admin controllers. See Decision 10.
  • Store credit / gift cards split across child orders → group-level payments, prorated through PaymentSplit like any other payment (RESOLVED 2026-08-15). A store-credit or gift-card payment is a Payment on the OrderGroup exactly like the gateway payment; every group payment gets one PaymentSplit row per child order, prorated by child totals with the same largest-remainder rule as order-level discounts. One attribution rule for every payment source, no priority ordering, no special-casing — and it composes with the resolved payment-source-agnostic transfer basis (the seller's earning never depends on how the buyer paid). Confirmed against the shipped Carts::Complete pipeline (payments attach before the split runs).
  • One payout provider per store, chosen by a preference (RESOLVED 2026-08-22). Store#preferred_payout_provider names it, payout_provider_instance resolves it, and blank means core's record-only System. Concurrent providers were considered and rejected: a seller's account reference is meaningful only relative to one provider (a Stripe acct_… means nothing to another), so supporting two at once turns that column into a per-provider map and adds the provider to the grouping key of the balance, the sweep and every reconciliation — a real tax on every marketplace for a case few will meet. The two realistic needs are served without it: a migration between providers works because each ledger row carries its own provider, so history stays truthful while new rows use the new one; and per-seller providers, if ever needed, are a nullable column on the seller falling back to the store's, the same override shape payouts_schedule_interval already uses. The nearer problem is not two providers but one that cannot pay every seller — Stripe Connect refuses unsupported countries — which is what payouts_enabled_at and the sweep's skip are for. The surveyed OSS marketplace reaches the same conclusion and enforces it harder: its payout module raises unless exactly one provider is registered, and its seller payout account is an untyped JSON blob with no provider column at all, so its schema could not tell two providers apart even with the guard removed. Its ledger is also one level — one order is one payout row, with no batching — so there is no prior art to copy for the two-level shape either.
  • Payout minimum threshold → core; rolling reserve / holdback → Enterprise (RESOLVED 2026-08-15). spree_sellers.minimum_payout_amount (decimal, nullable; nil ⇒ store preference default_minimum_payout_amount) — the sweep skips a seller whose balance(currency) is below the threshold and carries the balance to the next period. A percentage holdback with a release window is money-operations policy (chargeback buffer) and stays Enterprise, so core does not grow a third ledger row kind.
  • Marketplace-facilitator remittance → spree_sellers.tax_remittance (seller | platform, default seller), honored by core's transfer basis (RESOLVED 2026-08-15). platform ⇒ transfer.amount = total − tax_total − commission; seller keeps total − commission. Core owns the ledger math so it is provider-independent; deciding when a seller is platform-remitted (US facilitator nexus, EU deemed-supplier scenarios) stays Enterprise "automatic taxes", which simply sets the column. Amends the Decision 9 note that this mode is "not core": the flag and the math are core, the policy is not.
  • Seller-scoped promotions → post-6.0 (RESOLVED 2026-08-15 as deferred; shape recorded under Open Questions).
  • Basic Stripe Connect execution → OSS (boundary amendment) (RESOLVED 2026-07-15). Express onboarding + on-fulfillment transfers ship in the monorepo alongside the pulled-in Stripe gateway, for demo/adoption parity with the surveyed competitor — "money moves automatically" is the demo that sells, and transfers are inseparable from basic onboarding (a Stripe::Transfer needs a connected account). Enterprise repositions on money operations: automatic refund clawbacks (prorated transfer reversals + negative-balance netting), KYC/account-health workflows, ledger⇄Stripe reconciliation, payout reports incl. DAC7, facilitator taxes. Ledger reversal rows stay OSS in every mode. Amended 2026-10-27: the Stripe transfer reversal moved to OSS too (decisions.md). Supersedes #13323's "execution stays Enterprise" framing (amendment by the issue author; update the issue). See decisions.md 2026-07-15.
  • Spree::Seller name ownership → marketplace seller; inventory-operations' procurement model renamed Spree::Supplier (RESOLVED 2026-07-14). See the Key Decisions entry and decisions.md 2026-07-14.
  • Commission is not a Spree::Fee (RESOLVED 2026-07-14). Fee is buyer-facing and rolls into order totals; CommissionLine is an off-order platform↔seller ledger. See Decision 2.
  • Rule reference storage → arrays for sellers and categories, a table for products (RESOLVED 2026-08-17). Follows the cardinality rule from 6.0-delivery-method-rules.md, with one deliberate exception: Promotion::Rules::Category keeps its categories in a join table, and commission keeps them in a category_ids preference. The reason is what the array actually holds — matching walks upward from the product through self_and_ancestors, so a rule names only the categories an operator picked, never their descendants. A rate on "Electronics" is one id however deep the tree goes, and in practice nobody enumerates hundreds of categories or sellers into a single rule. Products stay in spree_commission_rule_products because a marketplace genuinely does name thousands.
  • A parent category covers everything beneath it, to any depth (RESOLVED 2026-08-17). Matching the promotion rules' behavior, and for the same reason: a marketplace that sets a rate on "Electronics" and later gets a "Electronics → Cameras → Mirrorless" leaf must not have that leaf silently fall through to the catch-all because the catalog was reorganised. Verified to four levels, with a sibling branch correctly not matching.
  • Retiring a rate retires its rules, and keeps them readable (RESOLVED 2026-08-17, shipped). CommissionRule and CommissionRuleProduct are acts_as_paranoid, so a soft-deleted rate's conditions are retired with it rather than deleted — and an edit that replaces a rule keeps the one it superseded. There is no restore UI for a rate any more than for a price list; soft delete exists to keep the historical picture, and a commission line is explained by the rule that matched it, so "why was this charged" has to stay answerable after the rule stops applying. This is a deliberate departure — no other rule model in core is paranoid — justified by commission lines being settlement records rather than configuration. Two consequences to keep: both uniqueness indexes constrain live rows only (partial on PostgreSQL/SQLite, a stored generated column on MySQL/MariaDB, verified against both), and CommissionRate#rules= identifies an incoming row against the rule of that kind the rate already carries, since clients send the whole set without ids and a blind build would collide with the live rule it was meant to replace.
  • Commission rules → typed classes, not a polymorphic subject (RESOLVED 2026-08-17, shipped; supersedes the original shape). A rule was (subject_type, subject_id), which could only ever name a record: a price band, a channel, a promotional window were each a migration plus an edit to the matcher, and a third party could add nothing. It is now STI over Spree.commission_rules, matching Spree::PriceRule and Spree::DeliveryMethodRule — a rule carries its own configuration, declares it through preference_schema, and a new kind is a subclass and a registration. Matching semantics are unchanged: every rule must hold, and a rule naming several records means any of them, so the OR moved inside a rule and there is still no match_policy. Reference lists follow the house cardinality rule — sellers and categories as normalize_id_preference arrays, products in a join table — which also deleted the hand-rolled store check in the controller, since the preference writer scope-checks as it writes. The admin surface follows the delivery-method rules editor: GET /commission_rates/rule_types for discovery, one row per condition, a picker where the kind names records and its preference schema otherwise.
  • Commission rule matching → every rule must hold (AND), a rule naming several records means any of them (OR) (RESOLVED 2026-07-14, restated 2026-08-17 for the typed shape). Expresses plain lists and the seller × category pairings today's Enterprise sells, with no match_policy knob; same semantics as the leading surveyed OSS engine, but precedence stays the operator's own ordering rather than implicit specificity. See Decision 4.
  • Commission on delivery revenue → include_shipping on the rate (RESOLVED 2026-07-14). Per-rate flag, default off (legacy was items-only); a fulfillment-scoped CommissionLine (nullable fulfillment_id, exactly-one-of with line_item_id). Matches the surveyed OSS competitor (global-only there) and Amazon referral-fee behavior. See Decision 4.
  • Split payment record → Spree::PaymentSplit + payments.order_group_id (RESOLVED 2026-07-14). One gateway payment on the group, one split row per child order; no cloned Payment rows. See Decision 5 + Design Details.
  • Seller teams → reuse Role/RoleUser/Invitation with resource: seller (RESOLVED 2026-07-14). The polymorphic rails already exist in core (Invitation's docstring names Seller); no SellerUser model. See Seller identity & teams.
  • Parent representation → dedicated Spree::OrderGroup (RESOLVED 2026-06-16). See Decision 8 + Design Details. Diverges from the legacy parent_id/splitted shape; requires the Enterprise backfill.
  • Commission tax rate source → per-CommissionRate field, resolved through the TaxProvider (RESOLVED 2026-06-16). Not a per-seller platform_fee_tax_rate column (legacy) and not a bare per-market lookup. The rate carries its own commission-tax configuration with a sensible store default; the actual rate is resolved via 6.0-tax-provider.md so it stays jurisdiction-correct. See Decision 3.
  • Fund ledger → two levels: Spree::SellerTransfer (per-order, on-fulfillment) + Spree::SellerPayout (per-interval settlement), both generic in core + pluggable PayoutProvider (system no-op in core; basic StripeConnect with the monorepo Stripe gateway per the 2026-07-15 amendment, extended by Enterprise with the money operations) (RESOLVED 2026-06-25). See Decision 9. Transfer credits the seller balance on fulfillment; payout sweeps unsettled transfers into a scheduled bank settlement (transfers belong_to their payout — auditable). seller.balance(currency) = Σ completed transfers − Σ completed payouts per currency. Splits the legacy gateway-namespaced transfer ledger (which conflated the two and outsourced settlement to Stripe) into core ledger + provider execution along the OSS/Enterprise seam.
  • Commission tax → one scalar on the line, in TaxLine's vocabulary (RESOLVED 2026-08-17). tax_amount + tax_rate + taxability_reason + the seller's country_code/state_code on Spree::CommissionLine, with Spree::CommissionTax as the value object the resolver returns. Reusing Spree::TaxLine itself was rejected: its rows sum into the order total and are exposed on the buyer-facing /orders/:id/tax_lines, so a commission row there would overcharge the shopper and leak settlement data. Same shape, opposite side of the ledger — so the words are shared and the rows are not. See Decision 3.
  • Commission VAT base → net item price, VAT added on top of the fee (RESOLVED 2026-06-25). For EU, commission is computed on the seller's net (ex-VAT) item price; the commission tax_amount (Decision 3) is then applied on top of the commission as a separate B2B service supply — the marketplace fee is a distinct taxable event from the consumer's item sale, so the two VATs never mix. The base toggle stays available for non-EU/edge merchants who genuinely want a gross base, but the EU default is net-base + fee-VAT. Shipped as tax_inclusive (2026-08-17), matching Spree::Market#tax_inclusive rather than the surveyed industry's include_tax — the flag says the commission base is tax-inclusive, which is the same adjective the rest of Spree already uses for a price that carries its tax. This makes the marketplace's commission invoice to the seller stand on its own (correct for EU invoicing + remittance).
  • Seller addresses → a stock location + a business identity (RESOLVED 2026-08-20). returns_address is dropped: returns route to a seller-owned StockLocation (default provisioned at creation) so received goods restock where the catalog can see them, which also requires StockLocation name-uniqueness and the default flag to become per-owner rather than per-store. Billing becomes a Spree::BusinessAddress, while the parts that are not an address at all become legal_name + registration_number on the seller and a Spree::TaxIdentifier owned by it — reusing the validation/evidence rails the tax plan already built, because EU reverse charge on the commission invoice needs a verified number with retained evidence. No per-seller tax rate (that stays CommissionRate + TaxProvider) and no Address STI — Spree::BusinessAddress shares spree_addresses and the table gains no type column (attempted and reverted, decisions.md 2026-08-23). See Decision 12.
  • Store-credit/gift-card payout → payment-source-agnostic (RESOLVED 2026-06-25). The SellerTransfer amount (which rolls up into the payout) is (seller's sale value) − (commission owed), independent of how the customer paid. Store credit / gift cards are the platform's funding concern, not the seller's — the seller is owed their full cut of the sale regardless. This drops the legacy store-credit dual-basis from the amount calculation; that branch existed only to reconcile the old store-credit funding model and does not belong in the payout basis. (The platform still tracks its own store-credit liability separately — that's orthogonal to what the seller receives.)
  • Commission precedence → an operator-ordered list (RESOLVED 2026-06-25 as integer priority; reshaped 2026-08-17 to acts_as_list, shipped). CommissionRate carries position (acts_as_list scope: :store_id, add_new_at: :top) and resolution walks it top-down, first match wins (Decision 4). The list on screen is the precedence, so reordering is dragging rather than assigning numbers; new rates land at the top so they take effect on creation instead of behind the catch-all. Spree::Seeds::CommissionRates puts one disabled marketplace-wide rate at the bottom, which yields the product > category > seller order merchants asked for without hardcoding a ladder. No specificity inference — a rate can name all three dimensions at once, so there is nothing to infer from.
  • Commission rate currency → required for fixed, ignored for percentage (RESOLVED 2026-06-25). A kind: 'fixed' rate must carry a currency (a flat "2" is meaningless without one); a kind: 'percentage' rate ignores currency (10% applies in any currency). Enforced by a model validation: validates :currency, presence: true, if: -> { kind == 'fixed' }. See the CommissionRate model.
  • Payout vs transfer trigger → transfer on-fulfillment, payout on-interval (RESOLVED 2026-06-25). These are the two distinct events of Decision 9: a SellerTransfer becomes due on-fulfillment (the seller earned it); a SellerPayout settles on the seller's scheduled interval (payouts_schedule_interval). The earlier "on-ship vs on-deliver vs scheduled" framing was a category error — it conflated the two. Core's system provider honors manual settlement natively; Enterprise implements daily/weekly/biweekly/monthly.

Open Questions

  1. Seller-funded vs platform-funded promotions. v1: discounts reduce the seller's sale value (seller-funded). Platform-funded promos ("we run a 10% site-wide sale and make sellers whole") need a funding flag on Promotion and a compensating ledger line — post-6.0. Unblocked by: a merchant asking for platform-funded campaigns once the ledger is live; the shape is a funded_by on Promotion + a positive SellerTransfer compensating row.

  2. Seller-scoped promotions (a seller creates promotions limited to its own products) — post-6.0 (resolved 2026-08-15 as deferred). Shape when it lands: spree_promotions.seller_id (nullable), a /api/v3/seller/promotions endpoint on the seller branch, and a rule guard that a seller promotion only matches line items with the same seller_id. Cheap on the single-store Promotion model; unblocked by the 6.0 headline scope shipping first.

  3. Seller-owned carrier accounts. Decision 13 keeps carrier-backed methods with the operator. When a seller needs to buy labels on their own account, the additive shape is spree_integrations.seller_id (nullable), an integrations page on the seller branch, and the seller-method validation widened to rate and fulfillment providers whose integration is the seller's own — nothing in the first cut has to change.

References

  • spree/spree#13323 — "Open source Spree Multi Seller for Spree 6" (the OSS/Enterprise scope split; amended 2026-07-15 — basic Stripe Connect execution moved to OSS, see decisions.md; the issue text needs a matching update).
  • Current Enterprise multi-vendor module (private source, actively maintained against Spree 5.4+): source-read for this port — the Seller lifecycle, per-item commission + commission-VAT formula, parent/child split flow, Stripe transfer ledger + reversal chain, seller-user permission baseline, and the settlement-statement report. Internals (file paths, class/table names) are deliberately not cited in this public file — the Enterprise repository holds the detailed port map. Public behavior cross-checked against the user docs (next bullet).
  • Surveyed modern open-source marketplace implementations (primary-source survey 2026-07-14; names and the detailed comparison deliberately kept out of this public file): source of the commission rule-engine shape (dimension-grouped matching, percentage | fixed, include_tax/include_shipping), the OrderGroup container pattern, and the payout-provider abstraction. Framework-specific machinery NOT to copy: big-number jsonb sidecar columns, remote-link join-table indirection (use Rails FKs + has_many), and external workflow/step engines (use Spree services + publish_event). The leading implementation's payout pipeline creates per-order payouts after capture and keeps no balance ledger and no reversal chain — Spree's two-level ledger is designed from scratch.
  • Current Enterprise behavior (user docs, spreecommerce.org/docs): user/vendors/seller-management (lifecycle: Invited → Onboarding → Ready for Review → Approved/Rejected/Suspended; branding; onboarding checklist), user/vendors/commission-rates (product > seller > marketplace-default ladder, category-seller pairing), user/vendors/seller-payouts (schedule intervals incl. bi-weekly + "use marketplace default"), user/vendors/multi-vendor-checkout (per-seller delivery selection, suborder split, per-seller tracking), user/settings/marketplace (default rate copied at invite, seller ToS), api-reference/storefront/sellers (public seller profile fields).
  • Related plans: 6.0-cart-order-split.md, 6.0-6.1-split-adjustments.md, 6.0-order-routing.md, 6.0-tax-provider.md, 6.0-delivery-rate-provider.md, 6.0-fulfillment-and-delivery.md, 6.0-returns-exchanges-claims.md, 6.0-inventory-operations.md (Supplier disambiguation), 5.4-6.0-eu-legal-compliance.md, 5.6-admin-spa-csv-import.md, 6.0-admin-spa.md, 6.0-admin-api.md, 6.0-channels-catalogs-b2b.md (B2B — deferred to 6.1, see decisions.md).