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.
Channels, Catalogs & B2B Companies
Status: Superseded in part — Phase 1 implemented 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)
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-levelSpree::Companyorganization 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_exemptbooleans are not built per decisions.md 2026-08-07; contacts shipped againstcustomer_id, notuser_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
Summary
Add three new concepts to Spree's multi-store architecture:
- Channel — lightweight distribution surface within a Store (online, POS, Meta, wholesale portal). Controls where products are sold and how orders are attributed. Also owns the storefront access posture — whether anonymous visitors can see prices, browse at all, or check out as a guest.
- Catalog — product assortment + optional pricing override. Controls what's available and at what price for a specific audience (B2B tier, VIP group, regional assortment).
- Company — B2B customer hierarchy (Company → CompanyLocation → CompanyContact) for businesses with multiple buyers and offices.
StoreProduct is replaced by ProductPublication — the join between Product and Channel that says "this product is listed on this channel." The legacy spree_products_stores join table stays as compat surface for the spree_multi_store extension; core no longer reads or writes it.
Product is now belongs_to :store (single owner) in core. Multi-store catalog sharing — historically every Product belonged to many Stores via spree_products_stores — moves to the spree_multi_store extension. This matches Medusa/Saleor/Vendure: the catalog has one owner, distribution to multiple selling surfaces happens through channels.
Problem
No product visibility control within a store.
StoreProductis binary — a product is in a store or it isn't. There's no way to say "this product is on the online store but not the POS" or "wholesalers see these 500 SKUs, retail sees 2000."No order attribution.
Order.channelexists as a free-text varchar but isn't connected to any model. You can't query "all POS orders this month" reliably or configure channel-specific behavior.No B2B company hierarchy.
CustomerGroupexists for user segmentation and pricing, but there's no way to model "Acme Corp has 3 offices, each with its own buyers, shipping addresses, and catalog assignments." B2B merchants need Company → Location → Contact.PriceList lacks a visibility counterpart. PriceList controls pricing, but there's no matching concept for product visibility. A wholesaler needs both different prices AND a different product assortment.
Current State
| What exists | What it does | Gap |
|---|---|---|
Store |
Config boundary — currency, tax, payments, fulfillment | Heavy, covers too much. No sub-store scoping. |
Market |
Geographic/currency region within a store | Read-only regions, no product visibility control |
StoreProduct |
Product ↔ Store join (binary visibility) | No channel/catalog dimension |
CustomerGroup |
User segmentation within a store | No company hierarchy |
PriceList + PriceRules |
Conditional pricing (customer group, market, zone, volume, user) | No visibility counterpart |
Order.channel |
Free-text varchar | Not an FK, not a model |
Architecture
Four concerns, four models:
Store (who you are — legal entity, config boundary)
→ Channels (where you sell — online, POS, Meta, wholesale)
→ ProductPublications (which products are listed on this channel)
→ Catalogs (what you sell at what price — assortment + optional PriceList)
→ CatalogProducts (which products are in this catalog)
→ PriceList (optional pricing override — existing model)
→ Markets (where your customers are — geography, currency — existing)
→ Companies (B2B — who your business customers are)
→ CompanyLocations (offices/branches with addresses)
→ CompanyContacts (buyers — linked to user accounts)
How they compose:
- A Channel has a default Catalog (all listed products, base prices)
- A Channel can have additional Catalogs assigned to CustomerGroups or CompanyLocations
- A Market can have a default Catalog (regional assortment)
- A CompanyLocation can have assigned Catalogs (B2B per-location assortment + pricing)
Product visibility resolution:
1. Request arrives with: store, channel, user (optional)
2. Base set: ProductPublications for this channel
3. If user belongs to a CompanyLocation with Catalogs:
→ Intersect with CatalogProducts from those Catalogs
4. Else if user belongs to a CustomerGroup with a Catalog:
→ Intersect with CatalogProducts from that Catalog
5. Else: show all channel listings (default catalog)
Price resolution (extends the Internal pricing provider's resolution — Spree::PricingProvider::Internal::Resolution, formerly Pricing::Resolver, moved 2026-08-19):
1. Check Catalog's PriceList (if Catalog has one)
2. Check other applicable PriceLists (existing PriceRule system)
3. Fall back to base price
Key Decisions (do not deviate without discussion)
Channel
- Lightweight model — not a config container. Store owns heavyweight config (currency, tax, payment methods, delivery methods). Channel is just a distribution surface.
- Belongs to Store (SingleStoreResource). One store can have many channels.
Order.channelbecomes a FK replacing the free-text varchar.- Each Channel can have its own PublishableApiKey — so a storefront app, a POS app, and a Meta integration each get their own key scoped to their channel.
- Default channel created per store — "Online Store" is always present.
storefront_access(tiered enum) lives on Channel,nilfalling back to a store-level default ofpublic. Gating is a per-channel posture, not store-wide — one store can run a public B2C channel and alogin_requiredwholesale channel side by side. Enforced in the v3 Store API, not the storefront.- Channel gains its own
guest_checkout,nil→ store fallback; theStorepreference is kept as the fallback (not removed — non-breaking), and the resolved value is enforced server-side in the v3 Store API for the first time.
ProductPublication (replaces StoreProduct)
- New
spree_product_publicationstable. Joins Product to Channel, not Product to Store. - No
store_idcolumn — the publication's store ischannel.store(delegated). Cross-store reporting joins throughspree_channels. - Carries publication-specific data —
published_at,unpublished_at(scheduled publishing). positionwas dropped from the original sketch — nothing in 5.5 reads it andacts_as_listadded aMAX(position)query per insert for no gain. Clean additive migration later if per-channel ordering ever becomes a real requirement.- Store-level scoping is direct —
Spree::Store has_many :productsviastore_idon Product. The historicstore.products through: :store_productsjoin is gone from core.
Catalog
- Belongs to Store. A catalog can be shared across channels within the same store.
- Has many CatalogProducts (visibility) + optional belongs_to PriceList (pricing).
- Catalog without PriceList = assortment-only (use base prices). Catalog with PriceList = assortment + pricing.
- Multiple Catalogs can apply — when a CompanyLocation has 2 Catalogs, product visibility is the UNION of both. Pricing uses the first matching Catalog's PriceList (priority by position).
- Default Catalog per Channel — optional. If set, only products in the default catalog are visible on that channel. If not set, all ProductPublications are visible.
Company (B2B)
- Company → CompanyLocation → CompanyContact hierarchy.
- Company belongs to Store. Represents a business customer (Acme Corp).
- CompanyLocation belongs to Company. Represents an office/branch. Has billing address, shipping address, tax exemption settings. Can have assigned Catalogs.
- CompanyContact belongs to CompanyLocation. Links to a User (Spree.user_class). A user can be a contact at multiple locations.
- CustomerGroup is NOT replaced. Companies and CustomerGroups serve different purposes: CustomerGroup is a flat segmentation tag (VIP, Wholesale). Company is a hierarchical B2B entity. A Company can be IN a CustomerGroup.
- Tax obligations from
6.0-tax-provider.md(2026-08-05): Company becomes an owner onspree_tax_identifiers(company_idFK — the durable VAT/tax registration for the entity, joining the resolution chain above the customer's own row), andCompanyLocationis the eventual home for per-branch registrations (Shopify'sCompanyLocation.taxRegistrationIdprecedent).Spree::TaxExemptionCertificatehangs off Company (has_many :tax_exemption_certificates) but is specified and built by the tax-provider plan's last phase, which is gated on Company shipping — see that plan for the schema and the model. Nothing is owed here beyond the association.
Design Details
Channel (shipped in 5.5)
See spree/core/app/models/spree/channel.rb. Final shape:
defaultboolean column +scope :default+ partial unique index(store_id) WHERE default = TRUEon Postgres/SQLite (model-level uniqueness validation on MySQL).before_validation :promote_first_channel_to_defaultauto-promotes the first channel created on a store;after_save :demote_other_defaultsenforces single-default invariant when an admin flips the flag.- No
default_catalog_id— waits for Catalog in 6.0. - Includes routing-rules associations +
preference :order_routing_strategyfrom6.0-order-routing.md. #add_products(product_ids, published_at:, unpublished_at:)bulk-UPSERTs publications. Idempotent: re-publishing an already-published product is a no-op for its window unless dates are explicitly passed (usesArel.sql('updated_at = <table>."updated_at"')for the conflict clause to satisfy PG's DO UPDATE requirement without rewriting columns).#remove_products(product_ids)mirrorsadd_products— destroys publications, touches the channel.- Touches every product via
Product.where(id: product_ids).touch_all+enqueue_search_indexafter the upsert, sinceupsert_allbypassesbelongs_to :product, touch: true.
ProductPublication (shipped in 5.5 — new table)
See spree/core/app/models/spree/product_publication.rb. Final shape:
- New table
spree_product_publicationswith columnsproduct_id,channel_id,published_at,unpublished_at,created_at,updated_at. Nostore_idcolumn —delegate :store, :store_id, to: :channelfor in-memory access; cross-store reporting queries join throughspree_channels. - Unique index on
(product_id, channel_id).(product_id, channel_id, store_id)was abandoned along with the in-place reshape. Spree::StoreProductdeleted. The class is gone in 5.5. Apps on 5.4 that referenced it directly must update toSpree::ProductPublication.- Legacy
spree_products_storestable left untouched. Core no longer reads or writes it. The upcoming spree_multi_store extension uses it to restore theProduct has_many :storesassociation for merchants who need shared catalogs across stores.
prefix :pp, validates (product, channel), validates unpublished_at_after_published_at, has a published scope.
Product (shipped in 5.5 — single store ownership)
See spree/core/app/models/spree/product.rb and spree/core/app/models/spree/product/channels.rb. Final shape:
belongs_to :store, optional: truewithbefore_validation :assign_default_store(usesSpree::Current.store→Spree::Store.defaultfallback).has_many :product_publications(autosave) +has_many :channels, -> { distinct }, through: :product_publications.accepts_nested_attributes_for :product_publicationsfor Rails nested-attribute form writes (legacy admin Publishing card).- Custom
product_publications=setter for SPA's hash-array payload — full-set semantics (rows absent from the payload are destroyed). Coexists with the nested-attributes path on different keys. - Deprecated
available_on=/discontinue_on=setters write through to every publication'spublished_at/unpublished_at. Readers prefer the current-channel publication's value with a ternary fallback (publication ? publication.send(attr) : super()) —||would masknilfrom an always-live publication. #stores/#stores=/#store_ids/#store_ids=bridges inSpree::Product::LegacyMultiStoreSupport(auto-included unlessSpreeMultiStoredefines), preserved as deprecation warnings for legacy callers.set_default_publicationcallback removed. New products created via the Admin API are not auto-published — the caller suppliesproduct_publications: [{ channel_id }]. The dashboard SPA's create form does auto-publish on the store's default channel (Shopify-style); the legacy admin form has a Publishing card with the same UX.
Store#default_channel via boolean column
# spree/core/app/models/concerns/spree/stores/channels.rb
has_one :default_channel, -> { default }, class_name: 'Spree::Channel'
def ensure_default_channel
return if default_channel
channels.create!(name: 'Online Store', code: Spree::Channel::DEFAULT_CODE)
end
The default scope on Channel resolves the right row by the boolean column — no string-code lookup, no fragile rename hazard.
Catalog
class Spree::Catalog < Spree.base_class
has_prefix_id :cat
include Spree::SingleStoreResource
include Spree::Metafields
include Spree::Metadata
belongs_to :store, class_name: 'Spree::Store'
belongs_to :price_list, class_name: 'Spree::PriceList', optional: true
has_many :catalog_products, class_name: 'Spree::CatalogProduct', dependent: :destroy
has_many :products, through: :catalog_products
# Who sees this catalog
has_many :catalog_assignments, class_name: 'Spree::CatalogAssignment', dependent: :destroy
validates :name, presence: true
acts_as_list scope: :store_id
scope :active, -> { where(active: true) }
attribute :active, :boolean, default: true
end
CatalogProduct
class Spree::CatalogProduct < Spree.base_class
belongs_to :catalog, class_name: 'Spree::Catalog', touch: true
belongs_to :product, class_name: 'Spree::Product'
validates :catalog, :product, presence: true
validates :product_id, uniqueness: { scope: :catalog_id }
acts_as_list scope: :catalog_id
end
CatalogAssignment (who sees this catalog)
class Spree::CatalogAssignment < Spree.base_class
belongs_to :catalog, class_name: 'Spree::Catalog'
# Assignable: Channel, CustomerGroup, CompanyLocation, Market
belongs_to :assignable, polymorphic: true
validates :catalog, :assignable, presence: true
validates :catalog_id, uniqueness: { scope: [:assignable_type, :assignable_id] }
end
Note: this is polymorphic, but the assignable set is small (4 types) and CatalogAssignment is never queried in hot paths — it's loaded once at session start and cached. The assignment direction is "who gets this catalog" not "what catalogs does this entity have" — so we query by catalog, not by assignable.
Company
class Spree::Company < Spree.base_class
has_prefix_id :comp
include Spree::SingleStoreResource
include Spree::Metafields
include Spree::Metadata
belongs_to :store, class_name: 'Spree::Store'
belongs_to :customer_group, class_name: 'Spree::CustomerGroup', optional: true
has_many :company_locations, class_name: 'Spree::CompanyLocation', dependent: :destroy
has_many :company_contacts, through: :company_locations
validates :name, presence: true
# Identity in an ERP/CRM is Spree::ExternalReference, not a column — a
# company is known to several systems under different keys
# (`6.0-third-party-pricing-inventory.md`, shipped 2026-08-18).
include Spree::HasExternalReferences
attribute :tax_exempt, :boolean, default: false
end
CompanyLocation
class Spree::CompanyLocation < Spree.base_class
has_prefix_id :cloc
belongs_to :company, class_name: 'Spree::Company', inverse_of: :company_locations
belongs_to :billing_address, class_name: 'Spree::Address', optional: true
belongs_to :shipping_address, class_name: 'Spree::Address', optional: true
has_many :company_contacts, class_name: 'Spree::CompanyContact', dependent: :destroy
has_many :users, through: :company_contacts
# Catalog assignments for this location
has_many :catalog_assignments, as: :assignable, class_name: 'Spree::CatalogAssignment'
has_many :catalogs, through: :catalog_assignments
has_many :orders, class_name: 'Spree::Order', inverse_of: :company_location
validates :name, presence: true
attribute :tax_exempt, :boolean, default: false # overrides company-level
attribute :external_id, :string
end
CompanyContact
class Spree::CompanyContact < Spree.base_class
has_prefix_id :cc
belongs_to :company_location, class_name: 'Spree::CompanyLocation', inverse_of: :company_contacts
belongs_to :user, class_name: Spree.customer_class.to_s
has_one :company, through: :company_location
validates :user, :company_location, presence: true
validates :user_id, uniqueness: { scope: :company_location_id }
attribute :role, :string, default: 'buyer' # buyer, admin, viewer
end
Company roles and approvals — storefront authorization (Enterprise on OSS seams)
Contact roles enforce through the storefront seams, never by decorating Store API controllers (decisions.md 2026-08-08). The full architecture, settled 2026-08-08 while designing the seams:
Company roles are data, not code. The string role attribute above is a
placeholder; the real model is an Enterprise Spree::CompanyRole —
capabilities JSON array over a fixed company capability vocabulary
(place_orders, approve_orders, view_location_purchases,
view_company_purchases, manage_company_contacts,
manage_company_addresses, …) with CompanyContact referencing a role. Data
because the company admin manages contacts and roles themselves, through
Enterprise storefront endpoints (/api/v3/store/company/*) gated by
manage_company_contacts, with anti-escalation mirroring the staff
RoleGrantGuard pattern. This is the commercetools associate-roles shape
(data roles over a fixed capability vocabulary) and the reason storefront
permission sets were not revived: code-defined sets cannot be edited by a
company admin in a UI. The vocabulary is Enterprise-owned and never shared
with the staff catalog (6.0-admin-rbac.md: write_orders means "manage
the store's orders" to staff, "place my company's orders" to a buyer).
Visibility is a policy subclass. Enterprise CompanyAccessPolicy < Spree::Storefront::AccessPolicy, registered via
Spree::Dependencies.storefront_access_policy_class. scope / readable? /
writable? widen carts, orders and shared wishlists per the contact's
capabilities — an approver lists their location's pending carts through the
same core endpoints every customer uses.
The approval flow rides an Enterprise-owned approval record
(5.5-6.0-order-cancellation-and-approval.md was superseded 2026-09-02 —
OSS ships no approval substrate):
- An employee checks out → an Enterprise
carts.complete.validatehook rejects when the contact lacksplace_ordersor exceeds their spending limit (well-knownapproval_requirederror). - The client calls the Enterprise submit-for-approval endpoint → cart-side approval record created, event published.
- The manager (
approve_orders) sees the pending cart via the widened policy and approves → an Enterprise workflow completes the cart as the approver, recording the approval (append-only history per the approval plan).
No new core seams are required: the access policy, the checkout validate
hooks, and events cover it. A standardized approval_required error code on
cart completion is a nice-to-have for this release. Contact roles never touch
Spree::Ability or the staff permission catalog.
Order gains Channel and CompanyLocation
class Spree::Order < Spree.base_class
belongs_to :channel, class_name: 'Spree::Channel', optional: true
belongs_to :company_location, class_name: 'Spree::CompanyLocation', optional: true
# Remove: string :channel column (replaced by FK)
def b2b?
company_location.present?
end
def company
company_location&.company
end
end
Store gains Channels (as-shipped in 5.5)
class Spree::Store < Spree.base_class
has_many :channels, class_name: 'Spree::Channel', dependent: :destroy
has_one :default_channel, -> { default }, class_name: 'Spree::Channel'
# 6.0 additions
has_many :catalogs, class_name: 'Spree::Catalog', dependent: :destroy
has_many :companies, class_name: 'Spree::Company', dependent: :destroy
# Direct ownership in 5.5 — products belong to a single store.
has_many :products, class_name: 'Spree::Product', dependent: :nullify
has_many :product_publications, through: :channels, source: :publications
after_create :ensure_default_channel
def ensure_default_channel
return if default_channel
channels.create!(name: 'Online Store', code: Spree::Channel::DEFAULT_CODE)
end
end
Product visibility query
class Spree::Products::ForContext
# Returns products visible to the current context
def call(store:, channel:, user: nil)
# Base: all active listings on this channel
products = channel.products.active
# If user has a company location with catalogs, filter to those
if (location = user_company_location(user, store))
catalog_ids = location.catalog_assignments.pluck(:catalog_id)
if catalog_ids.any?
catalog_product_ids = Spree::CatalogProduct.where(catalog_id: catalog_ids).select(:product_id)
products = products.where(id: catalog_product_ids)
end
# If user belongs to a customer group with a catalog
elsif (group_catalog_ids = user_group_catalog_ids(user, store)).any?
catalog_product_ids = Spree::CatalogProduct.where(catalog_id: group_catalog_ids).select(:product_id)
products = products.where(id: catalog_product_ids)
end
# Else: all channel listings (no catalog filtering)
products
end
end
Pricing integration
Existing Pricing::Context gains catalog awareness:
# In Spree::Pricing::Resolver
def resolve(variant, context)
# 1. Check catalog's PriceList (if context has a catalog with a PriceList)
if context.catalog&.price_list
price = find_price(variant, context.catalog.price_list, context.currency)
return price if price&.amount
end
# 2. Check other applicable PriceLists (existing logic)
# ... existing PriceRule matching ...
# 3. Fall back to base price
variant.price_in(context.currency)
end
Gated Storefront Access (5.6)
Channel owns the storefront's access posture — the gate that Medusa, Saleor, and Vendure all push to the storefront layer. Spree enforces it in the v3 Store API instead, so it can't be bypassed by calling the API directly. Two orthogonal controls, both resolved from the channel the request is bound to (X-Spree-Channel, falling back to store.default_channel).
Because it builds only on the Channel infrastructure shipped in 5.5 (model, preference DSL, X-Spree-Channel resolution, v3 Store API auth context) and needs no schema migration, this ships in 5.6 — ahead of the Catalog/Company work it will later compose with in 6.0.
storefront_access — what anonymous visitors may see (tiered enum)
# spree/core/app/models/spree/channel.rb
STOREFRONT_ACCESS = %w[public prices_hidden login_required].freeze
# Empty -> falls back to the Store-level preference (mirrors order_routing_strategy).
preference :storefront_access, :string, default: nil
validates :preferred_storefront_access, inclusion: { in: STOREFRONT_ACCESS }, allow_nil: true
# spree/core/app/models/spree/store.rb — the fallback default
preference :storefront_access, :string, default: 'public'
| Value | Products | Prices | Use case |
|---|---|---|---|
public |
visible to anyone | visible to anyone | today's behaviour, B2C |
prices_hidden |
browsable by anyone | null for guests | B2B2C teaser — "log in to see your price" |
login_required |
401 for guests | — | trade-only portal — anonymous sees nothing |
- Resolution lives directly in the
Spree::Channel::Gatingconcern (there is no separateHasStorefrontAccessPreferenceconcern):channel.resolved_storefront_access/resolved_guest_checkoutreturn the channel value, or the store value when the channel preference isnil.guest_checkoutis declarednullable: trueso a blank write staysnil(inherit) rather than coercing tofalse. - "Guest" = no authenticated customer — a request carrying only a publishable key (or a guest cart token) with no customer JWT. A logged-in customer is never gated.
- Enforcement (v3 Store API):
prices_hidden→ the gate injects ahide_pricesserializer flag;BaseSerializer#price_for/price_inand themoney_attributeshelper (used by the product, cart, order, and line-item serializers) render every price/total fieldnullfor guest requests, so the cart can't leak what the catalog withholds. Logged-in customers (incl. B2B) serialize normally.login_required→ abefore_actionon bothStore::BaseControllerandStore::ResourceController(the two parallel Store API branches) returns401for guest requests across all Store endpoints. Public endpoints — sign in / register, password reset, and pre-login reference data (countries, currencies, locales, markets, newsletter, tokenized digital downloads) — opt out viaallow_guest_storefront_access!.
- This is the explicit "deny anonymous" gate the visibility model lacked. In 5.6 it sits in front of channel-publication visibility (shipped 5.5): a
login_requiredguest401s before any product list is built, andprices_hiddennulls prices on whatever the channel exposes. When Catalogs land in 6.0 the same gate frontsProducts::ForContext— a guest never reaches the "show all channel listings (default catalog)" fallback, and a logged-in B2B buyer sees their company-location catalog at its PriceList price.
guest_checkout — may an order be placed without an account (channel override, store fallback)
# spree/core/app/models/spree/channel.rb
# Empty -> falls back to the Store-level preference (same pattern as storefront_access).
preference :guest_checkout, :boolean, default: nil
# spree/core/app/models/spree/store.rb — retained as the fallback default (NOT removed)
preference :guest_checkout, :boolean, default: true
- Channel overrides, Store falls back. A B2C channel can allow guest checkout while a wholesale channel on the same store forbids it — the store is the wrong granularity once channels exist, but its preference is kept as the fallback so existing accessors (
store.prefer_guest_checkout) and single-channel stores keep working unchanged. Resolution:channel.resolved_guest_checkoutreturns the channel value, or the store value when the channel preference isnil. - First server-side enforcement. Today guest checkout is unenforced in the API — the legacy
Spree::Config.allow_guest_checkoutwas "only used in the rails frontend, not implemented in API" andStore#prefer_guest_checkoutonly drove the legacy admin form. In 5.6Spree::Order#guest_checkout_disallowed?(enforced inSpree::Carts::Completeso controller, payment-session, and webhook completion paths are all covered) requires an authenticated customer when the order'schannel.resolved_guest_checkoutis false. prices_hiddenimplies no guest checkout.guest_checkout_disallowed?also returns true whenever the channel hides prices from guests (storefront_prices_hidden?), regardless of theguest_checkoutflag — a buyer who cannot see prices cannot meaningfully place an order. This dissolves the otherwise contradictory "prices hidden but guests may buy" configuration in the domain layer (no cross-record validation needed); the admin forms carry a hint saying guests must sign in to check out when prices are hidden.
Migration
- No schema migration. All three are model preferences stored in the existing serialized
preferencescolumn onspree_channels/spree_stores(same mechanism asorder_routing_strategy). - No backfill required, non-breaking. Channels default to
nil→ store fallback for bothstorefront_access(→public) andguest_checkout(→ the retainedStoredefault), so existing behaviour is preserved until a merchant overrides a channel. TheStore#prefer_guest_checkoutaccessor stays valid — it remains the fallback source.
Gating × Catalog composition
Channel gating (5.6) and the Catalog/Company layer (6.0) are orthogonal and run in sequence — the gate is the front door, the catalog is the personalized shelf behind it.
| Layer | Scope | Keyed on | Where it runs | Decides |
|---|---|---|---|---|
Gate (storefront_access / guest_checkout) |
whole Channel | authenticated vs guest | v3 Store API controller/serializer | can this request see the channel / see prices / check out |
| Catalog | per Company / CustomerGroup | membership | Products::ForContext + Pricing::Resolver |
which products + which prices for this buyer |
Ordering — the gate fires first. enforce_storefront_login_required! is a before_action, so on a login_required channel a guest gets 401 before Products::ForContext runs — no catalog work for gated guests. prices_hidden sets hide_prices in serializer_params, which nulls whatever price the catalog resolver produced, so a company-catalog price is still withheld from a gated guest.
Canonical B2B shape — one wholesale channel, many company catalogs:
- Anonymous → gate
401s; the whole channel is sealed. - Company A buyer (logged in) → passes the gate →
ForContextintersects channel publications with Company A's location catalogs → Catalog A assortment at Catalog A's PriceList. - Company B buyer → Catalog B assortment + pricing.
- Logged-in user with no company/catalog → passes the gate → channel default catalog (resolution step 5).
prices_hidden + per-company PriceList = "log in to see your price." A guest browses the default catalog with prices nulled; a logged-in company buyer sees prices, and the catalog layer makes them that company's negotiated prices. The two layers cooperate: the gate withholds from anonymous, the catalog personalizes per company.
Key constraint — the gate is authenticated-vs-guest, not per-group. hide_prices? / login_required only ask "is a customer logged in"; any authenticated customer passes. Consequences:
- The gate stops anonymous visitors, not logged-in-but-unapproved ones. There is no per-catalog or per-company
storefront_access. - Restricting what an unapproved-but-logged-in user sees is the catalog's job. For an "approved companies only" portal, give the channel an empty/minimal default catalog so step-5 fallback users see nothing purchasable — rather than expecting the gate to enforce approval.
guest_checkoutis channel-wide; fine for B2B since company buyers are always real users (order.customer.present?holds).
Design rule: use separate Channels for different access postures (a public B2C channel + a login_required wholesale channel, each with its own publishable key); use Catalogs for per-company variation within a channel that shares one posture. Mirrors Shopify — B2B is a separate gated market, catalogs personalize assortment + pricing inside it.
Migration Path
Phase 1 — shipped in 5.5
Migrations (spree/core/db/migrate/):
20260508204040_create_spree_channels.rb— Channel table (shipped 5.5 with order routing). Note: the in-migrationensure_default_marketbackfill that originally lived here was removed — default-channel seeding for existing stores moves to thespree:channels:create_defaultsrake task.20260601000001_create_spree_product_publications.rb— newspree_product_publicationstable with(product_id, channel_id, published_at, unpublished_at, created_at, updated_at)+ unique index on(product_id, channel_id).20260601000002_add_store_id_to_spree_products.rb— addsstore_id(nullable),units_sold_count(default 0),revenue(default 0) tospree_products+(store_id, units_sold_count)index. Existing rows havestore_id IS NULLuntil the backfill rake runs.20260602000001_add_default_to_spree_channels.rb— addsdefaultboolean tospree_channels+ partial unique index on(store_id) WHERE default = TRUE(Postgres/SQLite; MySQL relies on the model-level uniqueness validation).
The earlier additive-then-swap pattern (reshape spree_products_stores in place) was abandoned. It carried a denormalized store_id column on the publication table and a Spree::StoreProduct STI alias for back-compat. The simpler shape — separate table, single owner on Product — is what actually shipped.
Upgrade rake (spree:channels:upgrade chains):
spree:channels:create_defaults— creates the default "Online Store" channel for every existing store (viaStore#ensure_default_channel). Idempotent.spree:upgrade:populate_publications— for every product withstore_id IS NULL, reads the legacyspree_products_storesrows (raw SELECT with parameterized binding), picks a "home" store (preferring the row whose store isdefault: true, otherwise earliest bycreated_at), setsspree_products.store_id, and creates aProductPublicationrow on each attached store's default channel. Runs in a transaction per product. Idempotent.spree:channels:backfill_order_channel_ids— populatesspree_orders.channel_idfrom the legacyspree_orders.channelstring column.spree:channels:backfill_product_publication_dates— copies the legacyProduct.available_on/Product.discontinue_oncolumns (read raw viaproduct[:column]to bypass the channel-aware reader) into each publication'spublished_at/unpublished_atwhere currently NULL.
Deploy order: code → db:migrate → rake spree:channels:upgrade. No swap migration — there's nothing to swap.
Warning: Until
spree:channels:upgraderuns, every product hasstore_id IS NULLand is invisible toProduct.for_store(store). The admin product list, storefront catalog, and search indexer all return empty. The upgrade guide docs/developer/upgrades/5.4-to-5.5.mdx makes this prominent.
Model layer:
Spree::ProductPublicationon the newspree_product_publicationstable — nostore_idcolumn,store/store_iddelegated tochannel.Spree::Product belongs_to :store(single).for_store(store)scope is nowwhere(store_id: store.id)(was a join through publications).Spree::Product::Channelsconcern ownshas_many :product_publications,has_many :channels through:, the deprecatedavailable_on=/discontinue_on=cascade, and the SPA'sproduct_publications=hash-array setter. Noset_default_publicationcallback — explicit publishing only.Spree::Product::LegacyMultiStoreSupportconcern owns#stores/#stores=/#store_ids/#store_ids=deprecation bridges (auto-included unlessSpreeMultiStoreis defined; the spree_multi_store extension supersedes them).Spree::Product.available/.active/.not_discontinuedscopes are channel-aware viaSpree::Current.channel; jobs/rake without channel context use the legacy column fallback path.Spree::Channel#add_products/#remove_productsare the canonical bulk publishing API (used by both bulk-action controllers and the legacy/SPA Publishing cards).Spree::Current.channel+X-Spree-Channelheader resolution in API v3 base controller. Falls back tocurrent_store.default_channel.
Search provider:
Spree::SearchProvider::ProductPresenterindexes a per-productchannel_ids: [...]array (computed viaproduct.product_publications.joins(:channel).where(spree_channels: { store_id: store.id })).Spree::SearchProvider::Meilisearch#system_filter_conditionsaddschannel_ids = '<current channel>'.Spree::SearchIndexable#store_ids_for_indexingreads the record's ownstore_id(was hardcoded toSpree::Store.default.idin an earlier sketch — that broke multi-store indexing).
Admin API:
GET /api/v3/admin/channels
POST /api/v3/admin/channels
PATCH /api/v3/admin/channels/:id
DELETE /api/v3/admin/channels/:id
POST /api/v3/admin/channels/:id/add_products # body: { product_ids: [...], published_at?, unpublished_at? }
POST /api/v3/admin/channels/:id/remove_products # body: { product_ids: [...] }
POST /api/v3/admin/products/bulk_add_to_channels # body: { ids: [...], channel_ids: [...] }
POST /api/v3/admin/products/bulk_remove_from_channels # body: { ids: [...], channel_ids: [...] }
The originally-planned nested CRUD (GET/POST/PATCH/DELETE /admin/channels/:channel_id/product_publications/...) was dropped — the SPA never used it, no industry precedent (Shopify/Saleor/Vendure/Medusa all expose action endpoints, not nested CRUD), and the Spree::ProductPublication model is internal join-table noise that shouldn't be a top-level API surface.
- Admin Product API dropped
available_on,discontinue_on,make_active_atfrom params + serializer. - Admin Product serializer gains
many :product_publicationsviaexpand=product_publications(with:channelpreloaded to avoid N+1). - Bulk endpoints delegate to
Spree::Channel#add_products/#remove_products(single upsert per channel, no per-product saves). Spree::Channelgains adefault: booleanserializer field so the dashboard can identify the default channel for auto-publish on product create.
Store API:
Spree::Api::V3::ProductSerializer#available_onresolves from the current channel's publicationpublished_at, falling back to the legacyProduct.available_oncolumn. Shape unchanged — single-channel stores see zero behavior change.
Legacy admin:
/admin/channelsCRUD (controller + table registration + sidebar nav under Settings + permitted attributes +ConfigurationManagementpermission grant). The settings nav labels it "Sales channels".- Product edit page has a Publishing card (
spree/admin/app/views/spree/admin/products/form/_publishing.html.erb) — channel checkboxes via Manage panel, per-publication date editor via<details>row. Writes throughaccepts_nested_attributes_for :product_publications. Mirrors the SPA's<PublishingCard>. make_active_at/available_on/discontinue_oninputs removed from the legacy admin product form's Status card — date scheduling moves to the per-publication editor on the Publishing card.
Dashboard SPA:
<PublishingCard>atpackages/dashboard/src/components/spree/products/publishing-card.tsx— full Shopify-style publishing UI with status badges (Live / Scheduled / Hidden / Not available, gated by product status), per-channel schedule editor, Manage sheet for attach/detach.- New-product form auto-publishes on the store's default channel (uses the Channel
defaultboolean). - Settings → "Sales channels" page (
packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx). - Bulk actions on product list: Add to sales channels… / Remove from sales channels….
useChannelshook query-keyed bystoreIdso switching stores within the staleTime window doesn't serve the previous store's channels.
Sample data:
bin/rake spree:load_sample_dataseeds three channels (Online Store [default], Point of Sale, Wholesale) viadb/sample_data/channels.rband explicitly publishes every loaded product on the default channel viaLoader#publish_sample_products.
Phase 1.5 — 5.6: Gated storefront access
No schema migration (preferences only — see the Gated Storefront Access design section). Deliverable on top of the shipped 5.5 channel infrastructure:
Spree::Channelgainspreference :storefront_access(nil→ store fallback) +preference :guest_checkout(nil→ store fallback);Spree::Storegainspreference :storefront_access, default: 'public'and retains its existingguest_checkoutpreference as the fallback.- Resolution methods (
resolved_storefront_access/resolved_guest_checkout) live on theSpree::Channel::Gatingconcern;guest_checkoutusesnullable: true(the:booleanpreference branch now honorsnullable:) so "inherit" is expressible. - v3 Store API enforcement:
hide_pricesserializer flag +money_attributesprice-nulling forprices_hidden;before_action401 guard onStore::BaseController+Store::ResourceControllerforlogin_required(public endpoints opt out viaallow_guest_storefront_access!); guest-checkout guard in theSpree::Carts::Completeservice (so controller, payment-session, and webhook completion paths are all covered), with the controller also returning a401early. - Non-breaking, no backfill — channels default to store fallback, preserving today's behaviour.
Phase 2 — 6.1: Catalog + Company tree + pricing integration
class CreateCatalogsCompanies < ActiveRecord::Migration[7.2]
def change
add_reference :spree_channels, :default_catalog
create_table :spree_catalogs do |t|
t.references :store, null: false
t.references :price_list
t.string :name, null: false
t.boolean :active, null: false, default: true
t.integer :position
if t.respond_to?(:jsonb)
t.jsonb :metadata
else
t.json :metadata
end
t.timestamps
end
create_table :spree_catalog_products do |t|
t.references :catalog, null: false
t.references :product, null: false
t.integer :position
t.timestamps
end
add_index :spree_catalog_products, [:catalog_id, :product_id], unique: true
create_table :spree_catalog_assignments do |t|
t.references :catalog, null: false
t.string :assignable_type, null: false
t.bigint :assignable_id, null: false
t.timestamps
end
add_index :spree_catalog_assignments, [:catalog_id, :assignable_type, :assignable_id],
unique: true, name: 'idx_catalog_assignments_unique'
create_table :spree_companies do |t|
t.references :store, null: false
t.references :customer_group
t.string :name, null: false
t.string :external_id
t.boolean :tax_exempt, null: false, default: false
if t.respond_to?(:jsonb)
t.jsonb :metadata
else
t.json :metadata
end
t.timestamps
end
add_index :spree_companies, [:store_id, :external_id], unique: true,
where: 'external_id IS NOT NULL', name: 'idx_companies_external_id'
create_table :spree_company_locations do |t|
t.references :company, null: false
t.references :billing_address
t.references :shipping_address
t.string :name, null: false
t.string :external_id
t.boolean :tax_exempt, null: false, default: false
if t.respond_to?(:jsonb)
t.jsonb :metadata
else
t.json :metadata
end
t.timestamps
end
create_table :spree_company_contacts do |t|
t.references :company_location, null: false
t.references :user, null: false
t.string :role, null: false, default: 'buyer'
t.timestamps
end
add_index :spree_company_contacts, [:company_location_id, :user_id], unique: true
add_reference :spree_orders, :company_location
end
end
Phase 2 — 6.1 Admin API additions
# Catalogs
GET /api/v3/admin/catalogs
POST /api/v3/admin/catalogs
PATCH /api/v3/admin/catalogs/:id
DELETE /api/v3/admin/catalogs/:id
POST /api/v3/admin/catalogs/:id/products
DELETE /api/v3/admin/catalogs/:id/products/:product_id
POST /api/v3/admin/catalogs/:id/assign
# Companies
GET /api/v3/admin/companies
POST /api/v3/admin/companies
PATCH /api/v3/admin/companies/:id
DELETE /api/v3/admin/companies/:id
POST /api/v3/admin/companies/:company_id/locations
PATCH /api/v3/admin/company_locations/:id
DELETE /api/v3/admin/company_locations/:id
POST /api/v3/admin/company_locations/:location_id/contacts
DELETE /api/v3/admin/company_contacts/:id
Phase 3 — 6.0 cleanup
Most of the planned 6.0 cleanup already happened in 5.5 (cleaner data model from the start). Remaining items:
- Drop
Spree::Product.available_on,Spree::Product.discontinue_on,Spree::Product.make_active_atcolumns and the deprecated setters inSpree::Product::Channels.- Blocked on
6.0-replace-taxons-with-categories.mdPhase 5.Spree::CollectionRules::AvailableOnreadsspree_products.available_on; it must be reimplemented againstpublished_atfirst, or dropping the column breaks it. That plan's Phase 5 owns the reimplementation and is sequenced before this drop.
- Blocked on
- Drop
Spree::Product::LegacyMultiStoreSupport(multi-store catalogs live in the spree_multi_store extension from 5.5 onward). - Drop
Spree::Product.for_store's legacy column-fallback branch (Spree::Product.available/.not_discontinuedalways use publications onceSpree::Current.channelis unconditionally set). - Make
spree_products.store_idNOT NULL(it's nullable in 5.5 to accommodate the post-migrate / pre-backfill window). - Drop
spree_orders.channelstring column (5.5+ already ignores it viaignored_columns). - Drop the channel-aware-scope legacy fallback branch in
Spree::Product.available/.not_discontinued(always uses publications).
Already done in 5.5 (don't redo in 6.0):
Drop— deleted in 5.5.Spree::StoreProductSTI subclassDrop— newstore_idcolumn from the publications tablespree_product_publicationstable never had it.Rename— new table created; legacyspree_products_stores→spree_product_publicationsspree_products_storesleft for spree_multi_store.
Constraints on Current Work
Spree::StoreProductis gone. UseSpree::ProductPublicationdirectly. Don't reintroduce the STI alias or any reference tospree/core/app/models/spree/store_product.rb.Spree::ProductPublicationhas nostore_idcolumn. It's delegated tochannel.store. Don't write code that callsProductPublication.where(store_id: …)— use a join:Publication.joins(:channel).where(spree_channels: { store_id: … }).Product belongs_to :store(single). Don't write new code assumingproduct.storesis a real ActiveRecord association — the deprecation bridge returnsArray(store)and won't chain. Multi-store catalogs live in spree_multi_store.Channel#defaultis a boolean column. UseSpree::Channel.default.where(store: …)orstore.default_channel. Don't look up bycode: 'online'— merchants can rename it.- Channel-aware scopes assume
Spree::Current.channelis set. API requests set it via the X-Spree-Channel header concern; jobs / rake tasks fall back to the legacy column path. Don't add new code that readsSpree::Current.channelwithout expecting either branch. Spree::Channel#add_productsis idempotent and preserves existing publication windows when called withoutpublished_at/unpublished_atkwargs. Don't change this — bulk-publish ergonomics depend on it.- 6.0 adds
default_catalog_idtospree_channels(additive — won't conflict with the 5.5 schema). - PriceList stays as-is. Catalog optionally references a PriceList — don't duplicate pricing logic.
storefront_accessis resolved per request from the bound channel (X-Spree-Channel→store.default_channel), withnil→ store fallback. Usechannel.resolved_storefront_accessfor enforcement — don't readchannel.preferred_storefront_accessdirectly (it ignores the store fallback).guest_checkoutresolves channel-first, store-fallback. TheStorepreference stays valid as the fallback (not removed); new enforcement code should resolve viaorder.channel.resolved_guest_checkoutrather than readingstore.prefer_guest_checkoutdirectly.- Gating is enforced in the v3 Store API, not the storefront.
prices_hidden/login_requiredmust hold for direct API calls — don't push the check into a storefront-only layer. - The gate is authenticated-vs-guest, not per-group. Per-company assortment and pricing is the Catalog layer's job (
Products::ForContext), which runs after the gate — don't add per-company/per-catalog logic tostorefront_accessorhide_prices?. See "Gating × Catalog composition".
Resolved Questions
Default channel behavior. Channel resolution via
X-Spree-Channelrequest header (accepts channelcode, e.g.X-Spree-Channel: online). If header is absent or doesn't match an active channel, falls back tostore.default_channel(Channel.defaultscope on thedefaultboolean column). Shipped in 5.5.How is the default channel identified? Via a
defaultboolean column onSpree::Channel, not by code. Partial unique index on Postgres/SQLite, model-level uniqueness validation on MySQL. The first channel created on a store auto-promotes; flipping the flag on a later channel auto-demotes the previous default. Looking up bycode: 'online'would have been fragile (merchants can rename the default channel).Auto-publish on product create. Admin API: no auto-publish — the caller supplies
product_publications: [{ channel_id }]. Dashboard SPA's create form: yes, auto-publishes onChannel#default == true(Shopify-style). Sample data: explicitly publishes viaLoader#publish_sample_products. Theset_default_publicationmodel callback was removed — moving the decision to the layer that knows the merchant's intent.Multi-store catalogs. Core Spree 5.5+ models Product as
belongs_to :store(single owner). Merchants who need shared catalogs across stores install the spree_multi_store extension, which restoreshas_many :stores, through: :spree_products_storeson top of the legacy join table. Matches the Medusa/Saleor/Vendure pattern (channels are the multi-brand primitive, stores are the tenant root).Cross-store onboarding via
Channel#add_products. Allowed: if a multi-store admin's API key has update permission on a product owned by sibling store A, callingPOST /admin/channels/:id/add_products(where the channel belongs to store B) co-publishes the product onto store B's channel. The product's owningstore_iddoesn't change. This is the path by which the spree_multi_store extension's "publish across stores" UX threads through core.Catalog auto-sync. Manual assignment only for 6.0, with bulk product assignment via Admin API (
POST /catalogs/:id/products/bulk). Auto-sync using CollectionRule-style patterns is a future enhancement.CompanyContact roles and B2B approval workflows. Out of scope for this plan. The 6.1 deliverable is the data model: Company, CompanyLocation, CompanyContact with a simple
rolestring column. Role-based permissions, approval workflows, purchase limits, and invoice management are deferred to a dedicated B2B plan after 6.1.Gated storefront access model. A single tiered
storefront_accessenum on Channel (public/prices_hidden/login_required),nil→ store fallback — rather than independent booleans (which permit redundant/contradictory combinations) or a prices-only boolean (which can't express a full login wall). Enforced in the v3 Store API:prices_hiddennulls price fields for guests,login_required401s catalog reads for guests. This is the explicit "deny anonymous" gate the visibility resolver lacked. Targeted for 5.6 — it builds only on the 5.5 channel infrastructure and needs no schema change, so it ships ahead of the 6.0 Catalog/Company work.Where guest checkout lives. Channel gains a
guest_checkoutpreference (nil→ store fallback), so B2C and wholesale channels on one store can differ; theSpree::Storepreference is retained as the fallback for old accessors (not removed — non-breaking). The v3 API enforces the resolved value server-side for the first time (it was previously a legacy-frontend-only preference).
Open Questions
None at this time.
References
- Channel model:
spree/core/app/models/spree/channel.rb - ProductPublication model:
spree/core/app/models/spree/product_publication.rb - Product channels concern:
spree/core/app/models/spree/product/channels.rb - Legacy multi-store bridge:
spree/core/app/models/spree/product/legacy_multi_store_support.rb - Store channels concern:
spree/core/app/models/concerns/spree/stores/channels.rb - Upgrade rake:
spree/core/lib/tasks/channels.rake(spree:channels:upgrade) - Population rake:
spree/core/lib/tasks/publications.rake(spree:upgrade:populate_publications) - User-facing concept doc:
docs/developer/core-concepts/channels.mdx - Upgrade guide:
docs/developer/upgrades/5.4-to-5.5.mdx - SPA Publishing card:
packages/dashboard/src/components/spree/products/publishing-card.tsx - Legacy admin Publishing card:
spree/admin/app/views/spree/admin/products/form/_publishing.html.erb - Related plan:
6.0-product-types.md(ProductType defines product schema) - Related plan:
6.0-replace-taxons-with-categories.md(Collections for merchandising) - Related plan:
6.0-order-routing.md(Channel-aware order routing strategies) - Storefront access + resolution concern:
spree/core/app/models/spree/channel/gating.rb(Spree::Channel::Gating) - Nullable-boolean preference support:
spree/core/lib/spree/core/preferences/preferable.rb(:booleanbranch honorsnullable:) - v3 Store API gate:
spree/api/app/controllers/concerns/spree/api/v3/storefront_gating.rb; guest-checkout guard:Spree::Order#guest_checkout_disallowed?enforced inspree/core/app/services/spree/carts/complete.rb - Price nulling:
Spree::Api::V3::BaseSerializer.money_attributes(cart/order/line-item) +price_for/price_in - Pattern reference:
spree/core/app/models/spree/order_routing/has_strategy_preference.rb(sibling channel preference → store fallback) - B2B use-case docs to reconcile:
docs/use-case/b2b/b2b-capabilities.mdx,docs/use-case/b2b/b2b-buyer-capabilities.mdx(assert gated storefronts as a shipped Community-Edition capability)