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
Store-Scoped Configuration (#14427)
Damian Legawiec2836f0f4c8e9
diff --git a/docs/plans/6.0-store-scoped-configuration.md b/docs/plans/6.0-store-scoped-configuration.mdindex 4759794299..ffedf464c9 100644--- a/docs/plans/6.0-store-scoped-configuration.md+++ b/docs/plans/6.0-store-scoped-configuration.md@@ -1,14 +1,14 @@# Store-Scoped Configuration-**Status:** Design finalized, implementation not started+**Status:** Phases 1 and 2 shipped (2026-08-12) — all eight movers live on Store, exposed in the Admin API and dashboard. Phase 3 (deleting the globals) remains for 6.1**Target:** Spree 6.0 (globals deleted in 6.1)**Depends on:** Single-owner Product (`6.1-channels-catalogs-b2b.md`, shipped 5.5), Cart/Order split (`6.0-cart-order-split.md`), Tax provider (`6.0-tax-provider.md`, for the `tax_using_ship_address` retirement)**Author:** Damian + Claude-**Last updated:** 2026-08-04+**Last updated:** 2026-08-12## Summary-A full usage audit of `Spree::Config` (2026-08-04, multi-agent trace with adversarial verification over all 68 preferences) found 38 genuinely live settings, 6 read only by subsystems 6.0 replaced, and 7 with zero read sites anywhere. The live settings split into two kinds: **application configuration** (security, limits, jobs, URLs — properties of the installation) and **commerce behavior** (capture timing, inventory tracking, catalog visibility — properties of a store). Now that Products, Promotions, PaymentMethods and StockLocations are single-store resources, a global flag for per-store behavior is a design smell. This plan moves nine commerce-behavior globals to `Spree::Store` preferences — finishing the migration that `company` → `company_field_enabled` and `allow_guest_checkout` → `guest_checkout` already started — and retires the dead ones.+A full usage audit of `Spree::Config` (2026-08-04, multi-agent trace with adversarial verification over all 68 preferences) found 38 genuinely live settings, 6 that only subsystems 6.0 replaced ever read, and 7 with zero read sites anywhere. The live settings split into two kinds: **application configuration** (security, limits, jobs, URLs — properties of the installation) and **commerce behavior** (capture timing, inventory tracking, catalog visibility — properties of a store). Now that Products, Promotions, PaymentMethods and StockLocations are single-store resources, a global flag for per-store behavior is a design smell. This plan moves eight commerce-behavior globals to `Spree::Store` preferences — finishing the migration that `company` → `company_field_enabled` and `allow_guest_checkout` → `guest_checkout` already started — and retires the dead ones.## Problem@@ -25,13 +25,12 @@ That is what two sources of truth for one behavior produces: one quietly wins, t## Key Decisions (do not deviate without discussion)-- **The nine movers** (identical names on Store, defaults unchanged):+- **The eight movers** (identical names on Store, defaults unchanged):| Global today | Store preference | Default ||---|---|---|| `auto_capture` | `preferred_auto_capture` | `true` || `auto_capture_on_dispatch` | `preferred_auto_capture_on_dispatch` | `false` |- | `allow_checkout_on_gateway_error` | `preferred_allow_checkout_on_gateway_error` | `false` || `track_inventory_levels` | `preferred_track_inventory_levels` | `true` || `stock_reservations_enabled` | `preferred_stock_reservations_enabled` | `true` || `track_price_history` | `preferred_track_price_history` | `true` |@@ -44,22 +43,24 @@ That is what two sources of truth for one behavior produces: one quietly wins, t- **Globals become deprecated shells for one release** (`deprecated: 'Set …on the store'` in the preference DSL, which warns through `Spree::Deprecation` on access), deleted in 6.1. Repo-wide deprecation-bridge rule.- **`auto_capture` resolution chain:** payment method column when not `nil` → store preference. The dashboard already exposes the per-method column; the store preference replaces only the global fallback in `PaymentMethod#auto_capture?` (`payment_method.rb:178`). The per-method column stays the primary control.- **Storeless contexts read `Spree::Current.store`, falling back to the declared default** (decided 2026-08-04). Two readers have no record-level store: `Address` (no store association) and the `Product` availability scope (class-level). Both resolve through `Spree::Current.store`. Accepted trade-off: validation or a catalog query run outside a request — a console session, a seed, a job that forgets to set the store — silently uses the default rather than the store's value. This is why the alternative (threading a store argument through every caller, breaking a public scope) was rejected as disproportionate. **Any job that validates addresses or queries the catalog must set `Spree::Current.store`.**-- **`default_stock_reservation_ttl_minutes` is deprecated, not moved.** `Store#stock_reservation_ttl_minutes` already owns the value. `StockReservation.ttl_for` drops the global read and keeps its hard 10-minute floor for storeless contexts.+- **`default_stock_reservation_ttl_minutes` is deprecated, not moved** (done 2026-08-12). `Store#stock_reservation_ttl_minutes` already owns the value. `StockReservation.ttl_for` dropped the global read and keeps its hard 10-minute floor for storeless contexts.- **`track_price_history` goes to Store in 6.0, with Market as a noted future refinement** (decided 2026-08-04). EU Omnibus is per-country law, and Market already owns `return_window_days` and the other legal settings — but prices are not market-scoped today, so a Market home needs design work this plan will not carry. Store now; revisit when price/market scoping is on the table.-- **Stay global despite looking behavioral:** `credit_to_new_allocation` (ledger-shape convention — per-store variance makes one install's accounting inconsistent) and `non_expiring_credit_types` (reference data).-- **The seven dead settings get deprecation shells in 6.0, deleted in 6.1:** `products_per_page`, `alternative_shipping_phone`, `show_variant_full_price`, `reserve_stock_on`, `storefront_products_path`, `storefront_taxons_path`, `storefront_pages_path`. Zero read sites, audit-verified including dynamic-lookup forms. Shells only so an initializer that sets one doesn't crash boot mid-upgrade.+- **Stay global despite looking behavioral:** `credit_to_new_allocation` (ledger-shape convention — per-store variance makes one install's accounting inconsistent), `non_expiring_credit_types` (reference data) and `geocode_addresses` (decided 2026-08-12 — geocoding is infrastructure: it depends on the install's provider credentials and quota, not on how a shop sells).+- **`allow_checkout_on_gateway_error` is dropped rather than moved** (decided 2026-08-12, reversing this plan's own list). Nothing reads it in Spree 6. It used to gate a state-machine transition through the return value of `process_payments!`, but both completion workflows now discard that value and check whether payments actually cover the total (`Carts::Complete#process_payments`, `Orders::Complete#process_payments`) — and the rescue adds the gateway message to `errors` regardless, which `Orders::Complete` fails on. So with the flag on, a gateway error still cannot complete an order. Shipping it as a store preference would have put a dead toggle in the dashboard, which is worse than a dead global. Deprecated as "nothing reads this"; restoring the behavior means teaching the workflows to honor it, which is a feature, not a settings move.++- **`address_requires_state` is dropped rather than moved** (decided 2026-08-12). It was already deprecated and gated a check the country's own `states_required` flag decides. Two switches for one question is the drift this plan exists to remove, so `Address#state_validate` now reads the country alone. Installs that set it to `false` while their countries required states will see those addresses start failing validation — the country flag is the place to change.+- **The seven dead settings got deprecation shells in 6.0 (done 2026-08-12), deleted in 6.1:** `products_per_page`, `alternative_shipping_phone`, `show_variant_full_price`, `reserve_stock_on`, `storefront_products_path`, `storefront_taxons_path`, `storefront_pages_path`. Zero read sites, audit-verified including dynamic-lookup forms. Shells only so an initializer that sets one doesn't crash boot mid-upgrade.- **Already deprecated this cycle, recorded here for completeness:** `tax_using_ship_address` (the tax provider owns address choice per market), `allow_empty_price_amount` (price lists already allow blank), `always_include_confirm_step` (confirm is an advertised step, never enforced — the storefront renders a review screen when it wants one), `restock_inventory` / `return_eligibility_number_of_days` / `expedited_exchanges` / `expedited_exchanges_days_window` (the returns rework owns these), `use_user_locale` (locale comes from `x-spree-locale` or the `locale` param), `enable_legacy_default_price` (leave off).- **New behavior flags never start global.** From 6.0 on, a setting that shapes how a store sells is born on Store (or Market/Channel where regional), never in `Spree.config`.## Design Details-### Read sites to re-point (from the audit)+### Read sites re-pointed (all done 2026-08-12)| Setting | Read sites | Store reached via ||---|---|---|| `auto_capture` | `payment_method.rb:178` | PaymentMethod is store-owned || `auto_capture_on_dispatch` | `fulfillment.rb:280,615` | fulfillment → order/cart → store |-| `allow_checkout_on_gateway_error` | `purchase/payment_processing.rb:67` | concern on Cart/Order — `store` is present || `track_inventory_levels` | `variant.rb:669`, `product.rb:868` | variant → product → store || `stock_reservations_enabled` | `stock_reservations/reserve.rb:11`, `extend.rb:11`, `stock/quantifier.rb:69` | cart/order → store; stock_item → stock_location → store || `track_price_history` | `price.rb:189` | price → variant → product → store |@@ -71,7 +72,7 @@ That is what two sources of truth for one behavior produces: one quietly wins, t### Admin API + Dashboard-Store preferences already flow through the Admin API v3 store settings surface and the dashboard settings pages. Phase 2 adds the nine to the store serializer and permitted params, and surfaces them in the relevant dashboard sections (payments, inventory, catalog, checkout). Serializer changes ride the type-generation pipeline.+Store preferences already flow through the Admin API v3 store settings surface and the dashboard settings pages. Phase 2 adds the eight to the store serializer and permitted params, and surfaces them in the relevant dashboard sections (payments, inventory, catalog, checkout). Serializer changes ride the type-generation pipeline.### Incidental fixes (do regardless of the move)@@ -83,27 +84,37 @@ Store preferences already flow through the Admin API v3 store settings surface a### Phase 1 (6.0): move + deprecate-1. Add the nine preferences to `Spree::Store` with defaults matching the globals.+Shipped 2026-08-12. `Spree::StorePreferences` is the shared reader: including models define `preference_store` to say how they reach a store (Variant through its product, Price through variant → product, Fulfillment through its owner), and `Spree::StorePreferences.read(store, name)` falls back to the preference's declared default when there is no store — so a console session, a seed, or a job that never set the ambient store gets the default instead of an exception. Class-level callers with no record use `.current(name)`, which resolves `Spree::Current.store`.++The two resolve differently and the difference matters for address validation and product availability: `Spree::Current.store` itself falls back to `Spree::Store.default`, so `.current(name)` returns **the default store's configured value** and only reaches the declared default when the installation has no default store at all. `.read(nil, name)` always returns the declared default. Prefer `.current` when the ambient store is the right answer, and `.read(record_store, name)` when a specific record's store is.++Two fixes rode along: `Address#show_company_address_field?` used to raise on a storeless read (`Spree::Store.current.prefers_…`), and the product availability scope took its fallback currency from `Spree::Store.default` rather than the ambient store, so a multi-store install filtered the catalog by the wrong shop's currency.++The backfill has a wrinkle worth knowing: a store writes every declared default into its preferences hash the moment it is instantiated, so the key is always present and nothing distinguishes "the merchant chose this value" from "this is the seeded default" — not `preferences.key?`, and not comparing against `preference_default`. There is no explicit-vs-seeded flag to consult. `spree:store_settings:backfill_from_config` therefore records a marker in store metadata and visits each store at most once. The residual risk is one-directional and small: on the single run, a store whose value happens to equal the default takes the global's value. Afterwards the marker protects every later change. Two settings were also renamed on the way over (`company` → `company_field_enabled`, `default_stock_reservation_ttl_minutes` → `stock_reservation_ttl_minutes`), so the task maps global names to preference names rather than assuming they match.++Specs drive these through `stub_store_preferences` (`Spree::TestingSupport::Preferences`), which **stubs** rather than writes — the default store is shared suite-wide, so persisting a setting in one example would change the next. The stub is keyed on store id (code under test reaches its store through an association or a reload, so it holds a different instance of the same row) and leaves other stores and unnamed preferences answering for themselves.++1. Add the eight preferences to `Spree::Store` with defaults matching the globals.2. Re-point the read sites per the table above; `Address` and the product scope read `Spree::Current.store`.-3. Mark the nine globals plus the seven dead settings `deprecated:` in `spree/core/lib/spree/core/configuration.rb`.+3. Mark the eight globals plus the dead settings `deprecated:` in `spree/core/lib/spree/core/configuration.rb`.4. Ship `spree:store_settings:backfill_from_config` and add it to the 5.6→6.0 upgrade manifest.5. `StockReservation.ttl_for` drops its global read.### Phase 2 (6.0): expose-6. Admin API v3 store serializer and permitted params for the nine; regenerate types.+6. Admin API v3 store serializer and permitted params for the eight; regenerate types.7. Dashboard settings pages gain the new toggles in their natural sections.-8. Docs: `docs/v6/developer/customization/configuration.mdx` already carries the commerce/application split — move the nine into the store-settings docs once shipped.+8. Docs: `docs/v6/developer/customization/configuration.mdx` already carries the commerce/application split — move the eight into the store-settings docs once shipped.### Phase 3 (6.1): delete-9. Delete the nine deprecated globals, the seven dead settings, and the legacy shells listed above.+9. Delete the eight deprecated globals, the dead settings, and the legacy shells listed above.## Constraints on Current Work-- **Don't add new `Spree::Config` reads of the nine movers.** New code needing one of these values should read it from the store, or take it as an argument, so Phase 1 has fewer sites to chase.+- **Don't add new `Spree::Config` reads of the movers** — they are deprecated and no longer read by core. Read them through `Spree::StorePreferences` (include the concern and define `preference_store`, or call `.read`/`.current`).- **New behavior flags go on Store from the start** — never add a commerce-behavior preference to `Spree.config`.-- **Don't build UI against the global `auto_capture`.** The dashboard exposes the per-method column; that stays the primary control.+- **Don't build UI against the global `auto_capture`.** The dashboard exposes the per-method column as the primary control, with the store preference as its fallback.- **Background jobs that validate addresses or query the catalog must set `Spree::Current.store`** — after Phase 1 those paths read the ambient store and will otherwise silently use defaults.- The v6 configuration docs page keeps its commerce/application two-group structure; new settings slot into the right group.diff --git a/docs/v6/developer/customization/configuration.mdx b/docs/v6/developer/customization/configuration.mdxindex 9031080de0..1f7c7acf03 100644--- a/docs/v6/developer/customization/configuration.mdx+++ b/docs/v6/developer/customization/configuration.mdx@@ -8,7 +8,7 @@ Global settings live in `config/initializers/spree.rb` and apply to the whole ap```ruby config/initializers/spree.rbSpree.config do |config|config.minimum_password_length = 10- config.track_inventory_levels = false+ config.allow_empty_price_amount = trueend```@@ -18,13 +18,24 @@ Restart your Rails server after editing the initializer.This page lists only settings Spree 6 actually reads. Settings that exist for backwards compatibility are listed under [Deprecated settings](#deprecated-settings) rather than mixed in with the rest.+## Settings that belong to a store++Settings that shape how a shop sells — when cards are charged, whether stock is counted, which products appear without a price — are properties of a store, not of the installation, so they live on `Spree::Store` and are edited in the dashboard under **Settings → Store**:++`auto_capture`, `auto_capture_on_dispatch`, `track_inventory_levels`, `stock_reservations_enabled`, `stock_reservation_ttl_minutes`, `track_price_history`, `show_products_without_price`, `disable_sku_validation`, `address_requires_phone`, `company_field_enabled`, plus `guest_checkout` and `storefront_access` — those last two are owned by the channel, and the store's value is what a channel falls back to.++They were global before Spree 6. The global versions still exist for one release but are no longer read, so setting one in the initializer changes nothing — run `bin/rake spree:store_settings:backfill_from_config` during the upgrade to copy your values onto every store.++```ruby+store = Spree::Current.store+store.preferred_auto_capture # => true+store.update!(preferred_track_inventory_levels: false)+```+## Checkout and payments| Setting | Default | What it does ||---|---|---|-| `auto_capture` | `true` | Store-wide default for whether cards are charged immediately at checkout, or only authorized and captured later. Individual payment methods override it. |-| `auto_capture_on_dispatch` | `false` | Delays charging until goods actually go out. A parcel becomes ready to send once payment is authorized, and money is taken on dispatch. |-| `allow_checkout_on_gateway_error` | `false` | Lets a customer finish checkout even when the payment gateway returns an error. || `always_include_confirm_step` | `false` | Always shows a confirmation step, even when the payment method doesn't need one. || `tax_using_ship_address` | `true` | Calculates tax from the shipping address rather than the billing address. || `credit_to_new_allocation` | `false` | Records refunded store credit as a new entry each time instead of topping the original credit back up. |@@ -34,26 +45,15 @@ This page lists only settings Spree 6 actually reads. Settings that exist for ba| Setting | Default | What it does ||---|---|---|-| `stock_reservations_enabled` | `true` | Holds stock for shoppers while they check out, so the same item can't be sold twice. |-| `default_stock_reservation_ttl_minutes` | `10` | How long a stock hold lasts, for stores that haven't set their own value. || `guest_cart_expiry_days` | `30` | How long an abandoned guest cart is kept before deletion. || `customer_cart_expiry_days` | `90` | How long a signed-in customer's abandoned cart is kept. || `empty_cart_expiry_hours` | `48` | How long a cart with no items is kept. |-## Inventory--| Setting | Default | What it does |-|---|---|---|-| `track_inventory_levels` | `true` | Global switch for stock tracking. Turn it off and the store stops counting on-hand quantities and treats everything as always available. |-## Products and pricing| Setting | Default | What it does ||---|---|---|-| `show_products_without_price` | `false` | Whether products with no price in the shopper's currency still appear in listings and search. || `allow_empty_price_amount` | `false` | Allows a price to be left blank instead of requiring an amount. Prices in a price list already allow blank. |-| `disable_sku_validation` | `false` | Set to `true` to let more than one variant share the same SKU. |-| `track_price_history` | `true` | Records price changes so the store can show the lowest price of the last 30 days, as the EU Omnibus Directive requires. Turn off for non-EU stores. || `price_history_retention_days` | `30` | How many days of price history the `spree:price_history:prune` task keeps. || `always_use_translations` | `false` | Always read product, category and collection names from the translation tables, even in the store's own default language. |@@ -61,7 +61,6 @@ This page lists only settings Spree 6 actually reads. Settings that exist for ba| Setting | Default | What it does ||---|---|---|-| `address_requires_phone` | `false` | Makes a phone number mandatory on customer addresses. || `geocode_addresses` | `true` | Looks up latitude and longitude for saved addresses. |## Media@@ -146,7 +145,7 @@ Spree::Api::Config.jwt_expiration = 1800## Reading a setting```ruby-Spree::Config.track_inventory_levels # => true+Spree::Config.minimum_password_length # => 8Spree::Api::Config.jwt_expiration # => 3600```@@ -166,13 +165,22 @@ These still exist so upgrades don't break, but Spree 6 either ignores them or re| `use_user_locale` | Locale comes from the `x-spree-locale` header or the `locale` parameter || `allow_guest_checkout` | The `guest_checkout` setting on the store or channel || `company` | The `company_field_enabled` setting on the store |+| `address_requires_phone` | The `address_requires_phone` setting on the store |+| `default_stock_reservation_ttl_minutes` | The `stock_reservation_ttl_minutes` setting on the store |+| `auto_capture` | The `auto_capture` setting on the store |+| `auto_capture_on_dispatch` | The `auto_capture_on_dispatch` setting on the store |+| `stock_reservations_enabled` | The `stock_reservations_enabled` setting on the store |+| `track_inventory_levels` | The `track_inventory_levels` setting on the store |+| `show_products_without_price` | The `show_products_without_price` setting on the store |+| `disable_sku_validation` | The `disable_sku_validation` setting on the store |+| `track_price_history` | The `track_price_history` setting on the store || `address_requires_state` | State requirements come from the country || `checkout_zone` | [Delivery zones](/v6/developer/core-concepts/fulfillments#delivery-methods-and-zones) || `currency` | Store and market currencies || `disable_store_presence_validation` | Every store-owned record now requires a store |<Warning>-These settings have no effect at all in Spree 6, and are scheduled for removal: `products_per_page`, `alternative_shipping_phone`, `show_variant_full_price`, `reserve_stock_on`, `storefront_products_path`, `storefront_taxons_path`, `storefront_pages_path`. Setting them changes nothing.+These settings have no effect at all in Spree 6, and are scheduled for removal: `allow_checkout_on_gateway_error` (completion checks whether payments cover the total, so a failed gateway call never completes an order), `products_per_page`, `alternative_shipping_phone`, `show_variant_full_price`, `reserve_stock_on`, `storefront_products_path`, `storefront_taxons_path`, `storefront_pages_path`. Setting them changes nothing.</Warning>## Relateddiff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.tsindex 0e3585eb54..90e73b0630 100644--- a/packages/admin-sdk/src/params.ts+++ b/packages/admin-sdk/src/params.ts@@ -22,6 +22,24 @@ export interface StoreUpdateParams {preferred_storefront_url?: string | null/** Store-wide default for guest checkout. Channels fall back to this. */preferred_guest_checkout?: boolean+ /** Shows a company field on address forms. */+ preferred_company_field_enabled?: boolean+ /** Makes a phone number mandatory on customer addresses. */+ preferred_address_requires_phone?: boolean+ /** Store-wide default for charging cards at checkout rather than only authorizing them. A payment method's own setting wins when set. */+ preferred_auto_capture?: boolean+ /** Takes payment when goods are dispatched rather than at checkout. */+ preferred_auto_capture_on_dispatch?: boolean+ /** Counts on-hand quantities. Off means everything is treated as always available. */+ preferred_track_inventory_levels?: boolean+ /** Holds stock for shoppers while they check out, so the same item can't be sold twice. */+ preferred_stock_reservations_enabled?: boolean+ /** Records price changes for the EU Omnibus lowest-price-in-30-days display. */+ preferred_track_price_history?: boolean+ /** Whether products with no price in the shopper's currency still appear in listings. */+ preferred_show_products_without_price?: boolean+ /** Lets more than one variant share the same SKU. */+ preferred_disable_sku_validation?: 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. */diff --git a/packages/admin-sdk/src/types/generated/Store.ts b/packages/admin-sdk/src/types/generated/Store.tsindex 46980a2920..da664a9728 100644--- a/packages/admin-sdk/src/types/generated/Store.ts+++ b/packages/admin-sdk/src/types/generated/Store.ts@@ -1,4 +1,4 @@-// Typelizer digest 07a6d2c4cf573d4f911930c8ea99c73c+// Typelizer digest 43220c0f31c2c31c5ed6989321e76ea3//// DO NOT MODIFY: This file was automatically generated by Typelizer.import type {SetupTask} from '@/types'@@ -25,6 +25,15 @@ interface Store {preferred_unit_system: string;preferred_storefront_access: string;preferred_guest_checkout: boolean;+ preferred_company_field_enabled: boolean;+ preferred_address_requires_phone: boolean;+ preferred_auto_capture: boolean;+ preferred_auto_capture_on_dispatch: boolean;+ preferred_track_inventory_levels: boolean;+ preferred_stock_reservations_enabled: boolean;+ preferred_track_price_history: boolean;+ preferred_show_products_without_price: boolean;+ preferred_disable_sku_validation: boolean;preferred_order_routing_strategy: string;created_at: string;updated_at: string;diff --git a/packages/dashboard/src/locales/ar.json b/packages/dashboard/src/locales/ar.jsonindex b854adf1ae..78231f5ca6 100644--- a/packages/dashboard/src/locales/ar.json+++ b/packages/dashboard/src/locales/ar.json@@ -1248,11 +1248,31 @@}},"store": {+ "address_requires_phone": {+ "help": "جعل رقم الهاتف إلزاميًا في عناوين العملاء.",+ "label": "اشتراط رقم الهاتف"+ },+ "auto_capture": {+ "help": "تحصيل المبلغ فورًا بدلًا من حجزه فقط. يمكن لطريقة الدفع تجاوز هذا الإعداد.",+ "label": "تحصيل البطاقات عند الدفع"+ },+ "auto_capture_on_dispatch": {+ "help": "الانتظار حتى تخرج البضائع فعليًا قبل تحصيل المبلغ.",+ "label": "التحصيل عند الشحن"+ },+ "company_field_enabled": {+ "help": "إظهار حقل الشركة في نماذج العناوين أثناء الدفع.",+ "label": "حقل الشركة"+ },"customer_support_email": {"help": "عنوان الرد الظاهر للعملاء في رسائل المتجر.","label": "بريد دعم العملاء","placeholder": "[email protected]"},+ "disable_sku_validation": {+ "help": "السماح لأكثر من متغير باستخدام رمز SKU نفسه.",+ "label": "السماح بتكرار رمز SKU"+ },"guest_checkout": {"help": "الإعداد الافتراضي على مستوى المتجر لما إذا كان بإمكان المتسوّقين إتمام الشراء دون حساب. يمكن للقنوات تجاوزه.","label": "الدفع كضيف"@@ -1303,6 +1323,14 @@"preferred_weight_unit": {"label": "وحدة الوزن"},+ "show_products_without_price": {+ "help": "عرض المنتجات التي لا سعر لها بعملة العميل.",+ "label": "إظهار المنتجات بدون سعر"+ },+ "stock_reservations_enabled": {+ "help": "حجز المنتجات أثناء إتمام العميل للطلب حتى لا يُباع المنتج نفسه مرتين.",+ "label": "حجز المخزون أثناء الدفع"+ },"storefront_access": {"help": "الإعداد الافتراضي على مستوى المتجر لما يراه الزوار غير المسجّلين. يمكن للقنوات تجاوزه. عند إخفاء الأسعار، يجب على الضيوف تسجيل الدخول لإتمام الشراء.","label": "الوصول إلى المتجر",@@ -1311,6 +1339,14 @@"prices_hidden": "الأسعار مخفية — يجب على الزوار تسجيل الدخول لرؤية الأسعار","public": "عام — يمكن للجميع التصفّح ورؤية الأسعار"}+ },+ "track_inventory_levels": {+ "help": "احتساب الكميات المتوفرة. أوقفه لمعاملة كل منتج على أنه متاح دائمًا.",+ "label": "تتبع مستويات المخزون"+ },+ "track_price_history": {+ "help": "الاحتفاظ بالأسعار السابقة ليتمكن المتجر من عرض أقل سعر خلال آخر 30 يومًا، وفقًا لقواعد الاتحاد الأوروبي.",+ "label": "تسجيل سجل الأسعار"}},"store_credit": {@@ -2629,8 +2665,12 @@"store": {"default_package_description": "الصندوق المعتاد للشحن. يضيف مزوّدو أسعار النقل وزنه إلى كل طرد ويستخدمون أبعاده لتسعير الوزن الحجمي.","subtitle": "التكوين العام والإعدادات الافتراضية على مستوى المتجر.",+ "tab_addresses": "العناوين",+ "tab_catalog": "الكتالوج","tab_default_package": "الطرد الافتراضي","tab_general": "عام",+ "tab_inventory": "المخزون",+ "tab_payments": "المدفوعات","tab_standards": "المعايير والأشكال","tab_storefront_access": "الوصول إلى المتجر","title": "إعدادات المتجر"diff --git a/packages/dashboard/src/locales/de.json b/packages/dashboard/src/locales/de.jsonindex a7530b8f6b..bd1eb70a46 100644--- a/packages/dashboard/src/locales/de.json+++ b/packages/dashboard/src/locales/de.json@@ -1237,11 +1237,31 @@}},"store": {+ "address_requires_phone": {+ "help": "Eine Telefonnummer in Kundenadressen zur Pflicht machen.",+ "label": "Telefonnummer erforderlich"+ },+ "auto_capture": {+ "help": "Den Betrag sofort einziehen statt ihn nur zu reservieren. Eine Zahlungsart kann dies überschreiben.",+ "label": "Karten beim Bezahlen belasten"+ },+ "auto_capture_on_dispatch": {+ "help": "Erst abbuchen, wenn die Ware tatsächlich rausgeht.",+ "label": "Bei Versand belasten"+ },+ "company_field_enabled": {+ "help": "Ein Firmenfeld in den Adressformularen an der Kasse anzeigen.",+ "label": "Firmenfeld"+ },"customer_support_email": {"help": "Antwortadresse, die Kunden in Storefront-E-Mails angezeigt wird.","label": "E-Mail des Kundensupports","placeholder": "[email protected]"},+ "disable_sku_validation": {+ "help": "Mehrere Varianten dürfen dieselbe SKU verwenden.",+ "label": "Doppelte SKUs erlauben"+ },"guest_checkout": {"help": "Store-weite Vorgabe dafür, ob Kunden ohne Konto zur Kasse gehen können. Vertriebskanäle können dies überschreiben.","label": "Gast-Checkout"@@ -1292,6 +1312,14 @@"preferred_weight_unit": {"label": "Gewichtseinheit"},+ "show_products_without_price": {+ "help": "Produkte listen, die in der Währung des Kunden keinen Preis haben.",+ "label": "Produkte ohne Preis anzeigen"+ },+ "stock_reservations_enabled": {+ "help": "Artikel während des Bezahlvorgangs reservieren, damit sie nicht doppelt verkauft werden.",+ "label": "Bestand während des Bezahlens reservieren"+ },"storefront_access": {"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.","label": "Storefront-Zugriff",@@ -1300,6 +1328,14 @@"prices_hidden": "Preise verborgen – Besucher müssen sich anmelden, um Preise zu sehen","public": "Öffentlich – alle können stöbern und Preise sehen"}+ },+ "track_inventory_levels": {+ "help": "Bestände zählen. Ausschalten, um jedes Produkt als immer verfügbar zu behandeln.",+ "label": "Lagerbestand verfolgen"+ },+ "track_price_history": {+ "help": "Frühere Preise speichern, damit der Shop den niedrigsten Preis der letzten 30 Tage anzeigen kann, wie es EU-Regeln verlangen.",+ "label": "Preisverlauf aufzeichnen"}},"store_credit": {@@ -2619,8 +2655,12 @@"store": {"default_package_description": "Der Karton, in dem Sie üblicherweise versenden. Carrier-Tarifanbieter addieren sein Gewicht zu jedem Paket und nutzen seine Abmessungen für Volumengewicht-Preise.","subtitle": "Allgemeine Konfiguration und shopweite Standardwerte.",+ "tab_addresses": "Adressen",+ "tab_catalog": "Katalog","tab_default_package": "Standardpaket","tab_general": "Allgemein",+ "tab_inventory": "Lagerbestand",+ "tab_payments": "Zahlungen","tab_standards": "Standards und Formate","tab_storefront_access": "Storefront-Zugriff","title": "Shop-Einstellungen"diff --git a/packages/dashboard/src/locales/en.json b/packages/dashboard/src/locales/en.jsonindex 11e71b8a8f..14c855ff96 100644--- a/packages/dashboard/src/locales/en.json+++ b/packages/dashboard/src/locales/en.json@@ -1237,11 +1237,31 @@}},"store": {+ "address_requires_phone": {+ "help": "Make a phone number mandatory on customer addresses.",+ "label": "Require phone number"+ },+ "auto_capture": {+ "help": "Take payment straight away instead of only reserving the amount. A payment method can override this.",+ "label": "Charge cards at checkout"+ },+ "auto_capture_on_dispatch": {+ "help": "Wait until goods actually go out before taking the money.",+ "label": "Charge on dispatch"+ },+ "company_field_enabled": {+ "help": "Show a company field on address forms during checkout.",+ "label": "Company field"+ },"customer_support_email": {"help": "Reply-to address shown to customers in storefront emails.","label": "Customer support email","placeholder": "[email protected]"},+ "disable_sku_validation": {+ "help": "Let more than one variant share the same SKU.",+ "label": "Allow duplicate SKUs"+ },"guest_checkout": {"help": "Store-wide default for whether shoppers can check out without an account. Channels can override this.","label": "Guest checkout"@@ -1292,6 +1312,14 @@"preferred_weight_unit": {"label": "Weight unit"},+ "show_products_without_price": {+ "help": "List products that have no price in the shopper’s currency.",+ "label": "Show products without a price"+ },+ "stock_reservations_enabled": {+ "help": "Reserve items while a shopper checks out so the same one cannot be sold twice.",+ "label": "Hold stock during checkout"+ },"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.","label": "Storefront access",@@ -1300,6 +1328,14 @@"prices_hidden": "Prices hidden — visitors must sign in to see prices","public": "Public — anyone can browse and see prices"}+ },+ "track_inventory_levels": {+ "help": "Count on-hand quantities. Turn off to treat every product as always available.",+ "label": "Track stock levels"+ },+ "track_price_history": {+ "help": "Keep past prices so the storefront can show the lowest price of the last 30 days, as EU rules require.",+ "label": "Record price history"}},"store_credit": {@@ -2619,8 +2655,12 @@"store": {"default_package_description": "The box you usually ship in. Carrier rate providers add its weight to every package and use its dimensions for dimensional-weight pricing.","subtitle": "General configuration and store-wide defaults.",+ "tab_addresses": "Addresses",+ "tab_catalog": "Catalog","tab_default_package": "Default package","tab_general": "General",+ "tab_inventory": "Inventory",+ "tab_payments": "Payments","tab_standards": "Standards and formats","tab_storefront_access": "Storefront access","title": "Store settings"diff --git a/packages/dashboard/src/locales/fr.json b/packages/dashboard/src/locales/fr.jsonindex f9814bb721..a2bb548b9c 100644--- a/packages/dashboard/src/locales/fr.json+++ b/packages/dashboard/src/locales/fr.json@@ -1237,11 +1237,31 @@}},"store": {+ "address_requires_phone": {+ "help": "Rendre le numéro de téléphone obligatoire dans les adresses des clients.",+ "label": "Numéro de téléphone obligatoire"+ },+ "auto_capture": {+ "help": "Encaisser immédiatement au lieu de simplement réserver le montant. Un moyen de paiement peut modifier ce réglage.",+ "label": "Débiter les cartes au paiement"+ },+ "auto_capture_on_dispatch": {+ "help": "Attendre l’expédition réelle des marchandises avant d’encaisser.",+ "label": "Débiter à l’expédition"+ },+ "company_field_enabled": {+ "help": "Afficher un champ société dans les formulaires d’adresse lors du paiement.",+ "label": "Champ société"+ },"customer_support_email": {"help": "Adresse de réponse affichée aux clients dans les e-mails de la boutique.","label": "E-mail du support client","placeholder": "[email protected]"},+ "disable_sku_validation": {+ "help": "Permettre à plusieurs déclinaisons de partager la même UGS.",+ "label": "Autoriser les UGS en double"+ },"guest_checkout": {"help": "Valeur par défaut à l'échelle de la boutique pour la possibilité de commander sans compte. Les canaux peuvent la remplacer.","label": "Commande invité"@@ -1292,6 +1312,14 @@"preferred_weight_unit": {"label": "Unité de poids"},+ "show_products_without_price": {+ "help": "Lister les produits sans prix dans la devise du client.",+ "label": "Afficher les produits sans prix"+ },+ "stock_reservations_enabled": {+ "help": "Réserver les articles pendant le paiement pour éviter de vendre deux fois le même.",+ "label": "Réserver le stock pendant le paiement"+ },"storefront_access": {"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.","label": "Accès à la vitrine",@@ -1300,6 +1328,14 @@"prices_hidden": "Prix masqués — les visiteurs doivent se connecter pour voir les prix","public": "Public — tout le monde peut parcourir et voir les prix"}+ },+ "track_inventory_levels": {+ "help": "Compter les quantités disponibles. Désactivez pour traiter chaque produit comme toujours disponible.",+ "label": "Suivre les niveaux de stock"+ },+ "track_price_history": {+ "help": "Conserver les anciens prix afin d’afficher le prix le plus bas des 30 derniers jours, comme l’exige la réglementation européenne.",+ "label": "Enregistrer l’historique des prix"}},"store_credit": {@@ -2619,8 +2655,12 @@"store": {"default_package_description": "Le carton habituel d'expédition. Les transporteurs ajoutent son poids à chaque colis et utilisent ses dimensions pour le poids volumétrique.","subtitle": "Configuration générale et valeurs par défaut à l'échelle de la boutique.",+ "tab_addresses": "Adresses",+ "tab_catalog": "Catalogue","tab_default_package": "Colis par défaut","tab_general": "Général",+ "tab_inventory": "Stock",+ "tab_payments": "Paiements","tab_standards": "Normes et formats","tab_storefront_access": "Accès à la vitrine","title": "Paramètres de la boutique"diff --git a/packages/dashboard/src/locales/pl.json b/packages/dashboard/src/locales/pl.jsonindex e26862db66..d108bc4630 100644--- a/packages/dashboard/src/locales/pl.json+++ b/packages/dashboard/src/locales/pl.json@@ -1251,11 +1251,31 @@}},"store": {+ "address_requires_phone": {+ "help": "Uczyń numer telefonu obowiązkowym w adresach klientów.",+ "label": "Wymagaj numeru telefonu"+ },+ "auto_capture": {+ "help": "Pobieraj płatność od razu, zamiast tylko rezerwować kwotę. Metoda płatności może to nadpisać.",+ "label": "Obciążaj karty przy zamówieniu"+ },+ "auto_capture_on_dispatch": {+ "help": "Pobieraj pieniądze dopiero wtedy, gdy towar faktycznie wyjeżdża.",+ "label": "Obciążaj przy wysyłce"+ },+ "company_field_enabled": {+ "help": "Pokaż pole firmy w formularzach adresowych podczas składania zamówienia.",+ "label": "Pole firmy"+ },"customer_support_email": {"help": "Adres zwrotny pokazywany klientom w wiadomościach ze sklepu.","label": "E-mail obsługi klienta","placeholder": "[email protected]"},+ "disable_sku_validation": {+ "help": "Pozwól, aby kilka wariantów miało ten sam SKU.",+ "label": "Zezwalaj na powtórzone SKU"+ },"guest_checkout": {"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ć.","label": "Zakupy jako gość"@@ -1306,6 +1326,14 @@"preferred_weight_unit": {"label": "Jednostka wagi"},+ "show_products_without_price": {+ "help": "Wyświetlaj produkty, które nie mają ceny w walucie klienta.",+ "label": "Pokazuj produkty bez ceny"+ },+ "stock_reservations_enabled": {+ "help": "Rezerwuj produkty na czas składania zamówienia, aby ten sam nie został sprzedany dwa razy.",+ "label": "Rezerwuj towar podczas zamawiania"+ },"storefront_access": {"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.","label": "Dostęp do sklepu",@@ -1314,6 +1342,14 @@"prices_hidden": "Ceny ukryte — odwiedzający muszą się zalogować, aby zobaczyć ceny","public": "Publiczny — każdy może przeglądać i widzieć ceny"}+ },+ "track_inventory_levels": {+ "help": "Licz dostępne ilości. Wyłącz, aby traktować każdy produkt jako zawsze dostępny.",+ "label": "Śledź stany magazynowe"+ },+ "track_price_history": {+ "help": "Przechowuj poprzednie ceny, aby sklep mógł pokazać najniższą cenę z ostatnich 30 dni, zgodnie z przepisami UE.",+ "label": "Zapisuj historię cen"}},"store_credit": {@@ -2657,8 +2693,12 @@"store": {"default_package_description": "Karton, w którym zwykle wysyłasz. Dostawcy stawek przewoźników dodają jego wagę do każdej paczki i używają wymiarów do wyceny wagi wymiarowej.","subtitle": "Ogólna konfiguracja i domyślne ustawienia dla całego sklepu.",+ "tab_addresses": "Adresy",+ "tab_catalog": "Katalog","tab_default_package": "Domyślna paczka","tab_general": "Ogólne",+ "tab_inventory": "Stan magazynowy",+ "tab_payments": "Płatności","tab_standards": "Standardy i formaty","tab_storefront_access": "Dostęp do sklepu","title": "Ustawienia sklepu"diff --git a/packages/dashboard/src/locales/zh-CN.json b/packages/dashboard/src/locales/zh-CN.jsonindex 6f90e1922b..7c41708296 100644--- a/packages/dashboard/src/locales/zh-CN.json+++ b/packages/dashboard/src/locales/zh-CN.json@@ -1234,11 +1234,31 @@}},"store": {+ "address_requires_phone": {+ "help": "将电话号码设为客户地址的必填项。",+ "label": "要求填写电话号码"+ },+ "auto_capture": {+ "help": "立即收取款项,而不是仅预授权。支付方式可覆盖此设置。",+ "label": "结账时扣款"+ },+ "auto_capture_on_dispatch": {+ "help": "等到商品实际发出后再收款。",+ "label": "发货时扣款"+ },+ "company_field_enabled": {+ "help": "在结账时的地址表单中显示公司字段。",+ "label": "公司字段"+ },"customer_support_email": {"help": "在店面邮件中向客户显示的回复(Reply-to)地址。","label": "客户支持邮箱","placeholder": "[email protected]"},+ "disable_sku_validation": {+ "help": "允许多个变体使用相同的 SKU。",+ "label": "允许重复 SKU"+ },"guest_checkout": {"help": "店铺范围内的默认设置,控制顾客是否可以无需账户即可结账。渠道可以覆盖此设置。","label": "访客结账"@@ -1289,6 +1309,14 @@"preferred_weight_unit": {"label": "重量单位"},+ "show_products_without_price": {+ "help": "列出在顾客币种下没有价格的商品。",+ "label": "显示无价格的商品"+ },+ "stock_reservations_enabled": {+ "help": "顾客结账时预留商品,避免同一件商品被重复售出。",+ "label": "结账期间锁定库存"+ },"storefront_access": {"help": "店铺范围内的默认设置,控制匿名访客可以看到的内容。渠道可以覆盖此设置。隐藏价格时,访客须登录后才能结账。","label": "店铺访问权限",@@ -1297,6 +1325,14 @@"prices_hidden": "隐藏价格 — 访客须登录后才能查看价格","public": "公开 — 任何人都可以浏览并查看价格"}+ },+ "track_inventory_levels": {+ "help": "统计现有库存。关闭后,所有商品都视为始终有货。",+ "label": "跟踪库存数量"+ },+ "track_price_history": {+ "help": "保留历史价格,以便店铺按欧盟规定显示最近 30 天的最低价。",+ "label": "记录价格历史"}},"store_credit": {@@ -2615,8 +2651,12 @@"store": {"default_package_description": "常用的发货纸箱。承运商费率提供方会将其重量加到每个包裹上,并使用其尺寸计算体积重量。","subtitle": "通用配置与店铺级默认设置。",+ "tab_addresses": "地址",+ "tab_catalog": "商品目录","tab_default_package": "默认包裹","tab_general": "通用",+ "tab_inventory": "库存",+ "tab_payments": "支付","tab_standards": "标准与格式","tab_storefront_access": "店铺访问权限","title": "店铺设置"diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsxindex 46f3e639b8..94b7f6768c 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx@@ -94,6 +94,15 @@ function storeToFormValues(store: Store): StoreSettingsFormValues {preferred_storefront_access:(store.preferred_storefront_access as (typeof STOREFRONT_ACCESS_LEVELS)[number]) ?? 'public',preferred_guest_checkout: store.preferred_guest_checkout ?? true,+ preferred_company_field_enabled: store.preferred_company_field_enabled ?? false,+ preferred_address_requires_phone: store.preferred_address_requires_phone ?? false,+ preferred_auto_capture: store.preferred_auto_capture ?? true,+ preferred_auto_capture_on_dispatch: store.preferred_auto_capture_on_dispatch ?? false,+ preferred_track_inventory_levels: store.preferred_track_inventory_levels ?? true,+ preferred_stock_reservations_enabled: store.preferred_stock_reservations_enabled ?? true,+ preferred_track_price_history: store.preferred_track_price_history ?? true,+ preferred_show_products_without_price: store.preferred_show_products_without_price ?? false,+ preferred_disable_sku_validation: store.preferred_disable_sku_validation ?? false,}}@@ -178,6 +187,15 @@ function StoreSettingsForm({ store }: { store: Store }) {preferred_default_package_height: values.preferred_default_package_height,preferred_storefront_access: values.preferred_storefront_access,preferred_guest_checkout: values.preferred_guest_checkout,+ preferred_company_field_enabled: values.preferred_company_field_enabled,+ preferred_address_requires_phone: values.preferred_address_requires_phone,+ preferred_auto_capture: values.preferred_auto_capture,+ preferred_auto_capture_on_dispatch: values.preferred_auto_capture_on_dispatch,+ preferred_track_inventory_levels: values.preferred_track_inventory_levels,+ preferred_stock_reservations_enabled: values.preferred_stock_reservations_enabled,+ preferred_track_price_history: values.preferred_track_price_history,+ preferred_show_products_without_price: values.preferred_show_products_without_price,+ preferred_disable_sku_validation: values.preferred_disable_sku_validation,...extensionValues,})toast.success(t('admin.messages.store_settings_updated'))@@ -436,6 +454,105 @@ function StoreSettingsForm({ store }: { store: Store }) {</FieldGroup></CardContent></Card>+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.pages.settings.store.tab_addresses')}</CardTitle>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <SwitchField+ id="store-company-field-enabled"+ label={t('admin.fields.store.company_field_enabled.label')}+ help={t('admin.fields.store.company_field_enabled.help')}+ name="preferred_company_field_enabled"+ control={form.control}+ />+ <SwitchField+ id="store-address-requires-phone"+ label={t('admin.fields.store.address_requires_phone.label')}+ help={t('admin.fields.store.address_requires_phone.help')}+ name="preferred_address_requires_phone"+ control={form.control}+ />+ </FieldGroup>+ </CardContent>+ </Card>+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.pages.settings.store.tab_payments')}</CardTitle>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <SwitchField+ id="store-auto-capture"+ label={t('admin.fields.store.auto_capture.label')}+ help={t('admin.fields.store.auto_capture.help')}+ name="preferred_auto_capture"+ control={form.control}+ />+ <SwitchField+ id="store-auto-capture-on-dispatch"+ label={t('admin.fields.store.auto_capture_on_dispatch.label')}+ help={t('admin.fields.store.auto_capture_on_dispatch.help')}+ name="preferred_auto_capture_on_dispatch"+ control={form.control}+ />+ </FieldGroup>+ </CardContent>+ </Card>+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.pages.settings.store.tab_inventory')}</CardTitle>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <SwitchField+ id="store-track-inventory-levels"+ label={t('admin.fields.store.track_inventory_levels.label')}+ help={t('admin.fields.store.track_inventory_levels.help')}+ name="preferred_track_inventory_levels"+ control={form.control}+ />+ <SwitchField+ id="store-stock-reservations-enabled"+ label={t('admin.fields.store.stock_reservations_enabled.label')}+ help={t('admin.fields.store.stock_reservations_enabled.help')}+ name="preferred_stock_reservations_enabled"+ control={form.control}+ />+ </FieldGroup>+ </CardContent>+ </Card>+ <Card>+ <CardHeader>+ <CardTitle>{t('admin.pages.settings.store.tab_catalog')}</CardTitle>+ </CardHeader>+ <CardContent>+ <FieldGroup>+ <SwitchField+ id="store-show-products-without-price"+ label={t('admin.fields.store.show_products_without_price.label')}+ help={t('admin.fields.store.show_products_without_price.help')}+ name="preferred_show_products_without_price"+ control={form.control}+ />+ <SwitchField+ id="store-track-price-history"+ label={t('admin.fields.store.track_price_history.label')}+ help={t('admin.fields.store.track_price_history.help')}+ name="preferred_track_price_history"+ control={form.control}+ />+ <SwitchField+ id="store-disable-sku-validation"+ label={t('admin.fields.store.disable_sku_validation.label')}+ help={t('admin.fields.store.disable_sku_validation.help')}+ name="preferred_disable_sku_validation"+ control={form.control}+ />+ </FieldGroup>+ </CardContent>+ </Card><Slot name="store.form_main" context={{ store }} /></>}@@ -490,3 +607,39 @@ function SelectField<TValues extends FieldValues>({/>)}++interface SwitchFieldProps<TValues extends FieldValues> {+ id: string+ label: string+ help?: string+ name: FieldPath<TValues>+ control: Control<TValues>+}++function SwitchField<TValues extends FieldValues>({+ id,+ label,+ help,+ name,+ control,+}: SwitchFieldProps<TValues>) {+ return (+ <Field>+ <div className="flex items-start justify-between gap-4">+ <div className="flex flex-col">+ <FieldLabel htmlFor={id} className="cursor-pointer">+ {label}+ </FieldLabel>+ {help && <span className="text-xs text-muted-foreground">{help}</span>}+ </div>+ <Controller+ name={name}+ control={control}+ render={({ field }) => (+ <Switch id={id} checked={!!field.value} onCheckedChange={field.onChange} />+ )}+ />+ </div>+ </Field>+ )+}diff --git a/packages/dashboard/src/schemas/store.ts b/packages/dashboard/src/schemas/store.tsindex f42876d594..d208b7f182 100644--- a/packages/dashboard/src/schemas/store.ts+++ b/packages/dashboard/src/schemas/store.ts@@ -29,6 +29,15 @@ export const storeSettingsFormSchema = z.object({preferred_default_package_height: z.coerce.number().min(0),preferred_storefront_access: z.enum(STOREFRONT_ACCESS_LEVELS),preferred_guest_checkout: z.boolean(),+ preferred_company_field_enabled: z.boolean(),+ preferred_address_requires_phone: z.boolean(),+ preferred_auto_capture: z.boolean(),+ preferred_auto_capture_on_dispatch: z.boolean(),+ preferred_track_inventory_levels: z.boolean(),+ preferred_stock_reservations_enabled: z.boolean(),+ preferred_track_price_history: z.boolean(),+ preferred_show_products_without_price: z.boolean(),+ preferred_disable_sku_validation: z.boolean(),})export type StoreSettingsFormValues = z.infer<typeof storeSettingsFormSchema>diff --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 6e791a88ea..0d745a7e8a 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@@ -55,6 +55,15 @@ module Spree:preferred_storefront_access,:preferred_storefront_url,:preferred_guest_checkout,+ :preferred_company_field_enabled,+ :preferred_address_requires_phone,+ :preferred_auto_capture,+ :preferred_auto_capture_on_dispatch,+ :preferred_track_inventory_levels,+ :preferred_stock_reservations_enabled,+ :preferred_track_price_history,+ :preferred_show_products_without_price,+ :preferred_disable_sku_validation,:preferred_order_routing_strategy,:mail_from_address,:customer_support_email,diff --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 1cd3316a8c..202810ecdd 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@@ -25,6 +25,15 @@ module Spreepreferred_unit_system: :string,preferred_storefront_access: :string,preferred_guest_checkout: :boolean,+ preferred_company_field_enabled: :boolean,+ preferred_address_requires_phone: :boolean,+ preferred_auto_capture: :boolean,+ preferred_auto_capture_on_dispatch: :boolean,+ preferred_track_inventory_levels: :boolean,+ preferred_stock_reservations_enabled: :boolean,+ preferred_track_price_history: :boolean,+ preferred_show_products_without_price: :boolean,+ preferred_disable_sku_validation: :boolean,preferred_order_routing_strategy: :string,metadata: 'Record<string, unknown>'@@ -48,6 +57,15 @@ module Spree:preferred_unit_system,:preferred_storefront_access,:preferred_guest_checkout,+ :preferred_company_field_enabled,+ :preferred_address_requires_phone,+ :preferred_auto_capture,+ :preferred_auto_capture_on_dispatch,+ :preferred_track_inventory_levels,+ :preferred_stock_reservations_enabled,+ :preferred_track_price_history,+ :preferred_show_products_without_price,+ :preferred_disable_sku_validation,:preferred_order_routing_strategy,created_at: :iso8601, updated_at: :iso8601diff --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 81afc82563..0cbfba5ee5 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@@ -241,6 +241,37 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller doendend+ context 'with address params' do+ let(:params) { { preferred_company_field_enabled: true, preferred_address_requires_phone: true } }++ it 'updates the address settings' do+ subject+ expect(response).to have_http_status(:ok)+ store.reload+ expect(store.preferred_company_field_enabled).to eq(true)+ expect(store.preferred_address_requires_phone).to eq(true)+ end+ end++ context 'with commerce behavior params' do+ let(:params) do+ {+ preferred_auto_capture: false,+ preferred_track_inventory_levels: false,+ preferred_show_products_without_price: true+ }+ end++ it 'updates the store-scoped commerce settings' do+ subject+ expect(response).to have_http_status(:ok)+ store.reload+ expect(store.preferred_auto_capture).to eq(false)+ expect(store.preferred_track_inventory_levels).to eq(false)+ expect(store.preferred_show_products_without_price).to eq(true)+ end+ end+context 'with an invalid storefront_access value' dolet(:params) { { preferred_storefront_access: 'nonsense' } }diff --git a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rbindex a40e7c61ed..fcddc65e00 100644--- a/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/carts_controller_spec.rb@@ -766,8 +766,7 @@ RSpec.describe Spree::Api::V3::Store::CartsController, type: :controller doendcontext 'when stock_reservations_enabled is false' do- before { Spree::Config[:stock_reservations_enabled] = false }- after { Spree::Config[:stock_reservations_enabled] = true }+ before { stub_store_preferences(stock_reservations_enabled: false) }it 'does not create reservations' doorder.update!(email: '[email protected]')diff --git a/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rbindex 9e706e59a5..8b1b2a7813 100644--- a/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb+++ b/spree/api/spec/controllers/spree/api/v3/store/products_controller_spec.rb@@ -116,7 +116,7 @@ RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller dobefore doallow(store).to receive(:supported_currencies_list).and_return([Money::Currency.find('USD'), Money::Currency.find('EUR')])- Spree::Config.show_products_without_price = false+ stub_store_preferences(show_products_without_price: false)endit 'only returns products with prices in the current currency' dodiff --git a/spree/core/app/models/concerns/spree/product_scopes.rb b/spree/core/app/models/concerns/spree/product_scopes.rbindex 7def3f7614..b09f764487 100644--- a/spree/core/app/models/concerns/spree/product_scopes.rb+++ b/spree/core/app/models/concerns/spree/product_scopes.rb@@ -264,8 +264,11 @@ module Spreeendend- unless Spree::Config.show_products_without_price- currency ||= Spree::Store.default.default_currency+ # Class-level scope, so there is no product to ask — the ambient store+ # decides, and its currency is the fallback when none was passed.+ store = Spree::Current.store+ unless Spree::StorePreferences.read(store, :show_products_without_price)+ currency ||= store&.default_currencyscope = scope.with_currency(currency)enddiff --git a/spree/core/app/models/concerns/spree/purchase/payment_processing.rb b/spree/core/app/models/concerns/spree/purchase/payment_processing.rbindex 0a7ed75aa3..1c3f220c29 100644--- a/spree/core/app/models/concerns/spree/purchase/payment_processing.rb+++ b/spree/core/app/models/concerns/spree/purchase/payment_processing.rb@@ -2,9 +2,9 @@ module Spreemodule Purchase# Payment processing shared by Spree::Cart and Spree::Order.module PaymentProcessing- # Processes any pending payments. Returns true when every pending- # payment processed successfully; a GatewayError converts to the- # allow_checkout_on_gateway_error preference.+ # Processes any pending payments, recording a gateway failure on+ # +errors+. The completion workflows check whether payments actually+ # cover the total rather than trusting the return value.def process_payments!with_lock { process_payments_with(:process!) }end@@ -64,8 +64,8 @@ module Spreepayment.public_send(method)endrescue Spree::Core::GatewayError => e- result = !!Spree::Config[:allow_checkout_on_gateway_error]- errors.add(:base, e.message) && (return result)+ errors.add(:base, e.message)+ falseendendenddiff --git a/spree/core/app/models/concerns/spree/store_preferences.rb b/spree/core/app/models/concerns/spree/store_preferences.rbnew file mode 100644index 0000000000..5a0a4053e1--- /dev/null+++ b/spree/core/app/models/concerns/spree/store_preferences.rb@@ -0,0 +1,49 @@+module Spree+ # Reads a store-scoped commerce setting from a record that is not itself a+ # store.+ #+ # Spree 6 moved settings that shape how a shop sells from +Spree::Config++ # onto +Spree::Store+, and core reads the store with no fallback to the old+ # global — two sources of truth are what let them drift apart. Including+ # models say how they reach a store by defining +preference_store+; when they+ # can't reach one (a product with no store, a class-level scope, a console+ # session), the read falls back to the preference's own declared default+ # rather than raising.+ module StorePreferences+ extend ActiveSupport::Concern++ # @param name [Symbol] preference declared on Spree::Store+ # @return [Object] the store's value, or the preference default+ def store_preference(name)+ Spree::StorePreferences.read(preference_store, name)+ end++ # The store whose settings apply to this record. Override in models whose+ # route to a store isn't a +store+ association.+ # @return [Spree::Store, nil]+ def preference_store+ respond_to?(:store) ? store : nil+ end++ class << self+ # @param store [Spree::Store, nil]+ # @param name [Symbol] preference declared on Spree::Store+ # @return [Object] the store's value, or the preference default+ def read(store, name)+ return store.get_preference(name) if store++ # `preference_default` is defined per instance, not on the class, and+ # an unsaved store is enough to read a declared default.+ Spree::Store.new.preference_default(name)+ end++ # Reads a setting outside any record — class-level scopes and services+ # that have no owning row to ask. Resolves the ambient store.+ # @param name [Symbol] preference declared on Spree::Store+ # @return [Object] the current store's value, or the preference default+ def current(name)+ read(Spree::Current.store, name)+ end+ end+ end+enddiff --git a/spree/core/app/models/spree/address.rb b/spree/core/app/models/spree/address.rbindex a8bfe973ea..a91a99f7c7 100644--- a/spree/core/app/models/spree/address.rb+++ b/spree/core/app/models/spree/address.rb@@ -197,7 +197,7 @@ module Spreedef require_phone?# We want to collect phone number for quick checkout but not to validate it# as it's not available before payment by browser.- !quick_checkout && Spree::Config[:address_requires_phone]+ !quick_checkout && store_preference(:address_requires_phone, false)enddef require_zipcode?@@ -217,7 +217,7 @@ module Spreeenddef show_company_address_field?- Spree::Store.current.prefers_company_field_enabled?+ store_preference(:company_field_enabled, false)enddef editable?@@ -255,6 +255,17 @@ module Spreeprivate+ # Addresses carry no store association, so store-scoped settings resolve+ # through the ambient store. Outside a request (console, seeds, a job that+ # forgets to set the store) there may be none, so callers pass the+ # preference default explicitly.+ def store_preference(name, fallback)+ store = Spree::Current.store+ return fallback if store.nil?++ store.get_preference(name)+ end+def should_geocode?Spree::Config[:geocode_addresses] && (saved_changes.key?(:address1) || saved_changes.key?(:city) || saved_changes.key?(:state_id) || saved_changes.key?(:country_id)@@ -310,9 +321,9 @@ module Spreeenddef state_validate- # Skip state validation without country (also required)- # or when disabled by preference- return if country.blank? || !Spree::Config[:address_requires_state]+ # Skip state validation without country (also required).+ # Whether a state is required is the country's call.+ return if country.blank?return unless country.states_required# ensure associated state belongs to countrydiff --git a/spree/core/app/models/spree/fulfillment.rb b/spree/core/app/models/spree/fulfillment.rbindex b8bd564718..421d08bda3 100644--- a/spree/core/app/models/spree/fulfillment.rb+++ b/spree/core/app/models/spree/fulfillment.rb@@ -8,6 +8,7 @@ module Spreeinclude Spree::NumberIdentifierinclude Spree::HasCustomFieldsinclude Spree::Metadata+ include Spree::StorePreferencesif defined?(Spree::Security::Shipments)include Spree::Security::Shipmentsend@@ -87,6 +88,13 @@ module Spreeorder || cartend+ # `store` is delegated to the owner, which raises when a fulfillment has+ # neither an order nor a cart yet.+ # @return [Spree::Store, nil]+ def preference_store+ owner&.store+ end+# Bridge for legacy callers assigning +current_order+ (now a Spree::Cart)# to the order association — routes carts to the cart FK instead.def order=(record)@@ -697,7 +705,7 @@ module Spree# type-specific mechanics in the provider wave.def after_fulfillfulfillment_items.each(&:ship!)- process_order_payments if Spree::Config[:auto_capture_on_dispatch]+ process_order_payments if store_preference(:auto_capture_on_dispatch)touch :fulfilled_atrun_provider_create_fulfillmentupdate_order_fulfillment_statusdiff --git a/spree/core/app/models/spree/payment_method.rb b/spree/core/app/models/spree/payment_method.rbindex 10b7d5ad0c..f9a57c3f9d 100644--- a/spree/core/app/models/spree/payment_method.rb+++ b/spree/core/app/models/spree/payment_method.rb@@ -6,6 +6,7 @@ module Spreeacts_as_listinclude Spree::SingleStoreResource+ include Spree::StorePreferencesinclude Spree::HasCustomFieldsinclude Spree::Metadatainclude Spree::DisplayOn@@ -179,7 +180,7 @@ module Spreeenddef auto_capture?- auto_capture.nil? ? Spree::Config[:auto_capture] : auto_capture+ auto_capture.nil? ? store_preference(:auto_capture) : auto_captureenddef supports?(_source)diff --git a/spree/core/app/models/spree/price.rb b/spree/core/app/models/spree/price.rbindex ea37cea693..5505bf5d02 100644--- a/spree/core/app/models/spree/price.rb+++ b/spree/core/app/models/spree/price.rb@@ -3,6 +3,7 @@ module Spreehas_prefix_id :priceinclude Spree::VatPriceCalculation+ include Spree::StorePreferencespublishes_lifecycle_events@@ -180,13 +181,19 @@ module Spreeprice_histories.where(recorded_at: 30.days.ago..).order(:amount).firstend+ # Prices carry no store of their own; the variant's product owns it.+ # @return [Spree::Store, nil]+ def preference_store+ variant&.product&.store+ end+privatedef should_record_price_history?price_list_id.nil? &&amount.present? &&saved_change_to_amount? &&- Spree::Config[:track_price_history]+ store_preference(:track_price_history)enddef record_price_historydiff --git a/spree/core/app/models/spree/product.rb b/spree/core/app/models/spree/product.rbindex b9b3eb6075..6c199a3ed8 100644--- a/spree/core/app/models/spree/product.rb+++ b/spree/core/app/models/spree/product.rb@@ -32,6 +32,7 @@ module Spreeinclude Spree::Product::Slugsinclude Spree::Product::Channelsinclude Spree::SearchIndexable+ include Spree::StorePreferencesif defined?(Spree::VendorConcern)include Spree::VendorConcernend@@ -884,7 +885,7 @@ module Spreeenddef any_variants_not_track_inventory?- return true unless Spree::Config.track_inventory_levels+ return true unless store_preference(:track_inventory_levels)if variants.loaded?variants.any? { |v| !v.track_inventory? }diff --git a/spree/core/app/models/spree/stock/quantifier.rb b/spree/core/app/models/spree/stock/quantifier.rbindex c06a9d5c6c..92dada0513 100644--- a/spree/core/app/models/spree/stock/quantifier.rb+++ b/spree/core/app/models/spree/stock/quantifier.rb@@ -66,7 +66,7 @@ module Spree# @return [Integer]def reserved_quantityreturn @reserved_quantity if defined?(@reserved_quantity)- return @reserved_quantity = 0 unless Spree::Config[:stock_reservations_enabled]+ return @reserved_quantity = 0 unless reservations_enabled?return @reserved_quantity = 0 if stock_items.blank?excluded_owner_key = excluded_order.is_a?(Spree::Cart) ? :cart_id : :order_id@@ -131,6 +131,14 @@ module Spreeprivate+ # The stock location owns a store directly; otherwise the variant's+ # product does. Both can be absent, in which case the declared default+ # applies.+ def reservations_enabled?+ store = stock_location&.store || variant&.product&.store+ Spree::StorePreferences.read(store, :stock_reservations_enabled)+ end+def association_loaded?variant.association(:stock_items).loaded?enddiff --git a/spree/core/app/models/spree/stock_reservation.rb b/spree/core/app/models/spree/stock_reservation.rbindex 8de5ef3fb3..c2c3f85536 100644--- a/spree/core/app/models/spree/stock_reservation.rb+++ b/spree/core/app/models/spree/stock_reservation.rb@@ -44,12 +44,10 @@ module Spreeexpires_at > Time.currentend- # Resolves the reservation TTL: per-Store preference if set, otherwise- # the global Spree::Config[:default_stock_reservation_ttl_minutes]. Falls- # back to 10 minutes if both are unset (e.g. early-boot / fixture state).+ # Resolves the reservation TTL from the store, falling back to 10 minutes+ # when there is no store to ask (early-boot / fixture state).def self.ttl_for(order)minutes = order&.store&.preferred_stock_reservation_ttl_minutes- minutes = Spree::Config[:default_stock_reservation_ttl_minutes] if minutes.blank?minutes.to_i.then { |m| m > 0 ? m : 10 }.minutesenddiff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rbindex 42d06e3066..1100dbe6da 100644--- a/spree/core/app/models/spree/store.rb+++ b/spree/core/app/models/spree/store.rb@@ -66,8 +66,21 @@ module Spreepreference :storefront_url, :stringpreference :special_instructions_enabled, :boolean, default: falsepreference :stock_reservation_ttl_minutes, :integer, default: 10+ # Store-wide default for charging cards at checkout rather than only+ # authorizing them. A payment method's own auto_capture column wins when set.+ preference :auto_capture, :boolean, default: true+ preference :auto_capture_on_dispatch, :boolean, default: false+ preference :stock_reservations_enabled, :boolean, default: true+ # Catalog preferences+ preference :track_inventory_levels, :boolean, default: true+ preference :show_products_without_price, :boolean, default: false+ preference :disable_sku_validation, :boolean, default: false+ # Records price changes so the storefront can show the lowest price of the+ # last 30 days, as the EU Omnibus Directive requires.+ preference :track_price_history, :boolean, default: true# Address preferencespreference :company_field_enabled, :boolean, default: false+ preference :address_requires_phone, :boolean, default: false# digital assets preferencespreference :limit_digital_download_count, :boolean, default: truepreference :limit_digital_download_days, :boolean, default: truediff --git a/spree/core/app/models/spree/variant.rb b/spree/core/app/models/spree/variant.rbindex d9c5aea124..27ba729620 100644--- a/spree/core/app/models/spree/variant.rb+++ b/spree/core/app/models/spree/variant.rb@@ -9,6 +9,7 @@ module Spreeinclude Spree::HasCustomFieldsinclude Spree::Metadatainclude Spree::Searchable+ include Spree::StorePreferencespublishes_lifecycle_events@@ -643,9 +644,15 @@ module Spreeend# Shortcut method to determine if inventory tracking is enabled for this variant- # This considers both variant tracking flag and site-wide inventory tracking settings+ # This considers both the variant tracking flag and the store's settingdef should_track_inventory?- track_inventory? && Spree::Config.track_inventory_levels+ track_inventory? && store_preference(:track_inventory_levels)+ end++ # Variants carry no store of their own; the product owns it.+ # @return [Spree::Store, nil]+ def preference_store+ product&.storeenddef volume@@ -730,7 +737,7 @@ module Spreeenddef disable_sku_validation?- Spree::Config[:disable_sku_validation]+ store_preference(:disable_sku_validation)enddef clear_line_items_cachediff --git a/spree/core/app/services/spree/stock_reservations/extend.rb b/spree/core/app/services/spree/stock_reservations/extend.rbindex e3eaae1ddd..0e1f4d6667 100644--- a/spree/core/app/services/spree/stock_reservations/extend.rb+++ b/spree/core/app/services/spree/stock_reservations/extend.rb@@ -8,7 +8,7 @@ module SpreeSpree::Deprecation.warn('Calling Spree::StockReservations::Extend with order: is deprecated and will be removed in Spree 6.1. Pass cart: instead.')cart ||= orderend- return success(cart) unless Spree::Config[:stock_reservations_enabled]+ return success(cart) unless Spree::StorePreferences.read(cart&.store, :stock_reservations_enabled)expires_at = Time.current + Spree::StockReservation.ttl_for(cart)diff --git a/spree/core/app/services/spree/stock_reservations/reserve.rb b/spree/core/app/services/spree/stock_reservations/reserve.rbindex 5f24c128c9..4489c15845 100644--- a/spree/core/app/services/spree/stock_reservations/reserve.rb+++ b/spree/core/app/services/spree/stock_reservations/reserve.rb@@ -8,7 +8,7 @@ module SpreeSpree::Deprecation.warn('Calling Spree::StockReservations::Reserve with order: is deprecated and will be removed in Spree 6.1. Pass cart: instead.')cart ||= orderend- return success(cart) unless Spree::Config[:stock_reservations_enabled]+ return success(cart) unless Spree::StorePreferences.read(cart&.store, :stock_reservations_enabled)expires_at = Time.current + Spree::StockReservation.ttl_for(cart)diff --git a/spree/core/app/workflows/spree/fulfillments/fulfill.rb b/spree/core/app/workflows/spree/fulfillments/fulfill.rbindex 93e3f8af71..c048709c76 100644--- a/spree/core/app/workflows/spree/fulfillments/fulfill.rb+++ b/spree/core/app/workflows/spree/fulfillments/fulfill.rb@@ -131,7 +131,7 @@ module Spreefailure(@source, Spree.t('fulfillments.errors.backordered_units'))end- return if order.paid? || Spree::Config[:auto_capture_on_dispatch]+ return if order.paid? || @source.store_preference(:auto_capture_on_dispatch)failure(@source, Spree.t('fulfillments.errors.order_not_paid'))end@@ -226,7 +226,7 @@ module Spree# Dispatch is the trigger for taking the money when the merchant has# chosen to charge on dispatch rather than at checkout.def capture_payment_if_configured- return unless Spree::Config[:auto_capture_on_dispatch]+ return unless @fulfillment.store_preference(:auto_capture_on_dispatch)@fulfillment.process_order_paymentsenddiff --git a/spree/core/lib/spree/core/configuration.rb b/spree/core/lib/spree/core/configuration.rbindex fc9ad6ac39..6640a2f70c 100644--- a/spree/core/lib/spree/core/configuration.rb+++ b/spree/core/lib/spree/core/configuration.rb@@ -23,8 +23,8 @@ module Spreemodule Coreclass Configuration < Preferences::RuntimeConfiguration# Alphabetized to more easily lookup particular preferences- preference :address_requires_state, :boolean, default: true, deprecated: true # should state/state_name be required- preference :address_requires_phone, :boolean, default: false # Determines whether we require phone in address+ preference :address_requires_state, :boolean, default: true, deprecated: 'State requirements now come from the address country - see Spree::Country#states_required'+ preference :address_requires_phone, :boolean, default: false, deprecated: 'Use the address_requires_phone preference in the Spree::Store model'# Origin where the admin SPA is hosted (e.g. `https://admin.shop.com`).# Used by admin mailers; falls back to `http://localhost:5173` in dev# and the store's storefront URL otherwise. Set this in production.@@ -33,22 +33,22 @@ module Spree# Where the SSO callback returns the browser after an identity provider# redirect. Distinct from `admin_url`, which points at the legacy admin.preference :dashboard_url, :string, default: nil- preference :allow_checkout_on_gateway_error, :boolean, default: false+ preference :allow_checkout_on_gateway_error, :boolean, default: false, deprecated: 'Nothing reads this in Spree 6 — completion checks whether payments cover the total, so a failed gateway call never completes an order'preference :allow_empty_price_amount, :boolean, default: falsepreference :allow_guest_checkout, :boolean, default: true, deprecated: true # this is only used in the rails frontend, and is not implemented in API- preference :alternative_shipping_phone, :boolean, default: false # Request extra phone for ship addr+ preference :alternative_shipping_phone, :boolean, default: false, deprecated: 'Nothing reads this in Spree 6'preference :always_include_confirm_step, :boolean, default: false # Ensures confirmation step is always in checkout_progress bar, but does not force a confirm step if your payment methods do not support it.preference :always_put_site_name_in_title, :boolean, deprecated: truepreference :always_use_translations, :boolean, default: false- preference :auto_capture, :boolean, default: true # automatically capture the credit card (as opposed to just authorize and capture later)- preference :auto_capture_on_dispatch, :boolean, default: false # Captures payment for each shipment in Shipment#after_ship callback, and makes Shipment.ready when payment authorized.+ preference :auto_capture, :boolean, default: true, deprecated: 'Set it on the store instead' # automatically capture the credit card (as opposed to just authorize and capture later)+ preference :auto_capture_on_dispatch, :boolean, default: false, deprecated: 'Set it on the store instead' # Captures payment on dispatch rather than at checkout.preference :binary_inventory_cache, :boolean, default: false, deprecated: true # only invalidate product cache when a stock item changes whether it is in_stockpreference :checkout_zone, :string, default: nil, deprecated: true # replace with the name of a zone if you would like to limit the countriespreference :company, :boolean, default: false, deprecated: 'Use the company_field_enabled preference in the Spree::Store model' # Request company field for billing and shipping addrpreference :currency, :string, default: 'USD', deprecated: truepreference :credit_to_new_allocation, :boolean, default: falsepreference :disable_migration_check, :boolean, default: false # when turned on disables the startup warning about missing engine migrations- preference :disable_sku_validation, :boolean, default: false # when turned off disables the built-in SKU uniqueness validation+ preference :disable_sku_validation, :boolean, default: false, deprecated: 'Set it on the store instead' # when turned on disables the built-in SKU uniqueness validationpreference :disable_store_presence_validation, :boolean, default: false, deprecated: true # when turned off disables Store presence validation for Products and Payment Methodspreference :events_log_enabled, :boolean, default: true # Log all Spree events to Rails loggerpreference :expedited_exchanges, :boolean, default: false, deprecated: 'Exchanges are their own record in Spree 6 — see Spree::Exchange and the Exchanges::Fulfill workflow'@@ -91,12 +91,12 @@ module Spreepreference :mailer_logo, :string, deprecated: truepreference :max_level_in_taxons_menu, :integer, deprecated: truepreference :non_expiring_credit_types, :array, default: []- preference :products_per_page, :integer, default: 12+ preference :products_per_page, :integer, default: 12, deprecated: 'Nothing reads this in Spree 6 — pass per_page to the API instead'preference :restock_inventory, :boolean, default: true, deprecated: 'Restocking is decided per line item by Spree::ReturnLineItem#resellable'preference :return_eligibility_number_of_days, :integer, default: 365, deprecated: 'Use the return_window_days preference on Spree::Market, or a returns.create.validate hook'- preference :reserve_stock_on, :string, default: 'checkout' # 'checkout' (default) or 'cart' — landing in 6.0 alongside Cart/Order split- preference :stock_reservations_enabled, :boolean, default: true # Hold stock during checkout to prevent overselling- preference :default_stock_reservation_ttl_minutes, :integer, default: 10 # Fallback TTL when a Store doesn't override+ preference :reserve_stock_on, :string, default: 'checkout', deprecated: 'Nothing reads this in Spree 6 — see the stock_reservations_enabled preference on the store'+ preference :stock_reservations_enabled, :boolean, default: true, deprecated: 'Set it on the store instead' # Hold stock during checkout to prevent overselling+ preference :default_stock_reservation_ttl_minutes, :integer, default: 10, deprecated: 'Use the stock_reservation_ttl_minutes preference on the store'# Tiered cart-expiry reaper (docs/plans/6.0-cart-order-split.md Decision 5)preference :guest_cart_expiry_days, :integer, default: 30preference :customer_cart_expiry_days, :integer, default: 90@@ -104,20 +104,20 @@ module Spreepreference :send_core_emails, :boolean, default: true, deprecated: true # Default mail headers settingspreference :shipping_instructions, :boolean, deprecated: truepreference :show_only_complete_orders_by_default, :boolean, deprecated: true- preference :show_variant_full_price, :boolean, default: false # Displays variant full price or difference with product price. Default false to be compatible with older behavior- preference :show_products_without_price, :boolean, default: false+ preference :show_variant_full_price, :boolean, default: false, deprecated: 'Nothing reads this in Spree 6 — a storefront decides how it renders prices'+ preference :show_products_without_price, :boolean, default: false, deprecated: 'Set it on the store instead'preference :show_raw_product_description, :boolean, deprecated: truepreference :tax_using_ship_address, :boolean, default: truepreference :title_site_name_separator, :string, deprecated: true- preference :track_inventory_levels, :boolean, default: true # Determines whether to track on_hand values for variants / products.- preference :track_price_history, :boolean, default: true # Records price changes for Omnibus Directive compliance. Disable for non-EU stores.+ preference :track_inventory_levels, :boolean, default: true, deprecated: 'Set it on the store instead' # Determines whether to track on_hand values for variants / products.+ preference :track_price_history, :boolean, default: true, deprecated: 'Set it on the store instead' # Records price changes for Omnibus Directive compliance. Disable for non-EU stores.preference :price_history_retention_days, :integer, default: 30 # Days to retain price history records. Used by spree:price_history:prune rake task.preference :use_user_locale, :boolean, default: true# Sets the path used for products, taxons and pages.- preference :storefront_products_path, :string, default: 'products'- preference :storefront_taxons_path, :string, default: 't'- preference :storefront_pages_path, :string, default: 'pages'+ preference :storefront_products_path, :string, default: 'products', deprecated: 'Nothing reads this in Spree 6 — storefront routes are owned by the storefront'+ preference :storefront_taxons_path, :string, default: 't', deprecated: 'Nothing reads this in Spree 6 — storefront routes are owned by the storefront'+ preference :storefront_pages_path, :string, default: 'pages', deprecated: 'Nothing reads this in Spree 6 — storefront routes are owned by the storefront'# coupon codespreference :coupon_codes_web_limit, :integer, default: 500 # number of coupon codes to be generated in the web process, more than this will be generated in a background jobdiff --git a/spree/core/lib/spree/testing_support/preferences.rb b/spree/core/lib/spree/testing_support/preferences.rbindex 1c3d566a9a..d17502ea08 100644--- a/spree/core/lib/spree/testing_support/preferences.rb+++ b/spree/core/lib/spree/testing_support/preferences.rb@@ -22,6 +22,45 @@ module Spreefind("#preferences_#{preference}")['checked'].should be falseSpree::Config[preference].should be falseend++ # Stubs store-scoped commerce settings for the duration of one example.+ #+ # stub_store_preferences(track_inventory_levels: false)+ # stub_store_preferences(other_store, auto_capture: false)+ #+ # Stubs rather than writes: the suite-wide +@default_store+ is shared by+ # every example, so persisting a setting here would leak into whatever+ # runs next.+ #+ # Stubbing is keyed on the store's id rather than a single object, because+ # code under test reaches its store through an association or a reload and+ # so holds a different instance of the same row. Stores with another id —+ # and preferences not listed here — keep their real values.+ #+ # Reads funnel through +get_preference+ and the generated+ # +preferred_<name>+ accessor, so both are stubbed.+ def stub_store_preferences(store = nil, **preferences)+ store ||= @default_store+ store_id = store.id++ preferences.each do |name, value|+ allow_any_instance_of(Spree::Store).to receive(:get_preference).+ with(name).and_wrap_original do |original, *args|+ original.receiver.id == store_id ? value : original.call(*args)+ end++ allow_any_instance_of(Spree::Store).to receive(:"preferred_#{name}").+ and_wrap_original do |original, *args|+ original.receiver.id == store_id ? value : original.call(*args)+ end+ end++ # Preferences this call doesn't name must still answer for themselves.+ allow_any_instance_of(Spree::Store).to receive(:get_preference).+ with(satisfy { |name| !preferences.key?(name) }).and_call_original++ store+ endendendenddiff --git a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.ymlindex ec679cd69d..ebdcb670ed 100644--- a/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml+++ b/spree/core/lib/spree/upgrades/5_6_to_6_0/manifest.yml@@ -290,6 +290,30 @@ steps:preferences so they aren't double-enforced. Run aftermigrate_shipping_to_delivery. Idempotent.+ - id: store_settings_backfill_from_config+ name: "Copy moved commerce settings onto every store"+ task: "spree:store_settings:backfill_from_config"+ notes: |+ Settings that describe how a shop sells moved from Spree::Config onto+ Spree::Store in 6.0: auto_capture, auto_capture_on_dispatch,+ track_inventory_levels, stock_reservations_enabled, track_price_history,+ show_products_without_price, disable_sku_validation and+ address_requires_phone. Two more were renamed on the way over — company+ became company_field_enabled, and default_stock_reservation_ttl_minutes+ became stock_reservation_ttl_minutes.++ Core reads the store with no fallback to the global, so an install that+ set any of these in an initializer needs this step to keep its behavior.+ A global left at its default is skipped, as is any store already carrying+ a non-default value of its own.++ Remove the settings from your initializer afterwards — the globals are+ deprecated and are deleted in 6.1.++ Idempotent: each store is visited at most once, recorded in its metadata,+ so a later run never undoes a change made in the dashboard after the+ upgrade.+- id: product_types_backfillname: "Backfill product type store ownership"task: "spree:product_types:backfill"diff --git a/spree/core/lib/tasks/store_settings.rake b/spree/core/lib/tasks/store_settings.rakenew file mode 100644index 0000000000..1f02476895--- /dev/null+++ b/spree/core/lib/tasks/store_settings.rake@@ -0,0 +1,77 @@+namespace :spree do+ namespace :store_settings do+ # Settings that moved from Spree::Config onto Spree::Store, mapped to the+ # default they carried as globals and — where the two differ — the name the+ # store preference goes by. A global still at its default says nothing about+ # intent and is never copied.+ MOVED_SETTINGS = {+ address_requires_phone: { default: false },+ auto_capture: { default: true },+ auto_capture_on_dispatch: { default: false },+ company: { default: false, store_preference: :company_field_enabled },+ default_stock_reservation_ttl_minutes: { default: 10, store_preference: :stock_reservation_ttl_minutes },+ disable_sku_validation: { default: false },+ show_products_without_price: { default: false },+ stock_reservations_enabled: { default: true },+ track_inventory_levels: { default: true },+ track_price_history: { default: true }+ }.freeze++ # Marks a store the backfill has already visited. Preferences seed their+ # declared defaults on create, so a stored value that equals the default is+ # indistinguishable from one a merchant deliberately set back to it — there+ # is no "explicitly set" flag to read. Without this marker, a merchant who+ # turns a copied setting off would have it turned back on by the next run.+ BACKFILL_MARKER = 'store_settings_backfilled_from_config'.freeze++ desc <<~DESC+ Copies commerce settings that moved from Spree::Config onto every store+ (Spree 6.0).++ Spree 6.0 reads these from the store, with no fallback to the global, so+ an install that changed one in an initializer needs this step to keep its+ behavior. Globals left at their default are skipped.++ Idempotent: each store is copied to at most once and stores already+ carrying a non-default value are left alone, so a merchant's own change+ is never overwritten. Remove the settings from your initializer+ afterwards — the globals are deprecated and are deleted in 6.1.+ DESC+ task backfill_from_config: :environment do+ changed = MOVED_SETTINGS.reject do |name, config|+ Spree::Config.send(name) == config[:default]+ end++ if changed.empty?+ puts ' No moved settings differ from their defaults — nothing to copy.'+ next+ end++ Spree::Store.find_each do |store|+ metadata = store.metadata || {}++ if metadata[BACKFILL_MARKER]+ puts " #{store.name} (#{store.id}): already backfilled — skipped."+ next+ end++ changed.each do |name, config|+ preference = config[:store_preference] || name++ if store.get_preference(preference) != store.preference_default(preference)+ puts " #{store.name} (#{store.id}): #{preference} already customized — skipped."+ next+ end++ value = Spree::Config.send(name)+ store.set_preference(preference, value)++ puts " #{store.name} (#{store.id}): #{preference} = #{value}"+ end++ store.metadata = metadata.merge(BACKFILL_MARKER => true)+ store.save!+ end+ end+ end+enddiff --git a/spree/core/spec/lib/tasks/store_settings_spec.rb b/spree/core/spec/lib/tasks/store_settings_spec.rbnew file mode 100644index 0000000000..a16861d2ff--- /dev/null+++ b/spree/core/spec/lib/tasks/store_settings_spec.rb@@ -0,0 +1,98 @@+require 'spec_helper'+require 'rake'++describe 'spree:store_settings:backfill_from_config' do+ before(:all) do+ Rake::Task.define_task(:environment)+ load Spree::Core::Engine.root.join('lib', 'tasks', 'store_settings.rake')+ end++ let(:store) { @default_store }+ let(:marker) { 'store_settings_backfilled_from_config' }++ def run_task+ task = Rake::Task['spree:store_settings:backfill_from_config']+ task.reenable+ old = $stdout.dup+ $stdout.reopen(File::NULL, 'w')+ task.invoke+ ensure+ $stdout.reopen(old)+ end++ before do+ store.update!(preferred_address_requires_phone: false, metadata: (store.metadata || {}).except(marker))+ end++ after do+ Spree::Config.address_requires_phone = false+ store.update!(preferred_address_requires_phone: false, metadata: (store.metadata || {}).except(marker))+ end++ context 'when the global was changed from its default' do+ before { Spree::Config.address_requires_phone = true }++ it 'copies the value onto the store' do+ expect { run_task }.to change { store.reload.preferred_address_requires_phone }.from(false).to(true)+ end++ it 'marks the store so a later run leaves it alone' do+ run_task++ expect(store.reload.metadata[marker]).to be_truthy+ end++ # Preferences seed their defaults on create, so a value equal to the default+ # can't be distinguished from a deliberate one. The marker is what keeps a+ # merchant's later change from being undone by a second run.+ it 'does not re-copy after the merchant changes the value back' do+ run_task+ store.update!(preferred_address_requires_phone: false)++ expect { run_task }.not_to change { store.reload.preferred_address_requires_phone }.from(false)+ end+ end++ context 'when the global is still at its default' do+ before { Spree::Config.address_requires_phone = false }++ it 'copies nothing' do+ expect { run_task }.not_to change { store.reload.preferred_address_requires_phone }.from(false)+ end+ end++ # Two settings were renamed on the way onto the store, so the task can't+ # assume the global and the preference share a name.+ context 'when a renamed global was changed' do+ after do+ Spree::Config.company = false+ Spree::Config.default_stock_reservation_ttl_minutes = 10+ store.update!(+ preferred_company_field_enabled: false,+ preferred_stock_reservation_ttl_minutes: 10,+ metadata: (store.metadata || {}).except(marker)+ )+ end++ it 'copies company onto company_field_enabled' do+ Spree::Config.company = true++ expect { run_task }.to change { store.reload.preferred_company_field_enabled }.from(false).to(true)+ end++ it 'copies the reservation TTL onto its renamed preference' do+ Spree::Config.default_stock_reservation_ttl_minutes = 25++ expect { run_task }.to change { store.reload.preferred_stock_reservation_ttl_minutes }.from(10).to(25)+ end++ # Distinct values on both sides, so a run that wrongly copied would be+ # visible — with a boolean the two would agree and the test prove nothing.+ it 'leaves a store that already customized the renamed preference alone' do+ Spree::Config.default_stock_reservation_ttl_minutes = 25+ store.update!(preferred_stock_reservation_ttl_minutes: 40)++ expect { run_task }.not_to change { store.reload.preferred_stock_reservation_ttl_minutes }.from(40)+ end+ end+enddiff --git a/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb b/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rbindex c74c96fc75..6cf9c86616 100644--- a/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb+++ b/spree/core/spec/models/concerns/spree/purchase/payment_processing_spec.rb@@ -64,20 +64,20 @@ RSpec.shared_examples 'a payment processing host' docontext 'when a payment raises a GatewayError' dobefore { expect(payment).to receive(:process!).and_raise(Spree::Core::GatewayError) }- it 'returns true when configured to allow checkout on gateway failures' do- Spree::Config.set allow_checkout_on_gateway_error: true- expect(record.process_payments!).to be true+ it 'returns false' do+ expect(record.process_payments!).to be falseend- it 'returns false when not configured to allow checkout on gateway failures' do- Spree::Config.set allow_checkout_on_gateway_error: false- expect(record.process_payments!).to be false+ it 'records the gateway message so completion can report it' do+ record.process_payments!++ expect(record.errors[:base]).to be_presentendend# Regression spec for https://github.com/spree/spree/issues/8148it 'updates the record with correct payment total' do- Spree::Config[:auto_capture] = true+ stub_store_preferences(auto_capture: true)record.process_payments!expect(payment).to be_completeddiff --git a/spree/core/spec/models/concerns/spree/store_preferences_spec.rb b/spree/core/spec/models/concerns/spree/store_preferences_spec.rbnew file mode 100644index 0000000000..f24bc2a453--- /dev/null+++ b/spree/core/spec/models/concerns/spree/store_preferences_spec.rb@@ -0,0 +1,49 @@+require 'spec_helper'++describe Spree::StorePreferences do+ let(:store) { @default_store }++ describe '.read' do+ it "returns the store's value" do+ stub_store_preferences(store, track_inventory_levels: false)++ expect(described_class.read(store, :track_inventory_levels)).to be(false)+ end++ # A console session, a seed, or a job that never set the ambient store must+ # not blow up — it falls back to what the preference declares.+ it 'falls back to the declared default without a store' do+ expect(described_class.read(nil, :track_inventory_levels)).to be(true)+ expect(described_class.read(nil, :show_products_without_price)).to be(false)+ end+ end++ describe '.current' do+ it 'reads through the ambient store' do+ stub_store_preferences(store, show_products_without_price: true)++ expect(described_class.current(:show_products_without_price)).to be(true)+ end+ end++ describe '#store_preference' do+ it 'reads through the store the record belongs to' do+ payment_method = create(:payment_method, store: store)+ stub_store_preferences(store, auto_capture: false)++ expect(payment_method.store_preference(:auto_capture)).to be(false)+ end++ it 'follows an overridden preference_store' do+ other_store = create(:store)+ product = create(:product, store: other_store)+ stub_store_preferences(other_store, track_inventory_levels: false)++ expect(product.variants.first.store_preference(:track_inventory_levels)).to be(false)+ end++ it 'falls back to the declared default when the record has no store' do+ expect(Spree::Product.new.store_preference(:track_inventory_levels)).to be(true)+ end+ end+enddiff --git a/spree/core/spec/models/spree/address_spec.rb b/spree/core/spec/models/spree/address_spec.rbindex 3456b1ff8b..401ee12990 100644--- a/spree/core/spec/models/spree/address_spec.rb+++ b/spree/core/spec/models/spree/address_spec.rb@@ -134,10 +134,6 @@ describe Spree::Address, type: :model dobefore doallow(Spree::State).to receive(:find_all_by_name_or_abbr) { [state] }-- configure_spree_preferences do |config|- config.address_requires_state = true- endendit 'state_name is not nil and country does not have any states' do@@ -190,21 +186,22 @@ describe Spree::Address, type: :model doexpect(address.state_name).to be_nilend- it 'address_requires_state preference is false' do- Spree::Config.set address_requires_state: false+ it 'does not require a state when the country does not require one' do+ address.country = create(:country, states_required: false)address.state = niladdress.state_name = nilexpect(address).to be_validendit 'does not require phone' do- Spree::Config.set address_requires_state: falseaddress.phone = ''expect(address).to be_validendcontext 'when phone is required' do- before { Spree::Config.set address_requires_phone: true }+ before { @default_store.update!(preferred_address_requires_phone: true) }++ after { @default_store.update!(preferred_address_requires_phone: false) }it 'validates presence of the phone' doaddress.phone = ''@@ -759,24 +756,34 @@ describe Spree::Address, type: :model docontext 'when quick_checkout is false' dolet(:address) { build_stubbed(:address, quick_checkout: false) }- context 'and Spree::Config[:address_requires_phone] is true' do- before { Spree::Config[:address_requires_phone] = true }+ context 'and the store requires a phone' do+ before { @default_store.update!(preferred_address_requires_phone: true) }- after { Spree::Config[:address_requires_phone] = false }+ after { @default_store.update!(preferred_address_requires_phone: false) }it 'returns true' doexpect(address.require_phone?).to be(true)endend- context 'and Spree::Config[:address_requires_phone] is false' do- before { Spree::Config[:address_requires_phone] = false }+ context 'and the store does not require a phone' do+ before { @default_store.update!(preferred_address_requires_phone: false) }it 'returns false' doexpect(address.require_phone?).to be(false)endendend++ context 'when there is no current store' do+ let(:address) { build_stubbed(:address, quick_checkout: false) }++ before { allow(Spree::Current).to receive(:store).and_return(nil) }++ it 'falls back to the preference default' do+ expect(address.require_phone?).to be(false)+ end+ endenddescribe 'country_iso= and state_abbr= writer methods' dodiff --git a/spree/core/spec/models/spree/order/payment_spec.rb b/spree/core/spec/models/spree/order/payment_spec.rbindex 8c804f7c45..9e65c626b3 100644--- a/spree/core/spec/models/spree/order/payment_spec.rb+++ b/spree/core/spec/models/spree/order/payment_spec.rb@@ -7,7 +7,7 @@ module Spreecontext 'processing payments' dobefore do# So that Payment#purchase! is called during processing- Spree::Config[:auto_capture] = true+ stub_store_preferences(auto_capture: true)allow(order).to receive_message_chain(:line_items, :empty?).and_return(false)enddiff --git a/spree/core/spec/models/spree/order_inventory_spec.rb b/spree/core/spec/models/spree/order_inventory_spec.rbindex 63013c1708..52b6d39700 100644--- a/spree/core/spec/models/spree/order_inventory_spec.rb+++ b/spree/core/spec/models/spree/order_inventory_spec.rb@@ -44,7 +44,7 @@ describe Spree::OrderInventory, type: :model docontext 'store doesnt track inventory' dolet(:variant) { create(:variant) }- before { Spree::Config.track_inventory_levels = false }+ before { stub_store_preferences(track_inventory_levels: false) }it 'creates only on hand inventory units' dovariant.stock_items.delete_alldiff --git a/spree/core/spec/models/spree/order_routing/strategy/parity_spec.rb b/spree/core/spec/models/spree/order_routing/strategy/parity_spec.rbindex 434987a7a9..ff5355eafa 100644--- a/spree/core/spec/models/spree/order_routing/strategy/parity_spec.rb+++ b/spree/core/spec/models/spree/order_routing/strategy/parity_spec.rb@@ -289,12 +289,7 @@ RSpec.describe 'OrderRouting strategy parity', type: :model do# ---------------------------------------------------------------context 'with stock reservations enabled' do- around do |ex|- original = Spree::Config[:stock_reservations_enabled]- Spree::Config[:stock_reservations_enabled] = true- ex.run- Spree::Config[:stock_reservations_enabled] = original- end+ before { stub_store_preferences(stock_reservations_enabled: true) }context 'another order holds a reservation at NYC' dolet(:other_order) do@@ -395,12 +390,7 @@ RSpec.describe 'OrderRouting strategy parity', type: :model doendcontext 'stock reservations globally disabled' do- around do |ex|- original = Spree::Config[:stock_reservations_enabled]- Spree::Config[:stock_reservations_enabled] = false- ex.run- Spree::Config[:stock_reservations_enabled] = original- end+ before { stub_store_preferences(stock_reservations_enabled: false) }let(:order) doo = create(:order, store: store, ship_address: create(:ship_address))diff --git a/spree/core/spec/models/spree/payment_method_spec.rb b/spree/core/spec/models/spree/payment_method_spec.rbindex 4aa9cdd304..9f4174d530 100644--- a/spree/core/spec/models/spree/payment_method_spec.rb+++ b/spree/core/spec/models/spree/payment_method_spec.rb@@ -83,14 +83,12 @@ describe Spree::PaymentMethod, type: :model dosubject { gateway.auto_capture? }- let(:gateway) { TestGateway.new }+ let(:gateway) { TestGateway.new(store: store) }context 'when auto_capture is nil' do- before do- expect(Spree::Config).to receive('[]').with(:auto_capture).and_return(auto_capture)- end+ before { stub_store_preferences(store, auto_capture: auto_capture) }- context 'and when Spree::Config[:auto_capture] is false' do+ context "and when the store's auto_capture is false" dolet(:auto_capture) { false }it 'is false' do@@ -99,7 +97,7 @@ describe Spree::PaymentMethod, type: :model doendend- context 'and when Spree::Config[:auto_capture] is true' do+ context "and when the store's auto_capture is true" dolet(:auto_capture) { true }it 'is true' dodiff --git a/spree/core/spec/models/spree/price_spec.rb b/spree/core/spec/models/spree/price_spec.rbindex 309384a699..6341fc6ffb 100644--- a/spree/core/spec/models/spree/price_spec.rb+++ b/spree/core/spec/models/spree/price_spec.rb@@ -433,11 +433,7 @@ describe Spree::Price, type: :model docontext 'when track_price_history is disabled' dobefore do- Spree::Config[:track_price_history] = false- end-- after do- Spree::Config[:track_price_history] = true+ stub_store_preferences(price.preference_store, track_price_history: false)endit 'does not create a price history record' dodiff --git a/spree/core/spec/models/spree/product_spec.rb b/spree/core/spec/models/spree/product_spec.rbindex 1a41722db6..342469049e 100644--- a/spree/core/spec/models/spree/product_spec.rb+++ b/spree/core/spec/models/spree/product_spec.rb@@ -677,12 +677,12 @@ describe Spree::Product, type: :model dolet(:product) { create(:product) }it 'is infinite if track_inventory_levels is false' do- allow(Spree::Config).to receive(:track_inventory_levels).and_return(false)+ stub_store_preferences(track_inventory_levels: false)expect(build(:product).total_on_hand).to eql(Float::INFINITY)endit 'is infinite if variant is on demand' do- allow(Spree::Config).to receive(:track_inventory_levels).and_return(true)+ stub_store_preferences(track_inventory_levels: true)expect(build(:product, track_inventory: false).total_on_hand).to eql(Float::INFINITY)end@@ -1726,7 +1726,7 @@ describe Spree::Product, type: :model dosubject(:available_products) { described_class.available(nil, 'USD') }before do- Spree::Config.show_products_without_price = false+ stub_store_preferences(show_products_without_price: false)endlet!(:active_product_2) { create(:product, status: 'active') }@@ -1751,7 +1751,7 @@ describe Spree::Product, type: :model dosubject(:available_products) { described_class.available(nil, 'USD') }before do- Spree::Config.show_products_without_price = true+ stub_store_preferences(show_products_without_price: true)endlet!(:active_product_2) { create(:product, status: 'active') }diff --git a/spree/core/spec/models/spree/shipment_spec.rb b/spree/core/spec/models/spree/shipment_spec.rbindex 3d21ccd280..81d197f21e 100644--- a/spree/core/spec/models/spree/shipment_spec.rb+++ b/spree/core/spec/models/spree/shipment_spec.rb@@ -618,7 +618,6 @@ describe Spree::Shipment, type: :model doendcontext 'when order is completed' do- after { Spree::Config.set track_inventory_levels: true }before doallow(order).to receive_messages completed?: true@@ -626,7 +625,7 @@ describe Spree::Shipment, type: :model doendcontext 'with inventory tracking' do- before { Spree::Config.set track_inventory_levels: true }+ before { stub_store_preferences(track_inventory_levels: true) }it 'validates with inventory' doshipment.inventory_units = [create(:inventory_unit)]@@ -635,7 +634,7 @@ describe Spree::Shipment, type: :model doendcontext 'without inventory tracking' do- before { Spree::Config.set track_inventory_levels: false }+ before { stub_store_preferences(track_inventory_levels: false) }it 'validates with no inventory' doexpect(shipment.valid?).to be truediff --git a/spree/core/spec/models/spree/stock/packer_spec.rb b/spree/core/spec/models/spree/stock/packer_spec.rbindex 9620b44110..ed1990b96b 100644--- a/spree/core/spec/models/spree/stock/packer_spec.rb+++ b/spree/core/spec/models/spree/stock/packer_spec.rb@@ -59,7 +59,7 @@ module Spreecontext "doesn't track inventory levels" dolet(:inventory_units) { Array.new(2) { InventoryUnit.new(variant: create(:variant)) } }- before { Config.track_inventory_levels = false }+ before { stub_store_preferences(track_inventory_levels: false) }it "doesn't bother stock items status in stock location" doexpect(subject.stock_location).not_to receive(:fill_status)diff --git a/spree/core/spec/models/spree/stock/quantifier_spec.rb b/spree/core/spec/models/spree/stock/quantifier_spec.rbindex 2978ad8a25..569a85140a 100644--- a/spree/core/spec/models/spree/stock/quantifier_spec.rb+++ b/spree/core/spec/models/spree/stock/quantifier_spec.rb@@ -32,7 +32,7 @@ module Spreeendcontext 'when track_inventory_levels is false' do- before { configure_spree_preferences { |config| config.track_inventory_levels = false } }+ before { stub_store_preferences(track_inventory_levels: false) }specify { expect(subject.total_on_hand).to eq(Float::INFINITY) }@@ -129,7 +129,7 @@ module Spreelet(:other_line_item) { create(:line_item, order: other_order, variant: stock_item.variant) }context 'when stock_reservations_enabled is true' do- before { Spree::Config[:stock_reservations_enabled] = true }+ before { stub_store_preferences(stock_reservations_enabled: true) }it 'subtracts active reservations from total_on_hand' docreate(@@ -238,8 +238,7 @@ module Spreeendcontext 'when stock_reservations_enabled is false' do- before { Spree::Config[:stock_reservations_enabled] = false }- after { Spree::Config[:stock_reservations_enabled] = true }+ before { stub_store_preferences(stock_reservations_enabled: false) }it 'returns raw count_on_hand even when reservations exist' docreate(diff --git a/spree/core/spec/models/spree/stock_movement_spec.rb b/spree/core/spec/models/spree/stock_movement_spec.rbindex 9478e93e5e..d06949a4a5 100644--- a/spree/core/spec/models/spree/stock_movement_spec.rb+++ b/spree/core/spec/models/spree/stock_movement_spec.rb@@ -84,7 +84,7 @@ describe Spree::StockMovement, type: :model dodescribe '#update_stock_item_quantity' docontext 'when track inventory levels is false' dobefore do- Spree::Config[:track_inventory_levels] = false+ stub_store_preferences(track_inventory_levels: false)stock_movement.quantity = 1stock_movement.savestock_item.reloaddiff --git a/spree/core/spec/models/spree/stock_reservation_spec.rb b/spree/core/spec/models/spree/stock_reservation_spec.rbindex 882b9b18b7..f9b842a80f 100644--- a/spree/core/spec/models/spree/stock_reservation_spec.rb+++ b/spree/core/spec/models/spree/stock_reservation_spec.rb@@ -84,11 +84,8 @@ describe Spree::StockReservation, type: :model doexpect(described_class.ttl_for(order)).to eq(15.minutes)end- it 'falls back to the global default_stock_reservation_ttl_minutes' do- Spree::Config[:default_stock_reservation_ttl_minutes] = 7- expect(described_class.ttl_for(nil)).to eq(7.minutes)- ensure- Spree::Config[:default_stock_reservation_ttl_minutes] = 10+ it 'falls back to ten minutes without a store to ask' do+ expect(described_class.ttl_for(nil)).to eq(10.minutes)endenddiff --git a/spree/core/spec/models/spree/variant_spec.rb b/spree/core/spec/models/spree/variant_spec.rbindex ee917ceb3e..fbe1c8eb0a 100644--- a/spree/core/spec/models/spree/variant_spec.rb+++ b/spree/core/spec/models/spree/variant_spec.rb@@ -61,11 +61,11 @@ describe Spree::Variant, type: :model docontext 'disabled validation' dobefore do- Spree::Config[:disable_sku_validation] = true+ stub_store_preferences(disable_sku_validation: true)endafter do- Spree::Config[:disable_sku_validation] = false+ stub_store_preferences(disable_sku_validation: false)endcontext 'valid' do@@ -874,7 +874,7 @@ describe Spree::Variant, type: :model dodescribe '#in_stock?' dobefore do- Spree::Config.track_inventory_levels = true+ stub_store_preferences(track_inventory_levels: true)endcontext 'when stock_items are not backorderable' do@@ -1002,7 +1002,7 @@ describe Spree::Variant, type: :model dodescribe '#total_on_hand' doit 'is infinite if track_inventory_levels is false' do- Spree::Config[:track_inventory_levels] = false+ stub_store_preferences(track_inventory_levels: false)expect(build(:variant).total_on_hand).to eql(Float::INFINITY)end@@ -1103,19 +1103,19 @@ describe Spree::Variant, type: :model dodescribe '#should_track_inventory?' doit 'does not track inventory when global setting is off' do- Spree::Config[:track_inventory_levels] = false+ stub_store_preferences(track_inventory_levels: false)expect(build(:variant).should_track_inventory?).to eq(false)endit 'does not track inventory when variant is turned off' do- Spree::Config[:track_inventory_levels] = true+ stub_store_preferences(track_inventory_levels: true)expect(build(:on_demand_variant).should_track_inventory?).to eq(false)endit 'tracks inventory when global and variant are on' do- Spree::Config[:track_inventory_levels] = true+ stub_store_preferences(track_inventory_levels: true)expect(build(:variant).should_track_inventory?).to eq(true)enddiff --git a/spree/core/spec/services/spree/addresses/phone_validator_spec.rb b/spree/core/spec/services/spree/addresses/phone_validator_spec.rbindex 06ffdcd0aa..c0385b043d 100644--- a/spree/core/spec/services/spree/addresses/phone_validator_spec.rb+++ b/spree/core/spec/services/spree/addresses/phone_validator_spec.rb@@ -11,7 +11,11 @@ describe Spree::Addresses::PhoneValidator doendbefore do- Spree::Config[:address_requires_phone] = true+ @default_store.update!(preferred_address_requires_phone: true)+ end++ after do+ @default_store.update!(preferred_address_requires_phone: false)enddescribe '#validate' do@@ -19,7 +23,7 @@ describe Spree::Addresses::PhoneValidator dolet(:address) { create(:address, phone: nil) }before do- Spree::Config[:address_requires_phone] = false+ @default_store.update!(preferred_address_requires_phone: false)endit_behaves_like 'does not add a phone error'@@ -29,7 +33,7 @@ describe Spree::Addresses::PhoneValidator dolet(:address) { build_stubbed(:address, phone: '2025550123', country: nil) }before do- Spree::Config[:address_requires_phone] = false+ @default_store.update!(preferred_address_requires_phone: false)endit_behaves_like 'does not add a phone error'@@ -39,7 +43,7 @@ describe Spree::Addresses::PhoneValidator dolet(:address) { build_stubbed(:address, phone: '2025550123') }before do- Spree::Config[:address_requires_phone] = false+ @default_store.update!(preferred_address_requires_phone: false)address.country.iso = nilenddiff --git a/spree/core/spec/services/spree/carts/remove_out_of_stock_items_spec.rb b/spree/core/spec/services/spree/carts/remove_out_of_stock_items_spec.rbindex f238b1dd4f..0b96314e82 100644--- a/spree/core/spec/services/spree/carts/remove_out_of_stock_items_spec.rb+++ b/spree/core/spec/services/spree/carts/remove_out_of_stock_items_spec.rb@@ -82,7 +82,7 @@ RSpec.describe Spree::Carts::RemoveOutOfStockItems dolet(:line_item) { cart.line_items.first }before do- Spree::Config[:stock_reservations_enabled] = true+ stub_store_preferences(stock_reservations_enabled: true)variant.stock_items.update_all(count_on_hand: 1, backorderable: false)line_item.update!(quantity: 1)variant.stock_items.each do |stock_item|@@ -97,8 +97,6 @@ RSpec.describe Spree::Carts::RemoveOutOfStockItems doendend- after { Spree::Config[:stock_reservations_enabled] = true }-it 'keeps the line item in the cart' do_cart, messages, warnings = execute.valueexpect(messages).to be_emptydiff --git a/spree/core/spec/services/spree/stock_reservations/extend_spec.rb b/spree/core/spec/services/spree/stock_reservations/extend_spec.rbindex c9b6146434..61122b7c6a 100644--- a/spree/core/spec/services/spree/stock_reservations/extend_spec.rb+++ b/spree/core/spec/services/spree/stock_reservations/extend_spec.rb@@ -6,8 +6,7 @@ describe Spree::StockReservations::Extend dolet!(:reservation) { create(:stock_reservation, order: order, expires_at: 1.minute.from_now) }context 'when stock_reservations_enabled is true' do- before { Spree::Config[:stock_reservations_enabled] = true }- after { Spree::Config[:stock_reservations_enabled] = true }+ before { stub_store_preferences(store, stock_reservations_enabled: true) }it 'pushes expires_at out by the store TTL' doTimecop.freeze do@@ -28,8 +27,7 @@ describe Spree::StockReservations::Extend doendcontext 'when stock_reservations_enabled is false' do- before { Spree::Config[:stock_reservations_enabled] = false }- after { Spree::Config[:stock_reservations_enabled] = true }+ before { stub_store_preferences(store, stock_reservations_enabled: false) }it 'leaves expires_at untouched' dooriginal = reservation.expires_atdiff --git a/spree/core/spec/services/spree/stock_reservations/reserve_spec.rb b/spree/core/spec/services/spree/stock_reservations/reserve_spec.rbindex 0ddba5c9c3..a583769692 100644--- a/spree/core/spec/services/spree/stock_reservations/reserve_spec.rb+++ b/spree/core/spec/services/spree/stock_reservations/reserve_spec.rb@@ -11,8 +11,7 @@ describe Spree::StockReservations::Reserve dosubject(:result) { described_class.call(order: order) }context 'when stock_reservations_enabled is true' do- before { Spree::Config[:stock_reservations_enabled] = true }- after { Spree::Config[:stock_reservations_enabled] = true }+ before { stub_store_preferences(store, stock_reservations_enabled: true) }it 'creates a reservation for each tracked line item' doexpect { result }.to change(Spree::StockReservation, :count).by(1)@@ -85,8 +84,7 @@ describe Spree::StockReservations::Reserve doendcontext 'when stock_reservations_enabled is false' do- before { Spree::Config[:stock_reservations_enabled] = false }- after { Spree::Config[:stock_reservations_enabled] = true }+ before { stub_store_preferences(store, stock_reservations_enabled: false) }it 'is a no-op' doexpect { result }.not_to change(Spree::StockReservation, :count)diff --git a/spree/core/spec/workflows/spree/carts/add_item_spec.rb b/spree/core/spec/workflows/spree/carts/add_item_spec.rbindex 16457da387..0a1d39a2fc 100644--- a/spree/core/spec/workflows/spree/carts/add_item_spec.rb+++ b/spree/core/spec/workflows/spree/carts/add_item_spec.rb@@ -311,8 +311,7 @@ module Spreecontext 'when stock_reservations_enabled is false' dolet(:cart) { create(:cart, email: '[email protected]') }- before { Spree::Config[:stock_reservations_enabled] = false }- after { Spree::Config[:stock_reservations_enabled] = true }+ before { stub_store_preferences(stock_reservations_enabled: false) }it 'does not create a reservation' doexpect { execute }.not_to change { Spree::StockReservation.count }diff --git a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rbindex 239fa96b56..2504813bd5 100644--- a/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb+++ b/spree/core/spec/workflows/spree/fulfillments/fulfill_spec.rb@@ -288,6 +288,38 @@ module Spreeendend+ describe 'capturing payment on dispatch' do+ # The factory captures at checkout; undo that so the payment is merely+ # authorized, which is the state this setting exists to resolve.+ before do+ payment = order.payments.first+ payment.capture_events.delete_all+ payment.update_columns(state: 'pending')+ order.update_columns(payment_total: 0, payment_state: 'balance_due')+ end++ it 'captures the authorized payment when the store charges on dispatch' do+ stub_store_preferences(store, auto_capture_on_dispatch: true)++ subject.call(fulfillment: fulfillment)++ payment = order.payments.first.reload+ expect(payment).to be_completed+ expect(payment.captured_amount).to eq(payment.amount)+ expect(order.reload.payment_state).to eq('paid')+ end++ it 'leaves the payment authorized when it does not' do+ stub_store_preferences(store, auto_capture_on_dispatch: false)++ subject.call(fulfillment: fulfillment)++ payment = order.payments.first.reload+ expect(payment).to be_pending+ expect(payment.captured_amount).to eq(0)+ end+ end+describe 'hooks' dobefore { Spree.hooks.clear! }after { Spree.hooks.clear! }diff --git a/spree/core/spec/workflows/spree/orders/complete_spec.rb b/spree/core/spec/workflows/spree/orders/complete_spec.rbindex a90ce6392a..437f2fd672 100644--- a/spree/core/spec/workflows/spree/orders/complete_spec.rb+++ b/spree/core/spec/workflows/spree/orders/complete_spec.rb@@ -5,8 +5,6 @@ module Spreelet(:store) { @default_store }let(:order) { Spree::Order.create(email: '[email protected]') }- after { Spree::Config.set track_inventory_levels: true }-# Regression: the rollup writes its vocabulary (none/authorized/...) via# update_columns, so the model's validation must accept it — otherwise the# first derived value poisons the order and completion 422s forever.@@ -71,7 +69,7 @@ module Spreeendit 'does not sell inventory units if track_inventory_levels is false' do- Spree::Config.set track_inventory_levels: false+ stub_store_preferences(track_inventory_levels: false)expect(Spree::InventoryUnit).not_to receive(:sell_units)described_class.call(order: order)end