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.
B2B Companies (Hierarchy) & Catalogs
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 + Claude
Last updated: 2026-08-30
Amendment (2026-08-30) — the Catalog is the commercial agreement. Implementation of consequences 2–4 is tracked in its own plan,
6.0-catalog-agreement-rework.md(Draft) — extracted 2026-08-30 so this plan's Implemented status stops hiding unbuilt work. The one-question-per-entity doctrine (decisions.md 2026-08-30) settles how the three targeting entities relate: Channel answers where the buyer is shopping (publications, key binding, routing, stock allowlist, access gating — gating stays as Channel preferences because it must bind before identity exists), Catalog answers what this buyer's agreement is, and PriceList answers what the numbers are. Four consequences amend this plan:
- Catalog grows commercial terms — catalog-level
minimum_order_quantity+order_multiplecolumns with per-variant override rows, and per-currency order minimums, resolved per-field nearest-agreement-wins throughCatalog.for_context; a terms-only catalog (empty assortment, no list) is legitimate. Owned by6.0-b2b-quantity-rules.md.- The list binding inverts:
spree_price_lists.catalog_idreplacesspree_catalogs.price_list_id. A price list is standalone (rule-matched) or owned by exactly one catalog; generic matching skips owned lists by the FK, which closes a leak in the shipped derived-set approach —Catalog.bound_price_list_idsreads active catalogs only, so deactivating a catalog dropped its (typically rule-less) list back into generic matching for the whole store. Detaching becomes an explicit act with a dashboard warning. One catalog serving several audiences via assignments replaces the lost list-sharing-across-catalogs.- Audience-shaped price rules are deprecated:
PriceRules::CustomerGroupRuleandPriceRules::UserRuleduplicate catalog assignment with different precedence; 6.0 deprecates them with the standard one-release bridge and a data task that converts each such list into an assortment-less catalog (assigned to the group; aUserRulelist maps to a single-member customer group) owning the list.PriceRules::ChannelRuleis grandfathered — kept working, nothing new builds on it; a channel's pricing story is its default catalog (which may own an assortment-less list).MarketRuleandVolumeRuleare context-shaped and stay first-class.- The dashboard flow inverts to catalog-first, and setup is one go. The catalog page becomes the agreement editor: audience assignments, assortment, pricing card (its owned list inline — fixed rows or the automatic ±% adjustment from
6.0-price-list-automatic-pricing.md), and terms; plus a products-with-prices view that shows, per product, assortment membership and the resolved price with its source (explicit / automatic / base) — making assortment↔pricing divergence visible instead of discoverable-by-accident. Creating a catalog creates its price list in the same flow — the New catalog form takes name, audience, assortment, and a pricing choice (base prices / ±% adjustment / fixed prices), and the admin catalogs create/update endpoints accept an inlineprice_listpayload for the owned list so the whole agreement is one submission; merchants never visit the price-lists page to stand up a catalog.
Summary
Rebuild the B2B company model as a multi-level organization tree and pull
Catalogs forward into 6.0. The Company → CompanyLocation → CompanyContact
tree that shipped with the tax-provider work is merged but unreleased, so this
plan replaces it outright — no bridges, no data migration — with a single
self-referential Spree::Company node (typed company | division), an
address book per node, and a membership join that gives a buyer standing over
a subtree. Catalogs (assortment + optional PriceList, assignable to channels,
customer groups, markets, and company nodes with subtree semantics) move from
6.1 into 6.0 alongside it.
The strategic driver: no competitor ships organization hierarchy in open
source. Shopify's B2B is flat Company → Location; Medusa's starter is flat
Company → Employee; depth exists only in paid tiers elsewhere. Spree 6.0
ships it free, with the directory + hierarchy + catalogs in OSS and
governance (roles, approvals, spend limits, terms) layered on top by
Enterprise through hooks and policies — those plans live in the
ee repository, never here.
Why the shipped model is being replaced
The merged tree copied Shopify's shape because the tax work needed only the
minimum. Shopify's CompanyLocation conflates three jobs — organizational
sub-unit, ship-to/bill-to address pair, and commercial-terms anchor — which is
its best-known weakness: one billing entity with forty ship-to sites means
forty locations and forty rounds of catalog/terms/exemption assignment. The
replacement unbundles those jobs (tree node / address book / membership) and
makes flat usage the trivial case: one node, several addresses, a few members
is exactly the old model's power with fewer moving parts. This is the last
moment the swap is free — nothing is released, so the old tables simply never
existed as far as any upgrade path is concerned.
Key Decisions (do not deviate without discussion)
- One structural entity, one table (2026-08-25).
Spree::Companyis a self-referential tree (parent_id), store-scoped, depth capped at 5 (constant, matching the commercetools/BigCommerce ceiling), cycle-checked on save.Spree::CompanyLocationandSpree::CompanyContactare deleted — models, tables, controllers, serializers, dashboard pages.kindstarts as a plain string; if the kinds ever grow diverging behavior, the sanctioned path is STI on this same table (the standardregisters_subclasses_viapattern) — never a separateDivisionmodel/table, which would force dual-FK or polymorphic references on every consumer. - Nodes are typed, and the type is load-bearing for tax.
kindiscompany(legal entity) ordivision(organizational unit). Tax identifiers and exemption certificates may exist only oncompanynodes; tax resolution for any node walks up to the nearest self-or-ancestorcompanynode and stops there — a division is its legal entity, a subsidiary never borrows its parent's registration. Root nodes must bekind: company(a division with no legal-entity ancestor has no tax identity). - Membership is subtree-scoped, and in OSS every member can do everything
(2026-08-25).
Spree::CompanyMembershipjoins a customer to a node; standing covers that node and everything below it. OSS ships no company roles, no permission checks between members — a member with standing may buy, see the subtree's purchases, and manage its addresses and members. All finer control (roles, capability checks, spend limits, approvals) enforces through injection points that are no-ops in OSS: the storefront access policy class (Spree::Dependencies.storefront_access_policy_class) and the checkoutvalidatehooks. Enterprise fills them; OSS never grows guard logic of its own. Therolestring on membership is a cosmetic label only (the capability model is Enterprise, per6.0-admin-rbac.md). - People join by email, from either side (2026-08-25). Staff (dashboard)
and members (storefront) add people the same way: an email that matches a
store customer becomes a membership immediately; an unknown email becomes
a
Spree::CompanyInvitation(plaintext token, 30-day expiry, functional invite email inspree/emails) whose acceptance runsCustomers::Createand lands as a membership. Memberships themselves stay always-active and customer-backed — pending state lives on the invitation, never as a nullablecustomer_idor a status column on the membership. - Addresses are an address book, not structure.
Spree::CompanyAddressjoins a node to ownedSpree::Addressrows withlabel+default_billing/default_shippingflags. How many ship-to sites a node has never dictates how many nodes exist. - Carts and orders point at a node.
company_id(any node — buying for a division is pointing at it), frozen at completion like every other order attribute. The bill-to/ship-to on the purchase are its normal address fields, conveniently filled from the node's address book. There is nocompany_location_idanywhere. - An empty assortment is a pricing-only overlay (2026-08-25, post-ship
amendment). A catalog with no curated products restricts nothing: its
price list applies and the audience keeps seeing the whole channel range —
which is how "everyone sees the public store, this company just gets
special prices" is expressed (Shopify reaches the same outcome via
catalogs defaulting to all-products). Any effective catalog with an empty
assortment lifts the restriction for that buyer entirely. Consequently the
price-list → assortment import is an explicit action
(
import_products_from_price_list,POST /admin/catalogs/:id/import_products, a dashboard button), never automatic — turning a catalog restrictive is a deliberate curation act. - Catalogs ship in 6.0 with the shape the 6.1 plan settled —
Catalog(assortment + optional PriceList),CatalogProduct, polymorphicCatalogAssignment— except the assignable set is CustomerGroup and Company (the node replaces CompanyLocation). Amended 2026-08-28: the set originally included Channel and Market, but nothing ever read those rows — resolution and pricing consult only company-subtree and customer-group assignments plus the channel'sdefault_catalog_id— so they were dropped pre-release rather than shipped as write-only traps. Assignments are buyer audiences; a channel's catalog is itsdefault_catalog_id(the fallback shape a sales surface wants, which buyer catalogs override); a market catalog returns only together with a designed regional-assortment reader (see decisions.md 2026-08-28). A catalog assigned to a company node applies to its subtree: effective catalogs for a purchase node are the union of assignments onself_and_ancestors. Visibility is the union across effective catalogs; pricing takes the nearest node's assignment first, and within one node charges the best price any of its catalogs gives (amended 2026-09-16, V-3635 — catalog position used to break that tie and so decided the money). - No
tax_exemptboolean anywhere (reaffirming decisions.md 2026-08-07 — exemption is certificates + provider resolution, never a flag). - No new state machines, no workflows for plain CRUD. Company, membership, address, and catalog writes are ordinary ResourceController CRUD. Certificate verify/revoke keeps its existing workflow.
- Enterprise governance layers on, never in. Spending limits, approvals,
company roles, payment terms, quotes: their plans live in
ee/docs/plans/, and they consume OSS hooks (carts.complete.validate), the storefront access policy class, dashboard slots, and events. Any mechanism they need that does not exist is an OSS contribution first. - Unreleased migrations are rewritten in place. The
2026080700000xcompany migrations are edited to the new schema rather than stacked on — 6.0 has not shipped, so no installation has run them. Worktree template databases must be rebuilt (pnpm wt:template).
Design Details
Spree::Company — the tree node
class Spree::Company < Spree.base_class
has_prefix_id :comp
include Spree::SingleStoreResource
include Spree::HasCustomFields
include Spree::Metadata
publishes_lifecycle_events
KINDS = %w[company division].freeze
MAX_DEPTH = 5
belongs_to :store, class_name: 'Spree::Store'
belongs_to :parent, class_name: 'Spree::Company', optional: true, inverse_of: :children
has_many :children, class_name: 'Spree::Company', foreign_key: :parent_id,
inverse_of: :parent, dependent: :destroy
has_many :company_addresses, class_name: 'Spree::CompanyAddress', dependent: :destroy
has_many :addresses, through: :company_addresses, class_name: 'Spree::Address'
has_many :memberships, class_name: 'Spree::CompanyMembership', dependent: :destroy
has_many :customers, through: :memberships, class_name: Spree.customer_class.to_s
has_many :tax_identifiers, class_name: 'Spree::TaxIdentifier', dependent: :destroy
has_many :tax_exemption_certificates, class_name: 'Spree::TaxExemptionCertificate',
dependent: :destroy
has_many :catalog_assignments, as: :assignable, class_name: 'Spree::CatalogAssignment',
dependent: :destroy
has_many :catalogs, through: :catalog_assignments
validates :name, presence: true
validates :kind, inclusion: { in: KINDS }
validates :external_id, uniqueness: { scope: :store_id }, allow_nil: true
validate :parent_in_same_store
validate :root_must_be_legal_entity # kind == 'company' when parent_id.nil?
validate :depth_within_cap # ancestors walk, bounded by MAX_DEPTH
validate :no_ancestry_cycle
end
Tree reads (all bounded by MAX_DEPTH, so ancestor walks are a loop over
parent, and subtree reads are a recursive CTE scope that works on
PostgreSQL, MySQL 8, and SQLite):
#ancestors/#self_and_ancestors— leaf → root order#self_and_descendants— recursive CTE, used by subtree standing checks, catalog assignment resolution, and the dashboard tree#root#legal_entity— nearest self-or-ancestor withkind == 'company'. The single tax anchor: identifiers and certificates are always read through it, and the walk stops at the firstcompanynode whether or not it holds anything (a subsidiary with no VAT id has no VAT id — it does not borrow its parent's).
kind has no database default (per the string-column rule); the model
normalizes a blank kind to company on initialize. Divisions cannot own tax
identifiers or exemption certificates — model validation plus a 422 from the
nested Admin API endpoints. This constraint is deliberately a validation, not
a schema difference, so a future "division with its own foreign VAT
registration" (Shopify's per-location taxRegistrationId precedent) can be
allowed later by relaxing the validation alone — resolution already reads
through legal_entity, which would then simply become
nearest-holder-or-legal-entity.
Spree::CompanyAddress — the address book
class Spree::CompanyAddress < Spree.base_class
has_prefix_id :caddr
belongs_to :company, class_name: 'Spree::Company', inverse_of: :company_addresses
belongs_to :address, class_name: 'Spree::Address', dependent: :destroy
# label: 'Headquarters', 'Plant 2 dock', …
# default_billing / default_shipping: at most one of each per node,
# enforced the same way Channel#default is (after_save demotion + partial
# unique index on PG/SQLite, model validation on MySQL).
end
The address rows are owned outright (mirroring what CompanyLocation did) —
never shared with a customer's address book. A node with no defaults falls
back to its nearest ancestor's defaults when the dashboard or Store API
prefills a checkout, but nothing is ever resolved implicitly at order time:
the order's own address columns are the truth, as today.
Spree::CompanyMembership — people
class Spree::CompanyMembership < Spree.base_class
has_prefix_id :cmem
belongs_to :company, class_name: 'Spree::Company', inverse_of: :memberships
belongs_to :customer, class_name: Spree.customer_class.to_s
validates :customer_id, uniqueness: { scope: :company_id }
# role: cosmetic label only ('buyer' by convention). OSS has no company
# permission model — every member can do everything within their standing;
# the capability model is Enterprise
# (ee/docs/plans/b2b-companies.md).
end
Standing — a membership at node N authorizes the customer to act for N
and every descendant of N. Customer#company_standing(store:) returns the
set of nodes the customer can purchase for within a store (memberships on
that store's trees, expanded by subtree). Customers stay global; companies
are store-scoped, so standing is always evaluated per store.
Spree::CompanyInvitation — bringing in people who have no account yet
Memberships stay always-active and always customer-backed; the
not-yet-registered case gets its own small model instead of a nullable
customer_id + status on the membership (mirroring the existing staff
invitation shape):
class Spree::CompanyInvitation < Spree.base_class
has_prefix_id :cinv
include Spree::Metadata # carries extension payloads (e.g. an Enterprise role reference)
belongs_to :company, class_name: 'Spree::Company', inverse_of: :invitations
belongs_to :inviter, class_name: Spree.customer_class.to_s, optional: true # nil when staff invites
has_secure_token :token # plaintext, like the staff invitation + setup tokens
normalizes :email, with: ->(email) { email.strip.downcase }
validates :email, presence: true
validates :email, uniqueness: { scope: :company_id, conditions: -> { pending } }
# expires_at set on create (EXPIRY = 30.days); accepted_at / revoked_at stamps
end
Flow (both entry points converge here):
POST …/memberswith acustomer_emailthat matches no customer in the store → invitation row +company_invitation.createdevent; the invitation email (with the token link) ships inspree/emails— it is functional mail like the staff invitation, not a marketing welcome, so the no-welcome-email rule (Customers::Create) is untouched. Headless storefronts own the acceptance page; the link target resolves like other customer-facing links (store URL), and the event lets a host app send its own mail instead.- Acceptance is unauthenticated by token:
GET …/:tokenshows what is being joined;POST …/:token/accepteither takes a registration payload — runningCustomers::Create, the single customer-creation workflow — or an authenticated request from a customer whose email meanwhile registered (the invitation binds to that customer). Either way the membership is created,accepted_atstamped, token spent. - Any member with standing (or staff) can revoke a pending invitation; expired/revoked tokens 404 on lookup. Re-inviting after expiry/revocation creates a fresh row — the pending-uniqueness scope permits it.
No roles on the invitation — it grants exactly what a direct membership
grants. Enterprise attaches its role payload through the same dialog slot,
stored on the invitation's metadata (or its own table referencing the
row), and applies it when acceptance creates the membership via the
company_invitation.accepted event.
Carts and orders
spree_carts.company_id and spree_orders.company_id replace
company_location_id. Spree::Purchase::Company (shared Cart/Order concern)
becomes:
#company— the explicit node, no heuristics on completed orders (frozen column wins, as today).#b2b?—company_id.present?.- Resolution for in-flight carts: explicit
company_idif set (validated — the cart's customer must have standing over that node, and the node must belong to the cart's store); otherwise sole standing: a customer whose standing in the store resolves to exactly one membership uses that membership's node; a customer with several memberships resolves to nothing until the cart says which node it is for. This replaces (and finally settles) the "provisional — revisit" heuristic in the shipped concern: ambiguity is resolved by an explicit cart attribute, not by guessing. - Tax reads all go through
company&.legal_entity—ResolveExemptionsreads the legal entity's certificatesfor_address, the identifier resolution chain reads the legal entity's identifiers above the customer's own row (unchanged precedence, new anchor).
Catalogs (pulled forward from the 6.1 plan)
Spree::Catalog, Spree::CatalogProduct, and Spree::CatalogAssignment
ship as the 6.1 plan specified (store-scoped catalog, product join,
polymorphic assignment, spree_channels.default_catalog_id) with these
amendments:
Assignable types: CustomerGroup, Company (narrowed from Channel/CustomerGroup/Market/Company on 2026-08-28 — the dropped two were write-only; see the amendment in Key Decisions).
CompanyLocationis gone; a company-node assignment applies to the node's subtree.The product join carries no position. A catalog decides what a buyer sees, never the order they see it in — the storefront resolver uses
CatalogProductpurely as a membership filter, and the listing keeps whatever sort the shopper chose. The column,acts_as_list, therepositionendpoint and the dashboard's drag handle are all removed; the admin lists an assortment by name. (Catalog#positionsurvives as the order of the catalogs screen itself. It stopped deciding prices on 2026-09-16 — see Pricing below.) Category and collection membership stays positioned, because those do drive storefront display order.Effective catalogs for a purchase node = union of assignments on
self_and_ancestors. The parent assigns the group-wide catalog once; a branch adds its own extra catalog without re-assigning the shared one.Visibility (
Spree::Products::ForContext.call(store:, channel:, customer:, company: nil)): base set is the channel's publications; if the buyer resolves to a company node with effective catalogs, intersect with their union; else if the customer's group has a catalog, intersect with that; else all channel listings (channel default catalog if set). The gated-access layer (5.6) still runs first — alogin_requiredguest never reaches this resolver. Reaffirmed 2026-09-04 (V-3570): those are alternatives, not layers — a buyer whose company subtree carries any catalog is never also served their customer group's, and trade tiers over a company tree are expressed as company assignments (see decisions.md). Amended 2026-10-01 (V-3722): visibility is also what a buyer may buy. Storefront cart adds resolve variants throughSpree::Cart#orderable_variants(this resolver, asked about the cart's own customer, resolved company and channel), so a hidden or unpublished product answers 404 like its product read; completion re-checks every line with anot_orderablerequirement, gifts included. Staff draft orders are exempt.Pricing: the resolver checks the effective catalogs' PriceLists in nearest-node-first order (the purchase node's own assignments before its parent's), then the existing PriceRule matching, then base price. Amended 2026-09-16 (V-3635): catalogs assigned to the same node rank equally and the buyer pays the best price among them. Position used to break that tie, which meant reordering the store-wide catalogs screen silently changed what a company was charged, and a company given two catalogs was billed from whichever sorted first rather than the cheaper — with no screen anywhere showing that two applied. Precedence between nodes is unchanged: a division's own agreement still answers over its parent's, cheaper or not, because that is an agreement someone negotiated.
Spree::Catalog.groups_for_*return the catalogs grouped by assigning node so the resolver can see the rank boundaries; every other reader keeps the flat union.No Company ↔ CustomerGroup link. The 6.1 sketch's
spree_companies.customer_group_idis dropped from the design: catalog assignment targets the company node directly, so the link's only remaining use would have been group-targeted promotions/price rules — and a company "being in" a group does not put its buyers in that group, so the link promised composition it could not deliver. Group-style targeting of companies (promotion rules, price rules) can arrive later as explicitCompanyRulekinds on those STI families.
Admin API v3
# Companies — tree-aware CRUD
GET /api/v3/admin/companies # ?q[parent_id_null]=1 for roots, ?q[parent_id_eq]= for children
POST /api/v3/admin/companies # accepts parent_id, kind
GET /api/v3/admin/companies/:id # include=children,addresses,memberships
PATCH /api/v3/admin/companies/:id # re-parenting allowed (revalidates depth/cycle/store)
DELETE /api/v3/admin/companies/:id # destroys the subtree (dependent: :destroy)
# Address book
GET/POST /api/v3/admin/companies/:company_id/addresses
PATCH/DELETE /api/v3/admin/company_addresses/:id
# Memberships + invitations (POST memberships takes customer_email — membership
# for an existing store customer, Spree::CompanyInvitation otherwise, same
# convergent behavior as the storefront endpoint)
GET/POST /api/v3/admin/companies/:company_id/memberships
DELETE /api/v3/admin/company_memberships/:id
GET /api/v3/admin/companies/:company_id/invitations
DELETE /api/v3/admin/company_invitations/:id # revoke
# Unchanged surfaces (anchor moves to the node; 422 on division nodes)
…/companies/:company_id/tax_identifiers (+ :validate)
…/companies/:company_id/tax_exemption_certificates (+ verify/revoke/download)
# Catalogs — per the 6.1 plan
GET/POST/PATCH/DELETE /api/v3/admin/catalogs
POST /api/v3/admin/catalogs/:id/products # bulk add { product_ids: [...] }
DELETE /api/v3/admin/catalogs/:id/products/:product_id
POST /api/v3/admin/catalogs/:id/assign # { assignable_type, assignable_id }
DELETE /api/v3/admin/catalog_assignments/:id
The /company_locations/* and /company_contacts/* routes, controllers, and
serializers are deleted. Company serializer gains parent_id, kind,
children_count, members_count; permissions stay on the customers
resource for companies and gain nothing new for catalogs beyond the existing
products pair (a catalog is merchandising data).
Store API — company self-service (every member, full power)
Resolved 2026-08-25: OSS ships full directory self-service on the Store API, with no role model — any member with standing over a node can act on that node and its subtree. Guards, limits, and role checks are Enterprise; OSS exposes only the injection points.
GET /api/v3/store/account/companies # my memberships: node id/name/kind + ancestor path
GET /api/v3/store/companies/:id # node detail (requires standing)
PATCH /api/v3/store/companies/:id # name, custom fields
GET/POST /api/v3/store/companies/:id/addresses
PATCH/DELETE /api/v3/store/company_addresses/:id
GET/POST /api/v3/store/companies/:id/members # POST takes customer_email — member or invitation, see below
DELETE /api/v3/store/company_members/:id
GET/DELETE /api/v3/store/companies/:id/invitations, /api/v3/store/company_invitations/:id
GET /api/v3/store/companies/:id/orders # completed purchases across the node's subtree
PATCH /api/v3/store/cart # company_id writable (validated against standing)
# Unauthenticated invitation acceptance
GET /api/v3/store/company_invitations/:token # lookup: company name, store, invited email
POST /api/v3/store/company_invitations/:token/accept # registration payload OR authenticated accept
- Authorization = standing + the access policy, never CanCanCan and never
roles. Every endpoint first requires a membership on the node or an
ancestor, then consults
Spree::Storefront::AccessPolicy(readable?/writable?/scope) — whose OSS default answers yes for any member. Enterprise registers itsCompanyAccessPolicysubclass viaSpree::Dependencies.storefront_access_policy_classto enforce capabilities, and its checkout guards ride the existingcarts.complete.validatehook. OSS controllers contain no conditional logic beyond the standing check and the policy call. - Adding a member takes an email and does the right thing (resolved
2026-08-25, folded in from the deferred list): if a customer with that
email exists in the store, the membership is created immediately; if not,
a
Spree::CompanyInvitationis created and the invite email goes out. Any member can invite — same no-permissions rule as everything else, and the same dialog slot (company_membership.form_fields) lets Enterprise attach its role payload to either outcome. - Cart/order Store serializers gain
company_id+company_name.Products::ForContextand the pricing resolver read the cart's node (or sole standing), so a signed-in buyer browses their catalog with no extra calls; a multi-node buyer sets the cart'scompany_idexplicitly. - Tax identifiers and exemption certificates stay admin-managed in 6.0 — buyer-submitted certificates are a natural follow-on but need the verification queue UX to make sense first.
- Accepted trade-off, stated plainly: within a company, OSS trusts every member. A member can remove other members (including all of them) or redirect deliveries by editing the address book. That is the deliberate price of shipping self-service without a roles system; merchants who need restraint buy the governance layer, and the injection points mean no OSS schema changes when they do.
Dashboard
- Companies list becomes tree-aware: roots with expandable children
(indent by depth;
?q[parent_id_eq]drives lazy loads), kind badge. - Company page (any node): parent breadcrumb, kind, sub-units card (children with add/re-parent), address book card, members card (replacing the location page's buyers list; add-by-email with a pending invitations section + revoke), tax registration + certificates cards hidden on divisions (with a pointer to the legal entity). The separate location route is deleted.
- Catalogs: list + detail under Products (assortment table with the standard paginated picker, price list select, assignments card).
- Slot contract changes (Enterprise consumes these; its plan is updated
in lockstep):
company_contact.*slots becomecompany_membership.*with{ companyId, onChange }/{ membership, companyId, canEdit }context;company_location.form_main/form_sidebarare deleted — every node is a company page, socompany.form_main/form_sidebar(context gainskind) are the only mount points. The membership dialog keeps the payload-merge mechanism (onChangemerges into the create request).
Deletion inventory (all unreleased)
- Models/tables:
Spree::CompanyLocation,Spree::CompanyContact(+spree_company_locations,spree_company_contacts). company_location_idon carts/orders →company_id(migration rewritten in place).- Admin API: locations/contacts controllers, serializers, routes,
company_location_paramsconcern. - Dashboard:
companies/locations.$locationId.tsx, location sheet, related hooks/schemas/table wiring; SDK + generated types regenerate. Spree::Purchase::Companyprovisional resolution comment + heuristic.
Migration Path
No released data exists — the 5.x → 6.0 upgrade manifest gains no company step, and the in-place migration rewrite means a fresh 6.0 install creates the new schema directly.
Phases (each lands green on its own):
- Core tree — Company rework (parent/kind/validations/tree reads),
CompanyAddress, CompanyMembership, CompanyInvitation (+ invite mailer in
spree/emails,company_invitation.*events), carts/orders FK rename,Purchase::Company+ standing resolution, tax anchor vialegal_entity, ResolveExemptions/identifier-chain updates, factories + specs (shared examples run against both Cart and Order hosts). - Admin API — tree-aware companies CRUD, addresses, memberships, division 422s on tax endpoints, serializers, OpenAPI + typegen pipeline.
- Catalogs core + admin — models,
ForContext,Pricing::Resolverintegration, admin CRUD + assignment endpoints,default_catalog_id. - Store API —
account/companies, the/store/companies/*self-service surface (standing + access-policy authorization), the unauthenticated invitation lookup/accept endpoints (accept wired throughCustomers::Create), writable cartcompany_id, catalog-aware product listing/pricing through the existing gate. - Dashboard — companies tree UI, node page, catalogs pages, slot
renames; Enterprise plan (
ee) updated to the new slot contracts. - Docs + sample data — wholesale channel demo gains a two-level company
with a division and per-tree catalog;
docs/use-case/b2b/*reconciled.
Constraints on Current Work
- Never reference
company_location_idor the location/contact models in new code, specs, or docs — they are deleted, not deprecated (unreleased code gets no bridge, the recorded exception to the bridges convention). - Tax reads on a purchase go through
company&.legal_entity, never throughcompanydirectly — a division holds no registrations and code that reads the node's own identifiers silently loses the exemption. - Standing checks are subtree checks. Any authorization-ish question
("may this customer act for node N") is
memberships on self_and_ancestors(N), never an equality check on one node. The admin customer filter is the worked example:Spree.customer_class'swith_standing_for_companyscope (2026-08-30, ransackable) matches members of the node OR any ancestor, and a plaincompanies_id_inpredicate is WRONG here — it hides the group-level buyer who legitimately purchases for a subsidiary, and would offer a narrower set than the cart's own standing validation accepts. - No governance fields on OSS models. Spending limits, approval settings,
role capabilities, payment terms do not get columns here — their plans live
in
ee/docs/plans/and consume hooks/slots/policies (the model-not-the-feature rule, decisions.md 2026-08-07). - A variant a buyer names resolves through what that buyer may see,
never
current_store.variants. Product reads and wishlist items narrow through the Store API'sStorefrontProducts; carts throughSpree::Cart#orderable_variants. A new storefront endpoint accepting a variant or product id picks one of the two (V-3722). - Catalog and company lookups are store-scoped like every controller
lookup (
current_store.companies,current_store.catalogs) including incidental resolutions (parent_id,assignable_id,price_list_id). kindvalues are the fixed two. New node semantics (franchise, cost centre labels, …) are custom fields or future additive kinds — never overloaded ontodivision. Behavioral divergence between kinds means STI on the same table, never a second model.- Storefront company endpoints authorize by standing + the access policy,
never by role. No
if role == 'admin'(or any member-vs-member permission logic) ever appears in OSS controllers, models, or the dashboard — that logic belongs to the Enterprise policy subclass and hook handlers. OSS code adds injection points, not guards.
Open Questions
The four design questions (naming/STI, Store API scope, address book,
catalog inheritance) were resolved 2026-08-25 and folded into Key Decisions,
as was member invitation for not-yet-registered emails (initially deferred,
pulled back in the same day — Spree::CompanyInvitation). Genuinely
deferred:
- Buyer-submitted exemption certificates via the Store API — deferred until the admin verification queue UX exists to receive them; the certificate model and verify workflow already support it.
References
- Supersedes the Catalog + Company phase of
6.0-channels-catalogs-b2b.md(Channels Phase 1 + gated access remain that plan's shipped record). 6.0-tax-provider.mdPhase 7 — the shipped Company tree this replaces; its exemption/identifier contracts are unchanged, only the anchor moves.6.0-admin-rbac.md— company capability vocabulary stays Enterprise-owned.ee/docs/plans/b2b-companies.md— governance layer, OSS/Enterprise boundary, slot contracts (updated with this plan).5.5-6.0-order-cancellation-and-approval.md— superseded 2026-09-02; the Enterprise approval flow keeps its own record (OSS ships no approval substrate).- decisions.md 2026-08-07 (Company pulled forward; no
tax_exempt; the model-not-the-feature rule), 2026-08-08 (storefront authorization on hooks/policies). - Dashboard slots:
packages/dashboard-core/src/components/slot.tsx; current company routes underpackages/dashboard/src/routes/_authenticated/$storeId/companies/.