Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Let several sellers sell the same thing
Damian Legawiec94492bf093a9
diff --git a/docs/plans/6.0-multi-vendor-marketplace.md b/docs/plans/6.0-multi-vendor-marketplace.mdindex 842239249a..6f2615e1dd 100644--- a/docs/plans/6.0-multi-vendor-marketplace.md+++ b/docs/plans/6.0-multi-vendor-marketplace.md@@ -170,6 +170,31 @@ Two questions were re-examined against the shipped auth (PR #14380) and RBAC (PR**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 vendor-resourced assignment passes (its store is the vendor'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)++Until now this plan assumed one product belongs to one seller (`products.vendor_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.vendor_id` (nullable — `nil` is the operator's own first-party listing) alongside the existing `spree_products.vendor_id`. 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.vendor_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.** `Product#variants=` is full-replacement — variants absent from the payload are destroyed — and the dashboard round-trips the whole array on every save. Removal must be filtered to the writer's own variants, or narrowing the read would make the write destructive.+- **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/vendor` branch scope-fetching through `current_vendor` (Decision 10), not a narrowing of the admin surface.++**Both shapes coexist with no mode switch.** A store selling only its own goods has `vendor_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-vendor scope" line under Product ownership & approval, which assumed duplicate product rows per seller.+## Design Details### Vendor identity & teams@@ -254,7 +279,8 @@ end| Table | Column | Why ||---|---|---|-| `spree_products` | `vendor_id` (nullable) | product ownership / split partition key |+| `spree_products` | `vendor_id` (nullable) | listing ownership — a seller's own product; nil on a shared one |+| `spree_variants` | `vendor_id` (nullable), `delivery_profile_id` (nullable) | which seller sells this variant, and how they ship it (Decision 11) || `spree_stock_locations` | `vendor_id` (nullable) | vendor-owned stock, feeds order routing || `spree_orders` | `vendor_id` (nullable), `order_group_id` (nullable) | child-order identity || `spree_line_items` | `vendor_id` (nullable, denormalized) | split partition + vendor scoping without 3-join hops |@@ -286,7 +312,7 @@ Spree::OrderGroup (the transaction container — customer, single payment, shareThe `OrderGroup` owns the customer + single payment + shared addresses; each child `Order` owns its own line items, fulfillments, and totals. The group carries no vendor reference — `vendor` 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 vendor 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 `vendor_id` snapshot, with `nil` (the operator's own first-party items) forming its own partition, and the split + `OrderGroup` happen **only when ≥ 2 partitions exist**. A mixed cart of vendor A + first-party items splits into two child orders (one with `vendor_id: nil`). A single-partition cart — all first-party, or all one vendor — completes as a **bare order exactly as today**: no group, no `PaymentSplit`; when that partition is a vendor's, the order still carries `vendor_id` and commission + ledger apply unchanged (Phase 2's compute-only mode is exactly this). Not a state-machine callback — and not the legacy shape either: the legacy module splits **~30 seconds after checkout** in a background job, leaving a window where the parent order exists un-split. 6.0 splits synchronously inside completion, so the checkout response already returns the finished `OrderGroup` and no `splitted`-pending state ever exists.-- **Partition key:** `line_item.vendor_id`, denormalized from `variant.product.vendor` when the item is added (matching legacy behavior). Denormalization is load-bearing, not an optimization: the split, vendor ability scoping, and vendor order lists all key on it. Because product ownership *can* change while an item sits in a cart, `Carts::Complete` revalidates each line's `vendor_id` against the product's current vendor before partitioning and refreshes stale lines (re-running package/delivery validation) — the same cart-revalidation class as price or availability drift.+- **Partition key:** `line_item.vendor_id`, denormalized from `variant.vendor` — the variant the customer actually chose, falling back to `variant.product.vendor` for a product whose seller owns the whole listing (Decision 11). Denormalization is load-bearing, not an optimization: the split, vendor ability scoping, and vendor 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 `vendor_id` before partitioning and refreshes stale lines (re-running package/delivery validation) — the same cart-revalidation class as price or availability drift.- **Per-vendor delivery selection happens at checkout, before the split.** Today's Enterprise checkout already groups packages by vendor and lets the customer pick a delivery method per vendor package (user docs: multi-vendor-checkout); 6.0 keeps that UX. The cart's packages come from `6.0-order-routing.md` (`for_allocation` — vendor items allocate from that vendor's stock location), delivery options per package come from `6.0-delivery-rate-provider.md` filtered to the package's vendor: a `DeliveryMethod` with `vendor_id` is offered only on that vendor's packages; `vendor_id: nil` methods are marketplace-wide. The chosen method + rate travel with the package into that vendor's child order at split. **This is a hard requirement on the cart/order-split checkout design** (see Constraints).- **Move semantics:** line items, their tax lines / discounts / fees (`6.0-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`).@@ -558,7 +584,7 @@ The legacy module writes **reverse commission rows** when items are refunded (pe- Products carry `vendor_id` (nullable — the operator's own first-party products have none). Vendor users only see/manage their own (ability tenancy condition).- **Approval reuses the product status workflow — no new approval model.** Vendor-created products default to `draft`; a store preference `vendor_products_require_approval` (default `true`) controls whether vendors 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 Vendor's products" stays intact — the operator retains full edit rights over vendor products (naming, taxons, publication to channels).- Vendor bulk product CSV import/export rides the existing `Spree::Import` / `Spree::Export` pipeline (see `5.6-admin-spa-csv-import.md`) with the vendor context stamped on created records — no marketplace-specific importer.-- **SKU uniqueness relaxes to per-vendor scope.** Two vendors legitimately sell the same manufacturer SKU (the legacy module disables SKU validation outright); 6.0 scopes the uniqueness check by `vendor_id` instead of dropping it.+- **SKU uniqueness relaxes to per-vendor scope.** Two vendors legitimately sell the same manufacturer SKU (the legacy module disables SKU validation outright); 6.0 scopes the uniqueness check by the **variant's** `vendor_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 vendor" curated pages come from a vendor-subject `CollectionRule` kind (`6.0-replace-taxons-with-categories.md`), replacing the legacy `Spree::TaxonRules::Vendor`.### Vendor notifications@@ -612,7 +638,7 @@ This is **new OSS code**, not a rename of existing core — there is no in-placeThe 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 (clawbacks, netting, KYC ops, reconciliation) and keeps Shopify/WooCommerce.2. **Build order** (each phase shippable):- **Phase 0 — admin-branch hardening (ships first, no Vendor 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_resource` (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 the audiences **beyond staff** a resource opens up, with `grantable_keys(audience)` (unknown audience ⇒ empty, never raises) — a generalization of the originally-planned `vendor_grantable` boolean, so a third panel needs no schema change (decisions.md 2026-08-16); `orders`/`fulfillments`/`products`/`stock`/`dashboard` opened to `vendor`. **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 vendor "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 vendor holding `write_orders` gets `can :manage, Spree::Order` on the model class exactly as an admin does; which records it may touch is `current_vendor` scope-fetching in the controller, so a vendor-branch controller that authorizes without scope-fetching reads store-wide.- - **Phase 1 — Vendor identity.** `Spree::Vendor` model (see Vendor identity & teams: lifecycle, branding, ToS acceptance, holiday mode), onboarding task registry + core tasks, vendor teams via `RoleUser`/`Invitation` (`resource: vendor`) + `UserRoles#vendors`, self-serve application endpoint, core `Spree::VendorMailer` lifecycle emails (see Vendor notifications), product ownership (`products.vendor_id` + approval preference), Admin API Marketplace/vendors endpoints + Store API vendor profiles, vendor CSV import/export on the `Spree::Import` pipeline. **The Vendor API branch anchor** (`Vendor::BaseController`/`ResourceController`, `vendor_api` audience, `Spree.vendor_authentication_strategies`, `/vendor/auth/*`, `/vendor/me`, `/vendor/profile`, onboarding, team, vendor-scope guard, `Spree::Ability` `resource:` option) + the seeded default vendor role. Products/orders/fulfillments on the vendor branch follow as each domain lands (products in Phase 1, orders/fulfillments/ledger reads in Phase 3). No splitting yet.+ - **Phase 1 — Vendor identity.** `Spree::Vendor` model (see Vendor identity & teams: lifecycle, branding, ToS acceptance, holiday mode), onboarding task registry + core tasks, vendor teams via `RoleUser`/`Invitation` (`resource: vendor`) + `UserRoles#vendors`, self-serve application endpoint, core `Spree::VendorMailer` lifecycle emails (see Vendor notifications), product ownership (`products.vendor_id` + approval preference), Admin API Marketplace/vendors endpoints + Store API vendor profiles, vendor CSV import/export on the `Spree::Import` pipeline. **Phase 1b — the shared catalog (Decision 11):** `variants.vendor_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. 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 Vendor API branch anchor** (`Vendor::BaseController`/`ResourceController`, `vendor_api` audience, `Spree.vendor_authentication_strategies`, `/vendor/auth/*`, `/vendor/me`, `/vendor/profile`, onboarding, team, vendor-scope guard, `Spree::Ability` `resource:` option) + the seeded default vendor role. Products/orders/fulfillments on the vendor 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-vendor orders, no split).- **Phase 3 — Order splitting + fund ledger.** `OrderGroup`, `Carts::SplitByVendor` inside `Carts::Complete`, per-vendor delivery selection at checkout, `PaymentSplit`, derived group status, reversals, the two-level `VendorTransfer` (on-fulfillment) + `VendorPayout` (scheduled sweep) + `PayoutProvider::System` + `vendor.balance(currency)`. **Gated on `6.0-cart-order-split.md` and `6.0-6.1-split-adjustments.md` landing first** — and cart-order-split is today a one-page stub: it must be expanded (checkout/delivery-selection/payment flow on Cart) before this phase's design can freeze. Flagging early: the 6.0 headline feature sits downstream of the two biggest unstarted refactors.- **Phase 3b — OSS Stripe provider** (after Phase 3, alongside the Stripe gateway pull-in: the payment-sessions-API gateway classes come into the monorepo from the standalone `spree_stripe` repo, likely into `spree/core`, leaving the legacy v2-API/storefront code behind): Express onboarding link in the vendor dashboard, `account.updated` status webhook, `transfer!` on fulfillment with `source_transaction`, payout-schedule mapping + payout webhooks. Ledger-only `reverse!`.diff --git a/docs/plans/decisions.md b/docs/plans/decisions.mdindex 22e17217ee..d82dbf488b 100644--- a/docs/plans/decisions.md+++ b/docs/plans/decisions.md@@ -1,3 +1,58 @@+## 2026-08-16: Several sellers share a product by sharing it — the seller is on the variant, not on an offer record++Damian's call, after a survey of how marketplace platforms model a shared+catalog and an audit of what it would cost Spree.++**The gap.** The marketplace plan assumed one product, one seller. Two sellers+of the same book produced two unrelated products and two listings. That suits+unique goods and fails commodities, and it is the capability the legacy module+was most often asked for and could never provide.++**Why not an offer record.** Every surveyed implementation introduces one, and+every one of them is built on top of a commerce engine or a merchant's existing+catalog — they cannot put a seller on the variant and cannot re-key inventory.+Their offer is a variant they were not permitted to write. We own the variant.+An offer here would duplicate its seller, sku, price, stock, condition and+delivery config, and would cost a second pricing pipeline, a stock-anchor+migration (stock items are uniquely keyed on `(variant, stock_location)`), a+new line-item FK with the cart's variant-keyed deduplication reworked around+it, and offer-relative rewrites of the purchasability predicates. Putting the+seller on the variant makes all of that true by construction: two sellers are+two variant rows, so two stock rows; prices resolve unchanged; and the line+item already reaches the seller through the variant it points at — which is+exactly what the order split partitions on.++"Offer" survives as storefront vocabulary. Presentation need not be a table.++**Condition is an OptionType**, so it splits the variant like any other axis+and inherits the option machinery. That also makes the buy box key on the+option combination, giving the industry's separate new/used featured offers+without a second mechanism.++**An audit found four things that must ship with it**, three of which are+pre-existing faults the change would expose rather than create: `Product#variants=`+destroys variants absent from the payload, so removal must be filtered to the+writer's own or a narrower read would make the write destructive; delivery+profile is product-level and memoised per product, so sellers would share+whichever profile resolved first (fixed by a variant-level override, which+follows `Variant#tax_category` exactly and is worth having for plain merchants);+option filtering matches each option type independently against the product, so+"Blue AND XL" already matches a product with no Blue XL variant; and product+rollups become buy-box-relative, which is what makes them correct again rather+than a change of meaning.++**Operators see every seller's variants** — they run the marketplace. Seller+isolation is the vendor API branch scope-fetching through `current_vendor`+(Decision 10), not a narrowing of the admin surface.++**Catalog matching stays out of core.** Deciding two submissions are the same+item is hard enough that several platforms sell it separately. Core ships exact+matching on a typed identifier, with the namespace stored rather than inferred+from the value's shape; fuzzy matching is an extension.++Supersedes the plan's "SKU uniqueness relaxes to per-vendor scope" line, which+assumed duplicate product rows per seller.+## 2026-08-16: Grant audiences are a vocabulary, not a vendor flagPhase 0 of `6.0-multi-vendor-marketplace.md`. Damian's call, after