Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Document the company tree and catalogs, and seed them into the wholesale demo
Damian Legawiec527a12283371
diff --git a/CLAUDE.md b/CLAUDE.mdindex ad276664a9..4bdbe51b8a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -28,7 +28,7 @@ Active plans (6.0 target, work pending):- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain. **COMPLETE (2026-08-05):** all three entities (+ permanent `ReturnLineItem`/`ExchangeLineItem`/`ClaimLineItem` line items), `Spree::HasStatus`, all fifteen workflows (each with a leading `validate` hook), `Refund#originator`, admin + store v3 APIs (transitions as PATCH member actions; no destroy — cancel instead), dashboard pages. Legacy chain **removed**: ReturnAuthorization/CustomerReturn/Reimbursement/ReimbursementType/legacy ReturnItem + eligibility validators + ReturnsCalculator classes all deleted, but their **tables deliberately survive to 6.1** as the data migration's source and rollback path. `spree:upgrade:migrate_returns` (`Spree::ReturnsMigrator`, defined in the rake file like its sibling upgrade tasks; anonymous-AR readers) is in the 5.6→6.0 manifest after the adjustments step; it needs no cursor because the preserved `number` is uniquely indexed on the new tables, so "what's left" is a `where.not(number: ...)` query and an interrupted run resumes for free. `ReturnAuthorizationReason`→`ReturnReason` (alias one release) + new `ClaimReason`; `Metafields` on all three. Capability replacements: `Spree::ReturnMailer#refunded_email` on `return.refunded` (replaces the reimbursement email), `Order#outstanding_balance` drops the reimbursement term (refunds already net out of `payment_total`), `Return#refunded_total` counts store credits too, store credit issued with `originator` + `memo` only (categories dropped 2026-08-18). **Reasons** ship admin-only CRUD (`/api/v3/admin/{return,claim,refund}_reasons`, `settings` scope) + a combined Settings → Reasons dashboard page + reason pickers on the create dialogs; `mutable` is never client-writable and the immutability guard lives on `Spree::NamedType` (`can_be_deleted?` + rename/destroy guards) because secret API keys authorize by scope and never consult CanCanCan. **No state machines (2026-08-02):** plain `status` string + inclusion validation; all fifteen transitions are workflows (`Returns::Receive`, `Exchanges::Fulfill`, `Claims::Resolve`, …) with `validate` hooks for return-eligibility policy and refunds as `external_step`. Nothing happens in a model or transition callback. Statuses live in a `class_attribute` via the core `Spree::HasStatus` concern (`has_status` + additive `add_status(value, after:)`, generating predicates and scopes) — extensible by design, additive only, and no transition graph (that would be a state machine again). **Return eligibility is a hook, not a policy engine (2026-08-03):** no window/restocking-fee/final-sale flag in core — a `validate` handler decides, enforcing for customers while letting staff override (it reads `created_by`), and region-varying policy reads `order.market`. Medusa/Saleor/Vendure ship no policy at all; Shopify's engine has no API. A `ReturnPolicy` model can arrive later behind the same hook.- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename (RefreshToken shipped in 5.4)- `6.0-store-context-and-first-run-setup.md` — Store context becomes credential-derived (design finalized 2026-08-13): publishable key selects the store on the Store API, Admin API honors `X-Spree-Store-Id` with membership checked against the *requested* store (header-less JWT → default store + deprecation, required 6.1), hostname-based store resolution retired (`FindDefault`'s `url:` is dead; never read `request.host` to pick a store). First-run setup replaces the `[email protected]`/`spree123` dummy seed: seed creates an admin only when `ADMIN_EMAIL`/`ADMIN_PASSWORD` are explicitly set; otherwise a one-time setup-token flow (dashboard `/setup` + unauthenticated `auth/setup` endpoints; `has_secure_token :setup_token` on Store — plaintext like invitation tokens, printed by installer, `spree:setup:token` reprints, cleared on completion — required in EVERY environment; `Spree::Stores::DashboardUrl` is the single resolver for the dashboard origin — used by the setup link, invitation emails and the SSO callback — resolving `dashboard_url` pref/`SPREE_DASHBOARD_URL` → deprecated `admin_url` → this app's own `/dashboard` mount when `spree_dashboard` serves a build → dev Vite → store URL; never a hardcoded port, and the CLI rebuilds the link host-side since the seed runs before any dashboard is up). **App configuration reads ENV:** `RuntimeConfiguration.preference` accepts `env:` (precedence: explicit value → env var → coded default), so deployment settings are configurable without touching Ruby; `dashboard_url` is env-backed via `SPREE_DASHBOARD_URL` and `admin_url` is deprecated in its favour. Applies to `Spree::Config` only — per-store behavior belongs in Store preferences. The setup flow creates the first admin and adopts/renames the seeded store; no general store CRUD in the OSS Admin API. **Constraints now:** never assume `current_store == Store.default` in Admin API code; store-touching cache keys include the store id by construction (enforced by the cache-key audit spec in core — global data needs a reviewed allowlist entry); new scripts pass `ADMIN_EMAIL`/`ADMIN_PASSWORD` explicitly. **Isolation tripwires (2026-08-13):** `Spree::StoreScopeGuard` wraps every v3 API request in dev/test and flags store-less secondary-key lookups and unscoped scans on store-owned tables (schema-derived set; id/FK filters and `SELECT 1 AS one` are exempt as loads-from-scoped-rows and uniqueness validations — exemption is NOT proof of scoping, request-derived ids still need `current_store` fetching; `log` default, `raise` in this repo's API suite, `SPREE_STORE_SCOPE_GUARD` to change) — wrap deliberately global lookups in `Spree::StoreScopeGuard.skip { }`. A store-owned model with an unscoped `acts_as_list` also fails the core suite (positions bleed across stores). **Country-aware setup (2026-08-15, shipped):** setup asks for `country_code` (required) plus `locale` (country's official languages, filtered to those Spree translates, + English) and `currency` — both optional to the endpoint and defaulted from the country, both editable in the form; an unresolvable currency is a pre-token-spend 422, never silently ignored. Country data from unauthenticated `GET auth/setup/countries`. `Spree::Stores::ProvisionDefaults.call(store:, country:, locale:, currency:)` owns every country-derived per-store default (bootstrap market updated in place, warehouse country, Domestic/International zones + flat rates, pickup method — all in the derived currency) and absorbs the `StockLocations`/`DeliveryZones`/`PickupDelivery` seeds; exactly two callers — the setup endpoint and `Seeds::AdminUser`'s env branch (`STORE_COUNTRY`/`STORE_LOCALE`/`STORE_CURRENCY`, defaults `US`/`en`). It also restates seeded zero-amount rates (digital delivery) into the store currency. Sample data builds around the default market, never resets it. **Constraints:** a store's country changes through its **market**, never `Store#default_country_code=` (on a store with a market that writer is a dead column — readers delegate to the market, the after_update sync copies locale/currency only); country- or currency-dependent seeds go into `ProvisionDefaults`, not `Seeds::All`; never give the service a third caller.-- `6.0-tax-provider.md` — Per-Market TaxProvider (market selects the provider, providers stateless/argless; global config class stays as fallback), replaces TaxRate.adjust + Calculator; reference provider: Avalara (decisions.md 2026-07-30). **Shipped to 6-0-dev (core-rewrite waves):** `Spree::TaxProvider::Base`/`Internal` as the sole TaxLine write path, called from `Carts::RecalculateTotals` behind the `money_frozen?` freeze. **Contract refined 2026-08-05 after the spree/spree#14056 review (decisions.md):** TaxLine gains `taxability_reason` + jurisdiction snapshot (e-invoice category/exemption codes derived at invoicing time, never stored); new `Spree::TaxIdentifier` model (customer/cart/order dual-FK, frozen order snapshot; validation via the kind-keyed `Spree.tax_id_validators` registry + async job on the geocoding precedent — NOT a provider method, and no registry client in core); exemptions = typed `estimate` input via `tax_resolve_exemptions_service` (boolean `exempt?` removed, no flags anywhere); explicit `tax_date:`; `refund(order, return_items, tax_date:)`; capability declarations (Internal declares no US local tax / no reverse charge / no one-stop-shop thresholds; `estimate` keeps its no-op return — a structured result + indeterminacy channel deferred as safely additive). **Phases 3-5 in development:** the enriched contract, `Spree::TaxIdentifier` + validator registry, exemption value objects, per-Market selection with commit/void/refund as external steps, and the Zone decoupling (rates carry `country_code`/`state_code` — codes, not FKs, since Country/State are being dropped; `spree_tax_rates.zone_id` stays through 6.0 as the conversion source). **Phases 3-5 + the Zone decoupling shipped to `feature/v-3526` (PR #14410).** **Phase 7 shipped to `feature/v-3526` (2026-08-12):** the minimal Company tree pulled forward out of the B2B plan — Company → CompanyLocation → CompanyContact, `company_location_id` on both carts and orders, `company_id` as a fourth TaxIdentifier owner, `Spree::TaxExemptionCertificate` hanging off Company scoped by `country_code`/`state_code`, and the `ResolveExemptions` body; **no `tax_exempt` boolean anywhere** (supersedes the B2B plan's sketches), and Catalog/pricing/visibility stay 6.1. A buyer's company resolves only within the sale's own store, since customers are global. Pending after that: Phase 6 `spree_tax_avalara`, **Phase 8 cross-border pricing with tax-inclusive prices** (2026-08-11 live pass: `Pricing::Context.from_order` never carried the cart's market so market-scoped price lists were unreachable from a cart; `recalculate_for_address_change!` called the non-persisting `update_price`; restatement was applied even to prices set for the destination — the rule is now derive net-fixed unless the winning price list carries a `geographic?` rule, Shopify's model), Phase 9 6.1 cleanup (drop `zone_id`, `null: false` on the tax `store_id`s, decide `Market#tax_inclusive`). Still open: delivery-rate tax display bypasses the provider+- `6.0-tax-provider.md` — Per-Market TaxProvider (market selects the provider, providers stateless/argless; global config class stays as fallback), replaces TaxRate.adjust + Calculator; reference provider: Avalara (decisions.md 2026-07-30). **Shipped to 6-0-dev (core-rewrite waves):** `Spree::TaxProvider::Base`/`Internal` as the sole TaxLine write path, called from `Carts::RecalculateTotals` behind the `money_frozen?` freeze. **Contract refined 2026-08-05 after the spree/spree#14056 review (decisions.md):** TaxLine gains `taxability_reason` + jurisdiction snapshot (e-invoice category/exemption codes derived at invoicing time, never stored); new `Spree::TaxIdentifier` model (customer/cart/order dual-FK, frozen order snapshot; validation via the kind-keyed `Spree.tax_id_validators` registry + async job on the geocoding precedent — NOT a provider method, and no registry client in core); exemptions = typed `estimate` input via `tax_resolve_exemptions_service` (boolean `exempt?` removed, no flags anywhere); explicit `tax_date:`; `refund(order, return_items, tax_date:)`; capability declarations (Internal declares no US local tax / no reverse charge / no one-stop-shop thresholds; `estimate` keeps its no-op return — a structured result + indeterminacy channel deferred as safely additive). **Phases 3-5 in development:** the enriched contract, `Spree::TaxIdentifier` + validator registry, exemption value objects, per-Market selection with commit/void/refund as external steps, and the Zone decoupling (rates carry `country_code`/`state_code` — codes, not FKs, since Country/State are being dropped; `spree_tax_rates.zone_id` stays through 6.0 as the conversion source). **Phases 3-5 + the Zone decoupling shipped to `feature/v-3526` (PR #14410).** **Phase 7 shipped to `feature/v-3526` (2026-08-12):** the minimal Company tree pulled forward out of the B2B plan — `company_id` as a fourth TaxIdentifier owner, `Spree::TaxExemptionCertificate` hanging off Company scoped by `country_code`/`state_code`, and the `ResolveExemptions` body; **no `tax_exempt` boolean anywhere**. That Company→CompanyLocation→CompanyContact shape was **replaced unreleased by `6.0-b2b-companies-and-catalogs.md`** (2026-08-25): purchases carry `company_id` (any tree node) and tax reads anchor on `company_legal_entity`. A buyer's company resolves only within the sale's own store, since customers are global. Pending after that: Phase 6 `spree_tax_avalara`, **Phase 8 cross-border pricing with tax-inclusive prices** (2026-08-11 live pass: `Pricing::Context.from_order` never carried the cart's market so market-scoped price lists were unreachable from a cart; `recalculate_for_address_change!` called the non-persisting `update_price`; restatement was applied even to prices set for the destination — the rule is now derive net-fixed unless the winning price list carries a `geographic?` rule, Shopify's model), Phase 9 6.1 cleanup (drop `zone_id`, `null: false` on the tax `store_id`s, decide `Market#tax_inclusive`). Still open: delivery-rate tax display bypasses the provider- `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider wrapping Stock::Estimator (calculators stay — 2026-07-27 reversal), `store_id` on ShippingMethod; monorepo ships one reference multi-carrier provider (**EasyPost** — decisions.md 2026-08-06 reversal: BYOCA fit for larger merchants + only maintained official Ruby SDK; Shippo's ruby gem dead since 2020); method rows stay regional (no cross-market method entity). **Dynamic carrier rates (2026-08-09):** a carrier method is the carrier connection — `estimates(package)` returns one Estimate per service, each becoming its own named DeliveryRate (unique (fulfillment, method) rate index dropped; `DeliveryRate#name` falls back to the method name); `Spree::DeliveryMethodService` rows narrow/rename/mark-up services (no rows = all, method-level markup columns as default); selection + EasyPost label buy key off the selected rate's carrier/service; seeds/sample data reshaped Shopify-style (Domestic + International zones with basic methods)- `6.0-delivery-zones.md` — Zone → DeliveryZone with postal-code-range/prefix members (country-scoped); owns the full ~183-reference Zone consumer inventory; `Spree::Zone` dropped entirely by end of 6.0 (2026-07-27 — 6.0 is the breaking-change window) Member FKs convert to `country_code`/`state_code` strings per `6.0-drop-country-state-models.md` (2026-08-07)- `6.0-drop-country-state-models.md` — Delete the `Spree::Country`/`Spree::State` AR models in 6.0 (the tables and legacy FK columns survive to 6.1 as the upgrade task's source data); constants survive as `countries`-gem-backed value objects (carmen removed), consumers store `country_code` + `state_code` strings (always paired — subdivision codes aren't globally unique), Address validation semantics preserved (`STATES_REQUIRED` constants become runtime source of truth). No `id` was ever exposed, so the only v3 changes are the `state_abbr`→`state_code` and `country_iso`→`country_code` renames (Market's list moves `country_isos`→`country_codes`) — `Spree::Address` alone keeps `state_abbr` and `country_iso` as deprecated read/write bridges until 6.1. Amends tax-provider Phase 5 (TaxRate columns born as ISO strings, not FKs) and delivery-zone members. **Shipped (2026-08-14):** value objects live, carmen + country/state seeds + row-creating fallbacks deleted; `Spree::IsoData` curated registry + drift-guard spec, ISO columns on addresses/delivery-zone-members/market-countries/stock-locations/stores with `spree:upgrade:migrate_country_state_codes` in the 5.6→6.0 manifest, every consumer matching on codes, admin FK params closed, country endpoints uncached, factories built from real ISO data. `Spree::Zone`/`ZoneMember` are migration-only shells (no `zoneable` association; the data tasks resolve member ids against the legacy tables via SQL) and drop in 6.1 with the tables. **Constraint now:** no new `country_id`/`state_id` FKs or `belongs_to :country/:state` anywhere — a new model carrying geography declares `has_iso_geography` (`Spree::HasIsoGeography`, on `Spree::Base`; `state: false` for country-only tables) and stores ISO strings in columns named `country_code` + `state_code` — never `country_iso` or `state_abbr`; preference-based rules follow `Promotion::Rules::Country`@@ -55,7 +55,7 @@ Multi-version plans (some phases shipped, some pending):- `5.5-6.0-order-cancellation-and-approval.md` — First-class `OrderCancellation` + `OrderApproval` models. 5.5 models + migrations shipped; 6.0 drops denormalized columns.- `5.5-6.0-display-on-to-boolean.md` — Collapse `display_on` tri-state to a single `storefront_visible` boolean. 5.5 bridge (`storefront_visible` accessor + Ransacker on `Spree::DisplayOn`) shipped; 6.0 schema rename pending.- `6.0-order-routing.md` — Two-tier extension: pluggable `Spree::OrderRouting::Strategy::Base` + STI subclasses of `Spree::OrderRoutingRule`. Phase 1 (5.5) shipped: `Channel`, `OrderRoutingRule`, strategy base + Rules + Reducer + Legacy, `preferred_stock_location_id` + `channel_id` on Order. Phase 2+ (6.0) layers Catalog/Company on top via `6.0-channels-catalogs-b2b.md`.-- `6.0-channels-catalogs-b2b.md` — Channel + ProductPublication (replaces StoreProduct) + single-owner Product (`belongs_to :store`) + Publishing card (legacy admin + SPA) + `Channel#default` boolean shipped in 5.5. Channel-level gated storefront access (`storefront_access` enum + channel-owned `guest_checkout`, both with store fallback, enforced in the v3 Store API) targeted for 5.6. Catalog, Company/CompanyLocation/CompanyContact for B2B **deferred to 6.1** (the B2B release — see `docs/plans/decisions.md` 2026-06-16; filename keeps `6.0-` prefix for stable cross-refs). Multi-store catalogs (historic `Product has_many :stores`) move to the `spree_multi_store` extension.+- `6.0-channels-catalogs-b2b.md` — Channel + ProductPublication (replaces StoreProduct) + single-owner Product (`belongs_to :store`) + Publishing card (legacy admin + SPA) + `Channel#default` boolean shipped in 5.5; gated storefront access shipped in 5.6. The Catalog + Company phase is **superseded by `6.0-b2b-companies-and-catalogs.md`** (implemented 2026-08-25 — B2B pulled back into 6.0 as a headline). Multi-store catalogs (historic `Product has_many :stores`) move to the `spree_multi_store` extension.- `5.6-6.0-single-store-promotions-payment-methods.md` — Migrate `Spree::Promotion` + `Spree::PaymentMethod` from multi-store (`has_many :stores` via `spree_promotions_stores` / `spree_payment_methods_stores` join tables) to single-owner `belongs_to :store`, mirroring the 5.5 single-owner Product migration. 5.6 (implemented): `store_id` FK + required-store presence via `Spree::SingleStoreResource`, backfill rake task (loud per-record deprecation on shared records), shared `LegacyMultiStoreSupport` deprecation bridge, deletes the `ResourceController` `store_ids=` seam, deprecates `StoreScopedResource`; multi-store sharing moves to the `spree_multi_store` extension (join tables left intact). 6.0 cleanup: enforce `null: false`, drop join tables + bridges. Paired with `6.0-channels-catalogs-b2b.md`.- `5.6-project-layout-and-dashboard.md` — React Dashboard Developer Preview packaging + `backend/` → `api/` project layout. Implemented: `<Dashboard />` shell export from `@spree/dashboard` (source-only, relative imports only), monorepo-canonical `packages/dashboard-starter` thin host (embedded standalone into the `@spree/cli` tarball at build time via `scripts/sync-dashboard-starter.mjs` — no template repo; create-spree-app delegates to the project-local `spree add dashboard`), `spree add dashboard` + create-spree-app dashboard phase (opt-in via `--react-dashboard` while WIP — not prompted; env carries only `VITE_API_PROXY_TARGET` — never secret keys, and never `VITE_SPREE_API_URL`, which would flip the SDK to absolute cross-origin URLs and break dev on CORS), npm release job for `@spree/dashboard{,-ui,-core}` (0.x → `next` tag). Pending: layout rename + `detectApiDir` dual-layout CLI, `spree upgrade layout`; optional public template repo at 6.0 GA.- `5.6-dashboard-typed-plugin-routes.md` — Plugin file routes compiled into the host's TanStack route tree: `spree.dashboard.routes` marker + virtual-route-config composition in `@spree/dashboard/vite`, `createDashboardRouter` + `<Dashboard router>` ownership inversion, typed cast-free links, cross-package collision pre-flight with package-named errors. Runtime route registry stays for dynamic/in-app cases (catch-all is lowest priority). Implemented; published-tarball spike passed.@@ -73,6 +73,7 @@ Pending design work (drafts, no implementation yet):- `6.1-exchange-rates.md` — `Spree::ExchangeRate` + `ExchangeRateProvider` (ECB feed as the credential-free default, registry copied from `tax_providers`/`delivery_rate_providers`, keyed providers via `Spree::Integration`). **Rates fill fields, they never price anything** — a merchant gets editable suggestions for the other currencies and what persists is a plain number they own; Spree's "one explicit amount per currency, no FX" stance is unchanged. Never at charge time: EU VAT Directive Art. 91 pins the rate to the instant VAT becomes chargeable, so a commission invoice's VAT figure must be frozen with its rate/date/source or the platform cannot reproduce its own filed documents (Shopify converts at capture and is the wrong pattern here; Vendure/Medusa/Saleor never convert in core). Rates are stored historically and looked up **most-recent-on-or-before**, never exact-date (the ECB skips weekends); cross-currency derives through the base per Art. 91, never stored as a third row; rate precision is NOT money's `decimal(_,2)`. **Constraints now:** never set `Money.default_bank` or call `exchange_to` (the empty rate store raising `UnknownRate` is correct); new money configuration is born per currency, never one amount + a currency column; no conversion endpoint on any API. Also records two live promotion bugs found while researching it — `Calculator::FlatRate` silently discounts **zero** on a currency mismatch, and `Promotion::Rules::ItemTotal` stores a bare threshold with no currency — both independent of this feature.Shipped plans:+- `6.0-b2b-companies-and-catalogs.md` — B2B companies as a **multi-level organization tree** + Catalogs pulled into 6.0 (**implemented 2026-08-25**; replaced the unreleased Company→CompanyLocation→CompanyContact prototype outright — migrations rewritten in place, no bridges). One `spree_companies` table: self-referential `parent_id`, `kind` = `company` (legal entity) | `division`, depth capped at `MAX_DEPTH` (5), roots must be `company`; **`#legal_entity` (nearest self-or-ancestor company node) is the single tax anchor** — TaxIdentifier/TaxExemptionCertificate refuse division owners, and purchases read `company_legal_entity`, never the node. `CompanyAddress` (owned rows, labeled, one default per kind via Channel-style demotion + partial index), `CompanyMembership` (always customer-backed; standing = node + subtree, checked via `Customer#standing_for?`/`company_standing(store:)` — never node equality), `CompanyInvitation` (plaintext token, 30-day expiry, pending-scoped uniqueness; mail in `spree/emails`, acceptance via `CompanyInvitations::Accept` running `Customers::Create`; both member-adding surfaces converge on `Companies::AddMember` by email). Carts/orders carry `company_id` (any node; cart-side standing validation, sole-membership resolution in `resolved_company`, frozen at completion). **Catalogs:** `Catalog` (assortment + optional PriceList) + positioned `CatalogProduct` + polymorphic `CatalogAssignment` (Channel|CustomerGroup|Market|Company — company assignments cover the subtree; `spree_channels.default_catalog_id`); visibility = `Products::ForContext` (union of effective catalogs, wired into the store products listing), pricing = catalog price lists nearest-node-first in `Pricing::Resolver` (catalog-bound lists excluded from generic rule matching — a rule-less list must not leak to everyone). Store API self-service (`/store/account/companies`, `/store/companies/*`, unauthenticated invitation lookup/accept, writable cart `company_id`) authorizes by **standing + `Storefront::AccessPolicy`** (company branch answers yes for any member — OSS has no company roles; Enterprise narrows via the policy class + checkout hooks). Dashboard: lazy tree list, node page (sub-units/members+invitations/address book; tax cards hidden on divisions), catalogs pages; slots renamed `company_membership.*`, `company.form_*` only. **Constraints:** never reference the deleted location/contact models; no governance fields on OSS models; `kind` stays the fixed two (divergence = STI, never a second table); catalog/company lookups store-scoped including incidental ids.- `5.4-store-api-bridges.md` — Bridge 6.0 naming into 5.4 Store API (PR #13782)- `5.4-spree-starter-and-create-spree-app.md` — Replace monorepo server/ with spree-starter template repo- `5.4-option-type-enhancements.md` — `kind` (dropdown/color_swatch/buttons) on OptionType + `color_code` on OptionValuediff --git a/docs/developer/core-concepts/companies-and-catalogs.mdx b/docs/developer/core-concepts/companies-and-catalogs.mdxnew file mode 100644index 0000000000..f252ebfb74--- /dev/null+++ b/docs/developer/core-concepts/companies-and-catalogs.mdx@@ -0,0 +1,81 @@+---+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` — the nearest self-or-ancestor `company` node. A division *is* its legal entity; a subsidiary never borrows its parent's registration.+- **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, Discounts & Fees](/docs/developer/core-concepts/taxes-discounts-fees) 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. A catalog with no price list is assortment-only: it narrows what is visible, and base prices apply.+- **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). 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/docs.json b/docs/docs.jsonindex 9f8f246ade..df4a7821de 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -488,6 +488,7 @@"pages": ["developer/core-concepts/products","developer/core-concepts/pricing",+ "developer/core-concepts/companies-and-catalogs","developer/core-concepts/inventory","developer/core-concepts/media","developer/core-concepts/search-filtering"@@ -1856,6 +1857,7 @@"pages": ["developer/core-concepts/products","developer/core-concepts/pricing",+ "developer/core-concepts/companies-and-catalogs","developer/core-concepts/inventory","developer/core-concepts/media","developer/core-concepts/search-filtering"diff --git a/docs/plans/6.0-b2b-companies-and-catalogs.md b/docs/plans/6.0-b2b-companies-and-catalogs.mdindex 8b144f48b5..d14756900a 100644--- a/docs/plans/6.0-b2b-companies-and-catalogs.md+++ b/docs/plans/6.0-b2b-companies-and-catalogs.md@@ -1,6 +1,6 @@# B2B Companies (Hierarchy) & Catalogs-**Status:** Design Finalized (open questions resolved 2026-08-25)+**Status:** Implemented (2026-08-25 — phases 1–6: core tree + invitations, Admin API, Catalogs core + admin, Store API self-service, dashboard, sample data + docs)**Target:** Spree 6.0**Depends on:** `6.0-channels-catalogs-b2b.md` Phase 1 (Channels, shipped 5.5) + Phase 1.5 (gated storefront access, shipped 5.6); `6.0-tax-provider.md` Phases 3–7 (tax identifiers, exemption certificates, `ResolveExemptions` — shipped); PriceList system (existing)**Author:** Damian + Claudediff --git a/docs/use-case/b2b/b2b-capabilities.mdx b/docs/use-case/b2b/b2b-capabilities.mdxindex a4c351ac4f..d24add95d0 100644--- a/docs/use-case/b2b/b2b-capabilities.mdx+++ b/docs/use-case/b2b/b2b-capabilities.mdx@@ -63,8 +63,8 @@ See [<u>Set Up Wholesale Pricing</u>](https://spreecommerce.org/docs/user/how-to<Note>The following features are on the open-source roadmap and will be available in Spree 6.0.</Note>-- **B2B Buyer Organizations** — Company accounts with locations and contacts, allowing multiple buyers to operate under a single business account.-- **B2B Catalogs** — Curated per-segment product assortments, so different buyer groups can see different subsets of your catalog.+- **B2B Buyer Organizations** — Multi-level company accounts: an organization tree of companies and divisions, each with its own address book and members whose buying rights cover their branch of the tree. Buyers can manage their own organization from the storefront — no other open-source platform ships organization hierarchy for free.+- **B2B Catalogs** — Curated product assortments with optional price lists, assignable to a sales channel, a customer group, a market, or a company. A catalog assigned to a company applies to its whole subtree, so a group-wide range is set up once.## Enterprise Editiondiff --git a/spree/core/db/sample_data/wholesale.rb b/spree/core/db/sample_data/wholesale.rbindex a02736ea63..319120abfa 100644--- a/spree/core/db/sample_data/wholesale.rb+++ b/spree/core/db/sample_data/wholesale.rb@@ -69,3 +69,26 @@ if blank_prices.any?endSpree.price_list_activate_workflow.call(price_list: price_list) unless price_list.active?++# A two-level organization tree so the demo walks the whole B2B story: the+# buyer is a member of the EMEA division and buys for it, while the catalog is+# assigned once at the root and covers the subtree+# (docs/plans/6.0-b2b-companies-and-catalogs.md).+company = store.companies.find_or_create_by!(name: 'Acme Industrial') do |record|+ record.kind = 'company'+ record.external_id = 'ACME-1'+end++division = store.companies.find_or_create_by!(name: 'Acme EMEA') do |record|+ record.kind = 'division'+ record.parent = company+end++division.memberships.find_or_create_by!(customer: buyer)++# The per-tree catalog: assigned to the root, so the division's buyers see it+# too. Assortment-only — pricing keeps coming from the wholesale price list,+# which shows the two axes composing.+catalog = store.catalogs.find_or_create_by!(name: 'Wholesale Assortment')+catalog.add_products(store.products.order(:id).limit(20).ids)+catalog.catalog_assignments.find_or_create_by!(assignable: company)