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.

Add the ability for individual staff members to set their preferred local… (#14203)

Damian Legawiecf5e33b97f96a
diff --git a/spree/admin/app/controllers/concerns/spree/admin/locale_concern.rb b/spree/admin/app/controllers/concerns/spree/admin/locale_concern.rb
new file mode 100644
index 0000000000..011813eb86
--- /dev/null
+++ b/spree/admin/app/controllers/concerns/spree/admin/locale_concern.rb
@@ -0,0 +1,47 @@
+module Spree
+ module Admin
+ # Decouples the admin UI language from the store's content language.
+ #
+ # `I18n.locale` drives the UI chrome (`Spree.t` labels) and follows the
+ # staff member's chosen admin language. `Mobility.locale` drives translated
+ # record fields (product/store names) and is pinned to the store's content
+ # locale — otherwise switching the admin to, say, Polish would make every
+ # Mobility-backed field fall back to nil for stores that don't translate
+ # their catalog into Polish.
+ #
+ # Shared by `Spree::Admin::BaseController` and `UserSessionsController`; the
+ # latter subclasses `Devise::SessionsController`, so it can't inherit this
+ # via the controller chain — hence a concern both include.
+ module LocaleConcern
+ extend ActiveSupport::Concern
+
+ # Cookie storing the admin UI language chosen on the login screen, so a
+ # guest's pre-auth selection carries into the authenticated session. A
+ # signed-in user's saved `selected_locale` still takes precedence.
+ ADMIN_LOCALE_COOKIE = :spree_admin_locale
+
+ private
+
+ # Read all record content in the store's content locale, independent of
+ # the chosen UI language.
+ def pin_content_locale!
+ Mobility.locale = current_store&.default_locale.presence || I18n.default_locale
+ end
+
+ def admin_user_selected_locale
+ try_spree_current_user&.selected_locale
+ end
+
+ def admin_locale_cookie
+ cookies[ADMIN_LOCALE_COOKIE]
+ end
+
+ # True when the admin UI is actually translated into +locale+
+ # (`Spree.available_locales`) — distinct from the storefront's
+ # store-scoped `supported_locale?`.
+ def supported_admin_locale?(locale)
+ locale.present? && Spree.available_locales.map(&:to_s).include?(locale.to_s)
+ end
+ end
+ end
+end
diff --git a/spree/admin/app/controllers/spree/admin/base_controller.rb b/spree/admin/app/controllers/spree/admin/base_controller.rb
index e1b373cebe..fc64c6fcd3 100644
--- a/spree/admin/app/controllers/spree/admin/base_controller.rb
+++ b/spree/admin/app/controllers/spree/admin/base_controller.rb
@@ -2,6 +2,7 @@ module Spree
module Admin
class BaseController < Spree::BaseController
include Spree::Admin::BreadcrumbConcern
+ include Spree::Admin::LocaleConcern
layout :choose_layout
default_form_builder Spree::Admin::FormBuilder
@@ -84,6 +85,24 @@ module Spree
@default_locale ||= current_store&.preferred_admin_locale.presence || super
end
+ # Set the UI language (`I18n.locale`, via super) while pinning content
+ # reads to the store's locale — see Spree::Admin::LocaleConcern.
+ def set_locale
+ super
+ pin_content_locale!
+ end
+
+ # Resolve the admin UI locale for the current request. Unlike the
+ # storefront, the admin prefers the signed-in staff member's own saved
+ # `selected_locale` (the language of the back-office chrome), then the
+ # `spree_admin_locale` cookie (the per-browser choice made on the login
+ # screen, which carries from the pre-auth page into the session), then
+ # the store-wide `preferred_admin_locale` via `default_locale`.
+ def current_locale
+ @current_locale ||= [admin_user_selected_locale, admin_locale_cookie].
+ detect { |locale| supported_admin_locale?(locale) } || default_locale
+ end
+
def current_timezone
@current_timezone ||= current_store.preferred_timezone
end
diff --git a/spree/admin/app/controllers/spree/admin/user_sessions_controller.rb b/spree/admin/app/controllers/spree/admin/user_sessions_controller.rb
index 5b21537fd8..93dc2e5f8b 100644
--- a/spree/admin/app/controllers/spree/admin/user_sessions_controller.rb
+++ b/spree/admin/app/controllers/spree/admin/user_sessions_controller.rb
@@ -2,9 +2,20 @@ module Spree
module Admin
class UserSessionsController < defined?(Devise::SessionsController) ? Devise::SessionsController : Spree::Admin::BaseController
include Spree::Admin::AuthRateLimiting
+ include Spree::Admin::LocaleConcern
+
+ helper 'spree/locale'
layout 'spree/minimal'
+ # This controller inherits from Devise::SessionsController, so the
+ # `set_locale` before_action from Spree::Core::ControllerHelpers::Locale
+ # (mixed into Spree::Admin::BaseController) never runs here. Honor the
+ # pre-auth `?locale=` param ourselves so the login screen's language
+ # switcher works before any user is signed in, persisting the choice in a
+ # cookie so it carries into the authenticated session after sign-in.
+ before_action :set_login_locale
+
auth_rate_limit :rate_limit_login, redirect_to: -> { new_session_path(resource_name) }
# We need to overwrite this action because `return_to` url may be in a different domain
@@ -22,6 +33,22 @@ module Spree
def translation_scope
'devise.user_sessions'
end
+
+ private
+
+ def set_login_locale
+ pin_content_locale!
+
+ # A supported `?locale=` is applied and persisted; an unsupported one is
+ # ignored rather than shadowing an already-valid cookie. Falls back to
+ # the cookie set on a previous visit.
+ if supported_admin_locale?(params[:locale])
+ cookies[ADMIN_LOCALE_COOKIE] = { value: params[:locale], expires: 1.year }
+ I18n.locale = params[:locale]
+ elsif supported_admin_locale?(admin_locale_cookie)
+ I18n.locale = admin_locale_cookie
+ end
+ end
end
end
end
diff --git a/spree/admin/app/views/spree/admin/profile/edit.html.erb b/spree/admin/app/views/spree/admin/profile/edit.html.erb
index 312fb04038..c4ee7e26c8 100644
--- a/spree/admin/app/views/spree/admin/profile/edit.html.erb
+++ b/spree/admin/app/views/spree/admin/profile/edit.html.erb
@@ -17,6 +17,9 @@
<%= f.spree_email_field :email, required: true %>
<%= f.spree_text_field :first_name, required: true %>
<%= f.spree_text_field :last_name, required: true %>
+ <%= f.spree_select :selected_locale,
+ options_from_collection_for_select(admin_locales_options, :last, :first, @user.selected_locale || I18n.locale),
+ { label: Spree.t(:language), help_bubble: Spree.t(:admin_language_help), autocomplete: true } %>
<%= f.spree_file_field :avatar, crop: true %>
</div>
</div>
diff --git a/spree/admin/app/views/spree/admin/shared/_head.html.erb b/spree/admin/app/views/spree/admin/shared/_head.html.erb
index 4a3033bad7..cbfd900c7b 100644
--- a/spree/admin/app/views/spree/admin/shared/_head.html.erb
+++ b/spree/admin/app/views/spree/admin/shared/_head.html.erb
@@ -12,7 +12,7 @@
<% if @order.present? && @order.persisted? %><%= @order.number %> - <% end %>
<%= Spree.t(controller_name, default: controller_name.titleize) %>
<% end %>
- <% if defined?(current_store) && current_store.present? %>
+ <% if defined?(current_store) && current_store&.name.present? %>
- <%= current_store.name.capitalize %>
<% end %>
</title>
diff --git a/spree/admin/app/views/spree/admin/user_sessions/new.html.erb b/spree/admin/app/views/spree/admin/user_sessions/new.html.erb
index 4e77b96150..3698561b11 100644
--- a/spree/admin/app/views/spree/admin/user_sessions/new.html.erb
+++ b/spree/admin/app/views/spree/admin/user_sessions/new.html.erb
@@ -14,3 +14,12 @@
<%= turbo_save_button_tag Spree.t(:login), class: 'btn btn-primary btn-lg w-full' %>
<% end %>
+<% if admin_locales_options.many? %>
+ <%= form_tag new_session_path(resource_name), method: :get, class: 'form-group mt-4', data: { turbo: false } do %>
+ <%= label_tag :locale, Spree.t(:language), class: 'form-label' %>
+ <%= select_tag :locale,
+ options_for_select(admin_locales_options, params[:locale] || I18n.locale.to_s),
+ onchange: 'this.form.requestSubmit()', class: 'form-select' %>
+ <% end %>
+<% end %>
+
diff --git a/spree/admin/spec/controllers/spree/admin/base_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/base_controller_spec.rb
index f797d3a055..7a14b0030f 100644
--- a/spree/admin/spec/controllers/spree/admin/base_controller_spec.rb
+++ b/spree/admin/spec/controllers/spree/admin/base_controller_spec.rb
@@ -63,6 +63,99 @@ describe Spree::Admin::BaseController, type: :controller do
end
end
+ describe '#current_locale' do
+ stub_authorization!
+
+ let(:store) { Spree::Store.default }
+
+ around do |example|
+ original_locale = I18n.locale
+ example.run
+ ensure
+ I18n.locale = original_locale
+ end
+
+ before do
+ allow(controller).to receive(:current_store).and_return(store)
+ allow(store).to receive(:preferred_admin_locale).and_return('en')
+ allow(Spree).to receive(:available_locales).and_return(%i[en de fr])
+ end
+
+ context "when the current user has a selected_locale" do
+ before { allow(controller).to receive(:admin_user_selected_locale).and_return('de') }
+
+ it "uses the user's locale over the store admin locale" do
+ get :index
+ expect(I18n.locale).to eq(:de)
+ end
+ end
+
+ context "when the user's selected_locale is not an available admin locale" do
+ before { allow(controller).to receive(:admin_user_selected_locale).and_return('pl') }
+
+ it 'ignores it and falls back to the store admin locale' do
+ get :index
+ expect(I18n.locale).to eq(:en)
+ end
+ end
+
+ context 'when the user has no selected_locale' do
+ before { allow(controller).to receive(:admin_user_selected_locale).and_return(nil) }
+
+ it 'honors the admin locale cookie (set on the login screen)' do
+ request.cookies[Spree::Admin::LocaleConcern::ADMIN_LOCALE_COOKIE.to_s] = 'fr'
+ get :index
+ expect(I18n.locale).to eq(:fr)
+ end
+
+ it 'ignores an unsupported cookie value' do
+ request.cookies[Spree::Admin::LocaleConcern::ADMIN_LOCALE_COOKIE.to_s] = 'pl'
+ get :index
+ expect(I18n.locale).to eq(:en)
+ end
+
+ it 'falls back to the store admin locale when no cookie is set' do
+ get :index
+ expect(I18n.locale).to eq(:en)
+ end
+ end
+ end
+
+ describe '#set_locale (UI vs content locale decoupling)' do
+ stub_authorization!
+
+ let(:store) { Spree::Store.default }
+
+ around do |example|
+ original_i18n = I18n.locale
+ original_mobility = Mobility.locale
+ example.run
+ ensure
+ I18n.locale = original_i18n
+ Mobility.locale = original_mobility
+ end
+
+ before do
+ allow(controller).to receive(:current_store).and_return(store)
+ # Store content locale (fr) is deliberately distinct from both the chosen
+ # UI locale (de) and the app default (en), so only the explicit Mobility
+ # pin can produce it — guarding against a coincidental pass.
+ allow(store).to receive_messages(preferred_admin_locale: 'en', default_locale: 'fr')
+ allow(Spree).to receive(:available_locales).and_return(%i[en de fr])
+ allow(controller).to receive(:admin_user_selected_locale).and_return('de')
+ end
+
+ it 'sets the UI locale (I18n) to the selected admin language' do
+ get :index
+ expect(I18n.locale).to eq(:de)
+ end
+
+ it "pins the content locale (Mobility) to the store's content locale, not the UI locale" do
+ get :index
+ expect(Mobility.locale).to eq(:fr)
+ end
+ end
+
describe '#redirect_unauthorized_access' do
controller(AdminFakesController) do
def index
diff --git a/spree/admin/spec/controllers/spree/admin/user_sessions_controller_spec.rb b/spree/admin/spec/controllers/spree/admin/user_sessions_controller_spec.rb
new file mode 100644
index 0000000000..19ef016b06
--- /dev/null
+++ b/spree/admin/spec/controllers/spree/admin/user_sessions_controller_spec.rb
@@ -0,0 +1,79 @@
+require 'spec_helper'
+
+describe Spree::Admin::UserSessionsController, type: :controller do
+ # The real Devise sign-in routes are mounted by the host-app auth installer,
+ # not the admin engine's dummy app. Expose a routable action here so we can
+ # drive the `set_login_locale` before_action through a real request and
+ # assert on the response cookie + I18n.locale.
+ stub_authorization!
+
+ controller(described_class) do
+ # In the engine's dummy app Devise isn't loaded, so this controller falls
+ # back to Spree::Admin::BaseController, which brings the inherited
+ # `set_locale` before_action. Skip it so `set_login_locale` is the only
+ # locale setter under test — matching production, where the Devise parent
+ # has no such before_action.
+ skip_before_action :set_locale, raise: false
+
+ def show
+ render plain: "#{I18n.locale}/#{Mobility.locale}"
+ end
+ end
+
+ before do
+ routes.draw { get 'show' => 'spree/admin/user_sessions#show' }
+ @request.env['devise.mapping'] = Devise.mappings.values.first if defined?(Devise)
+ allow(Spree).to receive(:available_locales).and_return(%i[en de fr])
+ end
+
+ let(:cookie_key) { Spree::Admin::LocaleConcern::ADMIN_LOCALE_COOKIE }
+
+ # Response body is "<I18n.locale>/<Mobility.locale>" — the UI locale and the
+ # pinned content locale, so each test asserts the decoupling.
+ let(:ui_locale) { response.body.split('/').first }
+ let(:content_locale) { response.body.split('/').last }
+
+ around do |example|
+ original_i18n = I18n.locale
+ original_mobility = Mobility.locale
+ example.run
+ ensure
+ I18n.locale = original_i18n
+ Mobility.locale = original_mobility
+ end
+
+ context 'with a supported ?locale= param' do
+ it 'applies the UI locale and persists it to the cookie' do
+ get :show, params: { locale: 'de' }
+ expect(ui_locale).to eq('de')
+ expect(response.cookies[cookie_key.to_s]).to eq('de')
+ end
+
+ it "keeps the content locale (Mobility) on the store's content locale" do
+ get :show, params: { locale: 'de' }
+ expect(content_locale).not_to eq('de')
+ end
+ end
+
+ context 'with an unsupported ?locale= param' do
+ it 'ignores it' do
+ get :show, params: { locale: 'pl' }
+ expect(ui_locale).not_to eq('pl')
+ expect(response.cookies[cookie_key.to_s]).to be_nil
+ end
+
+ it 'falls back to a valid cookie rather than shadowing it' do
+ request.cookies[cookie_key.to_s] = 'fr'
+ get :show, params: { locale: 'pl' }
+ expect(ui_locale).to eq('fr')
+ end
+ end
+
+ context 'with the cookie already set and no param (post-redirect into the session)' do
+ it 'applies the cookie locale' do
+ request.cookies[cookie_key.to_s] = 'fr'
+ get :show
+ expect(ui_locale).to eq('fr')
+ end
+ end
+end
diff --git a/spree/admin/spec/views/spree/admin/shared/_head.html.erb_spec.rb b/spree/admin/spec/views/spree/admin/shared/_head.html.erb_spec.rb
new file mode 100644
index 0000000000..88f93583a0
--- /dev/null
+++ b/spree/admin/spec/views/spree/admin/shared/_head.html.erb_spec.rb
@@ -0,0 +1,30 @@
+require 'spec_helper'
+
+describe 'spree/admin/shared/_head.html.erb', type: :view do
+ let(:store) { build_stubbed(:store) }
+
+ before do
+ allow(view).to receive(:current_store).and_return(store)
+ allow(view).to receive(:controller_name).and_return('dashboard')
+ end
+
+ # Regression: store name fields are Mobility-translated. When the admin UI
+ # locale differs from the store's default locale and no translation exists,
+ # `current_store.name` is nil — the title must not call `nil.capitalize`.
+ context 'when the store name is blank in the current locale' do
+ let(:store) { build_stubbed(:store, name: nil) }
+
+ it 'renders without raising' do
+ expect { render }.not_to raise_error
+ end
+ end
+
+ context 'when the store has a name' do
+ let(:store) { build_stubbed(:store, name: 'acme') }
+
+ it 'appends the capitalized store name to the title' do
+ render
+ expect(rendered).to include('Acme')
+ end
+ end
+end
diff --git a/spree/core/app/helpers/spree/locale_helper.rb b/spree/core/app/helpers/spree/locale_helper.rb
index 7324408e4f..9d0d87807e 100644
--- a/spree/core/app/helpers/spree/locale_helper.rb
+++ b/spree/core/app/helpers/spree/locale_helper.rb
@@ -4,6 +4,14 @@ module Spree
supported_locales_for_all_stores.map { |locale| locale_presentation(locale) }
end
+ # Locales the admin UI is translated into, as [name, code] pairs for a
+ # select. Self-contained (reads Spree.available_locales directly) so it
+ # works outside the storefront/admin controller stack — e.g. the pre-auth
+ # login screen, which has no current store.
+ def admin_locales_options
+ Spree.available_locales.map { |locale| locale_presentation(locale) }
+ end
+
def available_locales_options
available_locales.map { |locale| locale_presentation(locale) }
end
diff --git a/spree/core/app/models/concerns/spree/admin_user_methods.rb b/spree/core/app/models/concerns/spree/admin_user_methods.rb
index 6fde5c25fd..39ef211ee2 100644
--- a/spree/core/app/models/concerns/spree/admin_user_methods.rb
+++ b/spree/core/app/models/concerns/spree/admin_user_methods.rb
@@ -40,6 +40,12 @@ module Spree
self.whitelisted_ransackable_associations = %w[spree_roles]
self.whitelisted_ransackable_attributes = %w[id email first_name last_name]
+
+ # Validations
+ validates :selected_locale,
+ inclusion: { in: -> { Spree.available_locales.map(&:to_s) } },
+ allow_blank: true,
+ if: :will_save_change_to_selected_locale?
end
def can_be_deleted?
diff --git a/spree/core/config/locales/en.yml b/spree/core/config/locales/en.yml
index 67de57d5c7..9e0db29177 100644
--- a/spree/core/config/locales/en.yml
+++ b/spree/core/config/locales/en.yml
@@ -748,6 +748,7 @@ en:
adjustment_total: Adjustment Total
adjustments: Adjustments
adjustments_deleted: Adjustments Deleted
+ admin_language_help: The language your admin dashboard is displayed in. Only affects what you see, not the store or other staff.
admin_locale: Admin locale
admin_locale_help: The language used for the admin dashboard. If not set, defaults to the application locale.
administration: Administration
diff --git a/spree/core/spec/models/spree/concerns/admin_user_methods_spec.rb b/spree/core/spec/models/spree/concerns/admin_user_methods_spec.rb
index 3f299468f7..b257019d6c 100644
--- a/spree/core/spec/models/spree/concerns/admin_user_methods_spec.rb
+++ b/spree/core/spec/models/spree/concerns/admin_user_methods_spec.rb
@@ -81,6 +81,35 @@ describe Spree::AdminUserMethods do
end
end
+ describe 'validations' do
+ describe 'selected_locale' do
+ before { allow(Spree).to receive(:available_locales).and_return(%i[en de]) }
+
+ it 'is valid when blank' do
+ admin_user.selected_locale = nil
+ expect(admin_user).to be_valid
+ end
+
+ it 'is valid when an available admin locale' do
+ admin_user.selected_locale = 'de'
+ expect(admin_user).to be_valid
+ end
+
+ it 'is invalid when not an available admin locale' do
+ admin_user.selected_locale = 'pl'
+ expect(admin_user).not_to be_valid
+ expect(admin_user.errors[:selected_locale]).to be_present
+ end
+
+ it 'does not block unrelated updates when the stored locale is no longer available' do
+ admin_user.update_column(:selected_locale, 'pl')
+
+ expect(admin_user.update(first_name: 'Jane')).to be(true)
+ expect(admin_user.reload.first_name).to eq('Jane')
+ end
+ end
+ end
+
describe 'ransackable attributes' do
it 'allows searching by id' do
expect(Spree.admin_user_class.ransackable_attributes).to include('id')