Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Configure the dashboard origin from the environment

Damian Legawieca1db8a32be52
diff --git a/CLAUDE.md b/CLAUDE.md
index a86af9fa6f..753e5a6c41 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -25,7 +25,7 @@ Active plans (6.0 target, work pending):
- `6.0-fulfillment-and-delivery.md` — Shipment→Fulfillment, ShippingMethod→DeliveryMethod, drop ShippingCategory, FulfillmentProvider strategy, pickup (merchant StockLocation) + pickup_point (third-party PickupPointProvider). **Shipped to 6-0-dev (Waves 2+4+6):** renames + deprecated twins, providers (Manual/Digital/Pickup/PickupPoint), dual-emit events, store pickup discovery endpoints, admin delivery_methods/delivery_zones CRUD + dashboard settings pages, FulfillmentMailer; Wave 7 shipping→delivery data migration remains. Pickup work beyond shipped code deferred to 6.1 (2026-08-06): contract hardening (`new(delivery_method)` ctor, `find_nearby` zipcode/query) + how-to guide; `PickupPointProvider::Base` stays **undocumented in 6.0** (v6 docs cover only the delivery rate provider interface) — never add pickup-provider docs in 6.0 work. Delivery mechanics live on provider classes (`pickup_point` provider ships but stays unregistered until 6.1; `local_delivery` cut = shipping + postal-code zone); the string fulfillment-type registry was deleted by `6.0-delivery-profiles.md`. **Partial fulfillment (2026-08-10, resolved question 12):** shipping a subset is `Spree::Fulfillments::Fulfill` (optional per-line-item `items:` + `tracking:` + `notify_customer:`; splits then fulfills in one transaction) — never a state-machine event, since split-then-ship in an `after_transition` is what service-workflows prohibits. **Side effects left the machine (2026-08-10, question 13):** `after_cancel`/`after_resume` are gone as transition callbacks — restock + carrier stand-down live in `Fulfillments::Cancel`/`::Resume` as inline steps (provider call is an `external_step`; `notify_provider: false` lets `Orders::Cancel` delegate and batch carrier I/O after its own transaction), `after_cancel`/`after_resume` are deprecated shells and the only trace left on the model — never add public model methods for workflows to call. **Status model (2026-08-11, question 14): the machine is REMOVED.** `status` = plain `HasStatus` `unfulfilled → fulfilled → delivered | canceled` (`pending`/`ready`/`ready_for_pickup` collapse — payment/stock gating is a `Fulfillments::Fulfill` validate guard, pickup renders modality-aware labels); `delivered` = confirmed receipt (`Fulfillments::MarkDelivered`, `delivered_at`, `fulfillment.delivered`) — the returns window + EU withdrawal anchor; carrier truth is the separate `tracking_status` axis (data, never a machine) written by `Fulfillments::UpdateTracking`, fed by EasyPost tracker webhooks (opt-in trackers for hand-entered numbers). Rollup domain `backorder | canceled | partial | unfulfilled | fulfilled | delivered`. **Phase 7 shipped 2026-08-11** (core + API + dashboard + EasyPost tracker webhook + `spree:migrate_fulfillment_statuses`); **label leads, fulfilled follows (2026-08-12):** `Fulfillments::PurchaseLabel` = explicit pre-ship label buy (loud failure, no email); `Fulfill` buys label BEFORE marking fulfilled (email always carries tracking; post-split failure keeps the split, never rolls it back); providers declare `generates_labels?` + idempotent `create_fulfillment`. **One tracking number per fulfillment (2026-08-11, question 15):** diverging parcels are split fulfillments; a `spree_fulfillment_trackings` model is 6.1 work and must absorb the entire carrier axis (per-row status/`delivered_at`, webhook matching by row) — never split the axis across fulfillment and tracking rows
- `6.0-returns-exchanges-claims.md` — First-class Return, Exchange, Claim models replacing ReturnAuthorization/Reimbursement chain. **COMPLETE (2026-08-05):** all three entities (+ permanent `ReturnLineItem`/`ExchangeLineItem`/`ClaimLineItem` line items), `Spree::HasStatus`, all fifteen workflows (each with a leading `validate` hook), `Refund#originator`, admin + store v3 APIs (transitions as PATCH member actions; no destroy — cancel instead), dashboard pages. Legacy chain **removed**: ReturnAuthorization/CustomerReturn/Reimbursement/ReimbursementType/legacy ReturnItem + eligibility validators + ReturnsCalculator classes all deleted, but their **tables deliberately survive to 6.1** as the data migration's source and rollback path. `spree:upgrade:migrate_returns` (`Spree::ReturnsMigrator`, defined in the rake file like its sibling upgrade tasks; anonymous-AR readers) is in the 5.6→6.0 manifest after the adjustments step; it needs no cursor because the preserved `number` is uniquely indexed on the new tables, so "what's left" is a `where.not(number: ...)` query and an interrupted run resumes for free. `ReturnAuthorizationReason`→`ReturnReason` (alias one release) + new `ClaimReason`; `Metafields` on all three. Capability replacements: `Spree::ReturnMailer#refunded_email` on `return.refunded` (replaces the reimbursement email), `Order#outstanding_balance` drops the reimbursement term (refunds already net out of `payment_total`), `Return#refunded_total` counts store credits too, `StoreCreditCategory.default_refund_category` (alias kept). **Reasons** ship admin-only CRUD (`/api/v3/admin/{return,claim,refund}_reasons`, `settings` scope) + a combined Settings → Reasons dashboard page + reason pickers on the create dialogs; `mutable` is never client-writable and the immutability guard lives on `Spree::NamedType` (`can_be_deleted?` + rename/destroy guards) because secret API keys authorize by scope and never consult CanCanCan. **No state machines (2026-08-02):** plain `status` string + inclusion validation; all fifteen transitions are workflows (`Returns::Receive`, `Exchanges::Fulfill`, `Claims::Resolve`, …) with `validate` hooks for return-eligibility policy and refunds as `external_step`. Nothing happens in a model or transition callback. Statuses live in a `class_attribute` via the core `Spree::HasStatus` concern (`has_status` + additive `add_status(value, after:)`, generating predicates and scopes) — extensible by design, additive only, and no transition graph (that would be a state machine again). **Return eligibility is a hook, not a policy engine (2026-08-03):** no window/restocking-fee/final-sale flag in core — a `validate` handler decides, enforcing for customers while letting staff override (it reads `created_by`), and region-varying policy reads `order.market`. Medusa/Saleor/Vendure ship no policy at all; Shopify's engine has no API. A `ReturnPolicy` model can arrive later behind the same hook.
- `6.0-platform-auth.md` — Drop Devise, own auth stack, User→Customer/Staff rename (RefreshToken shipped in 5.4)
-- `6.0-store-context-and-first-run-setup.md` — Store context becomes credential-derived (design finalized 2026-08-13): publishable key selects the store on the Store API, Admin API honors `X-Spree-Store-Id` with membership checked against the *requested* store (header-less JWT → default store + deprecation, required 6.1), hostname-based store resolution retired (`FindDefault`'s `url:` is dead; never read `request.host` to pick a store). First-run setup replaces the `[email protected]`/`spree123` dummy seed: seed creates an admin only when `ADMIN_EMAIL`/`ADMIN_PASSWORD` are explicitly set; otherwise a one-time setup-token flow (dashboard `/setup` + unauthenticated `auth/setup` endpoints; `has_secure_token :setup_token` on Store — plaintext like invitation tokens, printed by installer, `spree:setup:token` reprints, cleared on completion — required in EVERY environment) creates the first admin and adopts/renames the seeded store. No general store CRUD in the OSS Admin API. **Constraints now:** never assume `current_store == Store.default` in Admin API code; store-touching cache keys include the store id by construction; new scripts pass `ADMIN_EMAIL`/`ADMIN_PASSWORD` explicitly.
+- `6.0-store-context-and-first-run-setup.md` — Store context becomes credential-derived (design finalized 2026-08-13): publishable key selects the store on the Store API, Admin API honors `X-Spree-Store-Id` with membership checked against the *requested* store (header-less JWT → default store + deprecation, required 6.1), hostname-based store resolution retired (`FindDefault`'s `url:` is dead; never read `request.host` to pick a store). First-run setup replaces the `[email protected]`/`spree123` dummy seed: seed creates an admin only when `ADMIN_EMAIL`/`ADMIN_PASSWORD` are explicitly set; otherwise a one-time setup-token flow (dashboard `/setup` + unauthenticated `auth/setup` endpoints; `has_secure_token :setup_token` on Store — plaintext like invitation tokens, printed by installer, `spree:setup:token` reprints, cleared on completion — required in EVERY environment; `Spree::Stores::DashboardUrl` is the single resolver for the dashboard origin — used by the setup link, invitation emails and the SSO callback — never a hardcoded port). **App configuration reads ENV:** `RuntimeConfiguration.preference` accepts `env:` (precedence: explicit value → env var → coded default), so deployment settings are configurable without touching Ruby; `dashboard_url` is env-backed via `SPREE_DASHBOARD_URL` and `admin_url` is deprecated in its favour. Applies to `Spree::Config` only — per-store behavior belongs in Store preferences. creates the first admin and adopts/renames the seeded store. No general store CRUD in the OSS Admin API. **Constraints now:** never assume `current_store == Store.default` in Admin API code; store-touching cache keys include the store id by construction; new scripts pass `ADMIN_EMAIL`/`ADMIN_PASSWORD` explicitly.
- `6.0-tax-provider.md` — Per-Market TaxProvider, replaces TaxRate.adjust + Calculator; TaxRate gets direct country/state FKs (tax decoupled from Zone; Zone model dropped in 6.0 via `6.0-delivery-zones.md`); reference provider: Avalara (decisions.md 2026-07-30)
- `6.0-delivery-rate-provider.md` — Per-DeliveryMethod DeliveryRateProvider wrapping Stock::Estimator (calculators stay — 2026-07-27 reversal), `store_id` on ShippingMethod; monorepo ships one reference multi-carrier provider (**EasyPost** — decisions.md 2026-08-06 reversal: BYOCA fit for larger merchants + only maintained official Ruby SDK; Shippo's ruby gem dead since 2020); method rows stay regional (no cross-market method entity). **Dynamic carrier rates (2026-08-09):** a carrier method is the carrier connection — `estimates(package)` returns one Estimate per service, each becoming its own named DeliveryRate (unique (fulfillment, method) rate index dropped; `DeliveryRate#name` falls back to the method name); `Spree::DeliveryMethodService` rows narrow/rename/mark-up services (no rows = all, method-level markup columns as default); selection + EasyPost label buy key off the selected rate's carrier/service; seeds/sample data reshaped Shopify-style (Domestic + International zones with basic methods)
- `6.0-delivery-zones.md` — Zone → DeliveryZone with postal-code-range/prefix members (country-scoped); owns the full ~183-reference Zone consumer inventory; `Spree::Zone` dropped entirely by end of 6.0 (2026-07-27 — 6.0 is the breaking-change window)
diff --git a/docs/plans/6.0-store-context-and-first-run-setup.md b/docs/plans/6.0-store-context-and-first-run-setup.md
index 6312601117..35273b5071 100644
--- a/docs/plans/6.0-store-context-and-first-run-setup.md
+++ b/docs/plans/6.0-store-context-and-first-run-setup.md
@@ -57,7 +57,9 @@ A `StoreContext` concern in the v3 Admin base controller resolves `current_store
- `GET /api/v3/admin/auth/setup` → `{ "setup_required": true | false }`. True only while zero admin users exist. Safe to expose: it leaks one boolean that is also self-evident from a fresh install.
- `POST /api/v3/admin/auth/setup` → params: `setup_token`, `email`, `password`, `first_name`, `last_name`, `store_name`, optional `currency`/`country_iso`. Guards, in order: admin count is zero; token digest matches. Effects, in one transaction: create the admin user, `add_user` with the `admin` role on the default store, rename/configure the store, delete the setup-token row. Then issue the refresh cookie + JWT exactly like `InvitationAcceptancesController` and return the admin-user payload. Any later call 404s (setup no longer required).
-**Setup token mechanics.** The token is a `has_secure_token :setup_token` on `Spree::Store` — generated when the seed creates the default store, so a repeated `db:seed` reprints the same URL (`{admin_url}/setup?token=<token>`). `bin/rails spree:setup:token` prints the current link (generating one for stores predating the column; `ROTATE=1` rotates). The setup endpoint compares with `secure_compare` behind the zero-admins gate and clears the token when setup completes, so the flow is dead on every install that seeds credentials explicitly. Plaintext at rest, deliberately — the same posture as invitation tokens, and the token only works while the database contains nothing but seed data.
+**Setup token mechanics.** The token is a `has_secure_token :setup_token` on `Spree::Store` — generated when the seed creates the default store, so a repeated `db:seed` reprints the same URL. `Store#setup_url` builds it on top of `Spree::Stores::DashboardUrl`, the single resolver for "where is the dashboard" now shared by the setup link, invitation emails and the SSO callback: `Spree::Config[:dashboard_url]` (env-backed, see below) → the deprecated `admin_url` → the Vite dev server in development → the store's own URL.
+
+**App configuration reads the environment (2026-08-13).** `RuntimeConfiguration.preference` takes an `env:` option, so an app-level setting can be configured from the deployment environment instead of Ruby, with precedence explicit value → env var → coded default. `dashboard_url` is the first adopter (`SPREE_DASHBOARD_URL`) because the setup link is printed by `db:seed`, before anyone can reach a console to set a preference, and every worktree and container has a different dashboard origin (worktree provisioning writes it into `server/.env`). `admin_url` is deprecated in its favour — both named the same origin, and the split was a legacy-admin artifact. The option is deliberately limited to `Spree::Config`; per-store behavior belongs in Store preferences, which one global env var cannot express. `bin/rails spree:setup:token` prints the current link (generating one for stores predating the column; `ROTATE=1` rotates). The setup endpoint compares with `secure_compare` behind the zero-admins gate and clears the token when setup completes, so the flow is dead on every install that seeds credentials explicitly. Plaintext at rest, deliberately — the same posture as invitation tokens, and the token only works while the database contains nothing but seed data.
**Dashboard.** A fifth unauthenticated route, `/setup`: reads `?token=`, calls the lookup endpoint, renders the account + store form (same form/error conventions as invitation acceptance), and on success lands in `/$storeId`. The login page checks `setup_required` and links to `/setup` when true (covering the "opened /login first" path — they'll still need the token from the install output).
diff --git a/scripts/worktree/setup.sh b/scripts/worktree/setup.sh
index 3a86e763ca..18eac605bb 100755
--- a/scripts/worktree/setup.sh
+++ b/scripts/worktree/setup.sh
@@ -23,9 +23,16 @@ SPREE_PATH=$(pwd)
SECRET_KEY_BASE=$(openssl rand -hex 64)
DATABASE_NAME=$(db_name)
DATABASE_NAME_TEST=$(test_db_name)
+SPREE_DASHBOARD_URL=$(dashboard_url)
EOF
fi
+# Backfill for worktrees provisioned before this line existed — the seed's
+# first-run setup link is built from it.
+if ! grep -q '^SPREE_DASHBOARD_URL=' server/.env; then
+ printf 'SPREE_DASHBOARD_URL=%s\n' "$(dashboard_url)" >> server/.env
+fi
+
require_current_starter
if ! db_exists "$(db_name)"; then
diff --git a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
index e3a4dd12e8..d70757801e 100644
--- a/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/admin/auth_controller.rb
@@ -179,14 +179,9 @@ module Spree
redirect_to target, allow_other_host: true
end
- # Where the React dashboard is hosted. Falls back to the Vite dev server
- # in development, then to the store's own URL.
+ # Where the React dashboard is hosted.
def dashboard_url
- base = Spree::Config[:dashboard_url].presence ||
- (Rails.env.development? ? 'http://localhost:5173' : nil) ||
- current_store&.formatted_url
-
- base.to_s.chomp('/')
+ Spree::Stores::DashboardUrl.call(store: current_store)
end
# A technical SSO failure (missing code, token verification) must not be
diff --git a/spree/api/app/serializers/spree/api/v3/admin/invitation_serializer.rb b/spree/api/app/serializers/spree/api/v3/admin/invitation_serializer.rb
index 9a1c65cd9e..42916a2324 100644
--- a/spree/api/app/serializers/spree/api/v3/admin/invitation_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/admin/invitation_serializer.rb
@@ -34,10 +34,10 @@ module Spree
invitation.inviter.email
end
- # Absolute URL when `Spree::Config[:admin_url]` is set, otherwise
- # the path so the SPA can prepend `window.location.origin`.
+ # Absolute URL when a dashboard origin is configured, otherwise the
+ # path so the SPA can prepend `window.location.origin`.
attribute :acceptance_url do |invitation|
- if Spree::Config[:admin_url].present?
+ if Spree::Config[:dashboard_url].present?
Rails.application.routes.url_helpers.admin_invitation_acceptance_url(invitation)
else
"/accept-invitation/#{invitation.prefixed_id}?token=#{invitation.token}"
diff --git a/spree/core/app/finders/spree/stores/dashboard_url.rb b/spree/core/app/finders/spree/stores/dashboard_url.rb
new file mode 100644
index 0000000000..e03251d809
--- /dev/null
+++ b/spree/core/app/finders/spree/stores/dashboard_url.rb
@@ -0,0 +1,34 @@
+module Spree
+ module Stores
+ # Origin where the React dashboard is hosted, for every link that sends
+ # someone into it: invitation emails, the SSO callback, the first-run
+ # setup link.
+ #
+ # Configure it with the SPREE_DASHBOARD_URL environment variable (read
+ # through the `dashboard_url` preference). The fallbacks exist so links
+ # still work in dev and on installs that never set it — the Vite dev
+ # server in development, then the store's own URL — but neither is a
+ # substitute for configuring the real origin in production.
+ class DashboardUrl
+ # @param store [Spree::Store, nil] store whose URL ends the fallback chain
+ # @return [String] origin without a trailing slash, e.g. +https://admin.shop.com+
+ def self.call(store: nil)
+ base = Spree::Config[:dashboard_url].presence ||
+ legacy_admin_url ||
+ (Rails.env.development? ? 'http://localhost:5173' : nil) ||
+ store&.formatted_url
+
+ base.to_s.chomp('/')
+ end
+
+ # Reads the deprecated `admin_url` without tripping its warning on every
+ # link — the warning belongs to whoever set it, and Spree::Config[] would
+ # emit one per call here.
+ # @return [String, nil]
+ def self.legacy_admin_url
+ Spree::Config.admin_url.presence
+ end
+ private_class_method :legacy_admin_url
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/store.rb b/spree/core/app/models/spree/store.rb
index 83bfcc4222..da8fa24033 100644
--- a/spree/core/app/models/spree/store.rb
+++ b/spree/core/app/models/spree/store.rb
@@ -221,19 +221,12 @@ module Spree
has_secure_token :setup_token
# Link that claims this installation: the dashboard's first-run setup
- # screen with the store's token. Resolves the dashboard origin the same
- # way the SSO callback does — configured origin, the Vite dev server in
- # development, then the store's own URL — so a production install without
- # `dashboard_url` set never advertises a localhost port.
+ # screen with the store's token.
# @return [String, nil] nil when no token is outstanding
def setup_url
return if setup_token.blank?
- base = Spree::Config[:dashboard_url].presence ||
- (Rails.env.development? ? 'http://localhost:5173' : nil) ||
- formatted_url
-
- "#{base.to_s.chomp('/')}/setup?token=#{setup_token}"
+ "#{Spree::Stores::DashboardUrl.call(store: self)}/setup?token=#{setup_token}"
end
#
diff --git a/spree/core/config/routes.rb b/spree/core/config/routes.rb
index 65853fecef..d608e52781 100644
--- a/spree/core/config/routes.rb
+++ b/spree/core/config/routes.rb
@@ -43,11 +43,9 @@ Rails.application.routes.draw do
# Used by admin mailers; the SPA derives the URL from `window.location.origin` instead.
direct :admin_invitation_acceptance do |invitation, _options = {}|
path = "/accept-invitation/#{invitation.prefixed_id}?token=#{invitation.token}"
- base = Spree::Config[:admin_url].presence ||
- (Rails.env.development? ? 'http://localhost:5173' : nil) ||
- invitation.store&.formatted_url
+ base = Spree::Stores::DashboardUrl.call(store: invitation.store)
- base.present? ? "#{base.chomp('/')}#{path}" : path
+ base.present? ? "#{base}#{path}" : path
end
end
diff --git a/spree/core/lib/spree/core/configuration.rb b/spree/core/lib/spree/core/configuration.rb
index 6640a2f70c..5710c17476 100644
--- a/spree/core/lib/spree/core/configuration.rb
+++ b/spree/core/lib/spree/core/configuration.rb
@@ -25,14 +25,14 @@ module Spree
# Alphabetized to more easily lookup particular preferences
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.
- preference :admin_url, :string, default: nil
- # Origin where the React dashboard is hosted (e.g. `https://dashboard.shop.com`).
- # 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 :admin_url, :string, default: nil, deprecated: 'Use dashboard_url (or the SPREE_DASHBOARD_URL environment variable) instead — both name the origin where the dashboard is hosted.'
+ # Origin where the React dashboard is hosted (e.g. `https://dashboard.shop.com`),
+ # used for every link that sends someone into the dashboard: invitation
+ # emails, the SSO callback, and the first-run setup link. Set
+ # SPREE_DASHBOARD_URL in the environment rather than editing an
+ # initializer — the setup link is printed by `db:seed`, before there is
+ # any way to configure a running app.
+ preference :dashboard_url, :string, default: nil, env: 'SPREE_DASHBOARD_URL'
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: false
preference :allow_guest_checkout, :boolean, default: true, deprecated: true # this is only used in the rails frontend, and is not implemented in API
diff --git a/spree/core/lib/spree/core/preferences/runtime_configuration.rb b/spree/core/lib/spree/core/preferences/runtime_configuration.rb
index 3bee4b6c26..9136677594 100644
--- a/spree/core/lib/spree/core/preferences/runtime_configuration.rb
+++ b/spree/core/lib/spree/core/preferences/runtime_configuration.rb
@@ -40,8 +40,15 @@ module Spree
# Seeding defaults writes every preference, including the deprecated
# ones, so it goes straight to the accessor — warning on boot would fire
# for settings the application never touches.
+ #
+ # Env-backed settings are seeded with nil rather than their coded
+ # default: the reader treats a set value as an explicit choice, so
+ # writing the default here would shadow the environment. Their default
+ # applies in the reader instead.
def load_defaults
- self.class.defaults.each { |key, value| send("#{key}=", value) }
+ self.class.defaults.each do |key, value|
+ send("#{key}=", self.class.env_vars.key?(key) ? nil : value)
+ end
end
def warn_if_deprecated(preference)
@@ -54,10 +61,34 @@ module Spree
end
class << self
- def preference(name, _type, default: nil, deprecated: false)
+ # Application-level settings (as opposed to store preferences, which
+ # belong on Spree::Store). Passing +env+ lets an operator configure the
+ # setting from the deployment environment instead of Ruby — the
+ # supported path for anything infrastructural, since editing an
+ # initializer means a code change and a deploy.
+ #
+ # Precedence is explicit value → env var → coded default, so a value
+ # set in an initializer or at runtime always wins over the
+ # environment; the env var only fills an unset preference.
+ #
+ # @param env [String, nil] environment variable backing this setting
+ def preference(name, _type, default: nil, deprecated: false, env: nil)
defaults[name] = default
deprecations[name] = deprecated
- attr_accessor name
+ env_vars[name] = env if env
+
+ attr_writer name
+
+ if env
+ define_method(name) do
+ value = instance_variable_get("@#{name}")
+ return value unless value.nil?
+
+ ENV[env].presence || default
+ end
+ else
+ attr_reader name
+ end
end
def defaults
@@ -67,6 +98,11 @@ module Spree
def deprecations
@deprecations ||= {}
end
+
+ # @return [Hash{Symbol => String}] preferences backed by an env var
+ def env_vars
+ @env_vars ||= {}
+ end
end
end
end
diff --git a/spree/core/spec/finders/spree/stores/dashboard_url_spec.rb b/spree/core/spec/finders/spree/stores/dashboard_url_spec.rb
new file mode 100644
index 0000000000..548a15e594
--- /dev/null
+++ b/spree/core/spec/finders/spree/stores/dashboard_url_spec.rb
@@ -0,0 +1,39 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Stores::DashboardUrl do
+ subject { described_class.call(store: store) }
+
+ let(:store) { build(:store, url: 'shop.example.com') }
+
+ context 'with the dashboard_url preference set' do
+ before { Spree::Config.dashboard_url = 'https://admin.example.com/' }
+ after { Spree::Config.dashboard_url = nil }
+
+ it { is_expected.to eq('https://admin.example.com') }
+ end
+
+ context 'with SPREE_DASHBOARD_URL set' do
+ before { stub_const('ENV', ENV.to_h.merge('SPREE_DASHBOARD_URL' => 'https://admin.worktree.localhost')) }
+
+ it { is_expected.to eq('https://admin.worktree.localhost') }
+ end
+
+ context 'with only the deprecated admin_url set' do
+ before { Spree::Config.admin_url = 'https://legacy.example.com' }
+ after { Spree::Config.admin_url = nil }
+
+ it { is_expected.to eq('https://legacy.example.com') }
+ end
+
+ context 'with nothing configured outside development' do
+ before do
+ stub_const('ENV', ENV.to_h.except('SPREE_DASHBOARD_URL'))
+ allow(Rails.env).to receive(:development?).and_return(false)
+ end
+
+ it "falls back to the store's own URL, never a dev port" do
+ expect(subject).to eq(store.formatted_url)
+ expect(subject).not_to include('localhost:5173')
+ end
+ end
+end
diff --git a/spree/core/spec/lib/spree/core/preferences/runtime_configuration_spec.rb b/spree/core/spec/lib/spree/core/preferences/runtime_configuration_spec.rb
new file mode 100644
index 0000000000..4196e95b39
--- /dev/null
+++ b/spree/core/spec/lib/spree/core/preferences/runtime_configuration_spec.rb
@@ -0,0 +1,46 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Preferences::RuntimeConfiguration do
+ # App-level settings can be backed by an environment variable so operators
+ # configure a deployment without editing Ruby.
+ let(:configuration_class) do
+ Class.new(described_class) do
+ preference :plain_setting, :string, default: 'coded'
+ preference :env_setting, :string, default: 'coded', env: 'SPREE_SPEC_ENV_SETTING'
+ end
+ end
+
+ subject(:configuration) { configuration_class.new }
+
+ context 'when the environment variable is set' do
+ before { stub_const('ENV', ENV.to_h.merge('SPREE_SPEC_ENV_SETTING' => 'from-env')) }
+
+ it 'reads the environment over the coded default' do
+ expect(configuration[:env_setting]).to eq('from-env')
+ end
+
+ it 'still prefers an explicitly assigned value' do
+ configuration.env_setting = 'explicit'
+
+ expect(configuration[:env_setting]).to eq('explicit')
+ end
+
+ it 'leaves settings without an env option alone' do
+ expect(configuration[:plain_setting]).to eq('coded')
+ end
+ end
+
+ context 'when the environment variable is absent' do
+ before { stub_const('ENV', ENV.to_h.except('SPREE_SPEC_ENV_SETTING')) }
+
+ it 'falls back to the coded default' do
+ expect(configuration[:env_setting]).to eq('coded')
+ end
+
+ it 'treats a blank value as unset' do
+ stub_const('ENV', ENV.to_h.merge('SPREE_SPEC_ENV_SETTING' => ''))
+
+ expect(configuration[:env_setting]).to eq('coded')
+ end
+ end
+end
diff --git a/spree/core/spec/models/spree/store_spec.rb b/spree/core/spec/models/spree/store_spec.rb
index 70df660c11..f419406deb 100644
--- a/spree/core/spec/models/spree/store_spec.rb
+++ b/spree/core/spec/models/spree/store_spec.rb
@@ -310,19 +310,11 @@ describe Spree::Store, type: :model, without_global_store: true do
let(:store) { create(:store, url: 'shop.example.com') }
it 'points at the configured dashboard origin' do
- allow(Spree::Config).to receive(:[]).with(:dashboard_url).and_return('https://admin.example.com')
+ allow(Spree::Stores::DashboardUrl).to receive(:call).and_return('https://admin.example.com')
expect(store.setup_url).to eq("https://admin.example.com/setup?token=#{store.setup_token}")
end
- it "falls back to the store's own URL rather than a dev port" do
- allow(Spree::Config).to receive(:[]).with(:dashboard_url).and_return(nil)
- allow(Rails.env).to receive(:development?).and_return(false)
-
- expect(store.setup_url).to start_with(store.formatted_url)
- expect(store.setup_url).not_to include('localhost:5173')
- end
-
it 'is nil once the token is spent' do
store.update!(setup_token: nil)