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.

Improve local development and CONTRIBUTING.md guide

Damian Legawiecc7f428997823
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md
index 7f97a09523..4af670842b 100644
--- a/.github/CONTRIBUTING.md
+++ b/.github/CONTRIBUTING.md
@@ -18,7 +18,6 @@ Please read our [Code of Conduct](../CODE_OF_CONDUCT.md) before contributing.
- [Spree namespace](#spree-namespace)
- [Running engine tests](#running-engine-tests)
- [Running tests in parallel](#running-tests-in-parallel)
- - [Integration tests (legacy Rails admin)](#integration-tests-legacy-rails-admin)
- [Performance in development mode](#performance-in-development-mode)
- [TypeScript Development](#typescript-development)
- [Packages](#packages)
@@ -49,7 +48,8 @@ git clone --filter=blob:none https://github.com/spree/spree.git
### Prerequisites
-You need **Node.js 20+** to run the workspace scripts (including `pnpm server:setup`, which both backend and TypeScript contributors use). Install it via [nvm](https://github.com/nvm-sh/nvm), [mise](https://mise.jdx.dev), [fnm](https://github.com/Schniz/fnm), or your package manager (`brew install node` on macOS).
+- Docker (eg. [Docker Desktop for MacOS](https://www.docker.com/products/docker-desktop/))
+- Node 24 ([Install instructions](https://nodejs.org/en/download))
`pnpm` is provisioned automatically via [Corepack](https://nodejs.org/api/corepack.html) (bundled with Node) — the repository pins its version in `package.json`, and the first `pnpm` command will fetch the matching release. If Corepack is disabled in your environment, run `corepack enable` once.
@@ -57,22 +57,35 @@ You need **Node.js 20+** to run the workspace scripts (including `pnpm server:se
Spree is a monorepo with three main areas:
-- **`spree/`** — Ruby gems (core, api, admin, emails) distributed as separate packages via RubyGems
-- **`packages/`** — TypeScript packages (SDKs, CLI, project scaffolding, docs, React dashboard)
+- **`spree/`** — Ruby gems (core, api, emails, providers) distributed as separate packages via RubyGems
+- **`packages/`** — TypeScript packages (Admin Dashboard, Seller Panel, SDKs, CLI, project scaffolding, docs)
- **`server/`** — A Rails application cloned from [spree-starter](https://github.com/spree/spree-starter) that mounts the local Spree gems (not checked in — `pnpm server:setup` creates it)
### Setup
-A single command bootstraps the whole monorepo for both backend and frontend work. You need **Docker** running locally (Docker Desktop, OrbStack, or any compatible runtime) — no Ruby, Postgres, or Redis on your host.
+A single command bootstraps the whole monorepo for both backend and frontend work. You need **Docker** running locally (Docker Desktop, OrbStack, or any compatible runtime) — no Ruby, Postgres on your host.
```bash
pnpm install # workspace dependencies
pnpm server:setup # ~5–10 min on first run; idempotent
```
-`pnpm server:setup` clones [spree-starter](https://github.com/spree/spree-starter) into `./server/`, wires it to load Spree gems from the monorepo via a Docker compose overlay, builds the dev image, starts the stack (Postgres + Redis + Meilisearch + Rails `web` + Sidekiq `worker`), and prepares the database. The full sequence lives in `scripts/server-setup.sh`.
+`pnpm server:setup` clones [spree-starter](https://github.com/spree/spree-starter) into `./server/`, wires it to load Spree gems from the monorepo via a Docker compose overlay, builds the dev image, starts the stack (Postgres + Rails + Mailpit), and prepares the database. The full sequence lives in `scripts/server-setup.sh`.
-When it's done, the backend is up at [http://localhost:3000](http://localhost:3000) and the admin is at [http://localhost:3000/admin](http://localhost:3000/admin). Sign in with the seed admin: **`[email protected]`** / **`spree123`** (override at seed time with `ADMIN_EMAIL` / `ADMIN_PASSWORD` env vars — see `spree/core/app/services/spree/seeds/admin_user.rb`).
+When it's done, the backend is up at [http://localhost:3000](http://localhost:3000). The React dashboard and seller panel are **not** served by Rails in development (that hosted mode is a production topology whose static build would go stale on every `git pull`) — run them as their own dev servers:
+
+```bash
+pnpm dashboard:dev # admin dashboard → http://localhost:5173 (proxies /api to :3000)
+pnpm seller:dev # seller panel → http://localhost:5174
+```
+
+The setup command finishes by printing a **one-time setup link** (`http://localhost:5173/setup?token=…`) — with `pnpm dashboard:dev` running, open it to create the first admin account. If you lose the link, print it again with:
+
+```bash
+SPREE_PATH="$PWD" docker compose -f server/docker-compose.dev.yml -f scripts/docker-compose.edge.yml exec web bin/rails spree:setup:token
+```
+
+To skip the setup screen entirely, set `ADMIN_EMAIL` / `ADMIN_PASSWORD` env vars at seed time — the seed then creates that admin account directly (see `spree/core/app/services/spree/seeds/admin_user.rb`).
Optionally load sample products, taxonomies, and option types:
@@ -80,21 +93,22 @@ Optionally load sample products, taxonomies, and option types:
pnpm server:load_sample_data
```
-### Running a backend day-to-day
+### Running server day-to-day
After the one-time setup, use these to bring the stack up and down:
```bash
-pnpm server:dev # run the stack in the foreground — streams web + worker logs, Ctrl+C stops them
-pnpm server:stop # full teardown (also stops postgres / redis / meilisearch)
-pnpm server:restart # restart web + worker in place
-pnpm server:logs # follow web container logs (when the stack runs detached)
-pnpm server:console # open a Rails console inside the container
-pnpm server:seed # re-run database seeds
-pnpm server:build # rebuild the dev image (only after Dockerfile / .ruby-version changes)
+pnpm server:dev # run the stack in the foreground — streams Rails logs, Ctrl+C stops them
+pnpm server:stop # stop all containers (also postgres) — database and volumes survive
+pnpm server:teardown # remove everything: containers, volumes (database!), and the server/ directory
+pnpm server:restart # restart web + worker in place
+pnpm server:logs # follow web container logs (when the stack runs detached)
+pnpm server:console # open a Rails console inside the container
+pnpm server:seed # re-run database seeds
+pnpm server:build # rebuild the dev image (only after Dockerfile / .ruby-version changes)
```
-`server:dev` behaves like any TS dev server (`vite dev`, the dashboard's `pnpm dev`): it runs in the foreground and Ctrl+C stops the app containers. Postgres, Redis, and Meilisearch keep running for a fast next boot — `pnpm server:stop` shuts everything down.
+`server:dev` behaves like any TS dev server (`vite dev`, the dashboard's `pnpm dev`): it runs in the foreground and Ctrl+C stops the app containers. Postgres keep running for a fast next boot — `pnpm server:stop` shuts everything down while keeping your data. To get rid of the backend entirely (or start over from scratch), `pnpm server:teardown` removes the containers, the volumes, and the `server/` directory.
Run any CLI command against the running backend from `server/`:
@@ -103,37 +117,39 @@ cd server
pnpm exec spree migrate
pnpm exec spree generate model Brand name:string
pnpm exec spree upgrade --plan
-```
+``
See the [`@spree/cli` README](../packages/cli/README.md) for the full command surface.
Which command after which change:
| What changed | What to run |
-|---|---|
+| --- | --- |
| Ruby code in `spree/*` gems | Nothing — gems are bind-mounted; code reloads on the next request |
| A new migration in a gem | Nothing — the next `pnpm server:dev` boot applies it (or `cd server && pnpm exec spree migrate` while the stack runs) |
-| Gem dependencies (gemspec / Gemfile / lock drift after `git pull`) | Nothing — the next `pnpm server:dev` boot self-heals via `bundle check || bundle install` (or `cd server && pnpm exec spree bundle install` while the stack runs) |
+| Gem dependencies (gemspec / Gemfile / lock drift after `git pull`) | Nothing — the next `pnpm server:dev` boot self-heals via `bundle check | | bundle install` (or `cd server && pnpm exec spree bundle install` while the stack runs) |
| Compose files / `server/.env` | `pnpm server:dev` (force-recreates the containers) |
| `server/Dockerfile` / `.ruby-version` / starter update that breaks the image build ("lockfile can't be updated because frozen") | `pnpm server:build`, then `pnpm server:dev` — the build script handles the edge-rewritten `Gemfile.lock` automatically |
| Meilisearch image bump ("database version … is incompatible") | Remove the `server_meilisearch_data` volume, boot, then reindex (`pnpm exec spree rake spree:search:reindex`) — the index is derived data |
| Broken beyond repair | `pnpm server:setup` (full reset — wipes the database and volumes) |
-Re-run `pnpm server:setup` **only** to fully reset — it does `docker compose down -v` + `rm -rf ./server`, wiping all DB data.
+Re-run `pnpm server:setup` **only** to fully reset — it starts with the same teardown as `pnpm server:teardown` (`docker compose down -v` + `rm -rf ./server`), wiping all DB data.
### Native Ruby (advanced)
-If you prefer the fastest possible inner loop and don't mind installing Ruby, Postgres, Redis, and Meilisearch on your host directly, you can skip Docker:
+If you prefer the fastest possible inner loop and don't mind installing Ruby and Postgres on your host directly, you can skip Docker:
```bash
pnpm server:create # clones spree-starter, writes server/.env with SPREE_PATH=..
cd server
-bin/setup # installs Ruby (via mise), Postgres/Redis/Meilisearch (via brew bundle on macOS), gems, prepares the database
-bin/dev # starts Rails + Sidekiq + CSS watchers via Foreman
+bin/setup # installs Ruby (via mise), Postgres (via brew bundle on macOS), gems, prepares the database
+bin/dev # starts Rails
```
This path is faster per request but means more on your host. It also runs against your installed system services, not a sandboxed Docker stack.
+The first-admin flow is the same as on Docker: seeding prints a one-time setup link, and `bin/rails spree:setup:token` (from `server/`) prints it again.
+
## Backend Development (Ruby)
### Engines overview
@@ -141,10 +157,10 @@ This path is faster per request but means more on your host. It also runs agains
The Spree [Rails engines](https://guides.rubyonrails.org/engines.html) live inside `spree/` and are distributed as separate gems (Ruby packages installed via Bundler):
| Engine | Gem | Description |
-|---|---|---|
+| --- | --- | --- |
| `core` | `spree_core` | Models, services, business logic |
| `api` | `spree_api` | REST APIs |
-| `dashboard` | `spree_dashboard` | Hosts the React admin dashboard |
+| `dashboard` | `spree_dashboard` | Hosts/proxies the React admin dashboard |
| `emails` | `spree_emails` | Transactional emails |
### Spree namespace
@@ -167,7 +183,7 @@ bundle exec rake test_app
bundle exec rspec
```
-Replace `core` with `api`, `admin`, or `emails` to test other engines.
+Replace `core` with `api` or `emails` to test other engines.
By default engine tests run against SQLite3. To run against PostgreSQL, set the `DB` environment variable:
@@ -215,18 +231,6 @@ bundle exec parallel_rspec -n 4 spec
After schema changes, re-run `bundle exec rake parallel_setup` to update the worker databases.
-### Integration tests (legacy Rails admin)
-
-The legacy Rails admin (`spree/admin`) ships feature specs that run in a real browser via chromedriver. You only need this if you're touching the legacy admin UI.
-
-Install chromedriver on macOS:
-
-```bash
-brew install chromedriver
-```
-
-The 6.0 React dashboard (`packages/dashboard`) has its own end-to-end test suite running on Playwright against a real Rails backend — see [Dashboard E2E tests](#dashboard-e2e-tests) under TypeScript Development.
-
### Performance in development mode
Spree runs slower in development because caching is disabled and code reloads on each request. To turn on caching:
@@ -244,7 +248,7 @@ The backend setup is the same as for Ruby work — see [Setup](#setup) above. Wi
### Packages
| Package | Path | Published | Description |
-|---|---|---|---|
+| --- | --- | --- | --- |
| `@spree/sdk` | `packages/sdk` | yes | TypeScript SDK for the Spree Store API |
| `@spree/admin-sdk` | `packages/admin-sdk` | yes | TypeScript SDK for the Spree Admin API |
| `@spree/cli` | `packages/cli` | yes | CLI for managing Spree Commerce projects |
@@ -260,7 +264,7 @@ The backend setup is the same as for Ruby work — see [Setup](#setup) above. Wi
Run from the repository root — [Turborepo](https://turbo.build/) orchestrates tasks across all packages:
| Command | Description |
-|---|---|
+| --- | --- |
| `pnpm dev` | Watch mode for all packages (does not boot the backend — use `pnpm server:dev` for that) |
| `pnpm build` | Build all packages (Turbo resolves dependency order) |
| `pnpm test` | Run tests in all packages |
@@ -282,23 +286,38 @@ Tests use [Vitest](https://vitest.dev/) with [MSW](https://mswjs.io/) for API mo
### Working on the React dashboard
-The dashboard runs as a Vite dev server (port 5173) that proxies `/api/*` to the Rails backend on port 3000 — required for the auth refresh cookie to work over plain HTTP.
+The dashboard runs as a Vite dev server (port 5173) that proxies `/api/*` to the Rails backend on port 3000 — required for the auth refresh cookie to work over plain HTTP. The dev host is `packages/dashboard-starter` (the same app `spree add dashboard` scaffolds), which hot-reloads `@spree/dashboard`, `-core`, and `-ui` source through the workspace:
```bash
# Terminal 1: backend
pnpm server:dev
# Terminal 2: dashboard
-cd packages/dashboard
-pnpm dev # http://localhost:5173
+pnpm dashboard:dev # http://localhost:5173
```
-Sign in with `[email protected]` / `spree123`. To point at a non-default backend, set `VITE_SPREE_API_URL` (also needs to be set at build time for production bundles, not just dev):
+Sign in with the admin account you created through the setup link (or seeded via `ADMIN_EMAIL` / `ADMIN_PASSWORD` — see [Setup](#setup)).
+
+The marketplace **seller panel** works the same way from `packages/seller-dashboard-starter`:
```bash
-VITE_SPREE_API_URL=https://my-spree.example.com pnpm dev
+pnpm seller:dev # http://localhost:5174
```
+Seed a seller account to sign in as (`[email protected]` / `spree123`):
+
+```bash
+cd server && pnpm exec spree task sellers:sample_data
+```
+
+To point the dev server at a non-default backend, set `VITE_API_PROXY_TARGET` — the SDK keeps using same-origin URLs and the Vite proxy forwards them:
+
+```bash
+VITE_API_PROXY_TARGET=https://my-spree.example.com pnpm dashboard:dev
+```
+
+Don't use `VITE_SPREE_API_URL` in dev — it switches the SDK to absolute cross-origin URLs, bypassing the proxy (and breaking the auth refresh cookie). It's a build-time setting for production bundles only.
+
**Gotcha:** the dashboard imports `@spree/admin-sdk` from its **built** `dist/`, not source. If you edit `admin-sdk` (or `sdk-core`, or `sdk`) and want the dashboard to see the changes, run `pnpm build` from the monorepo root first (Turbo-cached). Editing dashboard code alone doesn't need this.
See `packages/dashboard/README.md` for the full architecture (auth, permissions, extension points, the three-package split between `dashboard`, `dashboard-core`, and `dashboard-ui`).
@@ -475,6 +494,6 @@ The MCP server URL for quick setup:
https://spreecommerce.org/docs/mcp
```
-## That's a wrap!
+## That's a wrap
Thank you for participating in Open Source and improving Spree - you're awesome!
diff --git a/docs/README.md b/docs/README.md
index 6f83c14005..2991b8641b 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -15,13 +15,19 @@ To run the documentation locally, you will need to install the Mintlify CLI.
npm i -g mint
```
-Then you can run the documentation locally with the following command:
+Then you can run the documentation locally. From the repository root:
```bash
-mint dev
+pnpm docs:dev
```
-This will start the documentation server on port 4000. You can then view the documentation at [http://localhost:4000](http://localhost:4000).
+This serves the documentation at [http://localhost:3333](http://localhost:3333).
+
+The port is pinned deliberately. Running `mint dev` on its own picks port 3000 and silently moves to 3001, 3002 and so on when that is taken — which, in a checkout that also runs a Rails server and a dashboard, means the docs land somewhere different each time. If you do run `mint dev` directly, pass the port yourself:
+
+```bash
+cd docs && mint dev --port 3333
+```
## License
diff --git a/docs/developer/core-concepts/catalogs.mdx b/docs/developer/core-concepts/catalogs.mdx
new file mode 100644
index 0000000000..66d223ae01
--- /dev/null
+++ b/docs/developer/core-concepts/catalogs.mdx
@@ -0,0 +1,147 @@
+---
+title: Catalogs
+description: Showing different products and prices to different audiences — a wholesale range, a channel-specific selection, or one company's negotiated pricing.
+---
+
+## Overview
+
+Not every shopper should see the same store. A wholesale buyer gets trade prices and a range retail never sees. A negotiated account has its own agreed pricing. A retail till carries a subset of what the website does.
+
+A catalog answers both halves of that at once: **what an audience sees**, and **what they pay**.
+
+```mermaid
+flowchart LR
+ Catalog --> Assortment["Assortment<br/><i>which products</i>"]
+ Catalog --> PriceList["Price list<br/><i>what they cost</i>"]
+ Catalog --> Audience["Assignments<br/><i>who gets it</i>"]
+```
+
+```mermaid
+erDiagram
+ Catalog ||--o{ CatalogProduct : "assortment"
+ Catalog ||--o{ CatalogAssignment : "audiences"
+ Catalog }o--o| PriceList : "optional pricing"
+ CatalogAssignment }o--|| Channel : "one of"
+ CatalogAssignment }o--|| CustomerGroup : "one of"
+ CatalogAssignment }o--|| Market : "one of"
+ CatalogAssignment }o--|| Company : "one of"
+
+ Catalog {
+ string name
+ boolean active
+ integer position
+ }
+```
+
+## The two modes
+
+The single most useful thing to understand about catalogs is that an **empty assortment means something different from a full one** — it's the switch between the two ways a catalog is used.
+
+<CardGroup cols={2}>
+ <Card title="Pricing overlay" icon="tag">
+ **Assortment empty.** Nothing is hidden — the audience browses the normal store — but the attached price list applies.
+
+ This is how "this company sees everything, just at their negotiated prices" is expressed.
+ </Card>
+ <Card title="Restricted range" icon="filter">
+ **Assortment has products.** The audience sees *only* what's in it.
+
+ This is how a wholesale-only range, or a channel-specific selection, is expressed.
+ </Card>
+</CardGroup>
+
+That's worth pausing on, because it's the one behaviour that surprises people: adding a product to an empty catalog doesn't add one item to what a customer sees — it switches the catalog into restricting mode, and they now see *only* that item.
+
+## Creating one
+
+```typescript Admin SDK
+const catalog = await adminClient.catalogs.create({
+ name: 'Wholesale',
+ price_list_id: 'plist_xxx',
+ active: true,
+})
+```
+
+The price list is optional. A catalog with an assortment and no price list restricts the range at normal prices; a catalog with a price list and no assortment adjusts prices without hiding anything.
+
+### Filling the assortment
+
+```typescript Admin SDK
+// Add products (a bare array of IDs)
+await adminClient.catalogs.products.create(catalog.id, ['prod_xxx', 'prod_yyy'])
+
+const { data: products } = await adminClient.catalogs.products.list(catalog.id)
+
+await adminClient.catalogs.products.delete(catalog.id, 'prod_xxx')
+```
+
+Products are positioned, so a catalog also controls the order they're presented in.
+
+When a catalog should restrict to exactly what its price list covers, there's a shortcut that copies those products in rather than making someone add them by hand:
+
+```typescript Admin SDK
+const { added_count } = await adminClient.catalogs.importProducts(catalog.id)
+```
+
+## Choosing the audience
+
+A catalog is assigned to one of four things:
+
+| Assign to | Meaning |
+|---|---|
+| **[Channel](/developer/core-concepts/channels)** | Everyone buying through this channel — an app, a retail till |
+| **[Customer group](/developer/core-concepts/customers)** | A segment — wholesale accounts, staff, a loyalty tier |
+| **[Market](/developer/core-concepts/markets)** | Everyone in a region |
+| **[Company](/developer/core-concepts/companies)** | One B2B organization |
+
+```typescript Admin SDK
+await adminClient.catalogs.assign(catalog.id, {
+ assignable_type: 'customer_group',
+ assignable_id: 'cgrp_xxx',
+})
+```
+
+<Note>
+**A company assignment covers the whole subtree.** Assign the group-wide catalog once at the root of a [company tree](/developer/core-concepts/companies) and every division below inherits it — no re-assigning per branch. A branch can still add its own catalog on top.
+</Note>
+
+## What a shopper ends up seeing
+
+When several catalogs could apply, they combine rather than compete:
+
+<Steps>
+ <Step title="Find the catalogs that apply">
+ For a company buyer, that's the catalogs on their node **and its ancestors**. Otherwise their customer group's catalogs. Otherwise the channel's default catalog, if it has one.
+ </Step>
+ <Step title="Combine the assortments">
+ The shopper sees the union of what those catalogs contain — so a division's extra catalog adds to the group's range rather than replacing it.
+ </Step>
+ <Step title="Any empty assortment lifts the restriction">
+ If one applicable catalog is a pricing overlay, the restriction is off and the shopper sees the full range. An overlay is explicitly "don't hide anything", and that has to win — otherwise adding negotiated pricing would accidentally narrow someone's catalog.
+ </Step>
+</Steps>
+
+Gated storefront access is checked before any of this — a shopper who has to sign in never reaches catalog resolution.
+
+## How pricing resolves
+
+Prices are checked in order, and the first match wins:
+
+1. Price lists attached to the applicable catalogs, **nearest first** — the buyer's own company node before its parent's
+2. Ordinary price lists whose rules match
+3. The product's base price
+
+Nearest-first is what lets a subsidiary hold a better-negotiated rate than the group's, without disturbing anyone else.
+
+<Warning>
+A price list attached to a catalog applies **because the catalog applies** — its own rules are not consulted, and it's excluded from ordinary rule matching.
+
+That exclusion is load-bearing: a price list with no rules would otherwise match everyone, and one company's negotiated pricing would leak to the entire storefront.
+</Warning>
+
+## Related
+
+- [Companies](/developer/core-concepts/companies) — B2B buyers and the subtree rule
+- [Pricing](/developer/core-concepts/pricing) — price lists and rules
+- [Products](/developer/core-concepts/products) — the catalog being narrowed
+- [Channels](/developer/core-concepts/channels) — per-channel default catalogs
diff --git a/docs/developer/core-concepts/commissions.mdx b/docs/developer/core-concepts/commissions.mdx
new file mode 100644
index 0000000000..5d7d519105
--- /dev/null
+++ b/docs/developer/core-concepts/commissions.mdx
@@ -0,0 +1,249 @@
+---
+title: Commissions
+description: What a marketplace charges its sellers — rates and the rules that target them, how a fee is calculated, and the settlement record left behind.
+---
+
+## Overview
+
+A marketplace earns by taking a cut of what its sellers sell. Commissions are how you describe that cut and how Spree records what was actually charged.
+
+There are two halves, and — as with [promotions and discounts](/developer/core-concepts/promotions) — keeping them apart is what makes the whole thing work:
+
+| | |
+|---|---|
+| **Commission rate** | Configuration. What you charge, and when. Editable. |
+| **Commission line** | The record of one charge on one sale. Frozen. |
+
+Editing a rate changes what the *next* sale is charged and never what a past one was.
+
+```mermaid
+flowchart LR
+ Sale["A seller's item sells"] --> Resolve["Find the first<br/>matching rate"]
+ Resolve --> Calc["Calculate the fee<br/>and its tax"]
+ Calc --> Line["Commission line<br/><i>frozen</i>"]
+
+ style Line fill:#e8f5e9,stroke:#2e7d32
+```
+
+<Note>
+**A commission is not a [fee](/developer/core-concepts/fees).** A fee is charged to the shopper and rolls into the order total. A commission is a settlement between the marketplace and the seller — the customer never sees it, and it never touches the order total.
+</Note>
+
+## Rates
+
+A rate says what to charge. It's either a percentage of the sale or a flat amount.
+
+```typescript Admin SDK
+await adminClient.commissionRates.create({
+ name: 'Electronics',
+ code: 'electronics',
+ kind: 'percentage',
+ value: '12.5',
+ enabled: true,
+})
+```
+
+| Attribute | Description |
+|---|---|
+| `name` | What operators call it |
+| `code` | An optional short handle, unique per store |
+| `kind` | `percentage` or `fixed` |
+| `value` | The percentage, for a percentage rate |
+| `enabled` | Whether it's in play |
+| `position` | Where it sits in the list — see below |
+| `tax_inclusive` | Whether the fee is charged on the gross or net amount |
+| `include_shipping` | Whether delivery is commissioned too |
+| `commission_tax_rate` | An explicit tax rate for the fee, overriding the default |
+
+## The list is the precedence
+
+This is the most important thing to understand about commission rates, and it's deliberately different from how you might expect.
+
+When a sale happens, Spree walks the store's enabled rates **in list order** and takes **the first one whose rules match**. There's no scoring, and no built-in hierarchy where a product rule beats a category rule.
+
+<Info>
+What an operator sees in the table is exactly what resolution does. A marketplace that wants a different answer drags a row up or down, rather than reasoning about which rule type counts as "more specific".
+</Info>
+
+Two consequences worth planning around:
+
+**A rate with no rules matches everything.** That's how you express a default — and it belongs at the **bottom** of the list, because anything below it is unreachable.
+
+**New rates are created at the top.** A rate is created to say something more specific than what's already there, and appending it below the catch-all would leave it dead on arrival.
+
+```mermaid
+flowchart TB
+ R1["1. Electronics — 12.5%<br/><i>category rule</i>"] --> R2
+ R2["2. Trusted sellers — 8%<br/><i>seller rule</i>"] --> R3
+ R3["3. Default — 15%<br/><i>no rules</i>"]
+
+ style R3 fill:#fff3e0,stroke:#e65100
+```
+
+If nothing matches, **no commission is charged**. That's a real answer, not a fallback — a marketplace with no rate covering a sale charges nothing rather than inventing a default nobody configured.
+
+## Rules
+
+Rules narrow when a rate applies. A rate can hold several, and **all of them must match** — while the IDs listed *within* one rule are alternatives.
+
+So "electronics **and** these three sellers" is two rules on one rate.
+
+```typescript Admin SDK
+// Every rule kind, with the schema describing its settings — so an editor
+// is built from what this marketplace actually has, not a hardcoded list
+const { data: types } = await adminClient.commissionRates.ruleTypes()
+
+await adminClient.commissionRates.update('crate_xxx', {
+ rules: [
+ { type: 'category_rule', preferences: { category_ids: ['ctg_xxx'] } },
+ { type: 'seller_rule', preferences: { seller_ids: ['sel_xxx', 'sel_yyy'] } },
+ ],
+})
+```
+
+Rules are replaced wholesale on update — send the full set you want.
+
+### The four rule types
+
+<AccordionGroup>
+ <Accordion title="Product rule — these specific products">
+ Charges the rate only for the products named.
+
+ Products are stored as real references rather than a list of IDs in a field, so a marketplace naming a thousand products stays workable.
+ </Accordion>
+ <Accordion title="Category rule — anything filed here">
+ Charges the rate for products in the named categories.
+
+ **A category matches its descendants too.** A rate on "Electronics" governs a camera under Electronics → Cameras, so you don't restate the rule every time someone adds a subcategory.
+ </Accordion>
+ <Accordion title="Seller rule — these sellers">
+ Charges the rate only when the seller is one of those named. This is how a negotiated rate for a large vendor is expressed.
+
+ A rule naming nobody narrows nothing — and rather than silently charging every seller, it's treated as not matching.
+ </Accordion>
+ <Accordion title="Item total rule — sales in a value band">
+ Charges the rate only on sales within a value range. "15% under 50, 10% above" is two rates, each holding one of these.
+
+ Bounds are **inclusive at the bottom and exclusive at the top**, so two bands can meet at a number without overlapping or leaving a gap.
+
+ The band is weighed against exactly the same figure the fee is charged on, so a band can never admit a sale the fee then treats as worth something different.
+ </Accordion>
+</AccordionGroup>
+
+One rule of each type per rate. Rules can only name products and sellers belonging to the same store — pointing one at another marketplace's catalog is refused rather than quietly ignored.
+
+## What the fee is charged on
+
+Two settings on the rate decide the base, and both matter more than they first appear.
+
+### Gross or net
+
+`tax_inclusive` decides whether the fee is charged on the amount including the customer's tax, or excluding it.
+
+**The default is net**, and that default is deliberate: the customer's VAT isn't the seller's revenue, and charging commission on it would tax the same money twice under two different regimes.
+
+Discounts come off either way. Commission is charged on what the customer actually paid, so a promotion is the seller's concession.
+
+### Delivery
+
+`include_shipping` adds a commission on the delivery charge as well as the goods.
+
+<Warning>
+A **flat** rate cannot commission delivery. A flat fee is charged per sale, so charging the same amount again on the parcel would double it. A marketplace wanting a flat charge on delivery states it as its own rate.
+</Warning>
+
+## Amounts and currencies
+
+Money is stated per currency, never converted:
+
+```typescript Admin SDK
+// A percentage, with a floor and a cap in each currency
+await adminClient.commissionRates.create({
+ name: 'Standard',
+ kind: 'percentage',
+ value: 10,
+ bounds: {
+ USD: { min_amount: 1, max_amount: 50 },
+ EUR: { min_amount: 1, max_amount: 45 },
+ },
+})
+
+// A flat fee, stated per currency
+await adminClient.commissionRates.create({
+ name: 'Listing fee',
+ kind: 'fixed',
+ value: 0,
+ amounts: { USD: '5.00', GBP: '4.00' },
+})
+```
+
+- **`amounts`** — what a flat fee charges, per currency
+- **`bounds`** — the floor and cap a percentage charges within, per currency
+
+Both replace the whole set on write, and writing `bounds` never disturbs `amounts`.
+
+Percentages and flat fees behave differently across currencies, for a good reason:
+
+| | Behaviour in a currency with no stated amount |
+|---|---|
+| **Flat rate** | Doesn't apply — resolution falls through to the next rate. Converting one currency's figure into another would invent a fee nobody set. |
+| **Percentage** | Still applies, uncapped. A ratio travels; its floor and cap don't. A marketplace that capped its dollar fees hasn't thereby said it wants no commission on euro sales. |
+
+A flat fee is charged **per unit**, not per line. Otherwise buying three cameras together would earn a third of buying them separately — letting the shopper decide the marketplace's revenue.
+
+## Tax on commission
+
+The commission is the marketplace's own service to the seller. That's a separate taxable supply from the seller's sale to the customer, with its own place of supply — which is why the two taxes are worked out independently and never mix.
+
+The tax rate is resolved in this order:
+
+1. An explicit `commission_tax_rate` on the rate
+2. The store's tax engine, using the **seller's** address
+3. The store's default commission tax rate
+
+<Warning>
+Commission tax follows the **seller's** jurisdiction, not the shopper's. A German marketplace charging a French seller is a cross-border B2B supply, and the shopper's location has nothing to do with it.
+</Warning>
+
+Each line carries a `taxability_reason` — `standard_rated`, `zero_rated`, `reverse_charge` — using the same vocabulary as [tax lines](/developer/core-concepts/taxes) on goods. An invoice explaining why a marketplace fee was reverse-charged should use the same words as one explaining it for goods.
+
+## Commission lines
+
+When an order is placed, the resolved rate is applied and the result frozen as a commission line — one per item, plus one per delivery where the rate includes it.
+
+| Attribute | Description |
+|---|---|
+| `amount` | The fee |
+| `tax_amount` | Tax on the fee |
+| `total` | The two added together |
+| `rate` / `kind` | A snapshot of what was applied |
+| `tax_rate` / `taxability_reason` | How it was taxed, and why |
+| `country_code` / `state_code` | The seller's jurisdiction |
+| `currency` | The sale's currency |
+| `line_item_id` / `fulfillment_id` | What was commissioned — exactly one |
+| `commission_rate_id` | The rate, if it still exists |
+
+```typescript Admin SDK
+const { data: lines } = await adminClient.commissionLines.list({
+ filter: { seller_id_eq: 'sel_xxx' },
+})
+```
+
+**Every field is a snapshot.** Editing the rate afterwards changes nothing here, and neither does deleting it — a retired rate is soft-deleted precisely so "which rate charged this" stays answerable.
+
+There is **no write path**. Lines are read-only in the API, and correcting a charge means recording a reversal rather than editing history — the discipline any ledger needs.
+
+## What this doesn't do
+
+Commission lines say what the marketplace charged. They don't move money.
+
+<Warning>
+Open source has **no payout ledger**. Paying sellers means connecting a provider such as Stripe Connect, or building against the commission lines and [payment splits](/developer/core-concepts/sellers#one-checkout-several-sellers). Scheduled payout runs, refund clawbacks and reconciliation are Enterprise features.
+</Warning>
+
+## Related
+
+- [Sellers](/developer/core-concepts/sellers) — marketplaces, order splitting and payment splits
+- [Taxes](/developer/core-concepts/taxes) — the tax vocabulary commission lines share
+- [Fees](/developer/core-concepts/fees) — buyer-facing charges, which commissions are not
+- [Promotions](/developer/core-concepts/promotions) — the same rules-and-record split, on the buyer side
diff --git a/docs/developer/core-concepts/companies-and-catalogs.mdx b/docs/developer/core-concepts/companies-and-catalogs.mdx
deleted file mode 100644
index 3cf4b9318b..0000000000
--- a/docs/developer/core-concepts/companies-and-catalogs.mdx
+++ /dev/null
@@ -1,81 +0,0 @@
----
-title: Companies & Catalogs
-description: How Spree models B2B buyer organizations — a multi-level company tree with members and an address book — and the catalogs that decide what each audience sees and pays.
----
-
-## Overview
-
-A business customer in Spree is a **tree of company nodes**, not a flat account. One node can stand alone — a company with a few members and addresses — or grow into a group: subsidiaries, divisions, regional units, each with its own buyers and ship-to sites.
-
-```mermaid
-erDiagram
- Company ||--o{ Company : "parent of"
- Company ||--o{ CompanyMembership : "has many"
- Company ||--o{ CompanyAddress : "has many"
- Company ||--o{ CompanyInvitation : "has many"
- Company ||--o{ TaxIdentifier : "legal entities only"
- Company ||--o{ TaxExemptionCertificate : "legal entities only"
-
- Company {
- string name
- string kind "company | division"
- string external_id
- }
- CompanyMembership {
- string role "cosmetic label"
- }
- CompanyAddress {
- string label
- boolean default_billing
- boolean default_shipping
- }
- CompanyInvitation {
- string email
- string token
- datetime expires_at
- }
-```
-
-Three ideas carry the whole model:
-
-- **The tree is structure.** `Spree::Company` is self-referential (`parent_id`), store-scoped, and shallow — depth is capped at five levels. How many ship-to sites a node has never dictates how many nodes exist; addresses are just an address book.
-- **Nodes are typed, and the type decides tax.** A `company` node is a legal entity; a `division` is an organizational unit. Tax registrations and exemption certificates exist only on legal entities, and a purchase's tax always resolves through the node's `legal_entity` — for a `company` that is the node itself, and for a `division` it is its nearest `company` ancestor, whose registrations then cover the division's purchases. The walk stops at that first `company` node whether or not it holds any registration, so a subsidiary with no VAT number of its own has none — it never borrows its parent's.
-- **Membership is standing over a subtree.** A `CompanyMembership` joins a customer to a node, and that standing covers the node and everything below it. Any authorization question — "may this customer act for node N?" — is a membership check on N and its ancestors, never an equality check on one node.
-
-## Members and invitations
-
-People join by email, from either side — staff in the dashboard or an existing member on the storefront. An email that matches a store customer becomes a membership immediately; an unknown email becomes a `Spree::CompanyInvitation` — a plaintext-token record with a 30-day expiry, whose invite email links to the storefront acceptance page. Accepting either registers a new account (through the standard customer-creation flow, with the invited email) or binds the invitation to the signed-in customer, and lands as a membership either way.
-
-Memberships stay always-active and always customer-backed: the pending state lives on the invitation, never as a status on the membership.
-
-**In open source, every member can do everything within their standing** — buy, see the subtree's purchases, manage addresses and members. There are no company roles; the `role` string on a membership is a cosmetic label. Finer control (roles, approvals, spending limits) is an Enterprise layer that enforces through the storefront access policy class (`Spree::Dependencies.storefront_access_policy_class`) and the checkout `validate` hooks — injection points that are deliberate no-ops in OSS.
-
-## Purchases
-
-Carts and orders carry a `company_id` pointing at any node — buying *for* a division means pointing at it. A buyer with exactly one membership resolves to it automatically; a buyer with several names the node on their cart (the `company_id` param on cart update, validated against their standing). The node is frozen onto the order at completion, like every other order attribute, so a placed order's tax treatment stays explainable no matter how the tree changes later.
-
-Exemption certificates and the company's tax registration always resolve through `company.legal_entity` — see [Taxes](/developer/core-concepts/taxes) for how they reach the tax provider.
-
-## Catalogs
-
-A `Spree::Catalog` narrows what an audience sees and — through an optional price list — what they pay.
-
-```mermaid
-erDiagram
- Catalog ||--o{ CatalogProduct : "assortment"
- Catalog ||--o{ CatalogAssignment : "audiences"
- Catalog }o--o| PriceList : "optional pricing"
- CatalogAssignment }o--|| Company : "or"
- CatalogAssignment }o--|| CustomerGroup : "or"
- CatalogAssignment }o--|| Market : "or"
- CatalogAssignment }o--|| Channel : "or"
-```
-
-- **Assortment** — a positioned product join, and the switch between a catalog's two modes. A *curated* assortment restricts: the audience sees only what's in it. An *empty* assortment is a pricing-only overlay: the attached price list applies and nothing is hidden — which is how "everyone sees the public store, this company just gets special prices" is expressed. An explicit import action copies the price list's products into the assortment when a restrictive catalog should start from the priced range.
-- **Audiences** — assignments to a channel, a customer group, a market, or a company node. A company assignment covers the node's **subtree**: assign the group-wide catalog once at the root, and a branch adds its own extra catalog without re-assigning the shared one.
-- **Visibility** — a buyer resolving to a company node sees the union of the effective catalogs on the node and its ancestors; otherwise their customer group's catalogs apply; otherwise every channel listing (narrowed to the channel's default catalog when one is set). Any effective catalog with an empty assortment lifts the restriction — the union then includes the whole range. Gated storefront access runs first — a login-gated guest never reaches this resolution.
-- **Pricing** — the effective catalogs' price lists are checked nearest node first (the purchase node's own assignments before its parent's), then the ordinary rule-matched price lists, then base prices. A price list attached to a catalog applies *because the catalog applies* — its own rules are not consulted, and it is excluded from generic rule matching so a rule-less list cannot leak to every shopper.
-
-## Storefront self-service
-
-The Store API ships a full company directory for members: their memberships with ancestor paths (`GET /store/account/companies`), node details and renaming, the address book, members and invitations, and the subtree's completed orders. Authorization on every endpoint is **standing plus the access policy** — never roles, never CanCanCan. The deliberate trade-off: within a company, OSS trusts every member; merchants who need restraint layer the Enterprise governance on the same injection points, with no schema changes.
diff --git a/docs/developer/core-concepts/companies.mdx b/docs/developer/core-concepts/companies.mdx
new file mode 100644
index 0000000000..a9623fee70
--- /dev/null
+++ b/docs/developer/core-concepts/companies.mdx
@@ -0,0 +1,248 @@
+---
+title: Companies
+description: B2B buyers as organizations — a company tree with members, shared addresses, and purchases made on the company's behalf.
+---
+
+## Overview
+
+Selling to businesses breaks an assumption most storefronts make: that a customer is a person. A business buyer is a person acting *for* an organization — one that has other buyers, several delivery sites, a VAT number, and a finance team who wants to see everything anyone ordered.
+
+A company in Spree models that. And because real organizations aren't flat, a company can be a **tree**: a parent with subsidiaries, divisions, regional units, each with its own people and addresses.
+
+```mermaid
+flowchart TB
+ Root["Acme Group<br/><i>company</i>"]
+ Root --> EU["Acme Europe<br/><i>company</i>"]
+ Root --> US["Acme US<br/><i>company</i>"]
+ EU --> Sales["Sales<br/><i>division</i>"]
+ EU --> Ops["Operations<br/><i>division</i>"]
+
+ style Root fill:#e3f2fd,stroke:#0077ff
+ style EU fill:#e3f2fd,stroke:#0077ff
+ style US fill:#e3f2fd,stroke:#0077ff
+```
+
+A node is one of two kinds, and the difference is about tax, not hierarchy:
+
+| Kind | What it is |
+|---|---|
+| `company` | A legal entity — it can hold a tax registration |
+| `division` | An organizational unit inside one — it cannot |
+
+Trees are capped at five levels, and the root must always be a `company`.
+
+```mermaid
+erDiagram
+ Company ||--o{ Company : "parent of"
+ Company ||--o{ CompanyMembership : "members"
+ Company ||--o{ Address : "address book"
+ Company ||--o{ CompanyInvitation : "pending invites"
+ Company ||--o{ TaxIdentifier : "legal entities only"
+ Company ||--o{ Order : "purchases"
+
+ Company {
+ string name
+ string kind
+ string parent_id
+ }
+ CompanyMembership {
+ string customer_id
+ string email
+ }
+```
+
+## Membership covers a subtree
+
+Someone belongs to a company through a membership, and **that standing reaches everything below the node** — not just the node itself.
+
+So a buyer attached to "Acme Europe" can act for Sales and Operations beneath it, without anyone creating three memberships. Give someone standing at the root and they cover the whole group.
+
+This is why authorization always asks "does this person have standing on this node *or any of its ancestors*", never "is this person a member of exactly this node".
+
+```typescript Store SDK
+// Which companies can this customer act for?
+const { data: memberships } = await client.account.companies()
+
+memberships.forEach((m) => {
+ m.company.name // "Acme Europe"
+ m.company.ancestors // [{ name: "Acme Group", … }] — the path above it
+})
+```
+
+<Note>
+**In open source, every member can do everything within their standing** — buy, see the subtree's orders, and manage addresses and members. There are no company roles; the `role` label on a membership is cosmetic.
+
+To restrict what individual people may do, see [company governance](#company-governance) below.
+</Note>
+
+## Adding people
+
+Both the dashboard and the storefront add members the same way — by email:
+
+```typescript Store SDK
+const result = await client.companies.members.create('comp_xxx', {
+ customer_email: '[email protected]',
+})
+```
+
+What comes back depends on whether that email is already a customer:
+
+- **An existing customer** becomes a member straight away.
+- **An unknown email** produces an invitation, valid for 30 days, and an email with a link.
+
+You can tell which by the ID prefix — `cmem_` for a membership, `cinv_` for an invitation.
+
+Accepting an invitation either signs an existing customer in, or registers a new account with the invited email. Either way it ends as a membership:
+
+```typescript Store SDK
+// The token comes from the invitation email — no sign-in needed to read it
+const invitation = await client.companyInvitations.lookup(token)
+invitation.company_name
+
+await client.companyInvitations.accept(token, {
+ first_name: 'Dana',
+ last_name: 'Reid',
+ password: 'a-strong-password',
+})
+```
+
+Memberships are always active and always backed by a real customer. Anything still waiting lives on the invitation, so there's no such thing as a half-active member.
+
+## Buying for a company
+
+A cart and an order can name a company. That's what turns a personal purchase into a company one — it decides which addresses are on offer, whose tax registration applies, and who else will see the order.
+
+```typescript Store SDK
+await client.carts.update(cartId, { company_id: 'comp_xxx' })
+```
+
+A buyer with exactly one membership doesn't need to choose; it resolves on its own. A buyer who belongs to several names the node — and it must be one they have standing on.
+
+The company is **frozen onto the order** at completion, like the addresses and prices. Reorganize the tree next year and last year's order still explains itself.
+
+```typescript Store SDK
+// Everything anyone in the subtree has bought
+const { data: orders } = await client.companies.orders.list('comp_xxx')
+```
+
+That subtree rollup is the feature a finance team actually asks for: one place showing what the whole organization spent, without chasing individual accounts.
+
+## The shared address book
+
+A company keeps its own addresses — ship-to sites, a billing address — separate from any individual's. They're labelled, and one of each kind can be the default.
+
+```typescript Store SDK
+await client.companies.addresses.create('comp_xxx', {
+ label: 'Northern Warehouse',
+ first_name: 'Goods',
+ last_name: 'Inwards',
+ address1: '14 Dock Road',
+ city: 'Rotterdam',
+ country_code: 'NL',
+ postal_code: '3011',
+ default_shipping: true,
+})
+```
+
+Note that a delivery site is just an address. Ten warehouses do not mean ten company nodes — nodes exist for organizational and legal structure, addresses for where things go.
+
+## Tax
+
+Tax registrations and exemption certificates live **only on legal entities**, and a purchase resolves tax through the node's nearest `company` ancestor.
+
+```typescript Admin SDK
+await adminClient.companies.taxIdentifiers.create('comp_xxx', {
+ kind: 'eu_vat',
+ value: 'NL123456789B01',
+})
+
+// Validation runs against the official registry, in the background
+await adminClient.companies.taxIdentifiers.validate('comp_xxx', 'txid_xxx')
+```
+
+<Warning>
+The walk stops at the first `company` node, **whether or not it holds a registration**. A subsidiary with no VAT number of its own therefore has none — it never quietly borrows its parent's, because in most jurisdictions that would be a false declaration.
+</Warning>
+
+Exemption certificates hang off a legal entity and are scoped to the country or state that issued them. Check whether a certificate is `active` rather than reading its status — a verified certificate stops exempting once it expires, and `active` accounts for that.
+
+See [Taxes](/developer/core-concepts/taxes) for how these reach the tax calculation.
+
+## Company governance
+
+Open source deliberately trusts every member equally. That's the right default for a company of five people, and the wrong one for a company of five hundred — where a junior buyer should not be able to place a £40,000 order, remove their manager, or see what another division spent.
+
+Company governance adds that control. It works through the same endpoints and the same data, so nothing about your storefront integration changes when it's switched on — the calls you already make simply start enforcing.
+
+<Card title="Requires a Spree Enterprise licence" icon="lock" href="https://spreecommerce.org/enterprise/">
+ Company roles, order approvals, spending limits and governance audit history are part of Spree Enterprise. See what's included, or talk to the team about your use case.
+</Card>
+
+### Company roles
+
+Where open source has a cosmetic label, Enterprise has real roles built from a fixed set of capabilities:
+
+| Capability | Allows |
+|---|---|
+| `place_orders` | Completing a purchase |
+| `approve_orders` | Approving what others submit |
+| `view_node_purchases` | Seeing this node's orders |
+| `view_company_purchases` | Seeing the whole subtree's orders |
+| `manage_company_members` | Adding and removing people |
+| `manage_company_addresses` | Editing the address book |
+
+Roles are **data, edited by the company's own administrator** rather than by your staff — the buying organization manages its own structure, which is the point of self-service. Guards prevent someone granting themselves more than they hold.
+
+These are entirely separate from [staff roles](/developer/core-concepts/staff-roles). A company role never reaches anything belonging to the store.
+
+### Order approvals
+
+A member without `place_orders` submits their basket instead of completing it. Someone with `approve_orders` reviews and releases it.
+
+```mermaid
+flowchart LR
+ Buyer["Buyer submits"] --> Pending["Awaiting approval"]
+ Pending --> Approved["Approved → order placed"]
+ Pending --> Rejected["Rejected, with a reason"]
+```
+
+Checkout returns a well-known `approval_required` response rather than a generic failure, so a storefront can show the right message and the right next step. The approval history is append-only — who asked, who decided, when.
+
+### Spending limits
+
+Limits are set per member or per node, with a reset period — £5,000 a month for a buyer, £50,000 for a division. They're enforced at completion, alongside approvals, so an over-limit basket is caught before payment rather than after.
+
+### Restricted self-service
+
+The same storefront endpoints — the company directory, address book, member management, order history — become capability-gated. A member without `view_company_purchases` sees their own node's orders and not the group's; a member without `manage_company_members` can read the team but not change it.
+
+<Info>
+**Nothing about the data model changes.** Governance enforces through a policy layer and the checkout validation hooks, over the same companies, memberships and endpoints described on this page. You can build a B2B storefront against open source today and have it work unchanged when governance is enabled.
+</Info>
+
+Payment terms and net invoicing, quotes, and a packaged buyer portal are on the Enterprise roadmap — [talk to the team](https://spreecommerce.org/enterprise/) if those matter to your timeline.
+
+## Managing companies as staff
+
+```typescript Admin SDK
+// Roots only
+const { data: roots } = await adminClient.companies.list({ parent_id_null: 1 })
+
+// Children of one node
+const { data: children } = await adminClient.companies.list({ parent_id_eq: 'comp_xxx' })
+
+const division = await adminClient.companies.create({
+ name: 'Sales',
+ kind: 'division',
+ parent_id: 'comp_xxx',
+})
+```
+
+Moving a branch is an update with a new `parent_id`. Deleting a node removes its whole subtree, and is refused outright once any order exists beneath it — history doesn't get deleted to tidy up an org chart.
+
+## Related
+
+- [Catalogs](/developer/core-concepts/catalogs) — giving a company its own range and prices
+- [Customers](/developer/core-concepts/customers) — the accounts memberships are built on
+- [Taxes](/developer/core-concepts/taxes) — registrations and exemptions
+- [Orders](/developer/core-concepts/orders) — company purchases
diff --git a/docs/developer/core-concepts/media.mdx b/docs/developer/core-concepts/media.mdx
index 315d1b1ab5..807929f215 100644
--- a/docs/developer/core-concepts/media.mdx
+++ b/docs/developer/core-concepts/media.mdx
@@ -1,14 +1,90 @@
---
title: Media
sidebarTitle: "Media"
-description: Manage product media in Spree — images, hosted and external video, named variants, focal points, and how media is uploaded, resized, and served via the Store API.
+description: The store-wide media library — uploading once and reusing everywhere, images and video, focal points, and how files are resized and served.
---
## Overview
-Spree handles uploads, processing, and delivery for product media. Images are automatically converted to WebP format and preprocessed into multiple sizes for optimal performance.
+Spree handles uploading, processing and serving the images and video a store shows. Files are converted to WebP and preprocessed into several sizes, so a listing page isn't downloading full-resolution photographs.
-## Product Media
+Files live in a **store-wide media library**. A file is uploaded once and can then be placed wherever it's needed — on a product, on a category, inside a description — without being uploaded again.
+
+```mermaid
+flowchart LR
+ Upload["Upload once"] --> Library["Media library"]
+ Library --> P["On a product"]
+ Library --> C["On a category"]
+ Library --> D["Inside a description"]
+```
+
+## The media library
+
+Every file in a store is in the library, whether or not it's currently placed on anything. That means a file can be uploaded ahead of time, browsed, searched, and reused.
+
+```typescript Admin SDK
+// Browse everything in the store
+const { data: media } = await adminClient.media.list()
+
+// Where is this file being used?
+const { data: usage } = await adminClient.media.usage('med_xxx')
+```
+
+| Field | What it tells you |
+|---|---|
+| `attached` | Whether the file is placed on anything yet |
+| `filename`, `content_type`, `byte_size` | What the file actually is |
+| `viewable_type` / `viewable_id` | What it's placed on, if anything |
+| `media_type` | `image`, `video` or `external_video` |
+| `alt` | Alt text, for accessibility and SEO |
+| `position` | Order within a gallery |
+
+### Reuse shares the file, not the record
+
+Placing a library file on a product creates a **new media row that shares the same underlying file**:
+
+```typescript Admin SDK
+await adminClient.products.media.create('prod_xxx', {
+ source_media_id: 'med_xxx',
+ alt: 'Worn over a navy jumper',
+ position: 2,
+})
+```
+
+The copy gets its own alt text, its own position, and its own variant links — because the same photograph might be the third image on one product and the hero on another, with different alt text describing what matters in each context. What it doesn't get is a second copy of the bytes.
+
+<Note>
+This is why there's no single "shared asset" record to manage. Each placement is independently editable, while storage is shared. Detaching a photo from one product has no effect on any other.
+</Note>
+
+### Deleting, safely
+
+A file in use can't be deleted by accident:
+
+```typescript Admin SDK
+// Returns 422 with the list of places it's used
+await adminClient.media.delete('med_xxx')
+
+// Remove it from everywhere, then delete
+await adminClient.media.delete('med_xxx', { detach: true })
+```
+
+The dashboard shows you the usage list and asks before doing the second one. Check `usage` before offering a delete in your own tooling.
+
+## What can carry media
+
+| Owner | Typical use |
+|---|---|
+| **Product** | The main gallery |
+| **Variant** | Images specific to one colour or size |
+| **Category** | A banner or tile for a navigation page |
+| **Collection** | The same, for a merchandising group |
+
+Categories and collections also have simple `image` and `square_image` slots. Setting one places the file; clearing it **removes the placement but keeps the file in the library**, so nothing is destroyed by tidying up a page.
+
+Sellers and stores keep their branding as plain attachments — a logo isn't merchandising, and it doesn't belong in a library people browse for product photos.
+
+## Product media
A media record carries:
@@ -19,9 +95,9 @@ A media record carries:
- **Preprocessed named variants** for fast delivery
- **`variant_ids`** — which product variants the media represents. An empty array means it represents the product as a whole.
-### Product-level Gallery
+### Product-level gallery
-In Spree 5.5 the **product** is the default owner of media. Before 5.5, every image was pinned to a specific variant (usually the master), and sharing the same image across variants meant re-uploading the file. From 5.5 onward, an image lives on the product, and any subset of variants can reference it through `variant_ids` — without duplicating the underlying file.
+Media belongs to the **product**, and any subset of its variants can reference the same file through `variant_ids` — so one photograph can represent three colourways without being uploaded three times.
#### Uploading a product-level image
@@ -341,9 +417,52 @@ curl 'https://api.mystore.com/api/v3/store/products/spree-tote?expand=media,vari
| `poster_url` | string \| null | Still frame for a video |
| `original_url` | string \| null | Full-size image URL (inline disposition) |
| `mini_url` ... `xlarge_url` | string \| null | Named variant URLs |
-| `download_url` | string \| null | Same blob as `original_url` but with `Content-Disposition: attachment`. Admin API only. |
-## Image Processing
+The Admin API adds the fields the library needs:
+
+| Field | Type | Description |
+|---|---|---|
+| `attached` | boolean | Whether the file is placed on anything, or sitting unused in the library |
+| `viewable_type` / `viewable_id` | string \| null | What it's placed on — `product`, `variant`, `category`, `collection` |
+| `filename`, `content_type`, `byte_size` | | What the file actually is |
+| `embed_url` | string \| null | The rendition used inside rich text — sized to fit, not cropped |
+| `signed_id` | string \| null | Lets a plain attachment field adopt this file without re-uploading |
+| `download_url` | string \| null | The same file with `Content-Disposition: attachment` |
+
+<Note>
+Two behaviours to expect when rendering a gallery:
+
+**`original_url` is null for any playable video** — there's no still image to size. Use `poster_url`.
+
+**A video's sized URLs come from its poster.** If a video has a poster, every `*_url` resolves from that frame, so a grid of mixed images and video renders uniformly.
+</Note>
+
+## Images in descriptions
+
+Rich text fields — a product description, a category's copy — can carry embedded images. In the dashboard, the editor opens the media library so a merchant picks an existing file or uploads a new one.
+
+Embedded images use their own rendition, sized to fit rather than cropped to a square. A size chart or a diagram keeps its proportions, where a gallery thumbnail would have had its edges cut off.
+
+<Warning>
+An embedded image is a plain image URL in the HTML — nothing records which description uses which file.
+
+Spree's usage check does its best by searching descriptions for the file, but it can't be exhaustive. Deleting a library file can leave a broken image in a description, so treat the usage list as a warning rather than proof a file is unused.
+</Warning>
+
+## Who can manage media
+
+Media is its own permission, separate from products:
+
+| Action | Requires |
+|---|---|
+| A product's own gallery — add, reorder, remove | Permission to edit **products** |
+| Browsing the library, checking usage, deleting a file outright | **Media** permission |
+
+The reasoning: reaching a file through a product you can already edit isn't the same as enumerating every file in the store. Someone who manages one product's photos shouldn't automatically be able to browse — or delete — everything the business has ever uploaded.
+
+Note the asymmetry that follows. Removing an image from a product removes the *placement* and needs only product permission; deleting the file everywhere is a library action and needs the media key.
+
+## Image processing
Spree uses [libvips](https://www.libvips.org/) for image processing. Images are automatically:
diff --git a/docs/developer/core-concepts/products.mdx b/docs/developer/core-concepts/products.mdx
index 5472521146..5d64fb6ebe 100644
--- a/docs/developer/core-concepts/products.mdx
+++ b/docs/developer/core-concepts/products.mdx
@@ -5,12 +5,14 @@ description: How Spree models products, variants, option types, images, prices,
## Overview
-A product represents something you sell. Each product has one or more **variants** — the actual purchasable items with their own SKU, price, and inventory. For example, a "T-Shirt" product might have variants for each size and color combination.
+A product is the listing a customer browses. A **variant** is the thing they actually buy.
-Products are organized into **categories** — a flexible hierarchy for grouping products. Categories can be filtered, sorted, and searched via the Store API.
+That split runs through everything on this page. The product holds what's shared — name, description, images, which categories it's filed under. Each variant holds what differs — its SKU, its price, its stock. A T-shirt is one product; small navy is a variant.
+
+**Every product has at least one variant**, even when there's nothing to choose. A book with no size or colour still has a single variant carrying its SKU, price and stock; you just never render a picker.
<Info>
-Product names, descriptions, slugs, and SEO fields are [translatable](/developer/core-concepts/translations#resource-translations).
+Product names, descriptions, slugs and SEO fields are [translatable](/developer/core-concepts/translations#resource-translations).
</Info>
```mermaid
@@ -61,21 +63,26 @@ erDiagram
## Product Attributes
| Attribute | Description | Translatable |
-|-----------|-------------|:---:|
+|---|---|:---:|
| `name` | Product name | Yes |
-| `description` | Full product description | Yes |
-| `slug` | URL-friendly identifier (e.g., `spree-tote`) | Yes |
-| `status` | `draft`, `active`, or `archived`. A marketplace adds `proposed` and `rejected` — see Seller submissions below | No |
-| `available_on` | Date the product becomes available for sale | No |
-| `discontinue_on` | Date the product is no longer available | No |
-| `meta_title` | Custom SEO title | Yes |
-| `meta_description` | SEO description | Yes |
-| `meta_keywords` | SEO keywords | Yes |
-| `purchasable` | Whether the product can be added to cart | No |
-| `in_stock` | Whether any variant has stock available | No |
-| `price` | Default variant's price in the current currency | No |
-| `thumbnail_url` | URL to the product's first image — always returned, no expand needed | No |
-| `tags` | Array of tag strings for filtering | No |
+| `description` / `description_html` | Description as plain text and as formatted HTML | Yes |
+| `slug` | URL identifier, e.g. `spree-tote` | Yes |
+| `status` | `draft`, `active` or `archived`. A marketplace adds `proposed` and `rejected` — see [Seller submissions](#seller-submissions) | No |
+| `available_on` | When it goes on sale | No |
+| `discontinue_on` | When it comes off | No |
+| `meta_title` / `meta_description` / `meta_keywords` | SEO fields | Yes |
+| `purchasable` | Whether it can be added to a cart | No |
+| `in_stock` | Whether any variant has stock | No |
+| `backorderable` | Whether it can be ordered while out of stock | No |
+| `preorder` / `preorder_ships_at` | Whether it's sold ahead of availability, and when it ships | No |
+| `available` | Whether it's on sale right now, by date and status | No |
+| `price` / `original_price` | The [default variant's](#the-default-variant) price, and its compare-at price | No |
+| `default_variant_id` | Which variant represents the product | No |
+| `variant_count` | How many variants it has | No |
+| `thumbnail_url` | First image — always returned, no expand needed | No |
+| `tags` | Tags, for filtering | No |
+
+The Admin API adds the operational fields on top: `product_type_id`, `delivery_profile_id`, `tax_category_id`, `seller_id`, `metadata`, `created_at` / `updated_at` / `deleted_at`.
## Listing Products
@@ -166,19 +173,21 @@ Pass `expand` to include related resources in a single response — see [expand
The examples above use the **Store API** (publishable key, read-only, customer-facing). To **create and manage** products, use the [Admin API](/api-reference/admin-api/introduction) — via the [Admin SDK](/developer/sdk/admin/quickstart) or the [Spree CLI](/developer/cli/admin-api).
-A product's purchasable attributes (SKU, prices, stock) live on its **variants**, which you can create inline:
+A product's purchasable attributes (SKU, prices, stock) live on its **variants**, which you can create inline.
+
+For a product with options, send the variants:
<CodeGroup>
```typescript Admin SDK
import { createAdminClient } from '@spree/admin-sdk'
-const client = createAdminClient({
+const adminClient = createAdminClient({
baseUrl: 'https://store.example.com',
secretKey: 'sk_xxx',
})
-const product = await client.products.create({
+const product = await adminClient.products.create({
name: 'Premium T-Shirt',
description: 'Soft, organic cotton.',
status: 'active',
@@ -190,7 +199,7 @@ const product = await client.products.create({
{ name: 'color', value: 'navy' },
],
prices: [{ currency: 'USD', amount: '29.99' }],
- stock_items: [{ stock_location_id: 'sloc_xxx', count_on_hand: 50 }],
+ stock_levels: [{ stock_location_id: 'sloc_xxx', count_on_hand: 50 }],
},
],
})
@@ -210,6 +219,18 @@ spree api post /products -d '{
</CodeGroup>
+For something with no options at all, send prices directly and skip the variants array — Spree forwards them to the product's single variant:
+
+```typescript Admin SDK
+await adminClient.products.create({
+ name: 'The Spree Handbook',
+ status: 'active',
+ prices: [{ currency: 'USD', amount: '19.99' }],
+})
+```
+
+Don't pass both.
+
Update, clone, or archive a product (deleting soft-deletes it):
<CodeGroup>
@@ -421,29 +442,56 @@ curl 'https://api.mystore.com/api/v3/store/products/filters?category_id=ctg_xxx'
## Variants
-Variants are the purchasable units of a product. Each variant has its own SKU, price, inventory, and images, and is defined by a unique combination of option values.
+**A product is not the thing you buy — a variant is.** The product is the listing; the variant is the actual item with a SKU, a price and stock.
+
+That distinction is worth holding onto, because everything purchasable lives on the variant:
| Attribute | Description |
-|-----------|-------------|
-| `sku` | Unique stock keeping unit |
-| `barcode` | Barcode (UPC, EAN, etc.) |
+|---|---|
+| `sku` | Stock keeping unit |
+| `barcode` | Barcode — UPC, EAN and so on |
| `price` | Price in the current currency |
-| `original_price` | Compare-at price for showing discounts |
-| `weight`, `height`, `width`, `depth` | Dimensions for shipping calculations |
-| `in_stock` | Whether stock is available |
-| `backorderable` | Whether the variant can be ordered when out of stock |
-| `option_values` | The option values that define this variant (e.g., Size: Small, Color: Red) |
+| `original_price` | Compare-at price, for showing a reduction |
+| `weight`, `height`, `width`, `depth` | Used for delivery rates and labels |
+| `in_stock` / `purchasable` | Whether it can be bought right now |
+| `backorderable` | Whether it can be ordered while out of stock |
+| `preorder` / `preorder_ships_at` | Whether it's sold ahead of availability |
+| `option_values` | What distinguishes it — Size: Small, Colour: Red |
+| `options_text` | Those values as one readable string |
+| `track_inventory` | Whether stock is counted at all |
+
+Variants also carry the customs attributes — `hs_code`, `country_of_origin`, `customs_description` — used when a parcel crosses a border. See [Fees](/developer/core-concepts/fees#customs-classification).
+
+### Every product has at least one variant
+
+There's no such thing as a product without one. A book with no size or colour still has a single variant holding its SKU, price and stock — you simply never show a picker for it.
+
+<Note>
+Earlier versions of Spree had a special "master variant" alongside the real ones, which meant every query had to remember to exclude it. **That concept is gone.** A product's variants are all real, all purchasable, and all the same kind of thing.
+</Note>
+
+### The default variant
+
+`default_variant_id` names the variant that represents the product — the price shown on a listing page, and what "add to cart" means before anyone picks anything.
+
+```typescript Store SDK
+const product = await client.products.get('spree-tote')
+
+product.default_variant_id // "var_xxx"
+product.price // that variant's price
+product.variant_count // 6
+```
-### Master Variant
+For a single-variant product that's the only variant. For a product with options it's the first one, unless you say otherwise. If the default is ever removed, another is promoted automatically — a product is never left without one.
-Every product has a **master variant** that holds default pricing and inventory. If a product has no option types (e.g., a book with no size/color), the master variant is the only purchasable variant.
+Products can also carry `buy_box_variant_id`, naming the variant a marketplace has chosen to feature when several sellers offer the same listing.
-### Regular Variants
+### Options make variants
-When a product has option types, each unique combination of option values creates a variant. For example, a T-shirt with sizes (S, M, L) and colors (Red, Green) has 6 variants:
+A product with option types has one variant per combination. A T-shirt in three sizes and two colours is six variants:
-| SKU | Size | Color |
-|-----|------|-------|
+| SKU | Size | Colour |
+|---|---|---|
| `TEE-S-R` | Small | Red |
| `TEE-S-G` | Small | Green |
| `TEE-M-R` | Medium | Red |
@@ -451,21 +499,19 @@ When a product has option types, each unique combination of option values create
| `TEE-L-R` | Large | Red |
| `TEE-L-G` | Large | Green |
-The product's `default_variant_id` points to the first non-master variant (or the master variant if none exist).
-
-Add a variant to an existing product via the Admin API (SKU, prices, and stock all live on the variant):
+Adding one to an existing product:
<CodeGroup>
```typescript Admin SDK
-const variant = await client.products.variants.create('prod_xxx', {
+await adminClient.products.variants.create('prod_xxx', {
sku: 'TEE-L-R',
options: [
{ name: 'size', value: 'Large' },
{ name: 'color', value: 'Red' },
],
prices: [{ currency: 'USD', amount: '24.99' }],
- stock_items: [{ stock_location_id: 'sloc_xxx', count_on_hand: 30 }],
+ stock_levels: [{ stock_location_id: 'sloc_xxx', count_on_hand: 30 }],
})
```
@@ -479,6 +525,8 @@ spree api post /products/prod_xxx/variants -d '{
</CodeGroup>
+Options are named by value rather than by ID, so you don't have to look up an option value before creating a variant that uses it.
+
## Option Types and Option Values
Option types define the axes of variation for a product (e.g., Size, Color, Material). Option values are the specific choices within each type (e.g., Small, Medium, Large).
@@ -549,9 +597,80 @@ spree api post /option_types -d '{
</CodeGroup>
+## Product Types
+
+Merchants who sell more than one kind of thing end up repeating themselves. Every pair of shoes needs Size and Colour, belongs under Footwear, and wants a Material field. Every book needs an ISBN and an author.
+
+A **product type** captures that once. Creating a product from a type gives it the right option types, the right categories, the right delivery profile, and a form asking for the fields that kind of product actually needs.
+
+```mermaid
+erDiagram
+ ProductType ||--o{ Product : "creates"
+ ProductType }o--o{ OptionType : "seeds"
+ ProductType }o--o{ Category : "seeds"
+ ProductType }o--o{ CustomFieldDefinition : "asks for"
+ ProductType }o--o| DeliveryProfile : "ships by"
+
+ ProductType {
+ string name
+ integer products_count
+ }
+```
+
+```typescript Admin SDK
+const shoes = await adminClient.productTypes.create({
+ name: 'Footwear',
+ option_type_ids: ['optt_size', 'optt_color'],
+ category_ids: ['ctg_footwear'],
+ delivery_profile_id: 'dp_standard',
+ custom_field_definitions: [
+ { id: 'cfdef_material', required: true, sort_order: 0 },
+ ],
+})
+
+await adminClient.products.create({
+ name: 'Trail Runner',
+ product_type_id: shoes.id,
+ status: 'draft',
+})
+```
+
+### A type is a template, not a controller
+
+This is the part that determines how you should think about them.
+
+<Warning>
+**Editing a product type never rewrites existing products.** Add an option type to Footwear next month and the shoes you created last month are untouched.
+</Warning>
+
+That's deliberate. A merchant who adds a field to a type is describing what *new* products should look like — not asking Spree to silently restructure a live catalogue, invalidate URLs, or change what customers can pick.
+
+So the pieces behave in two distinct ways:
+
+| Part of the type | Behaviour |
+|---|---|
+| Option types, categories, delivery profile | **Stamped at creation.** Copied onto the product, then independent |
+| Custom field definitions | **Live by reference.** The form always reflects the type as it is now |
+
+Seeding is also **additive** — it adds what's missing and never removes what a product already has. Reassigning a product's type is therefore safe: it seeds the new type's option types and categories alongside whatever was already there.
+
+If you *do* want an edited type to reach the products already using it, that's an explicit action:
+
+```typescript Admin SDK
+const { products_count } = await adminClient.productTypes.applyToProducts('pt_xxx')
+```
+
+It runs in the background and is additive like the rest — never a side effect of saving a type.
+
+<Info>
+`required` on a type's custom field is **advisory** — it marks the field in the dashboard but isn't enforced on write, since Spree saves the product and its fields in two steps. Validate in your own tooling if you need it enforced.
+</Info>
+
+A type in use can't be deleted; its products would lose the structure they were built from.
+
## Media
-Media can be attached to the product (via the master variant) or to individual variants. When displaying a product, show the images for the selected variant, falling back to the product-level images.
+Media can be attached to a product or to individual variants. When displaying a product, show the images for the selected variant, falling back to the product's own.
### Thumbnails
@@ -597,7 +716,7 @@ const product = await client.products.get('spree-tote', {
expand: ['media', 'variants'],
})
-// Product-level images (from master variant)
+// The product's own images
product.media // [{ original_url: "https://cdn.../tote-front.jpg", position: 1 }, ...]
// Each variant has its own thumbnail and media_count
diff --git a/docs/developer/core-concepts/sellers.mdx b/docs/developer/core-concepts/sellers.mdx
new file mode 100644
index 0000000000..762ca2aa8c
--- /dev/null
+++ b/docs/developer/core-concepts/sellers.mdx
@@ -0,0 +1,218 @@
+---
+title: Sellers
+description: Running a marketplace — vendors with their own catalog and panel, orders split per seller, and commission on every sale.
+---
+
+## Overview
+
+A marketplace sells things it doesn't own. Vendors list their own products, the marketplace takes a cut, and a shopper buying from three vendors at once expects one basket and one payment — not three checkouts.
+
+A **seller** is a vendor on your marketplace: their own products, their own staff, their own orders, and their own panel to work in.
+
+```mermaid
+flowchart TB
+ Customer["One customer, one payment"] --> Group["Order group"]
+ Group --> O1["Order — Seller A"]
+ Group --> O2["Order — Seller B"]
+ O1 --> F1["Seller A ships"]
+ O2 --> F2["Seller B ships"]
+
+ style Group fill:#e3f2fd,stroke:#0077ff
+```
+
+<Info>
+This is all open source. Sellers, product review, order splitting, commissions and the seller panel ship in the box — you don't need a commercial licence to run a marketplace on Spree.
+</Info>
+
+## The seller lifecycle
+
+A seller isn't simply created and switched on. Bringing a vendor onto a marketplace is a process with a decision at the end of it, and the status reflects where they are in it.
+
+```mermaid
+stateDiagram-v2
+ [*] --> pending
+ pending --> invited : marketplace invites them
+ invited --> onboarding : they accept
+ onboarding --> ready_for_review : they finish the checklist
+ ready_for_review --> approved : marketplace approves
+ ready_for_review --> rejected : sent back
+ rejected --> onboarding : they try again
+ approved --> suspended : paused
+ suspended --> approved : reinstated
+```
+
+| Status | Meaning |
+|---|---|
+| `pending` | Created, nothing sent yet |
+| `invited` | Invitation sent, not yet accepted |
+| `onboarding` | Working through the requirements |
+| `ready_for_review` | Waiting on the marketplace |
+| `approved` | Live — can sell |
+| `rejected` | Sent back, with a reason |
+| `suspended` | Paused, temporarily |
+| `canceled` | Gone |
+
+Only an **approved** seller can sell, and even then not while they're on holiday — sellers can pause their own listings without the marketplace suspending them.
+
+```typescript Admin SDK
+await adminClient.sellers.invite('sel_xxx')
+await adminClient.sellers.approve('sel_xxx')
+await adminClient.sellers.suspend('sel_xxx', { reason: 'Unresolved delivery complaints' })
+```
+
+Status is never set by writing to the field — each move is its own action, so approving a seller can run the checks that belong to approving.
+
+## Onboarding requirements
+
+What a vendor must do before selling differs by marketplace. A hardware marketplace wants insurance documents; a craft marketplace wants a filled-in profile and one product.
+
+So the checklist is **configured, not hardcoded**. Each store defines its own:
+
+```typescript Admin SDK
+const { data: types } = await adminClient.sellerRequirements.types()
+
+await adminClient.sellerRequirements.create({
+ type: 'Spree::SellerRequirements::MinimumProducts',
+ name: 'List at least three products',
+ required: true,
+ preferences: { minimum_count: 3 },
+})
+```
+
+Requirements come in three flavours, which is what lets one mechanism cover very different demands:
+
+| Kind | How it's satisfied |
+|---|---|
+| **Computed** | Automatically, from the seller's own data — a billing address exists, three products are listed |
+| **Attested** | The seller confirms something — accepting terms |
+| **Verified** | The seller submits something and the marketplace rules on it — a document, an operator review |
+
+Shipped out of the box: accepting terms, completing the profile, a billing address, a returns address, and a minimum number of products. Also available are generic document upload, attestation, operator review, and required custom fields.
+
+A seller sees their checklist and its progress:
+
+```typescript Seller SDK
+const onboarding = await sellerClient.onboarding.get()
+
+onboarding.progress // { done: 3, total: 5 }
+onboarding.requirements.forEach((r) => {
+ r.name // "Accept the seller terms"
+ r.status // complete | incomplete | pending | rejected
+ r.required // whether it blocks approval
+})
+
+await sellerClient.onboarding.submitForReview()
+```
+
+The checklist is **worked out when read**, never stored on the seller. So a requirement added next month applies immediately to everyone, and nothing has to be backfilled.
+
+<Note>
+The checklist is enforced at exactly two moments — submitting for review, and approval. Approval refuses while a required item is outstanding, unless an operator deliberately overrides it.
+
+Afterwards it's advisory. If a seller's insurance certificate lapses, that's flagged for the marketplace to act on; it does not silently stop their sales mid-trade.
+</Note>
+
+## Products belong to sellers
+
+A product can name a seller. No seller means it's the marketplace's own stock — a marketplace that also sells directly is a normal setup.
+
+Sellers don't publish; they **submit**, and the marketplace decides. That review flow, and the statuses behind it, are covered in [Products](/developer/core-concepts/products#seller-submissions).
+
+```typescript Seller SDK
+const product = await sellerClient.products.create({ name: 'Handmade Vase' })
+await sellerClient.products.submit(product.id)
+```
+
+Stores that trust their vendors can turn auto-approval on and skip the queue.
+
+## One checkout, several sellers
+
+This is the part that makes a marketplace different from a shop, and it's worth understanding before you build a storefront against it.
+
+A customer fills one basket, enters one address, and pays once. But each seller needs their own order — they fulfil separately, get paid separately, and must never see each other's business.
+
+So at completion, a checkout spanning several sellers becomes an **order group**: one container holding one order per seller.
+
+```mermaid
+erDiagram
+ OrderGroup ||--o{ Order : "one per seller"
+ OrderGroup ||--o{ Payment : "one payment"
+ Payment ||--o{ PaymentSplit : "apportioned"
+ Order }o--|| Seller : "belongs to"
+ Order ||--o{ Fulfillment : "shipped by that seller"
+```
+
+| Level | Owns |
+|---|---|
+| **Order group** | The customer, the addresses, the payment, the combined totals |
+| **Order** | One seller's items, fulfillments and money lines |
+
+The single payment is apportioned across the child orders as **payment splits**, so each seller's share of one charge is recorded exactly — which is what makes per-seller refunds and settlement possible later.
+
+Two details worth knowing:
+
+- **Group totals are added up, not divided.** The group's total is the sum of its children, so it always agrees with them.
+- **Delivery and order-level fees are shared out by item value**, so a seller whose goods made up most of the basket carries most of the delivery charge.
+
+<Warning>
+A storefront must handle the possibility of an order group. Completing a cart may yield one order or several, and a customer's order history should show the group as one purchase rather than confronting them with three orders they don't remember placing separately.
+</Warning>
+
+## Commission
+
+Commission is what the marketplace charges for the sale — configured as **rates**, and recorded per sale as immutable **commission lines**.
+
+```typescript Admin SDK
+const { data: lines } = await adminClient.commissionLines.list({
+ filter: { seller_id_eq: 'sel_xxx' },
+})
+```
+
+Three things are worth knowing here; the rest is on its own page.
+
+- **Rates are tried in list order**, and the first whose rules match wins. A rate with no rules matches everything, so the marketplace default belongs at the bottom.
+- **Commission is charged on the seller's net revenue by default**, after discounts and excluding the customer's tax.
+- **Commission tax follows the seller's jurisdiction**, not the shopper's — the marketplace is selling a service to the vendor, which is a separate supply from the vendor's sale to the customer.
+
+See [Commissions](/developer/core-concepts/commissions) for rate targeting, the four rule types, per-currency floors and caps, and how a fee is calculated and taxed.
+
+## Payouts
+
+Spree records what each seller earned and what the marketplace charged: the payment splits say what each seller's share of the money was, and the commission lines say what was deducted.
+
+<Warning>
+**Actually moving money to sellers is not implemented in open source.** There is no payout or transfer ledger here — a seller carries payout *preferences* (how often, and a minimum amount), but nothing acts on them.
+
+Paying vendors means connecting a provider such as Stripe Connect, or building against the payment splits and [commission lines](/developer/core-concepts/commissions). Scheduled payout runs, refund clawbacks, reconciliation and tax reporting are Enterprise features.
+</Warning>
+
+## The seller panel
+
+Sellers get their own application — not access to the marketplace's dashboard. It's a separate API with its own sign-in, and every request is scoped to the seller making it, so no endpoint even takes a seller ID.
+
+That last point is the security property worth relying on: a seller cannot ask for another seller's data, because there's nowhere in the request to name one.
+
+```typescript Seller SDK
+import { createSellerClient } from '@spree/seller-sdk'
+
+const sellerClient = createSellerClient({ baseUrl: 'https://marketplace.example.com' })
+
+await sellerClient.auth.login({ email: '[email protected]', password: '…' })
+
+const { data: orders } = await sellerClient.orders.list()
+await sellerClient.orders.fulfillments.fulfill(orderId, fulfillmentId, {
+ tracking: '1Z999AA10123456784',
+})
+```
+
+Sellers can manage their profile, invite their own team, list and submit products, see and fulfil their orders, manage their stock locations, and work through onboarding. They cannot see other sellers, the marketplace's own catalog, or anything belonging to the store at large.
+
+What a seller's staff may do is governed by [roles](/developer/core-concepts/staff-roles) owned by the seller — the same permission system as the back office, with a narrower set of keys, so a seller role can never reach store settings.
+
+## Related
+
+- [Commissions](/developer/core-concepts/commissions) — rates, rules, and what the marketplace charges
+- [Products](/developer/core-concepts/products#seller-submissions) — the listing review flow
+- [Orders](/developer/core-concepts/orders) — orders and their statuses
+- [Staff & Roles](/developer/core-concepts/staff-roles) — how seller teams are governed
+- [Seller API](/api-reference/seller-api/introduction) — the full endpoint reference
diff --git a/docs/developer/core-concepts/staff-roles.mdx b/docs/developer/core-concepts/staff-roles.mdx
index 9c568d3b1c..7770c84228 100644
--- a/docs/developer/core-concepts/staff-roles.mdx
+++ b/docs/developer/core-concepts/staff-roles.mdx
@@ -5,48 +5,83 @@ description: Manage Spree admin users, roles, invitations, and permissions — c
## Overview
-Admin users manage the store via the Admin Panel. They have roles that control what they can access.
+Staff manage a store through the dashboard and the Admin API. What each person can do is decided by the **roles** they hold.
```mermaid
erDiagram
- AdminUser ||--o{ RoleUser : "has many"
- RoleUser }o--|| Role : "belongs to"
- RoleUser }o--|| Store : "scoped to"
- AdminUser ||--o{ Invitation : "invites"
+ Store ||--o{ Role : "owns"
+ Seller ||--o{ Role : "owns"
+ Role ||--o{ RoleUser : "assigned through"
+ AdminUser ||--o{ RoleUser : "holds"
+ Role ||--o{ Invitation : "offered by"
- AdminUser {
- string id
- string email
+ Role {
+ string name
+ string description
+ json permissions
+ boolean mutable
}
-
RoleUser {
string role_id
- string resource_type
- string resource_id
- }
-
- Role {
- string name
+ string user_id
}
-
Invitation {
string email
string status
- string token
datetime expires_at
}
```
-## Roles
+Two things about that shape matter:
+
+**A role belongs to what it governs.** Every role names its owner — a Store for back-office staff, a [Seller](/developer/core-concepts/sellers) for a marketplace seller's own team. The owner is both who the role belongs to and who it applies to, so a role on a Store is a staff role by construction. Assigning someone a role therefore grants access to that owner and nothing else, which is what keeps one store's staff out of another's data.
+
+Because roles are scoped to their owner, two stores can each define a "Manager" without colliding.
+
+**A role carries its permissions directly.** The role holds a plain list of permission keys, so what a role can do is visible on the role itself rather than assembled from something else at runtime.
+
+## Roles and permissions
+
+A permission key is a verb and a resource — `read_orders`, `write_products`. Roles hold a list of them:
+
+```typescript Admin SDK
+const role = await adminClient.roles.create({
+ name: 'Fulfillment staff',
+ description: 'Can see orders and ship them, nothing else',
+ permissions: ['read_orders', 'write_fulfillments', 'read_products'],
+})
+```
+
+Every grantable key is discoverable, so a permission picker never needs a hardcoded list:
+
+```typescript Admin SDK
+const { data: permissions } = await adminClient.permissions.list()
+```
+
+Keys are grouped so they can be presented sensibly — orders, catalog, marketing, customers, settings, access and analytics.
+
+| Group | Covers |
+|---|---|
+| Orders | Orders, payments, fulfillments, refunds, gift cards, store credit |
+| Catalog | Products, media, categories, collections, stock, publishing |
+| Marketing | Promotions |
+| Customers | Customer accounts and groups |
+| Settings | Store settings, webhooks, integrations |
+| Access | API keys, staff, sellers, commissions |
+| Analytics | The dashboard |
+
+<Note>
+**The same vocabulary gates API keys.** A secret key's scopes come from this catalog too, so "what may this integration do" and "what may this person do" are described the same way — there is no second permission system to keep in step.
+</Note>
+
+### The admin role
-Admin users can have different roles that control their permissions:
+Each store gets one protected `admin` role meaning *everything in this store*. It can't be renamed, edited or deleted, and it isn't shared between stores — each owner has its own.
-| Role | Description |
-|------|-------------|
-| `admin` | Full access to all Admin Panel features |
+A role is deletable only when nothing depends on it: staff assignments and pending invitations have to be moved first, so nobody silently loses access.
<Info>
-You can create custom roles with specific permissions. See the [Customize Permissions guide](/developer/customization/permissions) for details.
+Roles are pure data. They're created through the dashboard, the Admin API, or seeds — there's no code-level role definition to keep in sync. For record-level rules beyond what keys express, see [Customize Permissions](/developer/customization/permissions).
</Info>
## Creating Admin Users
diff --git a/docs/developer/core-concepts/taxes.mdx b/docs/developer/core-concepts/taxes.mdx
index 18739a9ead..2abc766b7f 100644
--- a/docs/developer/core-concepts/taxes.mdx
+++ b/docs/developer/core-concepts/taxes.mdx
@@ -166,11 +166,11 @@ Whichever provider is in use, the result is the same: tax lines on the order, in
Business customers are often exempt, and the paperwork is real. Spree records a customer's or company's **tax identifier** — a VAT number, an ABN — and can validate it. Companies can also hold exemption certificates, scoped to the country or state that issued them.
-Exemption is decided when tax is worked out, not stored as a flag on the customer, so an expired certificate stops applying by itself. See [Companies & Catalogs](/developer/core-concepts/companies-and-catalogs).
+Exemption is decided when tax is worked out, not stored as a flag on the customer, so an expired certificate stops applying by itself. See [Companies](/developer/core-concepts/companies).
## Related
- [Order totals](/developer/core-concepts/order-totals) — how tax rolls into what a customer pays
- [Markets](/developer/core-concepts/markets) — where tax treatment and provider are chosen
- [Addresses](/developer/core-concepts/addresses) — what determines the rate
-- [Companies & Catalogs](/developer/core-concepts/companies-and-catalogs) — B2B tax identifiers and exemptions
+- [Companies](/developer/core-concepts/companies) — B2B tax identifiers and exemptions
diff --git a/docs/docs.json b/docs/docs.json
index f5fbb854f4..b03edd66a4 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -32,6 +32,10 @@
"library": "lucide"
},
"redirects": [
+ {
+ "source": "/developer/core-concepts/companies-and-catalogs",
+ "destination": "/developer/core-concepts/companies"
+ },
{
"source": "/developer/core-concepts/taxes-discounts-fees",
"destination": "/developer/core-concepts/order-totals"
@@ -484,6 +488,8 @@
"developer/core-concepts/channels",
"developer/core-concepts/markets",
"developer/core-concepts/customers",
+ "developer/core-concepts/companies",
+ "developer/core-concepts/sellers",
"developer/core-concepts/staff-roles"
]
},
@@ -492,7 +498,7 @@
"pages": [
"developer/core-concepts/products",
"developer/core-concepts/pricing",
- "developer/core-concepts/companies-and-catalogs",
+ "developer/core-concepts/catalogs",
"developer/core-concepts/inventory",
"developer/core-concepts/media",
"developer/core-concepts/search-filtering"
@@ -508,6 +514,7 @@
"developer/core-concepts/taxes",
"developer/core-concepts/discounts",
"developer/core-concepts/fees",
+ "developer/core-concepts/commissions",
"developer/core-concepts/promotions",
"developer/core-concepts/store-credits-gift-cards"
]
@@ -1854,6 +1861,8 @@
"developer/core-concepts/channels",
"developer/core-concepts/markets",
"developer/core-concepts/customers",
+ "developer/core-concepts/companies",
+ "developer/core-concepts/sellers",
"developer/core-concepts/staff-roles"
]
},
@@ -1863,7 +1872,7 @@
"pages": [
"developer/core-concepts/products",
"developer/core-concepts/pricing",
- "developer/core-concepts/companies-and-catalogs",
+ "developer/core-concepts/catalogs",
"developer/core-concepts/inventory",
"developer/core-concepts/media",
"developer/core-concepts/search-filtering"
@@ -1880,6 +1889,7 @@
"developer/core-concepts/taxes",
"developer/core-concepts/discounts",
"developer/core-concepts/fees",
+ "developer/core-concepts/commissions",
"developer/core-concepts/promotions",
"developer/core-concepts/store-credits-gift-cards"
]
diff --git a/package.json b/package.json
index 726708e68e..82d98b6680 100644
--- a/package.json
+++ b/package.json
@@ -19,10 +19,13 @@
"server:build": "bash scripts/server-build.sh",
"server:restart": "SPREE_PATH=$PWD docker compose -f server/docker-compose.dev.yml -f scripts/docker-compose.edge.yml restart web",
"server:stop": "SPREE_PATH=$PWD docker compose -f server/docker-compose.dev.yml -f scripts/docker-compose.edge.yml -f scripts/docker-compose.meilisearch.yml down",
+ "server:teardown": "bash scripts/server-teardown.sh",
"server:console": "cd server && spree console",
"server:logs": "cd server && spree logs",
"server:seed": "cd server && spree rails db:seed",
"server:load_sample_data": "cd server && spree task load_sample_data",
+ "dashboard:dev": "turbo build --filter='@spree/dashboard-starter^...' && pnpm --dir packages/dashboard-starter dev --port 5173 --strictPort",
+ "seller:dev": "turbo build --filter='@spree/seller-dashboard-starter^...' && pnpm --dir packages/seller-dashboard-starter dev --port 5174 --strictPort",
"wt:setup": "scripts/worktree/setup.sh",
"wt:template": "scripts/worktree/make-template.sh",
"wt:dev": "scripts/worktree/dev.sh",
@@ -30,6 +33,7 @@
"wt:seller": "scripts/worktree/dev-seller.sh",
"wt:storefront": "scripts/worktree/dev-storefront.sh",
"wt:e2e": "scripts/worktree/e2e.sh",
+ "docs:dev": "cd docs && mint dev --port 3333",
"changeset": "changeset",
"version:preview": "changeset version --ignore @spree/sdk"
},
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index f3a5ca5eb7..3a11262926 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -681,6 +681,13 @@ export interface ProductCreateParams {
slug?: string
status?: 'draft' | 'active' | 'archived'
tax_category_id?: string
+ /**
+ * Product type this product is created from (pt_...). A creation-time
+ * template: its option types and categories seed onto the product and its
+ * custom-field definitions drive the product's form. Editing the type later
+ * never rewrites existing products.
+ */
+ product_type_id?: string | null
/** Fulfillment profile deciding how this product ships (fp_...); null falls back to the store default. */
delivery_profile_id?: string | null
category_ids?: Array<string>
@@ -712,6 +719,8 @@ export interface ProductUpdateParams {
slug?: string
status?: 'draft' | 'active' | 'archived'
tax_category_id?: string
+ /** See `ProductCreateParams.product_type_id`. Reassigning is non-destructive. */
+ product_type_id?: string | null
/** See `ProductCreateParams.delivery_profile_id`. */
delivery_profile_id?: string | null
category_ids?: Array<string>
diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.ts
index 8b7fb8c9a8..182b45b149 100644
--- a/packages/sdk/src/types/index.ts
+++ b/packages/sdk/src/types/index.ts
@@ -233,8 +233,8 @@ export interface UpdateCartParams {
items?: LineItemInput[]
/**
* The company node this purchase is for. The buyer must have standing over
- * it; null clears it, and with it the company's catalog, pricing and tax
- * anchoring.
+ * it — a membership on that node or one of its ancestors. Null clears it,
+ * and with it the company's catalog, pricing and tax anchoring.
*/
company_id?: string | null
}
diff --git a/scripts/docker-compose.edge.yml b/scripts/docker-compose.edge.yml
index 1c2b034e46..32d5e33a0f 100644
--- a/scripts/docker-compose.edge.yml
+++ b/scripts/docker-compose.edge.yml
@@ -24,15 +24,16 @@ services:
# SPREE_PATH (e.g. `..` for the native bin/dev flow); the overlay-set
# value here wins because `environment:` beats `env_file:` in Compose.
#
- # SPREE_DASHBOARD_DIST_PATH: the monorepo mount already contains the
- # dashboard-starter's build output, so the spree_dashboard gem serves it
- # at /dashboard (single-node topology) with zero copying — run
- # `pnpm server:dashboard` to (re)build the dist; changes are served
- # immediately (the gem reads files per request, no restart). Until a
- # build exists the directory is absent and /dashboard responds 404.
+ # The React dashboard and seller panel are NOT served through Rails in
+ # this flow — the spree_dashboard gem's dist hosting is a production
+ # (single-node) topology, and a static build goes stale on every git
+ # pull. Run them as their own dev servers instead: `pnpm dashboard:dev`
+ # and `pnpm seller:dev` (both proxy /api to localhost:3000 by default).
+ # To test the hosted path deliberately, build a dist (`pnpm
+ # server:dashboard` / `pnpm server:seller`) and set
+ # SPREE_DASHBOARD_DIST_PATH / SPREE_SELLER_PANEL_DIST_PATH here yourself.
environment:
SPREE_PATH: ${SPREE_PATH}
- SPREE_DASHBOARD_DIST_PATH: ${SPREE_PATH}/packages/dashboard-starter/dist
volumes:
- ${SPREE_PATH}:${SPREE_PATH}
# Hard-bypass the starter's bin/docker-entrypoint, which auto-runs
diff --git a/scripts/server-setup.sh b/scripts/server-setup.sh
index fe192cca8f..4e699d991b 100755
--- a/scripts/server-setup.sh
+++ b/scripts/server-setup.sh
@@ -3,16 +3,14 @@
# load Spree gems from the monorepo (edge mode).
#
# Sequence:
-# 1. Tear down any prior stack + volumes (clean slate, even after a failed run)
-# 2. Force-remove ./server/ if it exists (Docker bind-mounted files end up
-# owned by UID 1000 inside the container; on macOS Docker Desktop maps
-# this to the host user, but we still need elevated rm if a prior run
-# left files in odd states).
-# 3. Clone spree-starter into server/
-# 4. Write server/.env with SPREE_PATH=.. (for the native bin/dev path —
+# 1. Tear down any prior stack + volumes and remove ./server/ (via
+# server-teardown.sh — clean slate, even after a failed run; also
+# available standalone as `pnpm server:teardown`)
+# 2. Clone spree-starter into server/
+# 3. Write server/.env with SPREE_PATH=.. (for the native bin/dev path —
# Docker edge flow overrides via compose env) + a fresh SECRET_KEY_BASE
-# 5. Build @spree/cli so `pnpm exec spree …` works in server/
-# 6. Start the edge stack and wait for it to finish booting. The edge web
+# 4. Build @spree/cli so `pnpm exec spree …` works in server/
+# 5. Start the edge stack and wait for it to finish booting. The edge web
# boot command (scripts/docker-compose.edge.yml) does the heavy lifting
# itself — bundle install against the monorepo gems (rewrites
# Gemfile.lock with the PATH block), spree:install:migrations, and
@@ -36,17 +34,7 @@ SERVER_DIR="$ROOT/server"
step() { printf '\n→ %s\n' "$1"; }
-step "Tearing down any prior stack (this also wipes the dev volumes)"
-# Reference the project by name (-p server) rather than via compose files,
-# so this works even after a prior run deleted ./server/. Orphan volumes
-# from a partially-failed prior run (server_bundle_cache, etc.) cause
-# `failed to mkdir /var/lib/docker/volumes/.../ruby: file exists` on the
-# next `up` if we don't wipe them here.
-docker compose -p server down -v --remove-orphans 2>/dev/null || true
-
-step "Removing any prior $SERVER_DIR"
-# Volumes are now released; bind-mounted files are accessible to rm again.
-rm -rf "$SERVER_DIR"
+bash "$ROOT/scripts/server-teardown.sh" --no-hint
step "Cloning spree-starter into server/ (branch: ${SPREE_STARTER_BRANCH:-6-0-dev})"
git clone --depth 1 --branch "${SPREE_STARTER_BRANCH:-6-0-dev}" https://github.com/spree/spree-starter.git "$SERVER_DIR"
@@ -58,15 +46,6 @@ printf 'SPREE_PATH=..\nSECRET_KEY_BASE=%s\n' "$(openssl rand -hex 64)" > "$SERVE
step "Building @spree/cli (so node ../packages/cli/dist/index.js works)"
pnpm --filter @spree/cli build
-step "Building the React Dashboard (served at /dashboard via spree_dashboard)"
-# The edge overlay points SPREE_DASHBOARD_DIST_PATH at this build output
-# through the monorepo mount — no copying, and rebuilds (`pnpm
-# server:dashboard`) are served immediately. Non-fatal: the backend works
-# without it (/dashboard just 404s until a build exists).
-if ! VITE_BASE_PATH=/dashboard/ pnpm --dir "$ROOT/packages/dashboard-starter" build; then
- echo " ⚠ dashboard build failed — continuing; run 'pnpm server:dashboard' later."
-fi
-
step "Starting the edge stack"
# Detached on purpose — `pnpm server:dev` runs the stack in the foreground
# (streaming logs, Ctrl+C to stop); setup needs to continue past the boot.
@@ -97,4 +76,21 @@ until code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 2 http://localho
elapsed=$((elapsed + 3))
done
-printf '\nServer ready: http://localhost:3000\nAdmin: http://localhost:3000/admin\nDashboard: http://localhost:3000/dashboard\n\n'
+step "Fetching the one-time first-run setup link"
+# The seed announces the setup URL, but during this flow that lands in the
+# detached container's logs where nobody sees it. Ask the running app to
+# print it again. The task refuses once an admin account exists (e.g.
+# ADMIN_EMAIL/ADMIN_PASSWORD were set at seed time), so an empty result is
+# informational, not an error.
+SETUP_URL="$(SPREE_PATH="$ROOT" docker compose -f "$DEV_COMPOSE" -f "$EDGE_OVERLAY" exec -T web bin/rails spree:setup:token 2>/dev/null | tr -d '\r' | grep -oE 'https?://[^[:space:]]+' | tail -1 || true)"
+
+printf '\nBackend ready: http://localhost:3000\n\n'
+printf 'The React dashboard and seller panel run as their own dev servers:\n'
+printf ' pnpm dashboard:dev # admin dashboard → http://localhost:5173\n'
+printf ' pnpm seller:dev # seller panel → http://localhost:5174\n\n'
+if [ -n "$SETUP_URL" ]; then
+ printf 'Then create the first admin account (one-time link, needs dashboard:dev running):\n %s\n\n' "$SETUP_URL"
+ printf 'Print it again later with:\n SPREE_PATH="$PWD" docker compose -f %s -f %s exec web bin/rails spree:setup:token\n\n' "$DEV_COMPOSE" "$EDGE_OVERLAY"
+else
+ printf 'No first-run setup link — an admin account already exists. Sign in at the dashboard.\n\n'
+fi
diff --git a/scripts/server-teardown.sh b/scripts/server-teardown.sh
new file mode 100755
index 0000000000..d3c210df42
--- /dev/null
+++ b/scripts/server-teardown.sh
@@ -0,0 +1,33 @@
+#!/usr/bin/env bash
+# server-teardown.sh — remove the ./server/ development backend entirely:
+# stop the Docker stack, wipe its volumes (database, bundle cache), and
+# delete the server/ directory. Recreate from scratch with `pnpm server:setup`.
+#
+# Safe to run from any state — a missing stack or directory is a no-op.
+# This is also the first phase of server-setup.sh (which passes --no-hint),
+# so a partially-failed prior run never blocks a fresh one.
+
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+cd "$ROOT"
+
+SERVER_DIR="$ROOT/server"
+
+step() { printf '\n→ %s\n' "$1"; }
+
+step "Tearing down the Docker stack (containers + volumes)"
+# Reference the project by name (-p server) rather than via compose files,
+# so this works even after a prior run deleted ./server/. Orphan volumes
+# from a partially-failed run (server_bundle_cache, etc.) cause
+# `failed to mkdir /var/lib/docker/volumes/.../ruby: file exists` on the
+# next `up` if we don't wipe them here.
+docker compose -p server down -v --remove-orphans 2>/dev/null || true
+
+step "Removing $SERVER_DIR"
+# Volumes are now released; bind-mounted files are accessible to rm again.
+rm -rf "$SERVER_DIR"
+
+if [ "${1:-}" != "--no-hint" ]; then
+ printf '\nDone. Recreate from scratch with: pnpm server:setup\n'
+fi