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.

Update plans

Damian Legawiec0d42f877f747
diff --git a/docs/plans/6.0-admin-rbac.md b/docs/plans/6.0-admin-rbac.md
index 5ddfaddf0f..7e298d1b34 100644
--- a/docs/plans/6.0-admin-rbac.md
+++ b/docs/plans/6.0-admin-rbac.md
@@ -117,7 +117,7 @@ pages.
no authorization framework.
- **B2B company accounts extend the storefront through seams, not controller
decoration (2026-08-08).** The Enterprise B2B module
- (`6.1-channels-catalogs-b2b.md`: Company → CompanyLocation →
+ (`6.0-channels-catalogs-b2b.md`: Company → CompanyLocation →
CompanyContact, buyer/approver/viewer contact roles, approvals, spending
limits) needs exactly three kinds of authority change, and each has an
open-source injection point already in place:
@@ -153,7 +153,7 @@ pages.
models; this plan promises nothing.
- **Catalog/product visibility per customer group or company is data scoping,
never a permission key.** "Can see catalog B" is a property of what the
- storefront query returns (channels/catalogs work, `6.1-channels-catalogs-b2b.md`),
+ storefront query returns (channels/catalogs work, `6.0-channels-catalogs-b2b.md`),
not of an authorization registry. Non-goal here, recorded so nobody models it
as one later.
@@ -562,7 +562,7 @@ all resolved 2026-08-07 and live in Key Decisions. Genuinely deferred:
- `6.0-admin-api.md` — `/me` shape, endpoint inventory (roles block)
- `6.0-admin-spa.md` — PermissionProvider, nav registries, `<Can>`
- `6.0-platform-auth.md` — Customer/Staff split (role resolution gated to staff)
-- `6.1-channels-catalogs-b2b.md` — catalog visibility as data scoping; Company
+- `6.0-channels-catalogs-b2b.md` — catalog visibility as data scoping; Company
models (B2B roles are a separate future Enterprise system)
- `6.0-multi-vendor-marketplace.md` — future seller-scoped role assignments
- `docs/plans/decisions.md` 2026-08-05 — model-level immutability guards
diff --git a/docs/plans/6.0-b2b-companies-and-catalogs.md b/docs/plans/6.0-b2b-companies-and-catalogs.md
new file mode 100644
index 0000000000..8b144f48b5
--- /dev/null
+++ b/docs/plans/6.0-b2b-companies-and-catalogs.md
@@ -0,0 +1,546 @@
+# B2B Companies (Hierarchy) & Catalogs
+
+**Status:** Design Finalized (open questions resolved 2026-08-25)
+**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-25
+
+## 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
+`spree-enterprise-v2` 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::Company` is a
+ self-referential tree (`parent_id`), store-scoped, depth capped at 5
+ (constant, matching the commercetools/BigCommerce ceiling), cycle-checked
+ on save. `Spree::CompanyLocation` and `Spree::CompanyContact` are deleted —
+ models, tables, controllers, serializers, dashboard pages. `kind` starts as
+ a plain string; **if the kinds ever grow diverging behavior, the sanctioned
+ path is STI on this same table** (the standard `registers_subclasses_via`
+ pattern) — never a separate `Division` model/table, which would force
+ dual-FK or polymorphic references on every consumer.
+- **Nodes are typed, and the type is load-bearing for tax.** `kind` is
+ `company` (legal entity) or `division` (organizational unit). Tax
+ identifiers and exemption certificates may exist **only on `company`
+ nodes**; tax resolution for any node walks up to the **nearest
+ self-or-ancestor `company` node** and stops there — a division *is* its
+ legal entity, a subsidiary never borrows its parent's registration. Root
+ nodes must be `kind: 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::CompanyMembership` joins 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
+ checkout `validate` hooks. Enterprise fills them; OSS never grows guard
+ logic of its own. The `role` string on membership is a cosmetic label only
+ (the capability model is Enterprise, per `6.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 in `spree/emails`) whose acceptance runs `Customers::Create`
+ and lands as a membership. Memberships themselves stay always-active and
+ customer-backed — pending state lives on the invitation, never as a
+ nullable `customer_id` or a status column on the membership.
+- **Addresses are an address book, not structure.** `Spree::CompanyAddress`
+ joins a node to owned `Spree::Address` rows with `label` +
+ `default_billing`/`default_shipping` flags. 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 no
+ `company_location_id` anywhere.
+- **Catalogs ship in 6.0** with the shape the 6.1 plan settled — `Catalog`
+ (assortment + optional PriceList), `CatalogProduct`, polymorphic
+ `CatalogAssignment` — except the assignable set is **Channel, CustomerGroup,
+ Market, Company** (the node replaces CompanyLocation). A catalog assigned
+ to a company node applies to its **subtree**: effective catalogs for a
+ purchase node are the union of assignments on `self_and_ancestors`.
+ Visibility is the union across effective catalogs; pricing takes the
+ **nearest node's** assignment first, then catalog position.
+- **No `tax_exempt` boolean 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
+ `spree-enterprise-v2/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 `2026080700000x`
+ company 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
+
+```ruby
+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.user_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 with `kind == 'company'`. **The
+ single tax anchor**: identifiers and certificates are always read through
+ it, and the walk stops at the first `company` node 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
+
+```ruby
+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
+
+```ruby
+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
+ # (spree-enterprise-v2/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):
+
+```ruby
+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):
+
+1. `POST …/members` with a `customer_email` that matches no customer in the
+ store → invitation row + `company_invitation.created` event; the
+ invitation email (with the token link) ships in `spree/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.
+2. Acceptance is unauthenticated by token: `GET …/:token` shows what is
+ being joined; `POST …/:token/accept` either takes a registration payload
+ — running `Customers::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_at` stamped, token spent.
+3. 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_id` if 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` — `ResolveExemptions`
+ reads the legal entity's certificates `for_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 exactly as the 6.1 plan specified (store-scoped catalog, positioned
+product join, polymorphic assignment, `spree_channels.default_catalog_id`)
+with these amendments:
+
+- **Assignable types: Channel, CustomerGroup, Market, Company.**
+ `CompanyLocation` is gone; a company-node assignment applies to the node's
+ subtree.
+- **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 — a `login_required` guest never
+ reaches this resolver.
+- **Pricing**: `Pricing::Resolver` checks the effective catalogs'
+ PriceLists in **nearest-node-first** order (the purchase node's own
+ assignments before its parent's, catalog `position` breaking ties within a
+ node), then the existing PriceRule matching, then base price.
+- **No Company ↔ CustomerGroup link.** The 6.1 sketch's
+ `spree_companies.customer_group_id` is 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 explicit
+ `CompanyRule` kinds 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 its `CompanyAccessPolicy` subclass via
+ `Spree::Dependencies.storefront_access_policy_class` to enforce
+ capabilities, and its checkout guards ride the existing
+ `carts.complete.validate` hook. 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::CompanyInvitation` is 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::ForContext` and 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's `company_id` explicitly.
+- 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 become `company_membership.*` with
+ `{ companyId, onChange }` / `{ membership, companyId, canEdit }` context;
+ `company_location.form_main` / `form_sidebar` are deleted — every node is a
+ company page, so `company.form_main` / `form_sidebar` (context gains
+ `kind`) are the only mount points. The membership dialog keeps the
+ payload-merge mechanism (`onChange` merges into the create request).
+
+### Deletion inventory (all unreleased)
+
+- Models/tables: `Spree::CompanyLocation`, `Spree::CompanyContact` (+
+ `spree_company_locations`, `spree_company_contacts`).
+- `company_location_id` on carts/orders → `company_id` (migration rewritten
+ in place).
+- Admin API: locations/contacts controllers, serializers, routes,
+ `company_location_params` concern.
+- Dashboard: `companies/locations.$locationId.tsx`, location sheet, related
+ hooks/schemas/table wiring; SDK + generated types regenerate.
+- `Spree::Purchase::Company` provisional 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):
+
+1. **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 via `legal_entity`,
+ ResolveExemptions/identifier-chain updates, factories + specs (shared
+ examples run against both Cart and Order hosts).
+2. **Admin API** — tree-aware companies CRUD, addresses, memberships,
+ division 422s on tax endpoints, serializers, OpenAPI + typegen pipeline.
+3. **Catalogs core + admin** — models, `ForContext`, `Pricing::Resolver`
+ integration, admin CRUD + assignment endpoints, `default_catalog_id`.
+4. **Store API** — `account/companies`, the `/store/companies/*`
+ self-service surface (standing + access-policy authorization), the
+ unauthenticated invitation lookup/accept endpoints (accept wired through
+ `Customers::Create`), writable cart `company_id`, catalog-aware product
+ listing/pricing through the existing gate.
+5. **Dashboard** — companies tree UI, node page, catalogs pages, slot
+ renames; Enterprise plan (`spree-enterprise-v2`) updated to the new slot
+ contracts.
+6. **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_id` or 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
+ through `company` directly — 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.
+- **No governance fields on OSS models.** Spending limits, approval settings,
+ role capabilities, payment terms do not get columns here — their plans live
+ in `spree-enterprise-v2/docs/plans/` and consume hooks/slots/policies (the
+ model-not-the-feature rule, decisions.md 2026-08-07).
+- **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`).
+- **`kind` values are the fixed two.** New node semantics (franchise, cost
+ centre labels, …) are custom fields or future additive kinds — never
+ overloaded onto `division`. 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:
+
+1. **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.md` Phase 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.
+- `spree-enterprise-v2/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` — approval substrate the
+ Enterprise flow rides (approver polymorphic, membership anticipated).
+- 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 under
+ `packages/dashboard/src/routes/_authenticated/$storeId/companies/`.
diff --git a/docs/plans/6.1-channels-catalogs-b2b.md b/docs/plans/6.0-channels-catalogs-b2b.md
similarity index 98%
rename from docs/plans/6.1-channels-catalogs-b2b.md
rename to docs/plans/6.0-channels-catalogs-b2b.md
index f32129daf9..4ad0b478b7 100644
--- a/docs/plans/6.1-channels-catalogs-b2b.md
+++ b/docs/plans/6.0-channels-catalogs-b2b.md
@@ -1,9 +1,9 @@
# Channels, Catalogs & B2B Companies
-**Status:** Phase 1 shipped in 5.5 (Channel + new `spree_product_publications` table + single-store Product + channel-aware scopes + Admin API action endpoints + Store API back-compat + legacy admin Channels CRUD + Publishing card + dashboard SPA + Meilisearch channel filter); gated storefront access **shipped in 5.6** (`Spree::Channel::Gating` + v3 Store API enforcement — see `5.6-store-channel-context-and-key-binding.md` for the follow-on channel-context endpoint + key binding); Catalog, Company tree, and pricing integration **deferred to 6.1** (the B2B release — see `decisions.md` 2026-06-16)
-**Target:** Spree 5.5 (Phase 1 ✓) → 5.6 (Gated Access ✓) → 6.1 (Catalog + Company)
+**Status:** Phase 1 shipped in 5.5 (Channel + new `spree_product_publications` table + single-store Product + channel-aware scopes + Admin API action endpoints + Store API back-compat + legacy admin Channels CRUD + Publishing card + dashboard SPA + Meilisearch channel filter); gated storefront access **shipped in 5.6** (`Spree::Channel::Gating` + v3 Store API enforcement — see `5.6-store-channel-context-and-key-binding.md` for the follow-on channel-context endpoint + key binding); the Catalog + Company phase is **superseded — see below**
+**Target:** Spree 5.5 (Phase 1 ✓) → 5.6 (Gated Access ✓) → 6.0 (Catalog + Company, via the superseding plan)
-> **Filename note:** this plan keeps its `6.0-` filename for stable cross-references (it's linked from CLAUDE.md and ~10 sibling plans), but the Phase 2 deliverable (Catalog + Company) now targets **6.1**. Don't infer the target from the filename — the header and per-phase headings are authoritative. Phase 1 (5.5) and the 5.6 Gated Access phase are unaffected.
+> **Superseded (2026-08-25):** the Phase 2 deliverable (Catalog + Company tree + pricing integration) is pulled back into **6.0** and redesigned by **`6.0-b2b-companies-and-catalogs.md`** — B2B is a 6.0 headline and the merged-but-unreleased Company → CompanyLocation → CompanyContact tree is replaced by a multi-level `Spree::Company` organization tree (typed nodes, address book, subtree-scoped memberships, subtree catalog inheritance). The Company/Catalog model sketches and the Phase 2 migration below are the **historical record only** — several details were superseded even before the redesign (`tax_exempt` booleans are not built per decisions.md 2026-08-07; contacts shipped against `customer_id`, not `user_id`) and none of them should be implemented from this file. Phase 1 (5.5) and the 5.6 Gated Access phase remain this plan's authoritative shipped record, including the Gating × Catalog composition rules, which the superseding plan inherits unchanged.
**Depends on:** ProductType (6.0-product-types.md), PriceList system (existing)
**Author:** Damian + Claude
**Last updated:** 2026-08-05
diff --git a/docs/plans/6.0-replace-taxons-with-categories.md b/docs/plans/6.0-replace-taxons-with-categories.md
index 6524fd851d..d25b1463fe 100644
--- a/docs/plans/6.0-replace-taxons-with-categories.md
+++ b/docs/plans/6.0-replace-taxons-with-categories.md
@@ -1,6 +1,6 @@
# Replace Taxons with Categories & Add Collections
-**Status:** Shipped to `6-0-dev` (PR #14302, merged 2026-07-19). The Category read/write surface landed earlier (5.5–5.6); PR #14302 completed the 6.0 core: the `spree_taxons` → `spree_categories` table rename + inheritance flip (`Spree::Category < Spree.base_class`, `Spree::Taxon` retained as a deprecation alias), the full `Collection` stack (model + join + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data-migration task, and de-ruling Category. **Remaining (all 6.1):** the channel-aware reimplementation of `CollectionRules::AvailableOn` — Phase 5, which ships now with an interim legacy-`available_on` `apply` and rides with `6.1-channels-catalogs-b2b.md`; and dropping `spree_taxon_rules` + `Spree::TaxonRule`/`TaxonRules::*` + the `Taxonomy` model and table (Phase 6). Taxonomy became **data-only** in 6.0 — Phase 5b removed every runtime path that created, touched or validated one, leaving only the upgrade task's reader and the pre-upgrade store-resolution fallbacks. Nothing 6.0-blocking is left.
+**Status:** Shipped to `6-0-dev` (PR #14302, merged 2026-07-19). The Category read/write surface landed earlier (5.5–5.6); PR #14302 completed the 6.0 core: the `spree_taxons` → `spree_categories` table rename + inheritance flip (`Spree::Category < Spree.base_class`, `Spree::Taxon` retained as a deprecation alias), the full `Collection` stack (model + join + rules + DB/Meilisearch manual sort + API), the taxon→category/collection data-migration task, and de-ruling Category. **Remaining (all 6.1):** the channel-aware reimplementation of `CollectionRules::AvailableOn` — Phase 5, which ships now with an interim legacy-`available_on` `apply` and rides with `6.0-channels-catalogs-b2b.md`; and dropping `spree_taxon_rules` + `Spree::TaxonRule`/`TaxonRules::*` + the `Taxonomy` model and table (Phase 6). Taxonomy became **data-only** in 6.0 — Phase 5b removed every runtime path that created, touched or validated one, leaving only the upgrade task's reader and the pre-upgrade store-resolution fallbacks. Nothing 6.0-blocking is left.
**Target:** Spree 6.0 (Category surface landed in 5.5–5.6; 6.0 renames the table, splits out `Collection`, and drops `Taxonomy`)
**Depends on:** API v3 conventions, ProductType plan (6.0-product-types.md), Rich Text Descriptions plan (6.0-rich-text-descriptions.md), Admin SPA plan (6.0-admin-spa.md — dashboard UI), Channels/Publications plan (6.0-channels-catalogs-b2b.md — the `CollectionRules::AvailableOn` rule's channel-aware implementation depends on its `available_on` → `ProductPublication#published_at` migration; see Migration Phase 5)
**Author:** Damian + Claude
diff --git a/docs/plans/6.0-store-scoped-configuration.md b/docs/plans/6.0-store-scoped-configuration.md
index a5be3ea794..7343683e13 100644
--- a/docs/plans/6.0-store-scoped-configuration.md
+++ b/docs/plans/6.0-store-scoped-configuration.md
@@ -2,7 +2,7 @@
**Status:** Phases 1 and 2 shipped (2026-08-12) — all eight movers live on Store, exposed in the Admin API and dashboard. The two capture booleans were folded into one `capture_method` string on 2026-08-13. Phase 3 (deleting the globals) remains for 6.1
**Target:** Spree 6.0 (globals deleted in 6.1)
-**Depends on:** Single-owner Product (`6.1-channels-catalogs-b2b.md`, shipped 5.5), Cart/Order split (`6.0-cart-order-split.md`), Tax provider (`6.0-tax-provider.md`, for the `tax_using_ship_address` retirement)
+**Depends on:** Single-owner Product (`6.0-channels-catalogs-b2b.md`, shipped 5.5), Cart/Order split (`6.0-cart-order-split.md`), Tax provider (`6.0-tax-provider.md`, for the `tax_using_ship_address` retirement)
**Author:** Damian + Claude
**Last updated:** 2026-08-12
diff --git a/docs/plans/6.0-tax-provider.md b/docs/plans/6.0-tax-provider.md
index 918236b0aa..60b82f8439 100644
--- a/docs/plans/6.0-tax-provider.md
+++ b/docs/plans/6.0-tax-provider.md
@@ -11,7 +11,7 @@
> **Contract refinement (2026-08-05):** the provider contract was reworked after the community review on spree/spree#14056, with every concern verified against primary sources (EN 16931 / VAT Directive / VIES), the major provider APIs (Avalara, Stripe Tax, TaxJar, Vertex) and platform practice (Medusa, Saleor, commercetools, Shopify, Magento, Odoo). Headlines: tax results carry a **taxability reason**, not just an amount; buyer tax identity becomes a first-class **`Spree::TaxIdentifier`** model with an order-time snapshot; exemption is a **typed estimate input** (the boolean `exempt?` is removed); the **effective date** is an explicit input; providers declare **capability limits** honestly. See Key Decisions.
**Target:** Spree 6.0
-**Depends on:** Split Adjustments (6.0-6.1-split-adjustments.md — shipped; provides TaxLine). Phase 7 pulls the Company tree forward out of `6.1-channels-catalogs-b2b.md` rather than waiting on it — that plan keeps Catalog, per-company pricing and product visibility, and inherits the models this phase ships.
+**Depends on:** Split Adjustments (6.0-6.1-split-adjustments.md — shipped; provides TaxLine). Phase 7 pulls the Company tree forward out of `6.0-channels-catalogs-b2b.md` rather than waiting on it — that plan keeps Catalog, per-company pricing and product visibility, and inherits the models this phase ships.
**Author:** Damian + Claude
**Last updated:** 2026-08-11
@@ -1216,7 +1216,7 @@ directly on admin-created orders. Refusing to guess is the point — picking one
business for another's purchase.
Choosing *between* branches is deliberately not answered here. It is the same question
-`6.1-channels-catalogs-b2b.md` leaves open for product visibility — its `user_company_location(user,
+`6.0-channels-catalogs-b2b.md` leaves open for product visibility — its `user_company_location(user,
store)` helper is called but never defined — and that plan defers buyer authority to a dedicated B2B
plan after 6.1. Whatever it settles on replaces `Spree::Purchase::Company#resolved_company_location`.
This is the only piece of B2B *behavior* in the phase; everything else is data.
@@ -1484,7 +1484,7 @@ manifest, so every install arriving at 6.1 has run them.
it.
- **No `tax_exempt` boolean anywhere.** Not on Company, not on CompanyLocation, not on Customer. Exemption
is a `Spree::TaxExemption` entry resolved from a certificate; a flag cannot name its jurisdiction or its
- lines. This supersedes the Company and CompanyLocation sketches in `6.1-channels-catalogs-b2b.md`.
+ lines. This supersedes the Company and CompanyLocation sketches in `6.0-channels-catalogs-b2b.md`.
- **Don't build Catalog while building Company.** Phase 7 ships Company, CompanyLocation, CompanyContact and
certificates only. Catalog, `default_catalog_id`, per-company pricing, `Products::ForContext` and the
CustomerGroup link stay with the B2B release, which inherits these models rather than redefining them.
@@ -1549,7 +1549,7 @@ Sources for the plain-English legal claims made above — for anyone verifying t
- Community review driving the 2026-08-05 revision: spree/spree#14056 (treatment-not-amount, VAT ID validity, immutability, capability honesty)
- Legacy Avalara integration (field mappings + user-level exemption storage precedent): `spree_avatax_official`
- Related plan: `6.0-6.1-split-adjustments.md` (TaxLine schema; order-level money freeze)
-- Related plan: `6.1-channels-catalogs-b2b.md` (Company/CompanyLocation — durable tax identifiers, exemption certificates)
+- Related plan: `6.0-channels-catalogs-b2b.md` (Company/CompanyLocation — durable tax identifiers, exemption certificates)
- Related plan: `6.0-service-workflows.md` (workflow tiers, hooks contract, `set_tax_line_context`)
- Related plan: `6.0-returns-exchanges-claims.md` (returns flow triggers `provider.refund`)
- Related plan: `6.0-delivery-rate-provider.md` (Zone survival scope; delivery-side rate display)
diff --git a/docs/plans/decisions.md b/docs/plans/decisions.md
index 23c2879b42..b544baed42 100644
--- a/docs/plans/decisions.md
+++ b/docs/plans/decisions.md
@@ -1138,7 +1138,7 @@ Plan: `docs/plans/6.0-consolidate-metadata-columns.md`.
## 2026-08-07: The tax plan builds the minimal Company tree; the B2B release keeps Catalog
Exemption certificates need an entity to hang off, and `Spree::Company` does not
-exist — `6.1-channels-catalogs-b2b.md` targets 6.1. Rather than leave the tax
+exist — `6.0-channels-catalogs-b2b.md` targets 6.1. Rather than leave the tax
plan's last phase blocked behind a release, `6.0-tax-provider.md` Phase 7 builds
**Company → CompanyLocation → CompanyContact** plus
`Spree::TaxExemptionCertificate`, and the B2B release inherits those models
@@ -1159,7 +1159,7 @@ flag cannot say which jurisdiction it holds in or which lines it covers, and
removing the boolean `exempt?` from the provider contract was the substance of
the 2026-08-05 refinement — reintroducing it a layer down would undo it.
Exemption is a certificate resolved into a typed `Spree::TaxExemption` entry.
-**`6.1-channels-catalogs-b2b.md` still needs this note added to its own Key
+**`6.0-channels-catalogs-b2b.md` still needs this note added to its own Key
Decisions** — deliberately not edited yet, at the author's instruction.
**Explicitly not pulled forward:** Catalog, CatalogProduct, CatalogAssignment,
@@ -3268,7 +3268,7 @@ plus the guest-token order-listing scope — live in
engine — its "rules" were ownership conditions and token blocks, and CanCanCan
block rules can't power `accessible_by`, so controllers carried both a scope
AND an `authorize!` for the same fact. Second, the Enterprise B2B module
-(`6.1-channels-catalogs-b2b.md`) must extend storefront authority without
+(`6.0-channels-catalogs-b2b.md`) must extend storefront authority without
decorating controllers, and a policy object is the right seam: **access
widening** (approver sees company-location purchases) = subclass the policy and
override `scope`/`readable?`/`writable?`; **action vetoes** (approvals,
@@ -3298,7 +3298,7 @@ which code-defined sets cannot provide. The policy protocol is generic
(`readable?`/`writable?`/`scope` with an ownership default), so wishlists,
newsletter subscriptions and any new resource route through the same seam
with no wiring; `/customers/me/*` endpoints stay owner-scoped by definition.
-Full B2B architecture: `6.1-channels-catalogs-b2b.md` → "Company roles and
+Full B2B architecture: `6.0-channels-catalogs-b2b.md` → "Company roles and
approvals".
## 2026-08-12 — OpenTelemetry: notifications in core, spans in an optional gem, traces only
@@ -3680,3 +3680,77 @@ customer internal notes. Both are the general shape: **a store-owned model
whose rows can exist unattached needs `store_id` wherever tenancy was
previously implied by a parent.**
Plan: `6.0-media-library.md`.
+
+## 2026-08-25 — B2B moves into 6.0; the company model becomes a multi-level organization tree
+
+B2B is a 6.0 deliverable — customers are waiting on it. The Catalog + Company
+phase parked in 6.1 comes back into 6.0, and `6.1-channels-catalogs-b2b.md`
+is renamed back to `6.0-channels-catalogs-b2b.md`, its Catalog/Company phase
+superseded by the new `6.0-b2b-companies-and-catalogs.md`.
+
+The Company → CompanyLocation → CompanyContact tree that shipped with
+tax-provider Phase 7 is merged but **unreleased**, so it is replaced outright
+— no bridges, no data migration, migrations rewritten in place (the recorded
+exception to the bridges convention applies: unreleased code gets no bridge).
+The replacement is the from-scratch design, chosen over patching a
+`parent_id` onto the shipped shape: Shopify's `CompanyLocation` conflates
+org-unit, address pair, and terms anchor — the known weakness that forces one
+node per ship-to site. No competitor ships organization hierarchy in open
+source (flat models everywhere; depth is paid at Vendure/BigCommerce, absent
+at Shopify/Medusa) — that gap is exactly what Spree 6.0 fills.
+
+**The model.** One entity, one table: `Spree::Company` self-referential
+(`parent_id`, depth cap 5, cycle-checked, store-scoped), typed by `kind` —
+`company` (legal entity) | `division` (org unit), roots must be legal
+entities. If the kinds ever grow diverging behavior the path is STI on the
+same table, never a separate `Division` model (which would force dual-FK or
+polymorphic references on every consumer). `CompanyAddress` is an address
+book (labeled rows, at-most-one default billing/shipping) so ship-to count
+never dictates node count. `CompanyMembership` joins a customer to a node
+with **subtree standing** — membership at N authorizes N and everything
+below. Carts and orders carry `company_id` (any node, frozen at completion);
+`company_location_id` is gone.
+
+**`kind` is load-bearing for tax.** Identifiers and exemption certificates
+live only on `company` nodes; every purchase-side tax read goes through
+`Company#legal_entity` — nearest self-or-ancestor `company` node, where the
+walk **stops** whether or not it holds anything. A division is its legal
+entity; a subsidiary never borrows its parent's registration. Kept as a
+validation rather than schema so per-division foreign registrations can be
+allowed later by relaxing the validation alone.
+
+**Catalogs inherit down the tree.** `CatalogAssignment`'s assignable set is
+Channel, CustomerGroup, Market, Company; a company-node assignment applies to
+its subtree, effective catalogs are the union over `self_and_ancestors`,
+pricing takes the nearest node's assignment first, then catalog position.
+The sketched Company↔CustomerGroup link is dropped — it promised composition
+it couldn't deliver (a company "in" a group never put its buyers in that
+group); group-style targeting of companies arrives, if ever, as explicit
+rule kinds on the promotion/price-rule STI families.
+
+**OSS trusts every member; governance is Enterprise, and its plans live in
+`spree-enterprise-v2/docs/plans/`.** The Store API ships full directory
+self-service — node detail, addresses, members, subtree order history,
+writable cart `company_id` (sole standing as the default; explicit node for
+multi-node buyers, finally settling the "provisional — revisit" resolution
+question) — where **any member with standing can do everything**, including
+removing other members. That trade-off is deliberate: OSS ships no company
+roles and no member-vs-member permission logic anywhere; it ships injection
+points — the storefront access policy class and the `carts.complete.validate`
+hooks, both no-ops in OSS — which the Enterprise governance layer (roles,
+approvals, spend limits, terms, quotes) fills without OSS schema changes.
+Plan: `6.0-b2b-companies-and-catalogs.md`.
+
+**Addendum (same day):** member invitation for unregistered emails was
+briefly deferred, then folded in. Adding a member takes an email from either
+surface — dashboard or storefront — and converges: existing store customer →
+membership immediately; unknown email → `Spree::CompanyInvitation`
+(company-scoped, plaintext `has_secure_token` like the staff invitation and
+setup tokens, 30-day expiry, functional invite email in `spree/emails`,
+`company_invitation.*` events), whose unauthenticated token-accept runs
+`Customers::Create` — the single customer-creation workflow — and lands as a
+membership. Memberships stay always-active and customer-backed; pending
+state lives on the invitation, never as a nullable `customer_id` or status
+column on the membership. Invitations carry no role — Enterprise attaches
+its payload via the same dialog slot (stored in invitation `metadata` or its
+own referencing table) and applies it on `company_invitation.accepted`.