Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Add B2B gated storefront access control to channels (5.6) (#14257)
Damian Legawiecc34a5ee0cf72
diff --git a/CLAUDE.md b/CLAUDE.mdindex 08df2da605..128d6c822d 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -37,7 +37,7 @@ Multi-version plans (some phases shipped, some pending):- `5.5-6.0-order-cancellation-and-approval.md` — First-class `OrderCancellation` + `OrderApproval` models. 5.5 models + migrations shipped; 6.0 drops denormalized columns.- `5.5-6.0-display-on-to-boolean.md` — Collapse `display_on` tri-state to a single `storefront_visible` boolean. 5.5 bridge (`storefront_visible` accessor + Ransacker on `Spree::DisplayOn`) shipped; 6.0 schema rename pending.- `6.0-order-routing.md` — Two-tier extension: pluggable `Spree::OrderRouting::Strategy::Base` + STI subclasses of `Spree::OrderRoutingRule`. Phase 1 (5.5) shipped: `Channel`, `OrderRoutingRule`, strategy base + Rules + Reducer + Legacy, `preferred_stock_location_id` + `channel_id` on Order. Phase 2+ (6.0) layers Catalog/Company on top via `6.0-channels-catalogs-b2b.md`.-- `6.0-channels-catalogs-b2b.md` — Channel + ProductPublication (replaces StoreProduct) + single-owner Product (`belongs_to :store`) + Publishing card (legacy admin + SPA) + `Channel#default` boolean shipped in 5.5. Catalog, Company/CompanyLocation/CompanyContact for B2B pending in 6.0. Multi-store catalogs (historic `Product has_many :stores`) move to the `spree_multi_store` extension.+- `6.0-channels-catalogs-b2b.md` — Channel + ProductPublication (replaces StoreProduct) + single-owner Product (`belongs_to :store`) + Publishing card (legacy admin + SPA) + `Channel#default` boolean shipped in 5.5. Channel-level gated storefront access (`storefront_access` enum + channel-owned `guest_checkout`, both with store fallback, enforced in the v3 Store API) targeted for 5.6. Catalog, Company/CompanyLocation/CompanyContact for B2B pending in 6.0. Multi-store catalogs (historic `Product has_many :stores`) move to the `spree_multi_store` extension.- `5.6-6.0-single-store-promotions-payment-methods.md` — Migrate `Spree::Promotion` + `Spree::PaymentMethod` from multi-store (`has_many :stores` via `spree_promotions_stores` / `spree_payment_methods_stores` join tables) to single-owner `belongs_to :store`, mirroring the 5.5 single-owner Product migration. 5.6 (implemented): `store_id` FK + required-store presence via `Spree::SingleStoreResource`, backfill rake task (loud per-record deprecation on shared records), shared `LegacyMultiStoreSupport` deprecation bridge, deletes the `ResourceController` `store_ids=` seam, deprecates `StoreScopedResource`; multi-store sharing moves to the `spree_multi_store` extension (join tables left intact). 6.0 cleanup: enforce `null: false`, drop join tables + bridges. Paired with `6.0-channels-catalogs-b2b.md`.Pending design work (drafts, no implementation yet):diff --git a/docs/plans/6.0-channels-catalogs-b2b.md b/docs/plans/6.0-channels-catalogs-b2b.mdindex 4796941b8a..4cf4ea8d46 100644--- a/docs/plans/6.0-channels-catalogs-b2b.md+++ b/docs/plans/6.0-channels-catalogs-b2b.md@@ -1,16 +1,16 @@# 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); Catalog, Company tree, and pricing integration land in 6.0-**Target:** Spree 5.5 (Phase 1 ✓) → 6.0 (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 targeted for 5.6; Catalog, Company tree, and pricing integration land in 6.0+**Target:** Spree 5.5 (Phase 1 ✓) → 5.6 (Gated Access) → 6.0 (Catalog + Company)**Depends on:** ProductType (6.0-product-types.md), PriceList system (existing)**Author:** Damian + Claude-**Last updated:** 2026-06-02+**Last updated:** 2026-07-01## SummaryAdd 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.+- **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.@@ -92,6 +92,8 @@ Store (who you are — legal entity, config boundary)- **`Order.channel` becomes 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**, `nil` falling back to a store-level default of `public`. Gating is a per-channel posture, not store-wide — one store can run a public B2C channel and a `login_required` wholesale channel side by side. Enforced in the v3 Store API, not the storefront.+- **Channel gains its own `guest_checkout`**, `nil` → store fallback; the `Store` preference 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)@@ -385,6 +387,85 @@ def resolve(variant, context)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)++```ruby+# 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::Gating` concern (there is no separate `HasStorefrontAccessPreference` concern): `channel.resolved_storefront_access` / `resolved_guest_checkout` return the channel value, or the store value when the channel preference is `nil`. `guest_checkout` is declared `nullable: true` so a blank write stays `nil` (inherit) rather than coercing to `false`.+- **"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 a `hide_prices` serializer flag; `BaseSerializer#price_for`/`price_in` and the `money_attributes` helper (used by the product, cart, order, and line-item serializers) render every price/total field `null` for guest requests, so the cart can't leak what the catalog withholds. Logged-in customers (incl. B2B) serialize normally.+ - `login_required` → a `before_action` on **both** `Store::BaseController` and `Store::ResourceController` (the two parallel Store API branches) returns `401` for 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 via `allow_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_required` guest `401`s before any product list is built, and `prices_hidden` nulls prices on whatever the channel exposes. When Catalogs land in 6.0 the same gate fronts `Products::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)++```ruby+# 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_checkout` returns the channel value, or the store value when the channel preference is `nil`.+- **First server-side enforcement.** Today guest checkout is unenforced in the API — the legacy `Spree::Config.allow_guest_checkout` was *"only used in the rails frontend, not implemented in API"* and `Store#prefer_guest_checkout` only drove the legacy admin form. In 5.6 `Spree::Order#guest_checkout_disallowed?` (enforced in `Spree::Carts::Complete` so controller, payment-session, and webhook completion paths are all covered) requires an authenticated customer when the order's `channel.resolved_guest_checkout` is false.+- **`prices_hidden` implies no guest checkout.** `guest_checkout_disallowed?` also returns true whenever the channel hides prices from guests (`storefront_prices_hidden?`), regardless of the `guest_checkout` flag — 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 `preferences` column on `spree_channels` / `spree_stores` (same mechanism as `order_routing_strategy`).+- **No backfill required, non-breaking.** Channels default to `nil` → store fallback for both `storefront_access` (→ `public`) and `guest_checkout` (→ the retained `Store` default), so existing behaviour is preserved until a merchant overrides a channel. The `Store#prefer_guest_checkout` accessor 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 `401`s; the whole channel is sealed.+- Company A buyer (logged in) → passes the gate → `ForContext` intersects 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_checkout` is channel-wide; fine for B2B since company buyers are always real users (`order.user.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@@ -465,6 +546,15 @@ The originally-planned nested CRUD (`GET/POST/PATCH/DELETE /admin/channels/:chan- `bin/rake spree:load_sample_data` seeds three channels (Online Store [default], Point of Sale, Wholesale) via `db/sample_data/channels.rb` and explicitly publishes every loaded product on the default channel via `Loader#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::Channel` gains `preference :storefront_access` (`nil` → store fallback) + `preference :guest_checkout` (`nil` → store fallback); `Spree::Store` gains `preference :storefront_access, default: 'public'` and **retains** its existing `guest_checkout` preference as the fallback.+- Resolution methods (`resolved_storefront_access` / `resolved_guest_checkout`) live on the `Spree::Channel::Gating` concern; `guest_checkout` uses `nullable: true` (the `:boolean` preference branch now honors `nullable:`) so "inherit" is expressible.+- v3 Store API enforcement: `hide_prices` serializer flag + `money_attributes` price-nulling for `prices_hidden`; `before_action` 401 guard on `Store::BaseController` + `Store::ResourceController` for `login_required` (public endpoints opt out via `allow_guest_storefront_access!`); guest-checkout guard in the `Spree::Carts::Complete` service (so controller, payment-session, and webhook completion paths are all covered), with the controller also returning a `401` early.+- Non-breaking, no backfill — channels default to store fallback, preserving today's behaviour.+### Phase 2 — 6.0: Catalog + Company tree + pricing integration```ruby@@ -599,6 +689,10 @@ Most of the planned 6.0 cleanup already happened in 5.5 (cleaner data model from- **`Spree::Channel#add_products` is idempotent and preserves existing publication windows** when called without `published_at` / `unpublished_at` kwargs. Don't change this — bulk-publish ergonomics depend on it.- **6.0 adds `default_catalog_id` to `spree_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_access` is resolved per request from the bound channel** (`X-Spree-Channel` → `store.default_channel`), with `nil` → store fallback. Use `channel.resolved_storefront_access` for enforcement — don't read `channel.preferred_storefront_access` directly (it ignores the store fallback).+- **`guest_checkout` resolves channel-first, store-fallback.** The `Store` preference stays valid as the fallback (not removed); new enforcement code should resolve via `order.channel.resolved_guest_checkout` rather than reading `store.prefer_guest_checkout` directly.+- **Gating is enforced in the v3 Store API, not the storefront.** `prices_hidden` / `login_required` must 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 to `storefront_access` or `hide_prices?`. See "Gating × Catalog composition".## Resolved Questions@@ -616,6 +710,10 @@ Most of the planned 6.0 cleanup already happened in 5.5 (cleaner data model from7. **CompanyContact roles and B2B approval workflows.** Out of scope for this plan. The 6.0 deliverable is the data model: Company, CompanyLocation, CompanyContact with a simple `role` string column. Role-based permissions, approval workflows, purchase limits, and invoice management are deferred to a dedicated B2B plan post-6.0.+8. **Gated storefront access model.** A single tiered `storefront_access` enum 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_hidden` nulls price fields for guests, `login_required` `401`s 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.++9. **Where guest checkout lives.** Channel gains a `guest_checkout` preference (`nil` → store fallback), so B2C and wholesale channels on one store can differ; the `Spree::Store` preference 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 QuestionsNone at this time.@@ -636,3 +734,9 @@ None at this time.- 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` (`:boolean` branch honors `nullable:`)+- v3 Store API gate: `spree/api/app/controllers/concerns/spree/api/v3/storefront_gating.rb`; guest-checkout guard: `Spree::Order#guest_checkout_disallowed?` enforced in `spree/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)diff --git a/packages/admin-sdk/.changeset/store-storefront-access-gating.md b/packages/admin-sdk/.changeset/store-storefront-access-gating.mdnew file mode 100644index 0000000000..9026bb4bf3--- /dev/null+++ b/packages/admin-sdk/.changeset/store-storefront-access-gating.md@@ -0,0 +1,5 @@+---+"@spree/admin-sdk": minor+---++Expose the store-wide gated storefront defaults on the Store resource. `Store.preferred_storefront_access` (`public`, `prices_hidden`, or `login_required`) and `Store.preferred_guest_checkout` are now serialized, and `StoreUpdateParams` accepts both — letting apps read and configure the store-level fallback that channels inherit when they don't set their own posture.diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex 9152691ac2..15c066befd 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -7,6 +7,13 @@ export interface StoreUpdateParams {preferred_timezone?: stringpreferred_weight_unit?: stringpreferred_unit_system?: string+ /**+ * Store-wide default storefront posture: `public`, `prices_hidden`, or+ * `login_required`. Channels fall back to this when they don't set their own.+ */+ preferred_storefront_access?: string+ /** Store-wide default for guest checkout. Channels fall back to this. */+ preferred_guest_checkout?: boolean/** Sender address used on all transactional emails (required by the model). */mail_from_address?: string/** Customer-facing reply-to address shown in the storefront/email footer. */@@ -730,6 +737,16 @@ export interface ChannelCreateParams {* to inherit the store-level preference.*/preferred_order_routing_strategy?: string | null+ /**+ * Storefront access posture: `public`, `prices_hidden`, or `login_required`.+ * `null` (or an empty string) inherits the store-level preference.+ */+ preferred_storefront_access?: string | null+ /**+ * Whether guest checkout is allowed on this channel. `null` inherits the+ * store-level preference.+ */+ preferred_guest_checkout?: boolean | null}export interface ChannelUpdateParams {@@ -738,6 +755,16 @@ export interface ChannelUpdateParams {active?: booleandefault?: booleanpreferred_order_routing_strategy?: string | null+ /**+ * Storefront access posture: `public`, `prices_hidden`, or `login_required`.+ * `null` (or an empty string) inherits the store-level preference.+ */+ preferred_storefront_access?: string | null+ /**+ * Whether guest checkout is allowed on this channel. `null` inherits the+ * store-level preference.+ */+ preferred_guest_checkout?: boolean | null}export interface CustomerGroupUpdateParams {diff --git a/packages/admin-sdk/src/types/generated/Channel.ts b/packages/admin-sdk/src/types/generated/Channel.tsindex 1d3de42ee0..4b83b6036d 100644--- a/packages/admin-sdk/src/types/generated/Channel.ts+++ b/packages/admin-sdk/src/types/generated/Channel.ts@@ -9,6 +9,8 @@ interface Channel {active: boolean;default: boolean;preferred_order_routing_strategy: string | null;+ preferred_storefront_access: string | null;+ preferred_guest_checkout: boolean | null;created_at: string;updated_at: string;}diff --git a/packages/admin-sdk/src/types/generated/Store.ts b/packages/admin-sdk/src/types/generated/Store.tsindex 4e440d8814..3fd35327b9 100644--- a/packages/admin-sdk/src/types/generated/Store.ts+++ b/packages/admin-sdk/src/types/generated/Store.ts@@ -16,6 +16,8 @@ interface Store {preferred_timezone: string;preferred_weight_unit: string;preferred_unit_system: string;+ preferred_storefront_access: string;+ preferred_guest_checkout: boolean;created_at: string;updated_at: string;url: string;diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex f413b17015..4283fba8fe 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -279,6 +279,25 @@"Spree::OrderRouting::Strategy::Rules": "Rules (ordered)","Spree::OrderRouting::Strategy::Legacy": "Legacy"}+ },+ "storefront_access": {+ "label": "الوصول إلى المتجر",+ "help": "يتحكم في ما يراه الزوار غير المسجّلين في هذه القناة. اتركه فارغًا للاستناد إلى إعداد المتجر. عند إخفاء الأسعار، يجب على الضيوف تسجيل الدخول لإتمام الشراء.",+ "inherit": "التوريث من المتجر",+ "options": {+ "public": "عام — يمكن للجميع التصفّح ورؤية الأسعار",+ "prices_hidden": "الأسعار مخفية — يجب على الزوار تسجيل الدخول لرؤية الأسعار",+ "login_required": "تسجيل الدخول مطلوب — يجب على الزوار تسجيل الدخول للتصفّح"+ }+ },+ "guest_checkout": {+ "label": "الدفع كضيف",+ "help": "ما إذا كان بإمكان المتسوّقين إتمام الشراء دون حساب في هذه القناة. اتركه فارغًا للاستناد إلى إعداد المتجر.",+ "inherit": "التوريث من المتجر",+ "options": {+ "true": "مسموح",+ "false": "غير مسموح"+ }}},"invitation_acceptance": {@@ -537,6 +556,19 @@"preferred_weight_unit": {"label": "وحدة الوزن"},+ "storefront_access": {+ "label": "الوصول إلى المتجر",+ "help": "الإعداد الافتراضي على مستوى المتجر لما يراه الزوار غير المسجّلين. يمكن للقنوات تجاوزه. عند إخفاء الأسعار، يجب على الضيوف تسجيل الدخول لإتمام الشراء.",+ "options": {+ "public": "عام — يمكن للجميع التصفّح ورؤية الأسعار",+ "prices_hidden": "الأسعار مخفية — يجب على الزوار تسجيل الدخول لرؤية الأسعار",+ "login_required": "تسجيل الدخول مطلوب — يجب على الزوار تسجيل الدخول للتصفّح"+ }+ },+ "guest_checkout": {+ "label": "الدفع كضيف",+ "help": "الإعداد الافتراضي على مستوى المتجر لما إذا كان بإمكان المتسوّقين إتمام الشراء دون حساب. يمكن للقنوات تجاوزه."+ },"mail_from_address": {"label": "عنوان المرسل","placeholder": "[email protected]",@@ -1374,7 +1406,8 @@"title": "إعدادات المتجر","subtitle": "التكوين العام والإعدادات الافتراضية على مستوى المتجر.","tab_general": "عام",- "tab_standards": "المعايير والأشكال"+ "tab_standards": "المعايير والأشكال",+ "tab_storefront_access": "الوصول إلى المتجر"},"emails": {"title": "إعدادات Email",diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex 13c818260f..911ab820a6 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -231,6 +231,25 @@"Spree::OrderRouting::Strategy::Rules": "Regeln (geordnet)","Spree::OrderRouting::Strategy::Legacy": "Legacy"}+ },+ "storefront_access": {+ "label": "Storefront-Zugriff",+ "help": "Legt fest, was anonyme Besucher in diesem Vertriebskanal sehen. Leer lassen, um die Store-Einstellung zu übernehmen. Wenn Preise verborgen sind, müssen Gäste sich zum Bezahlen anmelden.",+ "inherit": "Vom Store übernehmen",+ "options": {+ "public": "Öffentlich – alle können stöbern und Preise sehen",+ "prices_hidden": "Preise verborgen – Besucher müssen sich anmelden, um Preise zu sehen",+ "login_required": "Anmeldung erforderlich – Besucher müssen sich anmelden, um zu stöbern"+ }+ },+ "guest_checkout": {+ "label": "Gast-Checkout",+ "help": "Ob Kunden in diesem Vertriebskanal ohne Konto zur Kasse gehen können. Leer lassen, um die Store-Einstellung zu übernehmen.",+ "inherit": "Vom Store übernehmen",+ "options": {+ "true": "Erlaubt",+ "false": "Nicht erlaubt"+ }}},"invitation_acceptance": {@@ -489,6 +508,19 @@"preferred_weight_unit": {"label": "Gewichtseinheit"},+ "storefront_access": {+ "label": "Storefront-Zugriff",+ "help": "Store-weite Vorgabe dafür, was anonyme Besucher sehen. Vertriebskanäle können dies überschreiben. Wenn Preise verborgen sind, müssen Gäste sich zum Bezahlen anmelden.",+ "options": {+ "public": "Öffentlich – alle können stöbern und Preise sehen",+ "prices_hidden": "Preise verborgen – Besucher müssen sich anmelden, um Preise zu sehen",+ "login_required": "Anmeldung erforderlich – Besucher müssen sich anmelden, um zu stöbern"+ }+ },+ "guest_checkout": {+ "label": "Gast-Checkout",+ "help": "Store-weite Vorgabe dafür, ob Kunden ohne Konto zur Kasse gehen können. Vertriebskanäle können dies überschreiben."+ },"mail_from_address": {"label": "Absenderadresse","placeholder": "[email protected]",@@ -1326,7 +1358,8 @@"title": "Shop-Einstellungen","subtitle": "Allgemeine Konfiguration und shopweite Standardwerte.","tab_general": "Allgemein",- "tab_standards": "Standards und Formate"+ "tab_standards": "Standards und Formate",+ "tab_storefront_access": "Storefront-Zugriff"},"emails": {"title": "E-Mail-Einstellungen",diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 963add5ec0..dfcd61ff32 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -282,6 +282,25 @@"Spree::OrderRouting::Strategy::Rules": "Rules (ordered)","Spree::OrderRouting::Strategy::Legacy": "Legacy"}+ },+ "storefront_access": {+ "label": "Storefront access",+ "help": "Controls what anonymous visitors can see on this channel. Leave blank to inherit the store setting. When prices are hidden, guests must sign in to check out.",+ "inherit": "Inherit from store",+ "options": {+ "public": "Public — anyone can browse and see prices",+ "prices_hidden": "Prices hidden — visitors must sign in to see prices",+ "login_required": "Login required — visitors must sign in to browse"+ }+ },+ "guest_checkout": {+ "label": "Guest checkout",+ "help": "Whether shoppers can check out without an account on this channel. Leave blank to inherit the store setting.",+ "inherit": "Inherit from store",+ "options": {+ "true": "Allowed",+ "false": "Not allowed"+ }}},"invitation_acceptance": {@@ -540,6 +559,19 @@"preferred_weight_unit": {"label": "Weight unit"},+ "storefront_access": {+ "label": "Storefront access",+ "help": "Store-wide default for what anonymous visitors can see. Channels can override this. When prices are hidden, guests must sign in to check out.",+ "options": {+ "public": "Public — anyone can browse and see prices",+ "prices_hidden": "Prices hidden — visitors must sign in to see prices",+ "login_required": "Login required — visitors must sign in to browse"+ }+ },+ "guest_checkout": {+ "label": "Guest checkout",+ "help": "Store-wide default for whether shoppers can check out without an account. Channels can override this."+ },"mail_from_address": {"label": "Sender address","placeholder": "[email protected]",@@ -1374,7 +1406,8 @@"title": "Store settings","subtitle": "General configuration and store-wide defaults.","tab_general": "General",- "tab_standards": "Standards and formats"+ "tab_standards": "Standards and formats",+ "tab_storefront_access": "Storefront access"},"emails": {"title": "Email settings",diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex 2a7a9711c1..67eeb06857 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -231,6 +231,25 @@"Spree::OrderRouting::Strategy::Rules": "Règles (ordonnées)","Spree::OrderRouting::Strategy::Legacy": "Héritée"}+ },+ "storefront_access": {+ "label": "Accès à la vitrine",+ "help": "Contrôle ce que les visiteurs anonymes peuvent voir sur ce canal. Laisser vide pour hériter du paramètre de la boutique. Lorsque les prix sont masqués, les invités doivent se connecter pour passer à la caisse.",+ "inherit": "Hériter de la boutique",+ "options": {+ "public": "Public — tout le monde peut parcourir et voir les prix",+ "prices_hidden": "Prix masqués — les visiteurs doivent se connecter pour voir les prix",+ "login_required": "Connexion requise — les visiteurs doivent se connecter pour parcourir"+ }+ },+ "guest_checkout": {+ "label": "Commande invité",+ "help": "Indique si les clients peuvent commander sans compte sur ce canal. Laisser vide pour hériter du paramètre de la boutique.",+ "inherit": "Hériter de la boutique",+ "options": {+ "true": "Autorisé",+ "false": "Non autorisé"+ }}},"invitation_acceptance": {@@ -489,6 +508,19 @@"preferred_weight_unit": {"label": "Unité de poids"},+ "storefront_access": {+ "label": "Accès à la vitrine",+ "help": "Valeur par défaut à l'échelle de la boutique pour ce que les visiteurs anonymes peuvent voir. Les canaux peuvent la remplacer. Lorsque les prix sont masqués, les invités doivent se connecter pour passer à la caisse.",+ "options": {+ "public": "Public — tout le monde peut parcourir et voir les prix",+ "prices_hidden": "Prix masqués — les visiteurs doivent se connecter pour voir les prix",+ "login_required": "Connexion requise — les visiteurs doivent se connecter pour parcourir"+ }+ },+ "guest_checkout": {+ "label": "Commande invité",+ "help": "Valeur par défaut à l'échelle de la boutique pour la possibilité de commander sans compte. Les canaux peuvent la remplacer."+ },"mail_from_address": {"label": "Adresse d'expéditeur","placeholder": "[email protected]",@@ -1326,7 +1358,8 @@"title": "Paramètres de la boutique","subtitle": "Configuration générale et valeurs par défaut à l'échelle de la boutique.","tab_general": "Général",- "tab_standards": "Normes et formats"+ "tab_standards": "Normes et formats",+ "tab_storefront_access": "Accès à la vitrine"},"emails": {"title": "Paramètres d'e-mail",diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex 5deff001e0..a038d5fe0f 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -231,6 +231,25 @@"Spree::OrderRouting::Strategy::Rules": "Reguły (uporządkowane)","Spree::OrderRouting::Strategy::Legacy": "Starsza"}+ },+ "storefront_access": {+ "label": "Dostęp do sklepu",+ "help": "Określa, co anonimowi odwiedzający widzą w tym kanale. Pozostaw puste, aby dziedziczyć ustawienie sklepu. Gdy ceny są ukryte, goście muszą się zalogować, aby sfinalizować zakup.",+ "inherit": "Dziedzicz ze sklepu",+ "options": {+ "public": "Publiczny — każdy może przeglądać i widzieć ceny",+ "prices_hidden": "Ceny ukryte — odwiedzający muszą się zalogować, aby zobaczyć ceny",+ "login_required": "Wymagane logowanie — odwiedzający muszą się zalogować, aby przeglądać"+ }+ },+ "guest_checkout": {+ "label": "Zakupy jako gość",+ "help": "Czy klienci mogą składać zamówienia bez konta w tym kanale. Pozostaw puste, aby dziedziczyć ustawienie sklepu.",+ "inherit": "Dziedzicz ze sklepu",+ "options": {+ "true": "Dozwolone",+ "false": "Niedozwolone"+ }}},"invitation_acceptance": {@@ -489,6 +508,19 @@"preferred_weight_unit": {"label": "Jednostka wagi"},+ "storefront_access": {+ "label": "Dostęp do sklepu",+ "help": "Domyślne ustawienie dla całego sklepu określające, co widzą anonimowi odwiedzający. Kanały mogą je nadpisać. Gdy ceny są ukryte, goście muszą się zalogować, aby sfinalizować zakup.",+ "options": {+ "public": "Publiczny — każdy może przeglądać i widzieć ceny",+ "prices_hidden": "Ceny ukryte — odwiedzający muszą się zalogować, aby zobaczyć ceny",+ "login_required": "Wymagane logowanie — odwiedzający muszą się zalogować, aby przeglądać"+ }+ },+ "guest_checkout": {+ "label": "Zakupy jako gość",+ "help": "Domyślne ustawienie dla całego sklepu określające, czy klienci mogą składać zamówienia bez konta. Kanały mogą je nadpisać."+ },"mail_from_address": {"label": "Adres nadawcy","placeholder": "[email protected]",@@ -1340,7 +1372,8 @@"title": "Ustawienia sklepu","subtitle": "Ogólna konfiguracja i domyślne ustawienia dla całego sklepu.","tab_general": "Ogólne",- "tab_standards": "Standardy i formaty"+ "tab_standards": "Standardy i formaty",+ "tab_storefront_access": "Dostęp do sklepu"},"emails": {"title": "Ustawienia e-mail",diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 0369330c84..02512fd796 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -279,6 +279,25 @@"Spree::OrderRouting::Strategy::Rules": "规则(有序)","Spree::OrderRouting::Strategy::Legacy": "旧版"}+ },+ "storefront_access": {+ "label": "店铺访问权限",+ "help": "控制匿名访客在此渠道中可以看到的内容。留空则继承店铺设置。 隐藏价格时,访客须登录后才能结账。",+ "inherit": "继承店铺设置",+ "options": {+ "public": "公开 — 任何人都可以浏览并查看价格",+ "prices_hidden": "隐藏价格 — 访客须登录后才能查看价格",+ "login_required": "需要登录 — 访客须登录后才能浏览"+ }+ },+ "guest_checkout": {+ "label": "访客结账",+ "help": "顾客是否可以在此渠道中无需账户即可结账。留空则继承店铺设置。",+ "inherit": "继承店铺设置",+ "options": {+ "true": "允许",+ "false": "不允许"+ }}},"invitation_acceptance": {@@ -537,6 +556,19 @@"preferred_weight_unit": {"label": "重量单位"},+ "storefront_access": {+ "label": "店铺访问权限",+ "help": "店铺范围内的默认设置,控制匿名访客可以看到的内容。渠道可以覆盖此设置。隐藏价格时,访客须登录后才能结账。",+ "options": {+ "public": "公开 — 任何人都可以浏览并查看价格",+ "prices_hidden": "隐藏价格 — 访客须登录后才能查看价格",+ "login_required": "需要登录 — 访客须登录后才能浏览"+ }+ },+ "guest_checkout": {+ "label": "访客结账",+ "help": "店铺范围内的默认设置,控制顾客是否可以无需账户即可结账。渠道可以覆盖此设置。"+ },"mail_from_address": {"label": "发件人地址","placeholder": "[email protected]",@@ -1374,7 +1406,8 @@"title": "店铺设置","subtitle": "通用配置与店铺级默认设置。","tab_general": "通用",- "tab_standards": "标准与格式"+ "tab_standards": "标准与格式",+ "tab_storefront_access": "店铺访问权限"},"emails": {"title": "邮件设置",diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsxindex d3b69fb9f0..ea08b21d7e 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/channels.tsx@@ -49,7 +49,9 @@ import {type ChannelFormValues,channelFormSchema,channelValuesToParams,+ GUEST_CHECKOUT_VALUES,ORDER_ROUTING_STRATEGY_VALUES,+ STOREFRONT_ACCESS_VALUES,} from '@/schemas/channel'import '@/tables/channels'@@ -250,6 +252,9 @@ function EditChannelSheet({active: channel.active,default: channel.default,preferred_order_routing_strategy: channel.preferred_order_routing_strategy ?? '',+ preferred_storefront_access: channel.preferred_storefront_access ?? '',+ preferred_guest_checkout:+ channel.preferred_guest_checkout == null ? '' : String(channel.preferred_guest_checkout),})}}, [channel, form])@@ -303,17 +308,62 @@ function EditChannelSheet({)}+type ChannelSelectFieldName =+ | 'preferred_order_routing_strategy'+ | 'preferred_storefront_access'+ | 'preferred_guest_checkout'++// One channel-preference <Select> that shares the "inherit from store" blank+// option. Builds its own option list from `values` + the i18n `scope`+// (`<scope>.label` / `.help` / `.inherit` / `.options.<value>`).+function InheritableSelectField({+ form,+ name,+ scope,+ values,+}: {+ form: UseFormReturn<ChannelFormValues>+ name: ChannelSelectFieldName+ scope: string+ values: readonly string[]+}) {+ const { t } = useTranslation()+ const error = form.formState.errors[name]+ const options = values.map((value) => ({+ value,+ label: value === '' ? t(`${scope}.inherit`) : t(`${scope}.options.${value}`),+ }))+ return (+ <Field>+ <FieldLabel htmlFor={name}>{t(`${scope}.label`)}</FieldLabel>+ <Controller+ name={name}+ control={form.control}+ render={({ field }) => (+ <Select items={options} value={field.value ?? ''} onValueChange={field.onChange}>+ <SelectTrigger id={name} className="w-full" aria-invalid={!!error || undefined}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {options.map((o) => (+ <SelectItem key={o.value || 'inherit'} value={o.value}>+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )}+ />+ <span className="text-xs text-muted-foreground">{t(`${scope}.help`)}</span>+ <FieldError errors={[error]} />+ </Field>+ )+}+function ChannelFormFields({ form }: { form: UseFormReturn<ChannelFormValues> }) {const { t } = useTranslation()const { errors } = form.formState- const strategyOptions = ORDER_ROUTING_STRATEGY_VALUES.map((value) => ({- value,- label:- value === ''- ? t('admin.fields.channel.order_routing_strategy.inherit')- : t(`admin.fields.channel.order_routing_strategy.options.${value}`),- }))return (<FieldGroup>{errors.root?.message && (@@ -385,36 +435,26 @@ function ChannelFormFields({ form }: { form: UseFormReturn<ChannelFormValues> })</div></Field>- <Field>- <FieldLabel htmlFor="preferred_order_routing_strategy">- {t('admin.fields.channel.order_routing_strategy.label')}- </FieldLabel>- <Controller- name="preferred_order_routing_strategy"- control={form.control}- render={({ field }) => (- <Select- items={strategyOptions}- value={field.value ?? ''}- onValueChange={field.onChange}- >- <SelectTrigger id="preferred_order_routing_strategy" className="w-full">- <SelectValue />- </SelectTrigger>- <SelectContent>- {strategyOptions.map((o) => (- <SelectItem key={o.value || 'inherit'} value={o.value}>- {o.label}- </SelectItem>- ))}- </SelectContent>- </Select>- )}- />- <span className="text-xs text-muted-foreground">- {t('admin.fields.channel.order_routing_strategy.help')}- </span>- </Field>+ <InheritableSelectField+ form={form}+ name="preferred_order_routing_strategy"+ scope="admin.fields.channel.order_routing_strategy"+ values={ORDER_ROUTING_STRATEGY_VALUES}+ />++ <InheritableSelectField+ form={form}+ name="preferred_storefront_access"+ scope="admin.fields.channel.storefront_access"+ values={STOREFRONT_ACCESS_VALUES}+ />++ <InheritableSelectField+ form={form}+ name="preferred_guest_checkout"+ scope="admin.fields.channel.guest_checkout"+ values={GUEST_CHECKOUT_VALUES}+ /></FieldGroup>)}diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsxindex ac0efeeffe..920d2d0bac 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx@@ -27,6 +27,7 @@ import {SelectTrigger,SelectValue,Skeleton,+ Switch,useFormSubmitShortcut,} from '@spree/dashboard-ui'import { createFileRoute } from '@tanstack/react-router'@@ -43,6 +44,7 @@ import { toast } from 'sonner'import { useStoreSettings, useUpdateStoreSettings } from '@/hooks/use-store-settings'import { getAvailableUiLocales } from '@/i18n-setup'import {+ STOREFRONT_ACCESS_LEVELS,type StoreSettingsFormValues,storeSettingsFormSchema,UNIT_SYSTEMS,@@ -80,6 +82,9 @@ function storeToFormValues(store: Store): StoreSettingsFormValues {preferred_timezone: store.preferred_timezone,preferred_unit_system: (store.preferred_unit_system as 'metric' | 'imperial') ?? 'metric',preferred_weight_unit: store.preferred_weight_unit,+ preferred_storefront_access:+ (store.preferred_storefront_access as (typeof STOREFRONT_ACCESS_LEVELS)[number]) ?? 'public',+ preferred_guest_checkout: store.preferred_guest_checkout ?? true,}}@@ -151,6 +156,8 @@ function StoreSettingsForm({ store }: { store: Store }) {preferred_timezone: values.preferred_timezone,preferred_unit_system: values.preferred_unit_system,preferred_weight_unit: values.preferred_weight_unit,+ preferred_storefront_access: values.preferred_storefront_access,+ preferred_guest_checkout: values.preferred_guest_checkout,})toast.success(t('admin.messages.store_settings_updated'))// Reset FIRST so the form is no longer dirty — otherwise the language@@ -199,6 +206,14 @@ function StoreSettingsForm({ store }: { store: Store }) {})),[t, unitSystem],)+ const storefrontAccessOptions = useMemo(+ () =>+ STOREFRONT_ACCESS_LEVELS.map((value) => ({+ value,+ label: t(`admin.fields.store.storefront_access.options.${value}`),+ })),+ [t],+ )// Admin-UI language options come from the dashboard's own shipped locale// bundles (getAvailableUiLocales) — the SAME canonical source the profile// picker and top-bar switcher use, so the lists never desync. The leading@@ -291,6 +306,47 @@ function StoreSettingsForm({ store }: { store: Store }) {</FieldGroup></CardContent></Card>++ <Card>+ <CardHeader>+ <CardTitle>{t('admin.pages.settings.store.tab_storefront_access')}</CardTitle>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <SelectField+ id="store-storefront-access"+ label={t('admin.fields.store.storefront_access.label')}+ name="preferred_storefront_access"+ control={form.control}+ options={storefrontAccessOptions}+ help={t('admin.fields.store.storefront_access.help')}+ />+ <Field>+ <div className="flex items-start justify-between gap-4">+ <div className="flex flex-col">+ <FieldLabel htmlFor="store-guest-checkout" className="cursor-pointer">+ {t('admin.fields.store.guest_checkout.label')}+ </FieldLabel>+ <span className="text-xs text-muted-foreground">+ {t('admin.fields.store.guest_checkout.help')}+ </span>+ </div>+ <Controller+ name="preferred_guest_checkout"+ control={form.control}+ render={({ field }) => (+ <Switch+ id="store-guest-checkout"+ checked={!!field.value}+ onCheckedChange={field.onChange}+ />+ )}+ />+ </div>+ </Field>+ </FieldGroup>+ </CardContent>+ </Card></>}/>@@ -302,6 +358,7 @@ interface SelectFieldProps<TValues extends FieldValues> {id: stringlabel: stringplaceholder?: string+ help?: stringname: FieldPath<TValues>control: Control<TValues>options: ReadonlyArray<{ value: string; label: string }>@@ -311,6 +368,7 @@ function SelectField<TValues extends FieldValues>({id,label,placeholder,+ help,name,control,options,@@ -334,6 +392,7 @@ function SelectField<TValues extends FieldValues>({))}</SelectContent></Select>+ {help && <span className="text-xs text-muted-foreground">{help}</span>}<FieldError errors={[fieldState.error]} /></Field>)}diff --git a/packages/dashboard/src/schemas/channel.ts b/packages/dashboard/src/schemas/channel.tsindex 994cc01476..ead82550a5 100644--- a/packages/dashboard/src/schemas/channel.ts+++ b/packages/dashboard/src/schemas/channel.ts@@ -12,6 +12,13 @@ export const ORDER_ROUTING_STRATEGY_VALUES = [export type OrderRoutingStrategyValue = (typeof ORDER_ROUTING_STRATEGY_VALUES)[number]+// Empty string clears the channel-level override → falls back to store.+export const STOREFRONT_ACCESS_VALUES = ['', 'public', 'prices_hidden', 'login_required'] as const++// Tri-state form representation of the channel's boolean guest_checkout+// override: '' inherits the store value, 'true'/'false' set an explicit value.+export const GUEST_CHECKOUT_VALUES = ['', 'true', 'false'] as const+export const channelFormSchema = z.object({name: z.string().min(1, { error: requiredMessage('name') }),code: z@@ -23,6 +30,8 @@ export const channelFormSchema = z.object({active: z.boolean(),default: z.boolean(),preferred_order_routing_strategy: z.string(),+ preferred_storefront_access: z.string(),+ preferred_guest_checkout: z.string(),})export type ChannelFormValues = z.infer<typeof channelFormSchema>@@ -33,6 +42,8 @@ export const CHANNEL_DEFAULTS: ChannelFormValues = {active: true,default: false,preferred_order_routing_strategy: '',+ preferred_storefront_access: '',+ preferred_guest_checkout: '',}export function channelValuesToParams(@@ -44,5 +55,9 @@ export function channelValuesToParams(active: v.active,default: v.default,preferred_order_routing_strategy: v.preferred_order_routing_strategy || null,+ preferred_storefront_access: v.preferred_storefront_access || null,+ // '' → inherit (null); otherwise an explicit boolean.+ preferred_guest_checkout:+ v.preferred_guest_checkout === '' ? null : v.preferred_guest_checkout === 'true',}}diff --git a/packages/dashboard/src/schemas/store.ts b/packages/dashboard/src/schemas/store.tsindex be00e077c4..7111d33474 100644--- a/packages/dashboard/src/schemas/store.ts+++ b/packages/dashboard/src/schemas/store.ts@@ -11,12 +11,20 @@ export const WEIGHT_UNITS: Record<UnitSystem, readonly string[]> = {}const ALL_WEIGHT_UNITS = [...WEIGHT_UNITS.metric, ...WEIGHT_UNITS.imperial] as const+// Store-wide storefront posture. Unlike the channel field there is no blank+// "inherit" option — the store is the terminal fallback in the resolution+// chain, so it always holds a concrete value. Labels live in `en.json` under+// `admin.fields.store.storefront_access.options.*`.+export const STOREFRONT_ACCESS_LEVELS = ['public', 'prices_hidden', 'login_required'] as const+export const storeSettingsFormSchema = z.object({name: z.string().min(1, { error: requiredMessage('store.name') }),preferred_admin_locale: z.string().nullable().optional(),preferred_timezone: z.string().min(1, { error: requiredMessage('store.preferred_timezone') }),preferred_unit_system: z.enum(['metric', 'imperial']),preferred_weight_unit: z.enum(ALL_WEIGHT_UNITS),+ preferred_storefront_access: z.enum(STOREFRONT_ACCESS_LEVELS),+ preferred_guest_checkout: z.boolean(),})export type StoreSettingsFormValues = z.infer<typeof storeSettingsFormSchema>diff --git a/packages/sdk/.changeset/storefront-access-gating.md b/packages/sdk/.changeset/storefront-access-gating.mdnew file mode 100644index 0000000000..f4b0b1ced9--- /dev/null+++ b/packages/sdk/.changeset/storefront-access-gating.md@@ -0,0 +1,5 @@+---+"@spree/sdk": minor+---++Support gated storefronts in the Store API. A channel (or its store) can now hide prices from anonymous visitors or require a login to browse: when prices are hidden, monetary fields on products, carts, and orders return `null` for guests, and `login_required` channels reject unauthenticated requests with `401`. Guest checkout can likewise be disallowed per channel, in which case completing a cart without a signed-in customer returns `401`.diff --git a/spree/admin/app/helpers/spree/admin/channels_helper.rb b/spree/admin/app/helpers/spree/admin/channels_helper.rbindex 5175c503c0..842c770ff1 100644--- a/spree/admin/app/helpers/spree/admin/channels_helper.rb+++ b/spree/admin/app/helpers/spree/admin/channels_helper.rb@@ -9,6 +9,23 @@ module Spreedef channel_order_routing_strategy_optionsSpree.order_routing.strategies.map { |strategy| [strategy.display_name, strategy.to_s] }end++ # Storefront access levels for the channel edit form. A blank selection+ # clears the channel override and falls back to +Store#preferred_storefront_access+.+ def channel_storefront_access_options+ Spree::Channel::Gating::STOREFRONT_ACCESS.map do |value|+ [Spree.t("admin.channels.storefront_access_options.#{value}"), value]+ end+ end++ # Tri-state guest-checkout override for the channel edit form. A blank+ # selection clears the override and falls back to +Store#preferred_guest_checkout+.+ def channel_guest_checkout_options+ [+ [Spree.t('admin.channels.guest_checkout_allowed'), 'true'],+ [Spree.t('admin.channels.guest_checkout_blocked'), 'false']+ ]+ endendendenddiff --git a/spree/admin/app/views/spree/admin/channels/_form.html.erb b/spree/admin/app/views/spree/admin/channels/_form.html.erbindex 820d4e09df..a9c4b6a44d 100644--- a/spree/admin/app/views/spree/admin/channels/_form.html.erb+++ b/spree/admin/app/views/spree/admin/channels/_form.html.erb@@ -15,5 +15,15 @@{ label: Spree.t('admin.channels.order_routing_strategy'),help_bubble: Spree.t('admin.channels.order_routing_strategy_hint'),include_blank: Spree.t('admin.channels.order_routing_strategy_inherit') } %>+ <%= f.spree_select :preferred_storefront_access,+ options_for_select(channel_storefront_access_options, f.object.preferred_storefront_access),+ { label: Spree.t('admin.channels.storefront_access'),+ help_bubble: Spree.t('admin.channels.storefront_access_hint'),+ include_blank: Spree.t('admin.channels.storefront_access_inherit') } %>+ <%= f.spree_select :preferred_guest_checkout,+ options_for_select(channel_guest_checkout_options, f.object.preferred_guest_checkout&.to_s || ''),+ { label: Spree.t('admin.channels.guest_checkout'),+ help_bubble: Spree.t('admin.channels.guest_checkout_hint'),+ include_blank: Spree.t('admin.channels.guest_checkout_inherit') } %></div></div>diff --git a/spree/admin/app/views/spree/admin/stores/form/_checkout.html.erb b/spree/admin/app/views/spree/admin/stores/form/_checkout.html.erbindex e8579c46e2..4dac71e1a5 100644--- a/spree/admin/app/views/spree/admin/stores/form/_checkout.html.erb+++ b/spree/admin/app/views/spree/admin/stores/form/_checkout.html.erb@@ -15,6 +15,10 @@<hr class="my-6">+ <%= f.spree_select :preferred_storefront_access,+ options_for_select(channel_storefront_access_options, f.object.preferred_storefront_access),+ { label: Spree.t('admin.checkout_settings.storefront_access.label'),+ help_bubble: Spree.t('admin.checkout_settings.storefront_access.description') } %><%= f.spree_check_box :preferred_guest_checkout, label: Spree.t('admin.checkout_settings.guest_checkout.label'), help: Spree.t('admin.checkout_settings.guest_checkout.description') %><%= f.spree_check_box :preferred_company_field_enabled, label: Spree.t('admin.store_form.company_field.label'), help: Spree.t('admin.store_form.company_field.description') %><%= f.spree_check_box :preferred_special_instructions_enabled, label: Spree.t('admin.checkout_settings.special_instructions.label'), help: Spree.t('admin.checkout_settings.special_instructions.description') %>diff --git a/spree/admin/config/locales/en.yml b/spree/admin/config/locales/en.ymlindex 58e5709c90..d897916fe0 100644--- a/spree/admin/config/locales/en.yml+++ b/spree/admin/config/locales/en.yml@@ -117,9 +117,21 @@ en:code_hint: A short, stable identifier (e.g. "online", "pos", "wholesale"). Used by API clients via the X-Spree-Channel header and for order attribution.default: Default channeldefault_hint: Exactly one channel per store is the default. Used as the fallback when no channel is selected and as the auto-publish target for new products.+ guest_checkout: Guest checkout+ guest_checkout_allowed: Allowed+ guest_checkout_blocked: Not allowed+ guest_checkout_hint: Whether shoppers can check out without an account on this channel. Inherits the store setting when unset.+ guest_checkout_inherit: Inherit from storeorder_routing_strategy: Order routing strategyorder_routing_strategy_hint: Overrides the store-level routing strategy for orders attributed to this channel.order_routing_strategy_inherit: Inherit from store+ storefront_access: Storefront access+ storefront_access_hint: Controls what anonymous visitors can see on this channel. Inherits the store setting when unset. When prices are hidden, guests must sign in to check out — guest checkout does not apply.+ storefront_access_inherit: Inherit from store+ storefront_access_options:+ login_required: Login required — visitors must sign in to browse+ prices_hidden: Prices hidden — visitors must sign in to see prices+ public: Public — anyone can browse and see pricescheckout_settings:checkout_links:description: Links to these pages will be displayed in the checkout footer.@@ -132,6 +144,9 @@ en:special_instructions:description: Allow customers to add special instructions to their order.label: Display the special instructions field+ storefront_access:+ description: Default control over what anonymous visitors can see across the store. Individual sales channels can override this. When prices are hidden, guests must sign in to check out — guest checkout does not apply.+ label: Storefront accessclose_sidebar: Close sidebarcopied: Copied!copy_payment_link: Copy Payment Linkdiff --git a/spree/api/app/controllers/concerns/spree/api/v3/channel_resolution.rb b/spree/api/app/controllers/concerns/spree/api/v3/channel_resolution.rbindex 4698d8d4ed..7bf17fbaf9 100644--- a/spree/api/app/controllers/concerns/spree/api/v3/channel_resolution.rb+++ b/spree/api/app/controllers/concerns/spree/api/v3/channel_resolution.rb@@ -35,8 +35,10 @@ module Spree# +Spree::Current.channel+ itself, which avoids one query per# header-less API request.def set_current_channel- channel = channel_from_header- Spree::Current.channel = channel if channel+ # Memoize so a later +current_channel+ call (e.g. the storefront gate,+ # serializer params) reuses this row instead of re-querying the header.+ @current_channel = channel_from_header+ Spree::Current.channel = @current_channel if @current_channelenddef channel_from_headerdiff --git a/spree/api/app/controllers/concerns/spree/api/v3/storefront_gating.rb b/spree/api/app/controllers/concerns/spree/api/v3/storefront_gating.rbnew file mode 100644index 0000000000..ba110c5d78--- /dev/null+++ b/spree/api/app/controllers/concerns/spree/api/v3/storefront_gating.rb@@ -0,0 +1,65 @@+module Spree+ module Api+ module V3+ # Enforces channel-level storefront access gating on the Store API.+ # The posture is resolved from the request's channel+ # (+Spree::Channel#resolved_storefront_access+, with store fallback):+ #+ # - +login_required+ → 401 on every gated read for unauthenticated requests+ # - +prices_hidden+ → price fields serialized as +null+ for guests+ #+ # "Guest" means no authenticated customer (publishable key or guest cart+ # token without a customer JWT). Logged-in customers are never gated.+ module StorefrontGating+ extend ActiveSupport::Concern++ included do+ before_action :enforce_storefront_login_required!+ end++ class_methods do+ # Opts a controller out of the +login_required+ gate. Use for endpoints+ # that must stay reachable before authentication — sign in / register,+ # password reset, and pre-login reference data (countries, currencies,+ # locales, markets, newsletter, tokenized digital downloads).+ def allow_guest_storefront_access!+ skip_before_action :enforce_storefront_login_required!, raise: false+ end+ end++ protected++ # @return [Boolean] whether prices must be hidden from this request.+ def hide_prices?+ try_spree_current_user.blank? && !!current_channel&.storefront_prices_hidden?+ end++ # Injects the price-hiding flag so the shared +price_for+/+price_in++ # serializer helpers null prices for gated guests.+ def serializer_params+ super.merge(hide_prices: hide_prices?)+ end++ # Renders a 401 with the shared +authentication_required+ error code.+ # @param message_key [String] i18n key for the error message+ # @param default_message [String] fallback when the key is missing+ def render_authentication_required(message_key, default_message)+ render_error(+ code: ErrorHandler::ERROR_CODES[:authentication_required],+ message: Spree.t(message_key, default: default_message),+ status: :unauthorized+ )+ end++ private++ def enforce_storefront_login_required!+ return if try_spree_current_user.present?+ return unless current_channel&.storefront_login_required?++ render_authentication_required('api.errors.storefront_login_required', 'Authentication required to access this store')+ end+ end+ end+ end+enddiff --git a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rbindex 7f05d3588c..595312b972 100644--- a/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/admin/store_controller.rb@@ -39,6 +39,8 @@ module Spree:preferred_timezone,:preferred_weight_unit,:preferred_unit_system,+ :preferred_storefront_access,+ :preferred_guest_checkout,:mail_from_address,:customer_support_email,:new_order_notifications_email,diff --git a/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/store/auth_controller.rbindex 63a6e5cc9f..f6f6d5fa82 100644--- a/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/auth_controller.rb@@ -3,6 +3,7 @@ module Spreemodule V3module Storeclass AuthController < Store::BaseController+ allow_guest_storefront_access!# Tighter rate limits for auth endpoints (per IP to prevent brute force)rate_limit to: Spree::Api::Config[:rate_limit_login], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :create, with: RATE_LIMIT_RESPONSErate_limit to: Spree::Api::Config[:rate_limit_refresh], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :refresh, with: RATE_LIMIT_RESPONSE@@ -87,7 +88,8 @@ module Spreelocale: current_locale,currency: current_currency,user: current_user,- includes: []+ includes: [],+ hide_prices: hide_prices?}enddiff --git a/spree/api/app/controllers/spree/api/v3/store/base_controller.rb b/spree/api/app/controllers/spree/api/v3/store/base_controller.rbindex 6f7745cf4c..86451e7535 100644--- a/spree/api/app/controllers/spree/api/v3/store/base_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/base_controller.rb@@ -8,6 +8,11 @@ module Spree# this here keeps the +X-Spree-Channel+ header from accidentally# narrowing admin queries.include Spree::Api::V3::ChannelResolution+ # Mirrors Store::ResourceController. Both branches must carry the gate so+ # login_required / prices_hidden apply to every Store endpoint, not just+ # ResourceController ones. Public endpoints opt out with+ # +allow_guest_storefront_access!+.+ include Spree::Api::V3::StorefrontGating# Require publishable API key for all Store API requestsbefore_action :authenticate_api_key!diff --git a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rbindex 1f78d57e0a..fe9afd0a95 100644--- a/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/carts_controller.rb@@ -104,6 +104,10 @@ module Spreedef completefind_cart!+ if @cart.guest_checkout_disallowed?+ return render_authentication_required('api.errors.guest_checkout_not_allowed', 'You must be signed in to complete checkout')+ end+result = Spree::Dependencies.carts_complete_service.constantize.call(cart: @cart)if result.success?diff --git a/spree/api/app/controllers/spree/api/v3/store/countries_controller.rb b/spree/api/app/controllers/spree/api/v3/store/countries_controller.rbindex 95270038b4..bd8f2f7e1e 100644--- a/spree/api/app/controllers/spree/api/v3/store/countries_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/countries_controller.rb@@ -3,6 +3,7 @@ module Spreemodule V3module Storeclass CountriesController < Store::BaseController+ allow_guest_storefront_access!include Spree::Api::V3::HttpCaching# GET /api/v3/store/countriesdiff --git a/spree/api/app/controllers/spree/api/v3/store/currencies_controller.rb b/spree/api/app/controllers/spree/api/v3/store/currencies_controller.rbindex 33c2a56540..552af1b898 100644--- a/spree/api/app/controllers/spree/api/v3/store/currencies_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/currencies_controller.rb@@ -3,6 +3,7 @@ module Spreemodule V3module Storeclass CurrenciesController < Store::BaseController+ allow_guest_storefront_access!include Spree::Api::V3::HttpCaching# GET /api/v3/store/currenciesdiff --git a/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rbindex cf1393ce3a..6aaf4e08ac 100644--- a/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/customer/password_resets_controller.rb@@ -6,6 +6,7 @@ module Spreemodule Storemodule Customerclass PasswordResetsController < Store::BaseController+ allow_guest_storefront_access!rate_limit to: Spree::Api::Config[:rate_limit_password_reset],within: Spree::Api::Config[:rate_limit_window].seconds,store: Rails.cache,diff --git a/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/customers_controller.rbindex d084d93f99..f18e80866b 100644--- a/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/customers_controller.rb@@ -3,6 +3,7 @@ module Spreemodule V3module Storeclass CustomersController < Store::BaseController+ allow_guest_storefront_access!rate_limit to: Spree::Api::Config[:rate_limit_register], within: Spree::Api::Config[:rate_limit_window].seconds, store: Rails.cache, only: :create, with: RATE_LIMIT_RESPONSEskip_before_action :authenticate_user, only: [:create]@@ -64,7 +65,8 @@ module Spreelocale: current_locale,currency: current_currency,user: current_user,- includes: []+ includes: [],+ hide_prices: hide_prices?}enddiff --git a/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rb b/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rbindex 65276ef16f..4a8671633e 100644--- a/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/digitals_controller.rb@@ -3,6 +3,7 @@ module Spreemodule V3module Storeclass DigitalsController < Store::BaseController+ allow_guest_storefront_access!skip_before_action :authenticate_api_key!before_action :set_resourcediff --git a/spree/api/app/controllers/spree/api/v3/store/locales_controller.rb b/spree/api/app/controllers/spree/api/v3/store/locales_controller.rbindex 1618c8dfdc..284f57b5d0 100644--- a/spree/api/app/controllers/spree/api/v3/store/locales_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/locales_controller.rb@@ -3,6 +3,7 @@ module Spreemodule V3module Storeclass LocalesController < Store::BaseController+ allow_guest_storefront_access!include Spree::Api::V3::HttpCaching# GET /api/v3/store/localesdiff --git a/spree/api/app/controllers/spree/api/v3/store/markets/countries_controller.rb b/spree/api/app/controllers/spree/api/v3/store/markets/countries_controller.rbindex 7e601d5630..c3b545a43a 100644--- a/spree/api/app/controllers/spree/api/v3/store/markets/countries_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/markets/countries_controller.rb@@ -4,6 +4,7 @@ module Spreemodule Storemodule Marketsclass CountriesController < Store::BaseController+ allow_guest_storefront_access!include Spree::Api::V3::HttpCachingbefore_action :load_marketdiff --git a/spree/api/app/controllers/spree/api/v3/store/markets_controller.rb b/spree/api/app/controllers/spree/api/v3/store/markets_controller.rbindex 181fc5cdf5..8cd54f5c6e 100644--- a/spree/api/app/controllers/spree/api/v3/store/markets_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/markets_controller.rb@@ -3,6 +3,7 @@ module Spreemodule V3module Storeclass MarketsController < Store::BaseController+ allow_guest_storefront_access!include Spree::Api::V3::HttpCaching# GET /api/v3/store/marketsdiff --git a/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb b/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rbindex 8c36e07c94..aee2e8bd91 100644--- a/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/newsletter_subscribers_controller.rb@@ -3,6 +3,7 @@ module Spreemodule V3module Storeclass NewsletterSubscribersController < Store::BaseController+ allow_guest_storefront_access!rate_limit to: Spree::Api::Config[:rate_limit_register],within: Spree::Api::Config[:rate_limit_window].seconds,store: Rails.cache,diff --git a/spree/api/app/controllers/spree/api/v3/store/resource_controller.rb b/spree/api/app/controllers/spree/api/v3/store/resource_controller.rbindex 35989571c7..8bbc05f343 100644--- a/spree/api/app/controllers/spree/api/v3/store/resource_controller.rb+++ b/spree/api/app/controllers/spree/api/v3/store/resource_controller.rb@@ -7,6 +7,7 @@ module Spree# any concern added here MUST also be added to Store::BaseController.class ResourceController < Spree::Api::V3::ResourceControllerinclude Spree::Api::V3::ChannelResolution+ include Spree::Api::V3::StorefrontGatingprotecteddiff --git a/spree/api/app/serializers/spree/api/v3/admin/channel_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/channel_serializer.rbindex 308218d51c..53c1696885 100644--- a/spree/api/app/serializers/spree/api/v3/admin/channel_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/channel_serializer.rb@@ -4,9 +4,13 @@ module Spreemodule Adminclass ChannelSerializer < V3::ChannelSerializertypelize store_id: :string,- preferred_order_routing_strategy: [:string, nullable: true]+ preferred_order_routing_strategy: [:string, nullable: true],+ preferred_storefront_access: [:string, nullable: true],+ preferred_guest_checkout: [:boolean, nullable: true]attributes :preferred_order_routing_strategy,+ :preferred_storefront_access,+ :preferred_guest_checkout,created_at: :iso8601, updated_at: :iso8601endenddiff --git a/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rbindex 429a5e01ee..0fcc75b772 100644--- a/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/admin/store_serializer.rb@@ -18,6 +18,8 @@ module Spreepreferred_timezone: :string,preferred_weight_unit: :string,preferred_unit_system: :string,+ preferred_storefront_access: :string,+ preferred_guest_checkout: :boolean,metadata: 'Record<string, unknown>'attributes :metadata,@@ -32,6 +34,8 @@ module Spree:preferred_timezone,:preferred_weight_unit,:preferred_unit_system,+ :preferred_storefront_access,+ :preferred_guest_checkout,created_at: :iso8601, updated_at: :iso8601attribute :url, &:storefront_urldiff --git a/spree/api/app/serializers/spree/api/v3/base_serializer.rb b/spree/api/app/serializers/spree/api/v3/base_serializer.rbindex 1a0a112652..ed395e0e62 100644--- a/spree/api/app/serializers/spree/api/v3/base_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/base_serializer.rb@@ -16,6 +16,17 @@ module Spreeobject.prefixed_idend+ # Declares money/display attributes that render +null+ for gated+ # (prices_hidden) guests, keyed off the same +hide_prices+ flag the+ # +price_for+/+price_in+ helpers use — so the whole price surface+ # (product prices AND cart/order/line-item totals) is gated from one+ # place instead of per-attribute opt-in.+ def self.money_attributes(*names)+ names.each do |name|+ attribute(name) { |object| object.public_send(name) unless params[:hide_prices] }+ end+ end+# Context accessorsdef current_storeparams[:store]@@ -77,6 +88,7 @@ module Spree# Memoized per variant to avoid duplicate queriesdef price_for(variant, quantity: nil)return nil unless variant.respond_to?(:price_for)+ return nil if params[:hide_prices]@price_for_cache ||= {}cache_key = [variant.id, quantity]@@ -95,6 +107,7 @@ module Spree# Memoized per variant to avoid duplicate queriesdef price_in(variant)return nil unless variant.respond_to?(:price_in)+ return nil if params[:hide_prices]@price_in_cache ||= {}return @price_in_cache[variant.id] if @price_in_cache.key?(variant.id)diff --git a/spree/api/app/serializers/spree/api/v3/cart_serializer.rb b/spree/api/app/serializers/spree/api/v3/cart_serializer.rbindex 7c242ec460..6c9396348b 100644--- a/spree/api/app/serializers/spree/api/v3/cart_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/cart_serializer.rb@@ -35,22 +35,25 @@ module Spreeendattributes :number, :token, :email, :customer_note,- :currency, :locale, :total_quantity,- :item_total, :display_item_total,- :adjustment_total, :display_adjustment_total,- :discount_total, :display_discount_total,- :tax_total, :display_tax_total, :included_tax_total, :display_included_tax_total,- :additional_tax_total, :display_additional_tax_total, :total, :display_total,- :gift_card_total, :display_gift_card_total,- :amount_due, :display_amount_due,- :delivery_total, :display_delivery_total, :warnings+ :currency, :locale, :total_quantity, :warnings++ # Nulled for gated (prices_hidden) guests so the cart can't leak the+ # prices that product/variant serializers already withhold.+ money_attributes :item_total, :display_item_total,+ :adjustment_total, :display_adjustment_total,+ :discount_total, :display_discount_total,+ :tax_total, :display_tax_total, :included_tax_total, :display_included_tax_total,+ :additional_tax_total, :display_additional_tax_total, :total, :display_total,+ :gift_card_total, :display_gift_card_total,+ :amount_due, :display_amount_due,+ :delivery_total, :display_delivery_totalattribute :store_credit_total do |order|- order.total_applied_store_credit.to_s+ order.total_applied_store_credit.to_s unless params[:hide_prices]endattribute :display_store_credit_total do |order|- order.display_total_applied_store_credit.to_s+ order.display_total_applied_store_credit.to_s unless params[:hide_prices]endattribute :covered_by_store_credit do |order|diff --git a/spree/api/app/serializers/spree/api/v3/line_item_serializer.rb b/spree/api/app/serializers/spree/api/v3/line_item_serializer.rbindex 3171277643..81d9580c5b 100644--- a/spree/api/app/serializers/spree/api/v3/line_item_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/line_item_serializer.rb@@ -18,18 +18,23 @@ module Spreeline_item.variant&.prefixed_idend- attributes :quantity, :currency, :name, :slug, :options_text,- :price, :display_price, :total, :display_total,- :adjustment_total, :display_adjustment_total,- :additional_tax_total, :display_additional_tax_total,- :included_tax_total, :display_included_tax_total,- :discount_total, :display_discount_total,- :pre_tax_amount, :display_pre_tax_amount,- :discounted_amount, :display_discounted_amount,- :display_compare_at_amount+ attributes :quantity, :currency, :name, :slug, :options_text++ # Nulled for gated (prices_hidden) guests so the cart's line items can't+ # leak the prices that product/variant serializers already withhold.+ money_attributes :price, :display_price, :total, :display_total,+ :adjustment_total, :display_adjustment_total,+ :additional_tax_total, :display_additional_tax_total,+ :included_tax_total, :display_included_tax_total,+ :discount_total, :display_discount_total,+ :pre_tax_amount, :display_pre_tax_amount,+ :discounted_amount, :display_discounted_amount,+ :display_compare_at_amount# Return compare_at_amount as string, nil if zeroattribute :compare_at_amount do |line_item|+ next nil if params[:hide_prices]+amount = line_item.compare_at_amountamount.present? && amount.positive? ? amount.to_s : nilenddiff --git a/spree/api/app/serializers/spree/api/v3/order_serializer.rb b/spree/api/app/serializers/spree/api/v3/order_serializer.rbindex a3e4e26ae1..77db526eeb 100644--- a/spree/api/app/serializers/spree/api/v3/order_serializer.rb+++ b/spree/api/app/serializers/spree/api/v3/order_serializer.rb@@ -35,22 +35,26 @@ module Spreeattributes :number, :email, :customer_note,:currency, :locale, :total_quantity,- :item_total, :display_item_total,- :adjustment_total, :display_adjustment_total,- :discount_total, :display_discount_total,- :tax_total, :display_tax_total, :included_tax_total, :display_included_tax_total,- :additional_tax_total, :display_additional_tax_total, :total, :display_total,- :gift_card_total, :display_gift_card_total,- :amount_due, :display_amount_due,- :delivery_total, :display_delivery_total, :fulfillment_status, :payment_status,+ :fulfillment_status, :payment_status,completed_at: :iso8601+ # Nulled for gated (prices_hidden) guests, consistent with cart and+ # catalog price hiding.+ money_attributes :item_total, :display_item_total,+ :adjustment_total, :display_adjustment_total,+ :discount_total, :display_discount_total,+ :tax_total, :display_tax_total, :included_tax_total, :display_included_tax_total,+ :additional_tax_total, :display_additional_tax_total, :total, :display_total,+ :gift_card_total, :display_gift_card_total,+ :amount_due, :display_amount_due,+ :delivery_total, :display_delivery_total+attribute :store_credit_total do |order|- order.total_applied_store_credit.to_s+ order.total_applied_store_credit.to_s unless params[:hide_prices]endattribute :display_store_credit_total do |order|- order.display_total_applied_store_credit.to_s+ order.display_total_applied_store_credit.to_s unless params[:hide_prices]endattribute :covered_by_store_credit do |order|diff --git a/spree/api/config/locales/en.yml b/spree/api/config/locales/en.ymlindex 7cfa1ab00f..8cede02974 100644--- a/spree/api/config/locales/en.yml+++ b/spree/api/config/locales/en.yml@@ -9,6 +9,9 @@ en:invalid_resource: Invalid resource. Please fix errors and try again.invalid_taxonomy_id: Invalid taxonomy id.must_specify_api_key: You must specify an API key.+ errors:+ guest_checkout_not_allowed: You must be signed in to complete checkout.+ storefront_login_required: Authentication required to access this store.negative_quantity: quantity is negativenewsletter_verification_token_invalid: Newsletter verification token is invalid or has expired.order:diff --git a/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rbindex 5da3f352d3..5a43297c11 100644--- a/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb@@ -84,6 +84,14 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller doexpect(json_response).to have_key('mailer_logo_url')end+ it 'exposes the storefront-access gating defaults' do+ subject+ expect(json_response).to include(+ 'preferred_storefront_access' => store.preferred_storefront_access,+ 'preferred_guest_checkout' => store.preferred_guest_checkout+ )+ end+context 'without authentication' dolet(:headers) { {} }@@ -159,6 +167,28 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller doendend+ context 'with storefront-access gating params' do+ let(:params) { { preferred_storefront_access: 'login_required', preferred_guest_checkout: false } }++ it 'updates the store-wide gating defaults' do+ subject+ expect(response).to have_http_status(:ok)+ store.reload+ expect(store.preferred_storefront_access).to eq('login_required')+ expect(store.preferred_guest_checkout).to eq(false)+ end+ end++ context 'with an invalid storefront_access value' do+ let(:params) { { preferred_storefront_access: 'nonsense' } }++ it 'returns a validation error' do+ subject+ expect(response).to have_http_status(:unprocessable_content)+ expect(json_response['error']['code']).to eq('validation_error')+ end+ end+context 'without authentication' dolet(:headers) { {} }let(:params) { { name: 'Renamed Store' } }diff --git a/spree/api/spec/controllers/spree/api/v3/store/storefront_gating_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/storefront_gating_spec.rbnew file mode 100644index 0000000000..7a09c671d0--- /dev/null+++ b/spree/api/spec/controllers/spree/api/v3/store/storefront_gating_spec.rb@@ -0,0 +1,177 @@+require 'spec_helper'++RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do+ render_views++ include_context 'API v3 Store'++ let!(:product) { create(:product, status: 'active') }+ let(:channel) { store.default_channel }++ before do+ request.headers['X-Spree-Api-Key'] = api_key.token+ request.headers['X-Spree-Channel'] = channel.code+ end++ describe 'public storefront access (default)' do+ it 'shows prices to a guest' do+ get :index++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].first['price']).to be_present+ end+ end++ describe 'prices_hidden storefront access' do+ before { channel.update!(preferred_storefront_access: 'prices_hidden') }++ it 'nulls the price for a guest' do+ get :index++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].first['price']).to be_nil+ end++ it 'returns the price for an authenticated customer' do+ request.headers['Authorization'] = "Bearer #{jwt_token}"++ get :index++ expect(response).to have_http_status(:ok)+ expect(json_response['data'].first['price']).to be_present+ end+ end++ describe 'login_required storefront access' do+ before { channel.update!(preferred_storefront_access: 'login_required') }++ it 'rejects a guest with 401' do+ get :index++ expect(response).to have_http_status(:unauthorized)+ end++ it 'allows an authenticated customer' do+ request.headers['Authorization'] = "Bearer #{jwt_token}"++ get :index++ expect(response).to have_http_status(:ok)+ end+ end+end++RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller do+ render_views++ include_context 'API v3 Store'++ let(:channel) { store.default_channel }+ let(:guest_cart) { create(:order, store: store, channel: channel, user: nil, email: '[email protected]') }+ let(:user_cart) { create(:order, store: store, channel: channel, user: user) }++ before do+ request.headers['X-Spree-Api-Key'] = api_key.token+ request.headers['X-Spree-Channel'] = channel.code+ end++ describe 'guest checkout gating (Order#guest_checkout_disallowed?)' do+ context 'when the channel forbids guest checkout' do+ before { channel.update!(preferred_guest_checkout: false) }++ it 'blocks a cart with no registered user' do+ expect(guest_cart.guest_checkout_disallowed?).to be true+ end++ it 'allows a cart owned by a user' do+ expect(user_cart.guest_checkout_disallowed?).to be false+ end+ end++ context 'when the channel allows guest checkout' do+ before { channel.update!(preferred_guest_checkout: true) }++ it 'does not block a guest cart' do+ expect(guest_cart.guest_checkout_disallowed?).to be false+ end+ end++ context 'when the channel hides prices from guests but allows guest checkout' do+ before { channel.update!(preferred_storefront_access: 'prices_hidden', preferred_guest_checkout: true) }++ it 'still blocks a guest cart — a buyer who cannot see prices cannot check out' do+ expect(guest_cart.guest_checkout_disallowed?).to be true+ end+ end+ end++ describe 'POST #complete' do+ before do+ allow(controller).to receive(:find_cart!) { controller.instance_variable_set(:@cart, guest_cart) }+ end++ context 'when the channel forbids guest checkout' do+ before { channel.update!(preferred_guest_checkout: false) }++ it 'rejects a guest with 401 before attempting completion' do+ post :complete, params: { id: guest_cart.prefixed_id }++ expect(response).to have_http_status(:unauthorized)+ end+ end+ end+end++# OrdersController inherits Store::BaseController — proves the login gate now+# covers the BaseController branch, not just Store::ResourceController.+RSpec.describe Spree::Api::V3::Store::OrdersController, type: :controller do+ render_views++ include_context 'API v3 Store'++ let(:channel) { store.default_channel }++ before do+ request.headers['X-Spree-Api-Key'] = api_key.token+ request.headers['X-Spree-Channel'] = channel.code+ end++ describe 'login_required gate' do+ before { channel.update!(preferred_storefront_access: 'login_required') }++ it 'rejects a guest with 401 before loading the order' do+ get :show, params: { id: 'order_missing' }++ expect(response).to have_http_status(:unauthorized)+ end++ it 'lets an authenticated customer through the gate' do+ request.headers['Authorization'] = "Bearer #{jwt_token}"++ get :show, params: { id: 'order_missing' }++ # Passes the gate; the missing order yields a non-401 (404) response.+ expect(response).not_to have_http_status(:unauthorized)+ end+ end+end++# CountriesController opts out via allow_guest_storefront_access! — reference+# data must stay reachable so the login flow works on a login_required channel.+RSpec.describe Spree::Api::V3::Store::CountriesController, type: :controller do+ render_views++ include_context 'API v3 Store'++ before do+ request.headers['X-Spree-Api-Key'] = api_key.token+ request.headers['X-Spree-Channel'] = store.default_channel.code+ store.default_channel.update!(preferred_storefront_access: 'login_required')+ end++ it 'stays open to guests despite login_required' do+ get :index++ expect(response).not_to have_http_status(:unauthorized)+ end+enddiff --git a/spree/api/spec/serializers/spree/api/v3/price_gating_spec.rb b/spree/api/spec/serializers/spree/api/v3/price_gating_spec.rbnew file mode 100644index 0000000000..05470feb9d--- /dev/null+++ b/spree/api/spec/serializers/spree/api/v3/price_gating_spec.rb@@ -0,0 +1,47 @@+require 'spec_helper'++# The prices_hidden gate injects a +hide_prices+ serializer param. These specs+# guard that the cart / order / line-item money surface honors it — so a guest+# can't recover a hidden catalog price via the cart or order.+RSpec.describe 'v3 Store serializer price gating' do+ let(:store) { @default_store || create(:store, default: true) }+ let(:order) { create(:order_with_line_items, store: store, line_items_count: 1) }++ def serialize(serializer, hide:)+ JSON.parse(+ serializer.new(order, params: { store: store, currency: order.currency, hide_prices: hide }).to_h.to_json+ )+ end++ describe Spree::Api::V3::CartSerializer do+ it 'nulls totals, store-credit, and nested line-item prices for gated guests' do+ hash = serialize(described_class, hide: true)++ expect(hash['total']).to be_nil+ expect(hash['display_total']).to be_nil+ expect(hash['item_total']).to be_nil+ expect(hash['store_credit_total']).to be_nil+ hash['items'].each do |li|+ expect(li['price']).to be_nil+ expect(li['display_price']).to be_nil+ expect(li['total']).to be_nil+ end+ end++ it 'serializes money fields normally when not gated' do+ hash = serialize(described_class, hide: false)++ expect(hash['total']).to be_present+ expect(hash['items'].first['price']).to be_present+ end+ end++ describe Spree::Api::V3::OrderSerializer do+ it 'nulls totals for gated guests' do+ hash = serialize(described_class, hide: true)++ expect(hash['total']).to be_nil+ expect(hash['display_total']).to be_nil+ end+ end+enddiff --git a/spree/core/app/models/spree/channel.rb b/spree/core/app/models/spree/channel.rbindex 91cd697504..c8375011ab 100644--- a/spree/core/app/models/spree/channel.rb+++ b/spree/core/app/models/spree/channel.rb@@ -11,6 +11,7 @@ module Spreeinclude Spree::Metafieldsinclude Spree::Metadatainclude Spree::OrderRouting::HasStrategyPreference+ include Spree::Channel::Gating# Empty -> falls back to the Store-level preference.preference :order_routing_strategy, :string, default: nildiff --git a/spree/core/app/models/spree/channel/gating.rb b/spree/core/app/models/spree/channel/gating.rbnew file mode 100644index 0000000000..4219e97dd4--- /dev/null+++ b/spree/core/app/models/spree/channel/gating.rb@@ -0,0 +1,67 @@+module Spree+ class Channel+ # Storefront access gating for a channel. Decides what an anonymous+ # (not-logged-in) visitor may see and whether an order may be placed+ # without an account. Both controls fall back to the owning Store when the+ # channel preference is unset, mirroring +OrderRouting::HasStrategyPreference+.+ module Gating+ extend ActiveSupport::Concern++ # Posture controlling catalog/price visibility for anonymous visitors:+ # - +public+ products + prices visible to anyone+ # - +prices_hidden+ products browsable, prices null for guests+ # - +login_required+ catalog reads rejected for guests+ STOREFRONT_ACCESS = %w[public prices_hidden login_required].freeze++ included do+ # Empty -> falls back to the Store-level preference. `guest_checkout` is+ # `nullable` so a blank write stays nil (inherit) rather than coercing to+ # false, while an explicit true/false remains a channel override.+ preference :storefront_access, :string, default: nil+ preference :guest_checkout, :boolean, default: nil, nullable: true++ validate :storefront_access_must_be_valid+ end++ # @return [String] the effective access posture: the channel preference,+ # or the store fallback when unset, defaulting to +public+.+ def resolved_storefront_access+ preferred_storefront_access.presence ||+ store&.preferred_storefront_access.presence ||+ 'public'+ end++ # @return [Boolean] whether guest checkout is allowed: the channel+ # preference, or the store fallback when the channel value is unset.+ def resolved_guest_checkout+ value = preferred_guest_checkout+ return value unless value.nil?++ store.nil? ? true : store.preferred_guest_checkout+ end++ # @return [Boolean] true when guests must not see prices on this channel.+ def storefront_prices_hidden?+ resolved_storefront_access == 'prices_hidden'+ end++ # @return [Boolean] true when guests must authenticate before browsing.+ def storefront_login_required?+ resolved_storefront_access == 'login_required'+ end++ private++ def storefront_access_must_be_valid+ value = preferred_storefront_access+ return if value.blank?+ return if STOREFRONT_ACCESS.include?(value.to_s)++ errors.add(+ :preferred_storefront_access,+ Spree.t(:invalid_storefront_access, scope: [:errors, :messages], default: 'is not a valid storefront access level')+ )+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/order.rb b/spree/core/app/models/spree/order.rbindex 470058f608..630a1a6fdc 100644--- a/spree/core/app/models/spree/order.rb+++ b/spree/core/app/models/spree/order.rb@@ -513,6 +513,23 @@ module Spreeself.channel = store&.default_channelend+ # @return [Boolean] true when this order has no registered user and its+ # channel forbids guest checkout (see Spree::Channel::Gating). Enforced by+ # the checkout completion service and the v3 Store API so every completion+ # path (controller, payment webhook) is covered.+ #+ # A +prices_hidden+ channel also disallows guest completion regardless of+ # the +guest_checkout+ flag — prices are withheld from guests, and a buyer+ # who cannot see prices cannot meaningfully place an order. This dissolves+ # the otherwise contradictory "prices hidden but guests may buy" config.+ def guest_checkout_disallowed?+ return false if user_id.present?+ return false if channel.blank?+ return true if channel.storefront_prices_hidden?++ !channel.resolved_guest_checkout+ end+def allow_cancel?return false if !completed? || canceled?diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex 80db834c60..6d858992e6 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -46,7 +46,11 @@ module Spree# email preferencespreference :send_consumer_transactional_emails, :boolean, default: true# Checkout preferences+ # Store-level fallback for the channel-owned `guest_checkout` preference+ # (see Spree::Channel::Gating). Retained so existing accessors keep working.preference :guest_checkout, :boolean, default: true+ # Store-level fallback for the channel-owned `storefront_access` posture.+ preference :storefront_access, :string, default: 'public'preference :special_instructions_enabled, :boolean, default: falsepreference :stock_reservation_ttl_minutes, :integer, default: 10# Address preferences@@ -133,6 +137,7 @@ module Spreevalidates :preferred_digital_asset_authorized_clicks, numericality: { only_integer: true, greater_than: 0 }validates :preferred_digital_asset_authorized_days, numericality: { only_integer: true, greater_than: 0 }validates :preferred_stock_reservation_ttl_minutes, numericality: { only_integer: true, greater_than: 0 }+ validates :preferred_storefront_access, inclusion: { in: Spree::Channel::Gating::STOREFRONT_ACCESS }validates :mail_from_address, email: { allow_blank: false }# FIXME: we should remove this condition in v5if !ENV['SPREE_DISABLE_DB_CONNECTION'] &&diff --git a/spree/core/app/services/spree/carts/complete.rb b/spree/core/app/services/spree/carts/complete.rbindex 68744caedb..3ced15b05c 100644--- a/spree/core/app/services/spree/carts/complete.rb+++ b/spree/core/app/services/spree/carts/complete.rb@@ -10,6 +10,9 @@ module Spreedef call(cart:)return success(cart) if cart.completed?return failure(cart, 'Order is canceled') if cart.canceled?+ # Enforced here (not only in the controller) so every completion path —+ # API, payment-session webhook — honors the channel's guest-checkout gate.+ return failure(cart, Spree.t(:guest_checkout_not_allowed)) if cart.guest_checkout_disallowed?cart.with_lock doprocess_payments!(cart) if cart.payment_required?diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.ymlindex bea439d23c..e6afbc6954 100644--- a/spree/core/config/locales/en.yml+++ b/spree/core/config/locales/en.yml@@ -902,6 +902,7 @@ en:channel_store_mismatch: must belong to the same storeinvalid_order_routing_rule: is not a registered order routing ruleinvalid_order_routing_strategy: is not a registered order routing strategy+ invalid_storefront_access: is not a valid storefront access levelmust_be_origin_only: must be an origin (scheme and host) without path, query, or fragmentstore_association_can_not_be_changed: The store association can not be changedstore_is_already_set: Store is already set@@ -963,6 +964,7 @@ en:gift_card_using_store_credit_error: You can't apply the Gift Card after you applied the store credit.gift_cards: Gift Cardsguest_checkout: Guest Checkout+ guest_checkout_not_allowed: You must be signed in to complete checkout.has_no_shipped_units: has no shipped unitsheight: Heighthide: Hidediff --git a/spree/core/lib/spree/core/preferences/preferable.rb b/spree/core/lib/spree/core/preferences/preferable.rbindex c96578a536..fcdf1278ab 100644--- a/spree/core/lib/spree/core/preferences/preferable.rb+++ b/spree/core/lib/spree/core/preferences/preferable.rb@@ -135,7 +135,12 @@ module Spree::Preferences::Preferableint_value ||= 0 unless nullableint_value.present? ? int_value.to_i : int_valuewhen :boolean- if value.is_a?(FalseClass) ||+ # A nullable boolean keeps "unset" (nil / empty string) as nil so it can+ # fall back to another value, instead of collapsing it to false. An+ # explicit false is preserved (it is neither nil nor empty).+ if nullable && (value.nil? || (value.respond_to?(:empty?) && value.empty?))+ nil+ elsif value.is_a?(FalseClass) ||value.nil? ||value == 0 ||value&.to_s =~ /^(f|false|0)$/i ||diff --git a/spree/core/lib/spree/permitted_attributes.rb b/spree/core/lib/spree/permitted_attributes.rbindex 5decc98223..ddbe8322a7 100644--- a/spree/core/lib/spree/permitted_attributes.rb+++ b/spree/core/lib/spree/permitted_attributes.rb@@ -240,7 +240,8 @@ module Spree@@shipping_category_attributes = [:name]- @@channel_attributes = [:name, :code, :active, :default, :preferred_order_routing_strategy]+ @@channel_attributes = [:name, :code, :active, :default, :preferred_order_routing_strategy,+ :preferred_storefront_access, :preferred_guest_checkout]@@shipping_method_attributes = [:name, :admin_name, :code, :tracking_url, :tax_category_id, :display_on,:estimated_transit_business_days_min, :estimated_transit_business_days_max,@@ -278,7 +279,7 @@ module Spree:preferred_limit_digital_download_count, :preferred_limit_digital_download_days,:preferred_digital_asset_link_expire_time,:logo, :mailer_logo,- :preferred_guest_checkout]+ :preferred_guest_checkout, :preferred_storefront_access]@@store_credit_attributes = %i[amount currency category_id memo]diff --git a/spree/core/spec/models/spree/channel/gating_spec.rb b/spree/core/spec/models/spree/channel/gating_spec.rbnew file mode 100644index 0000000000..09e37033de--- /dev/null+++ b/spree/core/spec/models/spree/channel/gating_spec.rb@@ -0,0 +1,94 @@+require 'spec_helper'++RSpec.describe Spree::Channel::Gating, type: :model do+ let(:store) { create(:store) }+ let(:channel) { create(:channel, store: store) }++ describe '#resolved_storefront_access' do+ it 'defaults to public when neither channel nor store override it' do+ expect(channel.resolved_storefront_access).to eq('public')+ end++ it 'returns the channel override when present' do+ channel.update!(preferred_storefront_access: 'login_required')+ expect(channel.resolved_storefront_access).to eq('login_required')+ end++ it 'falls back to the store value when the channel is unset' do+ store.update!(preferred_storefront_access: 'prices_hidden')+ expect(channel.resolved_storefront_access).to eq('prices_hidden')+ end++ it 'prefers the channel value over the store value' do+ store.update!(preferred_storefront_access: 'login_required')+ channel.update!(preferred_storefront_access: 'public')+ expect(channel.resolved_storefront_access).to eq('public')+ end+ end++ describe '#resolved_guest_checkout' do+ it 'is nil on the channel by default (inherit)' do+ expect(channel.preferred_guest_checkout).to be_nil+ end++ it 'falls back to the store default (true) when the channel is unset' do+ expect(channel.resolved_guest_checkout).to be true+ end++ it 'returns the channel override even when the store allows guests' do+ channel.update!(preferred_guest_checkout: false)+ expect(channel.resolved_guest_checkout).to be false+ end++ it 'follows the store when the store forbids guests and the channel is unset' do+ store.update!(preferred_guest_checkout: false)+ expect(channel.resolved_guest_checkout).to be false+ end++ it 'clears the override (restores inheritance) when written blank' do+ store.update!(preferred_guest_checkout: false)+ channel.update!(preferred_guest_checkout: true)+ expect(channel.resolved_guest_checkout).to be true++ # A boolean preference would coerce this to false; the override must+ # instead delete the key so the store value applies again.+ channel.update!(preferred_guest_checkout: '')+ expect(channel.preferred_guest_checkout).to be_nil+ expect(channel.resolved_guest_checkout).to be false+ end+ end++ describe 'storefront_access validation' do+ it 'allows a blank value (inherit)' do+ channel.preferred_storefront_access = ''+ expect(channel).to be_valid+ end++ it 'allows every known level' do+ Spree::Channel::Gating::STOREFRONT_ACCESS.each do |level|+ channel.preferred_storefront_access = level+ expect(channel).to be_valid, "expected #{level} to be a valid storefront_access"+ end+ end++ it 'rejects an unknown level' do+ channel.preferred_storefront_access = 'secret'+ expect(channel).not_to be_valid+ expect(channel.errors[:preferred_storefront_access]).to be_present+ end+ end++ describe 'predicates' do+ it '#storefront_prices_hidden? is true only for prices_hidden' do+ channel.update!(preferred_storefront_access: 'prices_hidden')+ expect(channel.storefront_prices_hidden?).to be true+ expect(channel.storefront_login_required?).to be false+ end++ it '#storefront_login_required? is true only for login_required' do+ channel.update!(preferred_storefront_access: 'login_required')+ expect(channel.storefront_login_required?).to be true+ expect(channel.storefront_prices_hidden?).to be false+ end+ end+enddiff --git a/spree/core/spec/models/spree/preferences/preferable_spec.rb b/spree/core/spec/models/spree/preferences/preferable_spec.rbindex 369317a38c..da113b696f 100644--- a/spree/core/spec/models/spree/preferences/preferable_spec.rb+++ b/spree/core/spec/models/spree/preferences/preferable_spec.rb@@ -239,6 +239,34 @@ describe Spree::Preferences::Preferable, type: :model doendend+ context 'converts nullable boolean preferences' do+ before do+ A.preference :nullable_boolean, :boolean, default: nil, nullable: true+ end++ it 'stores nil when set to nil' do+ @a.set_preference(:nullable_boolean, nil)+ expect(@a.preferences[:nullable_boolean]).to be_nil+ end++ it 'stores nil when set to an empty string' do+ @a.set_preference(:nullable_boolean, '')+ expect(@a.preferences[:nullable_boolean]).to be_nil+ end++ it 'preserves an explicit false (does not collapse it to nil)' do+ @a.set_preference(:nullable_boolean, false)+ expect(@a.preferences[:nullable_boolean]).to be false+ @a.set_preference(:nullable_boolean, 'f')+ expect(@a.preferences[:nullable_boolean]).to be false+ end++ it 'preserves an explicit true' do+ @a.set_preference(:nullable_boolean, true)+ expect(@a.preferences[:nullable_boolean]).to be true+ end+ end+context 'converts array preferences to array values' dobefore doA.preference :is_array, :array, default: []diff --git a/spree/core/spec/services/spree/carts/complete_spec.rb b/spree/core/spec/services/spree/carts/complete_spec.rbindex 498a4da707..34ffd088ed 100644--- a/spree/core/spec/services/spree/carts/complete_spec.rb+++ b/spree/core/spec/services/spree/carts/complete_spec.rb@@ -27,6 +27,22 @@ RSpec.describe Spree::Carts::Complete doexpect(result.value).to eq(order)end+ context 'when the channel forbids guest checkout and the order has no user' do+ let(:channel) { store.default_channel }++ before do+ channel.update!(preferred_guest_checkout: false)+ order.update!(user: nil, channel: channel)+ end++ it 'fails without completing the order — covers webhook/service completion paths' do+ result = subject.call(cart: order)++ expect(result).to be_failure+ expect(order.reload).not_to be_completed+ end+ end+context 'when order is already completed' dobefore { order.update_columns(state: 'complete', completed_at: Time.current) }