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.

Fixed setting currency and locale in API v3 with Markets (#13664)

Damian Legawiec28207ce87f7b
diff --git a/spree/api/app/controllers/concerns/spree/api/v3/locale_and_currency.rb b/spree/api/app/controllers/concerns/spree/api/v3/locale_and_currency.rb
index c8f639fd8f..b6fe348090 100644
--- a/spree/api/app/controllers/concerns/spree/api/v3/locale_and_currency.rb
+++ b/spree/api/app/controllers/concerns/spree/api/v3/locale_and_currency.rb
@@ -1,60 +1,172 @@
module Spree
module Api
module V3
+ # Handles locale, currency, and market resolution for API v3 controllers.
+ #
+ # This concern is fully self-contained and does not depend on
+ # +Spree::Core::ControllerHelpers::Locale+ or +Spree::Core::ControllerHelpers::Currency+.
+ #
+ # Resolution order:
+ # 1. Market is resolved from +x-spree-country+ header (sets +Spree::Current.market+)
+ # 2. Locale is resolved: +x-spree-locale+ header > +params[:locale]+ > +Spree::Current.locale+ (market -> store fallback)
+ # 3. Currency is resolved: +x-spree-currency+ header > +params[:currency]+ > +Spree::Current.currency+ (market -> store fallback)
+ # 4. Mobility fallback locale is configured for the current store
module LocaleAndCurrency
extend ActiveSupport::Concern
included do
before_action :set_market_from_country
- before_action :set_locale_from_header
- before_action :set_currency_from_header
+ before_action :set_locale
+ before_action :set_currency
+ before_action :set_fallback_locale
end
protected
- # Override current_locale to check header first
+ # Returns the current locale for this request.
+ #
+ # Priority: x-spree-locale header > params[:locale] > Spree::Current.locale (market -> store fallback)
+ #
+ # @return [String] the locale code, e.g. +"en"+, +"fr"+
def current_locale
@current_locale ||= begin
- locale = locale_from_header || locale_from_params || default_locale
- locale.to_s if supported_locale?(locale)
- end || default_locale
+ locale = locale_from_header || locale_from_params
+ locale.to_s if locale.present? && supported_locale?(locale)
+ end || Spree::Current.locale
end
- # Override current_currency to check header first
+ # Returns the current currency for this request.
+ #
+ # Priority: x-spree-currency header > params[:currency] > Spree::Current.currency (market -> store fallback)
+ #
+ # @return [String] the currency ISO code, e.g. +"USD"+, +"EUR"+
def current_currency
@current_currency ||= begin
- currency = currency_from_header || currency_from_params || current_store&.default_currency
+ currency = currency_from_header || currency_from_params
currency = currency&.upcase
- supported_currency?(currency) ? currency : current_store&.default_currency
+ currency if currency.present? && supported_currency?(currency)
+ end || Spree::Current.currency
+ end
+
+ # Returns the default locale, delegating to +Spree::Current.locale+
+ # which falls back through market -> store.
+ #
+ # @return [String] the default locale code
+ def default_locale
+ Spree::Current.locale
+ end
+
+ # Returns the list of supported locale codes for the current store.
+ #
+ # When markets are configured, this aggregates locales from all markets.
+ #
+ # @return [Array<String>] supported locale codes
+ def supported_locales
+ @supported_locales ||= current_store&.supported_locales_list
+ end
+
+ # Checks if the given locale is supported by the current store.
+ #
+ # @param locale_code [String, nil] the locale code to check
+ # @return [Boolean]
+ def supported_locale?(locale_code)
+ return false if supported_locales.nil?
+
+ supported_locales.include?(locale_code&.to_s)
+ end
+
+ # Returns the list of supported currencies for the current store.
+ #
+ # When markets are configured, this aggregates currencies from all markets.
+ #
+ # @return [Array<Money::Currency>] supported currencies
+ def supported_currencies
+ @supported_currencies ||= current_store&.supported_currencies_list
+ end
+
+ # Checks if the given currency ISO code is supported by the current store.
+ #
+ # @param currency_iso_code [String, nil] the currency ISO code to check, e.g. +"USD"+
+ # @return [Boolean]
+ def supported_currency?(currency_iso_code)
+ return false if supported_currencies.nil?
+
+ supported_currencies.map(&:iso_code).include?(currency_iso_code&.upcase)
+ end
+
+ # Finds a record using the given block, falling back to the store's default locale
+ # if the record is not found in the current locale.
+ #
+ # Used for slug/permalink lookups where translated slugs may not exist in all locales.
+ #
+ # @yield the block that performs the lookup
+ # @return [ActiveRecord::Base] the found record
+ # @raise [ActiveRecord::RecordNotFound] if not found in any locale
+ def find_with_fallback_default_locale(&block)
+ result = begin
+ block.call
+ rescue ActiveRecord::RecordNotFound => _e
+ nil
end
+
+ result || Mobility.with_locale(current_store.default_locale) { block.call }
end
private
- def set_locale_from_header
+ # Sets +I18n.locale+ and +Spree::Current.locale+ from the resolved locale.
+ def set_locale
+ Spree::Current.locale = current_locale
I18n.locale = current_locale
end
- def set_currency_from_header
+ # Sets +Spree::Current.currency+ from the resolved currency.
+ def set_currency
Spree::Current.currency = current_currency
end
+ # Configures Mobility fallback locales for the current store.
+ #
+ # This runs after market resolution so fallbacks are aware of the store's
+ # full locale configuration.
+ def set_fallback_locale
+ return unless current_store.present?
+
+ Spree::Locales::SetFallbackLocaleForStore.new.call(store: current_store)
+ end
+
+ # Reads the locale from the +x-spree-locale+ request header.
+ #
+ # @return [String, nil]
def locale_from_header
request.headers['x-spree-locale'].presence
end
+ # Reads the currency from the +x-spree-currency+ request header.
+ #
+ # @return [String, nil]
def currency_from_header
request.headers['x-spree-currency'].presence
end
+ # Reads the locale from request params.
+ #
+ # @return [String, nil]
def locale_from_params
params[:locale].presence
end
+ # Reads the currency from request params.
+ #
+ # @return [String, nil]
def currency_from_params
params[:currency].presence
end
+ # Resolves the market from the +x-spree-country+ header or +params[:country]+.
+ #
+ # When a matching market is found, it is set on +Spree::Current.market+,
+ # which influences the default locale and currency fallbacks.
def set_market_from_country
country_iso = request.headers['x-spree-country'].presence || params[:country].presence
return unless country_iso
diff --git a/spree/api/app/controllers/spree/api/v3/base_controller.rb b/spree/api/app/controllers/spree/api/v3/base_controller.rb
index 4dc3cb95bb..77cc4ba4aa 100644
--- a/spree/api/app/controllers/spree/api/v3/base_controller.rb
+++ b/spree/api/app/controllers/spree/api/v3/base_controller.rb
@@ -6,8 +6,6 @@ module Spree
include CanCan::ControllerAdditions
include Spree::Core::ControllerHelpers::StrongParameters
include Spree::Core::ControllerHelpers::Store
- include Spree::Core::ControllerHelpers::Locale
- include Spree::Core::ControllerHelpers::Currency
include Spree::Api::V3::LocaleAndCurrency
include Spree::Api::V3::JwtAuthentication
include Spree::Api::V3::ApiKeyAuthentication
@@ -22,6 +20,7 @@ module Spree
protected
# Override to use current_user from JWT authentication
+ # @return [Spree.user_class]
def spree_current_user
current_user
end
@@ -29,10 +28,13 @@ module Spree
alias try_spree_current_user spree_current_user
# CanCanCan ability
+ # @return [Spree::Ability]
def current_ability
@current_ability ||= Spree::Ability.new(current_user, ability_options)
end
+ # Options passed to the CanCanCan ability
+ # @return [Hash]
def ability_options
{ store: current_store }
end
diff --git a/spree/api/spec/controllers/concerns/spree/api/v3/locale_and_currency_spec.rb b/spree/api/spec/controllers/concerns/spree/api/v3/locale_and_currency_spec.rb
new file mode 100644
index 0000000000..5c1644ffb0
--- /dev/null
+++ b/spree/api/spec/controllers/concerns/spree/api/v3/locale_and_currency_spec.rb
@@ -0,0 +1,147 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Api::V3::Store::ProductsController, type: :controller do
+ render_views
+
+ include_context 'API v3 Store'
+
+ let!(:product) { create(:product, stores: [store], status: 'active') }
+
+ before do
+ request.headers['X-Spree-Api-Key'] = api_key.token
+ end
+
+ after do
+ I18n.locale = :en
+ end
+
+ describe 'Spree::Api::V3::LocaleAndCurrency' do
+ describe 'locale resolution' do
+ before do
+ allow(store).to receive(:supported_locales_list).and_return(%w[en fr de])
+ allow(store).to receive(:default_locale).and_return('en')
+ end
+
+ it 'sets locale from x-spree-locale header' do
+ request.headers['x-spree-locale'] = 'fr'
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(I18n.locale).to eq(:fr)
+ end
+
+ it 'sets locale from params' do
+ get :index, params: { locale: 'fr' }
+
+ expect(response).to have_http_status(:ok)
+ expect(I18n.locale).to eq(:fr)
+ end
+
+ it 'prefers header over params' do
+ request.headers['x-spree-locale'] = 'de'
+ get :index, params: { locale: 'fr' }
+
+ expect(response).to have_http_status(:ok)
+ expect(I18n.locale).to eq(:de)
+ end
+
+ it 'falls back to store default locale for unsupported locale' do
+ request.headers['x-spree-locale'] = 'ja'
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(I18n.locale).to eq(:en)
+ end
+
+ it 'falls back to store default locale when no locale specified' do
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(I18n.locale).to eq(:en)
+ end
+
+ it 'resolves current_locale correctly' do
+ request.headers['x-spree-locale'] = 'fr'
+ get :index
+
+ expect(controller.send(:current_locale)).to eq('fr')
+ end
+ end
+
+ describe 'currency resolution' do
+ before do
+ allow(store).to receive(:supported_currencies_list).and_return(
+ [Money::Currency.find('USD'), Money::Currency.find('EUR')]
+ )
+ allow(store).to receive(:default_currency).and_return('USD')
+ end
+
+ it 'sets currency from x-spree-currency header' do
+ request.headers['x-spree-currency'] = 'EUR'
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(controller.send(:current_currency)).to eq('EUR')
+ end
+
+ it 'sets currency from params' do
+ get :index, params: { currency: 'EUR' }
+
+ expect(response).to have_http_status(:ok)
+ expect(controller.send(:current_currency)).to eq('EUR')
+ end
+
+ it 'falls back to store default currency for unsupported currency' do
+ request.headers['x-spree-currency'] = 'GBP'
+ get :index
+
+ expect(response).to have_http_status(:ok)
+ expect(controller.send(:current_currency)).to eq('USD')
+ end
+ end
+
+ describe 'market-aware locale resolution' do
+ let!(:germany) { create(:country, iso: 'DE', name: 'Germany') }
+ let!(:eu_market) { create(:market, store: store, name: 'Europe', default_locale: 'de', currency: 'EUR', countries: [germany]) }
+
+ before do
+ allow(store).to receive(:supported_locales_list).and_return(%w[en de fr])
+ allow(store).to receive(:supported_currencies_list).and_return(
+ [Money::Currency.find('USD'), Money::Currency.find('EUR')]
+ )
+ end
+
+ it 'uses market default locale when no explicit locale is provided' do
+ request.headers['x-spree-country'] = 'DE'
+ get :index
+
+ expect(I18n.locale).to eq(:de)
+ expect(controller.send(:current_locale)).to eq('de')
+ end
+
+ it 'uses market currency when no explicit currency is provided' do
+ request.headers['x-spree-country'] = 'DE'
+ get :index
+
+ expect(controller.send(:current_currency)).to eq('EUR')
+ end
+
+ it 'explicit locale header overrides market default locale' do
+ request.headers['x-spree-country'] = 'DE'
+ request.headers['x-spree-locale'] = 'fr'
+ get :index
+
+ expect(I18n.locale).to eq(:fr)
+ expect(controller.send(:current_locale)).to eq('fr')
+ end
+
+ it 'explicit currency header overrides market currency' do
+ request.headers['x-spree-country'] = 'DE'
+ request.headers['x-spree-currency'] = 'USD'
+ get :index
+
+ expect(controller.send(:current_currency)).to eq('USD')
+ end
+ end
+ end
+end
diff --git a/spree/core/app/models/spree/current.rb b/spree/core/app/models/spree/current.rb
index 594199489d..2939af21bc 100644
--- a/spree/core/app/models/spree/current.rb
+++ b/spree/core/app/models/spree/current.rb
@@ -1,23 +1,45 @@
module Spree
+ # Thread-safe, per-request attributes for the current store context.
+ #
+ # All attributes are automatically reset between requests by Rails.
+ # Fallback chains ensure sensible defaults when attributes are not explicitly set.
class Current < ::ActiveSupport::CurrentAttributes
- attribute :store, :market, :currency, :zone, :price_lists, :global_pricing_context
+ attribute :store, :market, :currency, :locale, :zone, :price_lists, :global_pricing_context
+ # Returns the current store, falling back to the default store.
+ # @return [Spree::Store]
def store
super || Spree::Store.default
end
+ # Returns the current market, falling back to the store's default market.
+ # @return [Spree::Market, nil]
def market
super || store&.default_market
end
+ # Returns the current currency.
+ # Fallback: market currency -> store default currency.
+ # @return [String] currency ISO code, e.g. +"USD"+
def currency
super || market&.currency || store&.default_currency
end
+ # Returns the current locale.
+ # Fallback: market default locale -> store default locale.
+ # @return [String] locale code, e.g. +"en"+, +"de"+
+ def locale
+ super || market&.default_locale || store&.default_locale
+ end
+
+ # Returns the current tax zone, falling back to the default tax zone.
+ # @return [Spree::Zone, nil]
def zone
super || Spree::Zone.default_tax
end
+ # Returns the current price lists for the global pricing context.
+ # @return [ActiveRecord::Relation<Spree::PriceList>]
def price_lists
super || begin
context = global_pricing_context
@@ -25,6 +47,8 @@ module Spree
end
end
+ # Returns the current global pricing context, built from store, currency, zone, and market.
+ # @return [Spree::Pricing::Context]
def global_pricing_context
super || begin
self.global_pricing_context = Spree::Pricing::Context.new(
diff --git a/spree/core/spec/models/spree/current_spec.rb b/spree/core/spec/models/spree/current_spec.rb
index 16f970cf3f..d97c7c4d53 100644
--- a/spree/core/spec/models/spree/current_spec.rb
+++ b/spree/core/spec/models/spree/current_spec.rb
@@ -72,6 +72,33 @@ RSpec.describe Spree::Current do
end
end
+ describe '#locale' do
+ context 'when locale is set' do
+ before { described_class.locale = 'fr' }
+
+ it 'returns the set locale' do
+ expect(described_class.locale).to eq('fr')
+ end
+ end
+
+ context 'when locale is not set but market has a default locale' do
+ let!(:store) { create(:store, default: true, default_locale: 'en') }
+ let!(:market) { create(:market, store: store, default: true, default_locale: 'de') }
+
+ it 'returns the market default locale' do
+ expect(described_class.locale).to eq('de')
+ end
+ end
+
+ context 'when locale is not set and no market exists' do
+ let!(:store) { create(:store, default: true, default_locale: 'en') }
+
+ it 'returns the store default locale' do
+ expect(described_class.locale).to eq('en')
+ end
+ end
+ end
+
describe '#market' do
context 'when market is set' do
let(:market) { create(:market) }