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.

19.5 KB
Raw Blame

B2B Storefront Purchasing — company self-service and checkout

Status: Implemented, in review (2026-08-27) — backend in spree/spree#14498, storefront in spree/storefront#214, both open. Everything in Design Details ships except the node rename, noted below.

Depends on: 6.0-b2b-companies-and-catalogs.md (implemented 2026-08-25 — the tree, memberships, invitations, the polymorphic address owner, and the Store API self-service surface this plan puts a face on).

Summary

The Store API already let a company's members manage their organization — memberships, invitations, the address book, the subtree's orders — but the storefront had no UI for any of it, and checkout knew nothing about companies: the buyer saw only their personal address book, and the invitation email linked to an acceptance page that did not exist.

This plan adds the missing storefront surface (a company section in the standard account area, the invitation acceptance page) and makes checkout company-aware (buying-for-company context, the company address book at the address step). It deliberately does NOT change how carts and orders are owned: a purchase keeps its two buyer-side parties — the person who placed it and the organization it is for — which is both what shipped and what the major B2B platforms converge on.

The storefront lives in its own repo (spree/storefront, branch 6-0-dev, cloned into a worktree by pnpm wt:setup and run with pnpm wt:storefront); this plan is the single record for the work in both repos.

Key Decisions (do not deviate without discussion)

  • No polymorphic owner on Cart/Order. The address move to owner_type/owner_id worked because an address has exactly one owner. A B2B purchase has two buyer-side parties with different jobs: the person (authentication, "my orders", transactional email, and the party Enterprise approvals and spend limits act on) and the organization (tax anchor, catalog and price resolution, the company orders view). Collapsing them into one polymorphic column would make "Alice bought this for Acme" unrepresentable. The industry pattern is the same dual axis: the person stays on the order and the purchasing organization is attached beside them (Shopify's purchasing-entity shape; the B2B builds on Medusa and BigCommerce likewise keep the employee and link the company). Spree already ships exactly this — customer_id plus company_id, standing-validated, sole-membership resolution, frozen at completion — so the model needs no change; this plan is surface, not schema.
  • OSS is the machinery, the buyer portal is Enterprise. The open-source storefront weaves company self-service into the standard account area, plain and unstyled beyond the storefront's own design system: members, invitations, addresses, company orders. The polished buyer portal — approvals inbox, spending dashboards, invoices, roles — is the packaged Enterprise product built on this machinery (tier boundary recorded in the Enterprise plans repo). Nothing in the OSS storefront may grow role-awareness: every member sees every company page, enforced by the server's standing checks, and Enterprise narrows via its access-policy subclass, not via UI flags.
  • Checkout references the company book; completion still copies. The storefront submits shipping_address_id when a saved address is picked, and the cart's ownership-guarded writers accepted only customer-owned rows. They now also accept an address owned by the cart's resolved company or an ancestor of it — the same self-and-ancestors chain Company#default_billing_address walks, so the book a division inherits for prefill is the book its buyers can pick from. Standing is already enforced upstream (a cart cannot name a company its customer lacks standing over), and completion keeps copying the address onto the order, so the book row is never frozen by a sale. A company address never enters the customer's book and vice versa; the guard refuses ids across that line exactly as it refuses another customer's.
  • A purchase deletes only the rows it owns. Pointing a cart at a book entry means the cart borrows it, so the bill/ship cascade was narrowed from dependent: :destroy to the ownerless rows — the guest's typed-in address and the snapshot completion writes. Without that, deleting a cart deleted whatever it happened to be pointing at, which for a company site is shared tenant data any member could have wiped. Purchase::Addresses#owns_address? is the one predicate; anything else that destroys a purchase asks it rather than restating the rule.
  • Company context is explicit past one membership. A buyer with a single standing gets catalog, pricing and tax resolved silently (sole_standing_company, shipped), but not the company address book, which needs the cart's company_id set; a buyer with several picks the node at checkout, writing the cart's company_id (shipped, standing-validated). The storefront never guesses between memberships. Buying personally remains possible: clearing the company clears catalog, pricing and tax anchoring with it.
  • The invitation acceptance page is part of this plan and is not optional. Spree::CompanyMailer links <storefront_url>/account/company-invitation?token=…, and that page used to 404. It handles both audiences the token flow serves: a new person registering (the account is created with the invited email) and an existing customer signing in to accept — refusing, as the API does, when the signed-in account's email is not the invited one.

Design Details

Storefront — account area (spree/storefront)

New pages under the authenticated account shell, listed in the account navigation only when GET /store/account/companies returns memberships:

  • /account/companies — the buyer's memberships with ancestor paths; links to each node. Skipped (redirect to the node) when there is exactly one.
  • /account/companies/[id] — the node page: the name and its ancestor path, members with add-by-email (POST …/members, which the server turns into a membership or an invitation), pending invitations with revoke, and the address book (list, create, edit, delete, set-default — all shipped endpoints). The name renders read-only: the API allows a rename and updateCompany is wired in the data layer, but no edit control ships yet — see Open Questions. Address rows reuse the storefront's existing address-card conventions; defaults are badges, actions behind a menu, as the dashboard settled.
  • /account/companies/[id]/orders — the subtree's completed orders (GET …/orders), rendered with the existing order-list components beside the buyer's personal "my orders".
  • /account/company-invitation — the acceptance page (unauthenticated route): token lookup shows who invited them to what (GET /store/company_invitations/:token returns company and store names), then either the register form (invited email fixed) or sign-in-and-accept. Success lands on the company page.

Storefront — checkout

  • Company context. When the authenticated buyer has standing, the cart page and the checkout header show "Buying for {company}" — a picker when several memberships, static text for one, absent for none. Picking writes company_id on the cart (shipped API); "buy personally" clears it. It sits on the cart as well as checkout because pricing context reads the cart's company: set later, the buyer reviews a basket priced for the wrong audience and watches the totals move at the last step.

  • Address step. With a company on the cart, AddressSelector lists the company book and the buyer's own, as labelled groups — the company's sites first, under the name of the node that owns them, then "Your addresses" — with the company's default shipping site preselected. The whole list comes from GET /store/carts/:id/addresses in one call, grouped by the owner each entry carries. Company entries submit by id like personal ones do; the "new address" form is unchanged and writes a plain cart address, never into the company book — curating the book is the account area's job. The Edit control is withheld from the company groups: those rows belong to the organization, and the customer address endpoint would refuse the write.

    Corrected 2026-10-19. This first shipped reassembling the list in the storefront from /account/companies, /companies/:id and the two address endpoints — three round-trips, and sole_standing_company restated in TypeScript, which is exactly what the cart endpoint below exists to prevent. Asking the cart also fixed a quieter wrong: every company address was labelled with the cart's node, so a headquarters dock a division inherits was filed under the division. Each entry now names its own owner.

  • Order display. The order-placed page and the account order page name the company the purchase was for (already on the store order serializer).

Backend deltas (spree/api, spree/core)

Planned as "widen one guard", and that part held — no migrations, no serializer changes, since cart and order already report the company and company addresses already carry label and the default flags. What the build added beyond it is recorded here because the plan under-read how far the customer-shaped assumptions reached.

  • Spree::Purchase::Addresses#ship_address_id= / #bill_address_id= share one selectable_address predicate that accepts the buyer's own book or the book of the company the purchase is for and its ancestors. Everything else about the writers is unchanged, including silently nulling on a refused id.
  • Company#address_book names that inherited reading list, and the store listing scope uses it. Reads inherit, writes stay with the node that owns the row — the Store API authorizes purely by what scope returns, so a division member must not reach its parent's entries through it.
  • Spree::HasAddressBook (new): owners declare where their default slots live (bill_address_id for a customer, default_bill_address_id for a company node), and every caller asks the owner instead of branching on its class. Addresses::Create / Update then work for any owner — before this, running a company entry through Update returned success while the default flag was silently dropped, because every branch that would have set it asked for the customer behind the address.
  • Each default flag carries three states, not two: true claims the slot, false gives it up when this address is what holds it, and silence leaves it alone. The release is a conditional UPDATE rather than a read-then- write, so a promotion landing in between is not undone.
  • Both company address controllers write through the address services and share one CompanyAddressWrites concern, matching the customer surface.
  • Specs: the company-book id accepted on a cart with standing; refused without a company, across companies the buyer has no standing over, for a descendant node, and for another customer's rows. The three-state flag rule is proved against both a customer and a company node in the HasAddressBook spec, including the race.

Follow-up (2026-10-15) — the guard was widened, the paths to it were not

The widened guard was only ever reachable from the model. Everything that resolves a client-supplied address id sat in front of it and narrowed to the customer first, so a company address was dropped before selectable_address saw it. This round closes that and extends the same reach to the surfaces staff use, since most B2B orders are keyed in rather than checked out.

  • Spree::Carts::Update#resolve_address_id looked the id up in cart.customer.addresses. This is the bug the storefront work was written against: a buyer picking a company site saw checkout keep whatever was in the slot before, with no error. It now asks the cart, which is the one place that knows both books.
  • selectable_address is public and takes a prefixed id or a raw key, so every caller shares one rule instead of restating it. selectable_addresses is its listing counterpart — the buyer's book unioned with the named company's address_book, soft-deleted rows excluded, limited to the countries of the purchase's market. The listing is a subset of what the writers accept: a billing address abroad is still accepted by id, but a picker never offers an address the checkout cannot deliver to.
  • The company book follows the cart's explicit company_id only (2026-10-22), never sole_standing_company. Which addresses a checkout offers is the storefront's decision; inferring the company from a sole membership made the accepted set depend on a rule the client could not see, since the cart reports the stored column. Catalog, pricing and tax keep the sole-standing fallback.
  • GET /store/carts/:id/addresses (new, read-only) returns that union. Without it a storefront has to merge the personal and company books and filter them by the market's countries itself — two places to drift from the server. Curating either book stays with the account and company surfaces; this endpoint only answers "what may this cart use". Signed-in customers only, unlike every other cart endpoint: the answer is the account's two books, not the cart's own contents, and a guest token proves possession of a cart — possibly one the buyer adopted from whoever started it — rather than of the account. It costs nothing, since a guest cart has neither book. Each entry carries its owner so a picker can label the books from the one response. Without it the client can tell a warehouse from a flat only by asking which company the cart is for — the resolution this endpoint exists to keep on the server. owner is part of every Address, not a checkout-only variant: one type serves the picker, the cart's own addresses and the company book (whose listing also mixes a node's own sites with inherited ones). It is null for an address in no book — a guest's, or the copy a placed order keeps.
  • Spree::Orders::Create accepts a company site as shipping_address_id/billing_address_id, and use_customer_default_address fills from the company's defaults (inherited from ancestors) when the request names one. It does not fall back to the buyer's personal default there: an order for the organization ships to the organization's sites, and substituting someone's home address is exactly the mis-delivery this surface exists to prevent.
  • Admin::Companies::AddressesController#index now lists inherited sites, matching the Store controller; writes still only reach the owning node.
  • Address#snapshot freezes the company line before dropping the owner. A node's entry normally stores none and reads the node's name through the owner, so every completed B2B order was recording a street with no business on it. The copy also keeps its owner_type so it still answers business_owned? — a business address names no person, and without it the snapshot starts demanding a contact name it never had.
  • Ownership is owner_id, never owner_type. The line above overloads the type column: a business snapshot has a type and no id. Every test of "does anyone own this row" therefore reads the id — owns_address?, and Customers::Anonymize, which matched on both and so quietly stopped erasing the contact details on B2B order snapshots. Nothing fails loudly when a privacy sweep covers less than it did, so new code near this column gets a spec rather than a careful reading.
  • Dashboard: the new-order page offers both books behind the existing "use default addresses" switch, through a headless AddressSelect in dashboard-ui.

Explicitly out of scope

  • Roles, approvals, spend limits, order-on-behalf, invoices — Enterprise (buyer portal).
  • Guest checkout for a company; a company must be bought for by a signed-in member.
  • Terms/net-payment and quotes — future plans on the Enterprise side.
  • The (wholesale) demo route group in the storefront stays what it is — a customer-group gated catalog demo. The company flow composes with it (a wholesale buyer may also be a company member) but shares no code paths.

Migration Path

Nothing to migrate: no schema changes, no renames. The storefront work is additive pages in a separate repo; the backend delta widens an acceptance guard.

Constraints on Current Work

  • New storefront company UI calls only the shipped Store API self-service endpoints — no new bespoke endpoints without updating this plan.
  • Anything resolving a client-supplied address id for a cart or an order asks the purchase (selectable_address / selectable_addresses), never a book directly. Narrowing to the customer in front of the guard is what broke this once already, and it fails silently.
  • Nothing storefront-side may branch on a member's "role" — OSS has none; gate on standing (the server already does) and nothing else.
  • Cart/order code must keep treating customer_id and company_id as two independent axes; nothing may infer one from the other beyond the shipped sole_standing_company fallback.

Open Questions

Both first-cut questions were answered 2026-08-26 and folded into Design Details: the address step hid the personal book once a company was on the cart (strict B2B, the Shopify behaviour), and the company picker appears on the cart page as well as checkout so catalog pricing is honest while the buyer is still filling the basket.

The first of those was reversed on 2026-10-19: checkout now shows both books as labelled groups. The strict reading only ever held in the storefront — the cart has always accepted an id from either book — so hiding half the list made the UI disagree with the API without preventing anything. Legibility replaced omission. If the strict behaviour is wanted back, it has to be enforced on the server (refuse a personal address id once a company is on the cart), which is a contract change needing its own entry here.

  1. Should a member be able to rename their own company node from the storefront? The Store API allows it and updateCompany is wired in the storefront data layer, but no edit control ships — the node page renders the name read-only. OSS has no company roles, so shipping it means any member can rename the organization every other member buys under, which is a larger blast radius than the rest of the surface (adding a member is additive; renaming is not). Left out deliberately rather than forgotten: the merchant can rename from the dashboard, and Enterprise's roles decide who may in the portal.

  2. Should the cart token rotate when a guest cart is associated to an account? It does not today, so whoever started a cart keeps a working token after the buyer signs in and adopts it. The address listing no longer accepts that token, but everything else on the cart still does — the line items, the chosen addresses, the email. Rotating closes it and costs a contract change: the token is on the cart serializer, so the new value comes back in the associate response, and any client holding the old one (a second tab, a retried request) loses the cart. Raised by the 2026-10-19 review; not decided.

References

  • 6.0-b2b-companies-and-catalogs.md — the shipped substrate.
  • Enterprise plans repo — buyer-portal roadmap entry (tier boundary).
  • spree/storefront 6-0-dev — account shell, AddressSelector, AddressSection (submits shipping_address_id), the (wholesale) demo group.