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.

Seperate Admin UI locales from translation locales (#14211)

Damian Legawiec101dd123b3a8
diff --git a/.claude/commands/autofix-pr.md b/.claude/commands/autofix-pr.md
new file mode 100644
index 0000000000..3f619185de
--- /dev/null
+++ b/.claude/commands/autofix-pr.md
@@ -0,0 +1,18 @@
+---
+allowed-tools: Bash(gh pr view:*), Bash(gh pr diff:*), Bash(gh pr checks:*), Bash(git status:*), Bash(git add:*), Bash(git commit:*), Bash(git push:*)
+---
+
+## Context
+
+- PR metadata: !`gh pr view --json number,title,body,headRefName,baseRefName,author,labels`
+- PR diff: !`gh pr diff`
+
+## Your Task
+
+Monitor a pull request and fix code review and CI issues automatically
+
+1. Monitor the pull request for any code review comments from reviewers and agents like Bugbot or coderabbit
+2. Monitor CI statuses, ignore codecov
+3. Fix any code review comments and CI issues automatically
+4. Commit and push the changes automatically
+5. Retry in bounded cycles (e.g., max 10 iterations); if blocked (required review, failing checks, permission errors), stop and report blockers clearly
diff --git a/packages/admin-sdk/.changeset/store-available-locales.md b/packages/admin-sdk/.changeset/store-available-locales.md
new file mode 100644
index 0000000000..48cf16870f
--- /dev/null
+++ b/packages/admin-sdk/.changeset/store-available-locales.md
@@ -0,0 +1,5 @@
+---
+"@spree/admin-sdk": minor
+---
+
+Expose `Store.available_locales` — the full canonical set of locale codes a merchant may translate content into, independent of the store's currently-configured `supported_locales`. Lets locale pickers offer any supported locale instead of only ones already in use.
diff --git a/packages/admin-sdk/src/types/generated/Store.ts b/packages/admin-sdk/src/types/generated/Store.ts
index e6594de061..4e440d8814 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 3c287129aed8cec6ab6d723141176664
+// Typelizer digest 2d7bb47b535b465c8fad0e4342c531e4
//
// DO NOT MODIFY: This file was automatically generated by Typelizer.
@@ -21,6 +21,7 @@ interface Store {
url: string;
supported_currencies: Array<string>;
supported_locales: Array<string>;
+ available_locales: Array<string>;
logo_url: string | null;
mailer_logo_url: string | null;
}
diff --git a/packages/dashboard-core/src/components/locale-select.tsx b/packages/dashboard-core/src/components/locale-select.tsx
index 78d8d355fd..95db5c68ce 100644
--- a/packages/dashboard-core/src/components/locale-select.tsx
+++ b/packages/dashboard-core/src/components/locale-select.tsx
@@ -5,6 +5,7 @@ import {
ComboboxChipsInput,
ComboboxContent,
ComboboxEmpty,
+ ComboboxInput,
ComboboxItem,
ComboboxList,
ComboboxValue,
@@ -63,6 +64,23 @@ function formatOption(code: string, name: string) {
return name === code ? upper : `${upper} — ${name}`
}
+/** Above this many options a plain `<Select>` is unwieldy — switch to a
+ * searchable combobox. Matches `CurrencySelect`. */
+const SEARCHABLE_THRESHOLD = 12
+
+/**
+ * Combobox `filter` factory shared by the single- and multi-select pickers:
+ * case-insensitive match on both the raw code and the localized `CODE — Name`
+ * label, so typing "pt", "BR", or "Portuguese" all find `pt-BR`.
+ */
+function localeFilter(labelFor: (locale: string) => string) {
+ return (locale: string, query: string) => {
+ const q = query.trim().toLowerCase()
+ if (!q) return true
+ return locale.toLowerCase().includes(q) || labelFor(locale).toLowerCase().includes(q)
+ }
+}
+
/**
* Static text label for a locale code: `EN — English`. Use this in tables
* and read-only contexts where the picker isn't needed but the same
@@ -91,13 +109,32 @@ export function LocaleSelect(props: LocaleSelectProps) {
// Union of `props.options` (everything the picker should show) and the
// currently selected values — so editing an existing record doesn't
// silently drop chips when the store's locale list later narrows.
+ // An empty `options` (store not loaded yet, or a backend that omits
+ // `available_locales`) falls back to the store's configured locales rather
+ // than rendering an empty picker — matching `CurrencySelect`.
const items = useMemo(() => {
- const base = props.options ?? storeLocales
+ const base = props.options?.length ? props.options : storeLocales
const selected = props.multiple ? props.value : props.value ? [props.value] : []
const merged = Array.from(new Set([...base, ...selected]))
return props.excludeCode ? merged.filter((l) => l !== props.excludeCode) : merged
}, [props.options, props.excludeCode, props.multiple, props.value, storeLocales])
+ // Precompute each option's `CODE — Name` label once. The searchable combobox
+ // below runs `renderOption` across every item on each keystroke (filter +
+ // render), so resolving `Intl.DisplayNames` per call would repeat ~N lookups
+ // per character; a lookup map keeps it to a single pass per list change.
+ const labels = useMemo(() => {
+ const map = new Map<string, string>()
+ for (const locale of items) map.set(locale, formatOption(locale, displayNameFor(locale)))
+ return map
+ }, [items, displayNameFor])
+
+ // `CODE — Name` label for a locale, from the precomputed map (falls back to a
+ // direct lookup for a value not in the current option list, e.g. a selected
+ // chip the list later dropped).
+ const labelFor = (locale: string) =>
+ labels.get(locale) ?? formatOption(locale, displayNameFor(locale))
+
if (props.multiple) {
return (
<MultiLocalePicker
@@ -105,7 +142,7 @@ export function LocaleSelect(props: LocaleSelectProps) {
items={items}
value={props.value}
onChange={props.onChange}
- displayNameFor={displayNameFor}
+ labelFor={labelFor}
placeholder={props.placeholder ?? t('admin.components.locale_select.multi_placeholder')}
emptyText={t('admin.components.locale_select.empty')}
disabled={props.disabled}
@@ -114,22 +151,50 @@ export function LocaleSelect(props: LocaleSelectProps) {
}
const value = props.value ?? ''
+ const placeholder = props.placeholder ?? t('admin.components.locale_select.placeholder')
+
+ // Long lists (e.g. the full set of translatable locales) are unusable as a
+ // plain dropdown — switch to a searchable combobox, matching `CurrencySelect`.
+ if (items.length > SEARCHABLE_THRESHOLD) {
+ return (
+ <Combobox
+ items={items}
+ value={value}
+ onValueChange={(next: string | null) => props.onChange(next ?? '')}
+ itemToStringLabel={(locale: string | null) => (locale ? labelFor(locale) : '')}
+ itemToStringValue={(locale: string | null) => locale ?? ''}
+ filter={localeFilter(labelFor)}
+ disabled={props.disabled}
+ >
+ <ComboboxInput id={props.id} aria-required={props.required} placeholder={placeholder} />
+ <ComboboxContent>
+ <ComboboxEmpty>{t('admin.components.locale_select.empty')}</ComboboxEmpty>
+ <ComboboxList>
+ {(locale: string) => (
+ <ComboboxItem key={locale} value={locale}>
+ {labelFor(locale)}
+ </ComboboxItem>
+ )}
+ </ComboboxList>
+ </ComboboxContent>
+ </Combobox>
+ )
+ }
+
return (
<Select value={value} onValueChange={props.onChange} disabled={props.disabled}>
<SelectTrigger id={props.id} aria-required={props.required}>
{/* Base UI's `<SelectValue>` defaults to the raw locale code. Use
the children render-prop so the trigger shows the same
`CODE — Name` as the items. */}
- <SelectValue
- placeholder={props.placeholder ?? t('admin.components.locale_select.placeholder')}
- >
- {(v) => (v ? formatOption(v as string, displayNameFor(v as string)) : (v as string))}
+ <SelectValue placeholder={placeholder}>
+ {(v) => (v ? labelFor(v as string) : (v as string))}
</SelectValue>
</SelectTrigger>
<SelectContent>
{items.map((locale) => (
<SelectItem key={locale} value={locale}>
- {formatOption(locale, displayNameFor(locale))}
+ {labelFor(locale)}
</SelectItem>
))}
</SelectContent>
@@ -142,7 +207,7 @@ function MultiLocalePicker({
items,
value,
onChange,
- displayNameFor,
+ labelFor,
placeholder,
emptyText,
disabled,
@@ -151,7 +216,7 @@ function MultiLocalePicker({
items: string[]
value: string[]
onChange: (locales: string[]) => void
- displayNameFor: (code: string) => string
+ labelFor: (code: string) => string
placeholder: string
emptyText: string
disabled?: boolean
@@ -168,14 +233,17 @@ function MultiLocalePicker({
onChange(next)
setInputValue('')
}}
+ // Search the same `CODE — Name` labels as the single-select picker — the
+ // canonical locale list is too long to scan by raw code alone.
+ itemToStringLabel={(locale: string | null) => (locale ? labelFor(locale) : '')}
+ itemToStringValue={(locale: string | null) => locale ?? ''}
+ filter={localeFilter(labelFor)}
disabled={disabled}
>
<ComboboxChips ref={anchorRef}>
<ComboboxValue>
{(selectedLocales: string[]) =>
- selectedLocales.map((l) => (
- <ComboboxChip key={l}>{formatOption(l, displayNameFor(l))}</ComboboxChip>
- ))
+ selectedLocales.map((l) => <ComboboxChip key={l}>{labelFor(l)}</ComboboxChip>)
}
</ComboboxValue>
<ComboboxChipsInput
@@ -190,7 +258,7 @@ function MultiLocalePicker({
<ComboboxList>
{(locale: string) => (
<ComboboxItem key={locale} value={locale}>
- {formatOption(locale, displayNameFor(locale))}
+ {labelFor(locale)}
</ComboboxItem>
)}
</ComboboxList>
diff --git a/packages/dashboard-core/src/providers/store-provider.tsx b/packages/dashboard-core/src/providers/store-provider.tsx
index 6afcbbcdd3..3f681fd9c5 100644
--- a/packages/dashboard-core/src/providers/store-provider.tsx
+++ b/packages/dashboard-core/src/providers/store-provider.tsx
@@ -17,7 +17,12 @@ interface StoreContextValue {
storeId: string
isLoading: boolean
currencies: string[]
+ /** Locales this store is configured to translate content into. */
locales: string[]
+ /** Every locale a merchant may translate content into — the full canonical
+ * set, independent of which locales the store currently uses. Drives locale
+ * pickers so a new locale can always be added. */
+ availableLocales: string[]
defaultCurrency: string
defaultLocale: string
/** IANA timezone for the store (e.g. `Europe/Berlin`). Falls back to the
@@ -92,6 +97,7 @@ export function StoreProvider({ storeId, children }: { storeId: string; children
const currencies = store?.supported_currencies ?? []
const locales = store?.supported_locales ?? []
+ const availableLocales = store?.available_locales ?? []
const defaultCurrency = store?.default_currency ?? 'USD'
const defaultLocale = store?.default_locale ?? 'en'
const timezone =
@@ -105,6 +111,7 @@ export function StoreProvider({ storeId, children }: { storeId: string; children
isLoading,
currencies,
locales,
+ availableLocales,
defaultCurrency,
defaultLocale,
timezone,
diff --git a/packages/dashboard/e2e/markets.spec.ts b/packages/dashboard/e2e/markets.spec.ts
index 52da80bb38..0553824264 100644
--- a/packages/dashboard/e2e/markets.spec.ts
+++ b/packages/dashboard/e2e/markets.spec.ts
@@ -13,7 +13,14 @@ const CTA = /add market/i
* are usually fine left alone — only override when the test cares about the
* specific value.
*/
-async function createMarket(page: Page, attrs: { name: string; countries: string[] }) {
+/** A supported locale to add: `search` is typed into the picker, `label`
+ * matches the rendered `CODE — Name` option (and the resulting chip). */
+type LocalePick = { search: string; label: RegExp }
+
+async function createMarket(
+ page: Page,
+ attrs: { name: string; countries: string[]; supportedLocales?: LocalePick[] },
+) {
await page.getByRole('button', { name: /add market/i }).click()
await expect(page.getByRole('heading', { name: /add market/i })).toBeVisible()
@@ -24,9 +31,29 @@ async function createMarket(page: Page, attrs: { name: string; countries: string
await page.getByRole('option', { name: country }).first().click()
}
+ for (const locale of attrs.supportedLocales ?? []) {
+ await addSupportedLocale(page, locale)
+ }
+
await page.getByRole('button', { name: /create market/i }).click()
}
+/**
+ * Add one locale to the "Supported locales" chips picker (`LocaleSelect`,
+ * multi-select). The picker offers the full canonical translation-locale set
+ * (`Spree::Locales::ALL`) — including regional variants like `pt-BR` that the
+ * store doesn't already use — so options are searchable: type, then click the
+ * matching `CODE — Name` option.
+ */
+async function addSupportedLocale(page: Page, { search, label }: LocalePick) {
+ const input = page.locator('#market-supported-locales')
+ await input.click()
+ await input.fill(search)
+ await page.getByRole('option', { name: label }).first().click()
+ // The selection renders as a chip with the same `CODE — Name` label.
+ await expect(page.getByText(label).first()).toBeVisible()
+}
+
// The seeded default store creates a default market for `US` via
// `Store#ensure_default_market` (anchored to `default_country_iso = 'US'`),
// plus a EUR market anchored to `Germany` (so the store is multi-currency —
@@ -51,6 +78,32 @@ test.describe('markets', () => {
await expect(rowButton(page, name)).toBeVisible({ timeout: 15_000 })
})
+ test('creates a market with non-standard regional supported locales', async ({ page }) => {
+ const creds = await login(page)
+ await gotoIndex(page, MARKETS_PATH(creds.store_id), CTA)
+
+ // Regional variants the store does not already use — these were unselectable
+ // before the picker offered the full translation-locale set. Picking them
+ // here exercises both selectability and persistence.
+ const name = `E2E Locale Market ${Date.now()}`
+ await createMarket(page, {
+ name,
+ countries: ['Mexico'],
+ supportedLocales: [
+ { search: 'pt-BR', label: /pt-br — /i },
+ { search: 'zh-CN', label: /zh-cn — /i },
+ ],
+ })
+
+ await expect(rowButton(page, name)).toBeVisible({ timeout: 15_000 })
+
+ // Reopen the market and confirm the regional variants persisted as chips.
+ await rowButton(page, name).click()
+ await expect(page.getByRole('heading', { name })).toBeVisible({ timeout: 15_000 })
+ await expect(page.getByText(/pt-br — /i).first()).toBeVisible()
+ await expect(page.getByText(/zh-cn — /i).first()).toBeVisible()
+ })
+
test('edits a market', async ({ page }) => {
const creds = await login(page)
await gotoIndex(page, MARKETS_PATH(creds.store_id), CTA)
diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/markets.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/markets.tsx
index 7bfdae4008..cb903c60b3 100644
--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/markets.tsx
+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/markets.tsx
@@ -303,6 +303,7 @@ function EditMarketSheet({
function MarketFormFields({ form }: { form: UseFormReturn<MarketFormValues> }) {
const { t } = useTranslation()
+ const { availableLocales } = useStore()
const { errors } = form.formState
const defaultLocaleField = form.watch('default_locale')
@@ -357,8 +358,10 @@ function MarketFormFields({ form }: { form: UseFormReturn<MarketFormValues> }) {
render={({ field }) => (
<LocaleSelect
id="market-default-locale"
+ required
value={field.value}
onChange={field.onChange}
+ options={availableLocales}
/>
)}
/>
@@ -381,6 +384,7 @@ function MarketFormFields({ form }: { form: UseFormReturn<MarketFormValues> }) {
id="market-supported-locales"
value={field.value}
onChange={field.onChange}
+ options={availableLocales}
excludeCode={defaultLocaleField}
/>
)}
diff --git a/spree/admin/app/helpers/spree/admin/stores_helper.rb b/spree/admin/app/helpers/spree/admin/stores_helper.rb
index 1f2be99f0f..3cf3e8a728 100644
--- a/spree/admin/app/helpers/spree/admin/stores_helper.rb
+++ b/spree/admin/app/helpers/spree/admin/stores_helper.rb
@@ -30,7 +30,8 @@ module Spree
opts[:width] ||= DEFAULT_ICON_SIZE
opts[:class] ||= ''
opts[:class] += ' store-icon rounded-lg text-gray-900 flex items-center justify-center'
- content_tag(:span, name[0].upcase, class: opts[:class], style: "height: #{opts[:height]}px; width: #{opts[:width]}px;")
+ letter = name.to_s.first&.upcase
+ content_tag(:span, letter, class: opts[:class], style: "height: #{opts[:height]}px; width: #{opts[:width]}px;")
end
end
end
diff --git a/spree/admin/app/views/spree/admin/markets/_form.html.erb b/spree/admin/app/views/spree/admin/markets/_form.html.erb
index a6688aa171..791cff22fb 100644
--- a/spree/admin/app/views/spree/admin/markets/_form.html.erb
+++ b/spree/admin/app/views/spree/admin/markets/_form.html.erb
@@ -13,11 +13,11 @@
<%= f.spree_select :currency, currency_options(f.object.currency), { label: Spree.t(:currency), required: true, autocomplete: true } %>
<%= f.spree_select :default_locale,
- options_from_collection_for_select(all_locales_options, :last, :first, f.object.default_locale || I18n.locale),
+ options_from_collection_for_select(translation_locales_options, :last, :first, f.object.default_locale || I18n.locale),
{ required: true, autocomplete: true } %>
<%= f.spree_select :supported_locales,
- options_from_collection_for_select(all_locales_options, :last, :first, f.object.supported_locales&.split(',')),
+ options_from_collection_for_select(translation_locales_options, :last, :first, f.object.supported_locales&.split(',')),
{ multiple: true, autocomplete: true, hint: Spree.t('admin.markets.supported_locales_hint') } %>
<hr class="my-6">
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.rb
index baffdd9d60..429a5e01ee 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
@@ -7,6 +7,7 @@ module Spree
default_currency: :string, default_locale: :string,
supported_currencies: [:string, multi: true],
supported_locales: [:string, multi: true],
+ available_locales: [:string, multi: true],
logo_url: [:string, nullable: true],
mailer_logo_url: [:string, nullable: true],
mail_from_address: [:string, nullable: true],
@@ -41,6 +42,15 @@ module Spree
attribute :supported_locales, &:supported_locales_list
+ # Canonical set of locales a merchant may translate content into,
+ # independent of the store's currently-configured locales. Identical
+ # for every store, so the locale pickers can offer the full list
+ # rather than only locales already in use (avoids a chicken-and-egg
+ # where a new locale can never be added). See `Spree::Locales::ALL`.
+ attribute :available_locales do
+ Spree::Locales::ALL
+ end
+
attribute :logo_url do |store|
image_url_for(store.logo)
end
diff --git a/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb b/spree/api/spec/controllers/spree/api/v3/admin/store_controller_spec.rb
index 3487391410..5da3f352d3 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
@@ -66,6 +66,13 @@ RSpec.describe Spree::Api::V3::Admin::StoreController, type: :controller do
expect(json_response['supported_locales']).to be_an(Array)
end
+ it 'exposes the full canonical set of translatable locales' do
+ subject
+ expect(json_response['available_locales']).to eq(Spree::Locales::ALL)
+ # Locales a store can adopt even if not yet in supported_locales.
+ expect(json_response['available_locales']).to include('pt-BR', 'zh-CN', 'en-GB')
+ end
+
it 'exposes the email-section attributes' do
subject
expect(json_response).to include(
diff --git a/spree/core/app/helpers/spree/locale_helper.rb b/spree/core/app/helpers/spree/locale_helper.rb
index 9d0d87807e..2e02dc3a13 100644
--- a/spree/core/app/helpers/spree/locale_helper.rb
+++ b/spree/core/app/helpers/spree/locale_helper.rb
@@ -16,6 +16,15 @@ module Spree
available_locales.map { |locale| locale_presentation(locale) }
end
+ # Locales a merchant may translate **content** into, as [name, code] pairs
+ # for a select. Backed by `Spree::Locales::ALL` (the canonical translation
+ # locale set) rather than the installed UI-translation bundles, so a
+ # market/store can adopt any supported locale instead of only ones already
+ # in use.
+ def translation_locales_options
+ Spree::Locales::ALL.map { |locale| locale_presentation(locale) }
+ end
+
def supported_locales_options
return if current_store.nil?
diff --git a/spree/core/app/services/spree/locales.rb b/spree/core/app/services/spree/locales.rb
new file mode 100644
index 0000000000..f0fbcc3796
--- /dev/null
+++ b/spree/core/app/services/spree/locales.rb
@@ -0,0 +1,52 @@
+module Spree
+ module Locales
+ # Canonical set of locale codes a merchant may translate **data** into
+ # (Mobility-backed content such as product names, descriptions, taxons,
+ # option values, etc.).
+ #
+ # This is deliberately **independent of the admin/storefront UI translation
+ # set** (`Spree.available_locales`, which reflects which `spree_i18n` UI
+ # bundles happen to be installed). In a headless setup the storefront ships
+ # its own UI translations, so the languages a merchant can store content in
+ # must not be constrained by which admin chrome translations exist.
+ #
+ # Codes follow BCP-47 casing (lowercase language, uppercase region —
+ # `pt-BR`, `zh-CN`) so the browser's `Intl.DisplayNames` resolves a clean
+ # localized label for each. The list is the full ISO 639-1 base-language set
+ # plus the regional variants that matter for commerce (British vs. US
+ # English, Brazilian vs. European Portuguese, Simplified vs. Traditional
+ # Chinese, etc.).
+ #
+ # The underlying translation tables accept any locale string, so this list
+ # governs only what the locale pickers offer — it is not a hard storage
+ # constraint.
+ ALL = %w[
+ aa ab ae af ak am an ar as av ay az
+ ba be bg bh bi bm bn bo br bs
+ ca ce ch co cr cs cu cv cy
+ da de de-AT de-CH dv dz
+ ee el en en-AU en-CA en-GB en-IN en-NZ eo es es-419 es-MX et eu
+ fa ff fi fj fo fr fr-CA fy
+ ga gd gl gn gu gv
+ ha he hi ho hr ht hu hy hz
+ ia id ie ig ii ik io is it iu
+ ja jv
+ ka kg ki kj kk kl km kn ko kr ks ku kv kw ky
+ la lb lg li ln lo lt lu lv
+ mg mh mi mk ml mn mr ms mt my
+ na nb nd ne ng nl nn no nr nv ny
+ oc oj om or os
+ pa pi pl ps pt pt-BR pt-PT
+ qu
+ rm rn ro ru rw
+ sa sc sd se sg si sk sl sm sn so sq sr ss st su sv sw
+ ta te tg th ti tk tl tn to tr ts tt tw ty
+ ug uk ur uz
+ ve vi vo
+ wa wo
+ xh
+ yi yo
+ za zh-CN zh-HK zh-TW zu
+ ].freeze
+ end
+end
diff --git a/spree/core/app/services/spree/locales/set_fallback_locale_for_store.rb b/spree/core/app/services/spree/locales/set_fallback_locale_for_store.rb
index eeac42b4a6..fcea5176e8 100644
--- a/spree/core/app/services/spree/locales/set_fallback_locale_for_store.rb
+++ b/spree/core/app/services/spree/locales/set_fallback_locale_for_store.rb
@@ -9,7 +9,13 @@ module Spree
object[locale] = [store_default_locale]
end
- fallbacks_instance = I18n::Locale::Fallbacks.new(fallbacks)
+ # Pass the store default as the terminal default so EVERY locale —
+ # including regional variants not in `supported_locales_list` (e.g.
+ # `pt-BR` when only `pt` is configured) — ultimately falls back to it.
+ # The store default resolves to the populated DB column via Mobility's
+ # `column_fallback`, so translated reads never return nil for a locale
+ # that lacks a translation row.
+ fallbacks_instance = I18n::Locale::Fallbacks.new(store_default_locale, fallbacks)
Mobility.store_based_fallbacks = fallbacks_instance
end
diff --git a/spree/core/spec/helpers/locale_helper_spec.rb b/spree/core/spec/helpers/locale_helper_spec.rb
index 2d2a44bf6c..e1266519cc 100644
--- a/spree/core/spec/helpers/locale_helper_spec.rb
+++ b/spree/core/spec/helpers/locale_helper_spec.rb
@@ -41,6 +41,30 @@ describe Spree::LocaleHelper, type: :helper do
it { expect(supported_locales_options).to contain_exactly(['Deutsch (DE)', 'de'], ['Français (FR)', 'fr']) }
end
+ describe '#translation_locales_options' do
+ subject { translation_locales_options }
+
+ let(:current_store) { eu_store }
+
+ it 'returns the full canonical translation-locale set in order' do
+ expect(subject.map(&:last)).to eq(Spree::Locales::ALL)
+ end
+
+ it 'returns [name, code] pairs suitable for a select' do
+ expect(subject).to all(be_an(Array).and(have_attributes(size: 2)))
+ expect(subject).to include(['Deutsch (DE)', 'de'], ['Français (FR)', 'fr'])
+ end
+
+ it 'offers regional variants a store may not yet use' do
+ expect(subject.map(&:last)).to include('pt-BR', 'pt-PT', 'zh-CN', 'es-MX', 'en-GB')
+ end
+
+ it 'is independent of the store\'s configured supported_locales' do
+ # eu_store only supports fr,de — the picker still offers everything.
+ expect(subject.map(&:last)).to include('en', 'ja', 'ar')
+ end
+ end
+
describe '#locale_presentation' do
it { expect(locale_presentation(:fr)).to eq( ['Français (FR)', 'fr']) }
diff --git a/spree/core/spec/services/spree/locales/set_fallback_locale_for_store_spec.rb b/spree/core/spec/services/spree/locales/set_fallback_locale_for_store_spec.rb
index f0414e6329..c3085eaf00 100644
--- a/spree/core/spec/services/spree/locales/set_fallback_locale_for_store_spec.rb
+++ b/spree/core/spec/services/spree/locales/set_fallback_locale_for_store_spec.rb
@@ -32,6 +32,16 @@ module Spree
expect(name).to eq(name_de)
end
end
+
+ context 'when the requested locale is a regional variant not in supported_locales_list' do
+ # Regression: a locale like `pt-BR` (not configured on the store, but
+ # now selectable in the markets locale picker) must still fall back to
+ # the store default rather than returning nil.
+ it 'falls back to the store default locale' do
+ name = Mobility.with_locale(:'pt-BR') { product.name }
+ expect(name).to eq(name_pl)
+ end
+ end
end
end
end
diff --git a/spree/core/spec/services/spree/locales_spec.rb b/spree/core/spec/services/spree/locales_spec.rb
new file mode 100644
index 0000000000..d6a0164d57
--- /dev/null
+++ b/spree/core/spec/services/spree/locales_spec.rb
@@ -0,0 +1,22 @@
+require 'spec_helper'
+
+RSpec.describe Spree::Locales do
+ describe 'ALL' do
+ subject { described_class::ALL }
+
+ it { is_expected.to be_frozen }
+
+ it 'uses BCP-47 casing for regional variants (lowercase language, uppercase region)' do
+ variants = subject.select { |code| code.include?('-') }
+ expect(variants).to all(match(/\A[a-z]{2,3}-[A-Z0-9]+\z/))
+ end
+
+ it 'includes commerce-critical regional variants' do
+ expect(subject).to include('en-GB', 'pt-BR', 'pt-PT', 'es-MX', 'fr-CA', 'zh-CN', 'zh-TW')
+ end
+
+ it 'has no duplicate codes' do
+ expect(subject).to eq(subject.uniq)
+ end
+ end
+end