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
Shared account editing and panel languages across both panels
Damian Legawiecefb7e4187a66
diff --git a/packages/dashboard-core/src/api-client.ts b/packages/dashboard-core/src/api-client.tsindex 86214445be..11024c23f1 100644--- a/packages/dashboard-core/src/api-client.ts+++ b/packages/dashboard-core/src/api-client.ts@@ -16,6 +16,34 @@import type { PermissionRule } from '@spree/admin-sdk'+/** What a panel may change on the signed-in person's own account. */+export interface PanelAccountParams {+ first_name?: string+ last_name?: string+ /** The panel's UI language, as a bundle code the panel ships (e.g. `de`). */+ selected_locale?: string+ /**+ * ActiveStorage signed id to set the photo, or `null` to remove it. Omit to+ * leave the current one alone — the only field here where `null` means+ * something the API acts on.+ */+ avatar?: string | null+}++/**+ * The account fields both panels' `/me` answer with. Deliberately the subset+ * they share — anything one API alone returns stays on its own client.+ */+export interface PanelAccountUser {+ id: string+ email: string+ first_name?: string | null+ last_name?: string | null+ full_name?: string | null+ selected_locale?: string | null+ avatar_url?: string | null+}+/** What the permission provider needs, whichever panel asked. */export interface PanelPermissions {/**@@ -90,6 +118,21 @@ export interface PanelApiClient {direct_upload: { url: string; headers: Record<string, string> }signed_id: string}>+ /**+ * Writes the signed-in person's own account — their name, photo and the+ * panel's language.+ *+ * Registered rather than imported for the same reason as everything else+ * here: the account menu's language switcher is one shared component, and+ * reaching for `adminClient` inside it would send a seller's language+ * change to an API they hold no credential for.+ *+ * Required, unlike most of this contract: the account menu lives in the+ * shared sidebar, so every panel mounting the shell already offers the+ * language switcher that calls this. An optional marker would describe a+ * host that does not exist and push a runtime guard onto every caller.+ */+ updateAccount(params: PanelAccountParams): Promise<{ user: PanelAccountUser }>stockLocations?: {list(params?: Record<string, unknown>): Promise<{ data: PanelStockLocation[]; meta?: unknown }>get(id: string): Promise<PanelStockLocation>diff --git a/packages/dashboard-core/src/hooks/use-switch-admin-locale.ts b/packages/dashboard-core/src/hooks/use-switch-admin-locale.tsindex c8619eaeab..d978c860ff 100644--- a/packages/dashboard-core/src/hooks/use-switch-admin-locale.ts+++ b/packages/dashboard-core/src/hooks/use-switch-admin-locale.ts@@ -1,6 +1,6 @@import { toastManager } from '@spree/dashboard-ui'import { useTranslation } from 'react-i18next'-import { adminClient } from '../client'+import { getApiClient } from '../api-client'import { i18n, markGenuineLocaleChoice, switchLocale } from '../lib/i18n'import { useAuth } from './use-auth'@@ -36,8 +36,17 @@ export function useSwitchAdminLocale() {return async (code: string): Promise<void> => {// Already adopted on the account AND on screen — nothing to do.if (code === user?.selected_locale && code === i18n.language) return+ // Resolved OUTSIDE the try: `getApiClient` throws a named error when no+ // client is registered, and that is a misconfigured host rather than a+ // failed save — caught below it would surface as "we could not save your+ // language", which sends the reader looking in the wrong place.+ //+ // Through the registered client rather than `adminClient`: this hook runs+ // in the account menu, which both panels mount, and a seller's language+ // change sent to the Admin API is a request they hold no credential for.+ const { updateAccount } = getApiClient()try {- const { user: updated } = await adminClient.me.update({ selected_locale: code })+ const { user: updated } = await updateAccount({ selected_locale: code })updateUser(updated)if (code !== i18n.language) {// Displayed language changes — persist the genuine choice + reload.diff --git a/packages/dashboard-core/src/lib/form-mappers.ts b/packages/dashboard-core/src/lib/form-mappers.tsindex 5d1ddcc53e..ebd88ceb4b 100644--- a/packages/dashboard-core/src/lib/form-mappers.ts+++ b/packages/dashboard-core/src/lib/form-mappers.ts@@ -1,3 +1,5 @@+import type { PanelAccountParams } from '../api-client'+/*** Treat a blank or whitespace-only string as "not set" — common when mapping* form values to API params, where a blank `<input>` should become `undefined`@@ -104,3 +106,41 @@ export function editableAddressToStockLocationParams(values: {phone: values.phone,}}++/**+ * The signed-in person's own account, mapped from either panel's edit form to+ * the params its API accepts.+ *+ * Shared because the three rules here are the same on both panels and each is+ * easy to get subtly wrong:+ *+ * - A name is sent as typed, empty string included. Blank is how a person+ * removes a name they once gave — the model normalizes it away — so+ * coercing blank to `undefined` would drop the field and leave the old name+ * in place while the form reported success.+ * - A blank language is omitted instead: it means none was chosen, never+ * "clear the one I have".+ * - The photo is a three-state field — a fresh upload sends its signed id, an+ * explicit clear sends `null` to purge the attachment, and an untouched+ * field is left out entirely.+ */+export function accountFormToParams(values: {+ first_name?: string | null+ last_name?: string | null+ selected_locale?: string | null+ avatar_signed_id: string | null+ avatar_cleared: boolean+}): PanelAccountParams {+ return {+ first_name: values.first_name ?? undefined,+ last_name: values.last_name ?? undefined,+ selected_locale: blankToUndefined(values.selected_locale),+ ...avatarParam(values.avatar_signed_id, values.avatar_cleared),+ }+}++function avatarParam(signedId: string | null, cleared: boolean) {+ if (signedId) return { avatar: signedId }+ if (cleared) return { avatar: null }+ return {}+}diff --git a/packages/dashboard-core/src/lib/i18n.ts b/packages/dashboard-core/src/lib/i18n.tsindex 16f971e4ca..bf702e4d9b 100644--- a/packages/dashboard-core/src/lib/i18n.ts+++ b/packages/dashboard-core/src/lib/i18n.ts@@ -1,5 +1,6 @@import i18n from 'i18next'import { initReactI18next } from 'react-i18next'+import { intlDisplayName } from '../hooks/use-display-name'// Relative path, not `@/...`: dashboard-core ships source; the consuming// project's `@/*` alias is theirs alone (see Phase 1's rationale).import en from '../locales/en.json'@@ -126,10 +127,84 @@ const coreLocales = import.meta.glob<{ default: Record<string, unknown> }>(/** Admin-UI locale codes the framework ships a bundle for (including `en`). */export function coreLocaleCodes(): string[] {- return [- 'en',- ...Object.keys(coreLocales).map((p) => p.replace('../locales/', '').replace('.json', '')),- ]+ return localeCodesFromBundlePaths(Object.keys(coreLocales))+}++/**+ * Turns a panel's locale-bundle paths into the `{ code, name }` pairs its+ * language pickers render, with `en` always first.+ *+ * The glob itself has to stay in the calling package — `import.meta.glob` is a+ * compile-time transform resolved against the file that writes it, so hoisting+ * it here would scan the framework's own locales instead of the panel's. What+ * IS shared is everything after that: stripping the path down to a code, and+ * naming each language in its own words.+ *+ * @param paths bundle paths from the caller's `import.meta.glob`, e.g.+ * `./locales/de.json`+ */+export function localesFromBundlePaths(paths: string[]): Array<{ code: string; name: string }> {+ return localeCodesFromBundlePaths(paths).map((code) => ({ code, name: localeEndonym(code) }))+}++// `en` first, then a code per bundle path. The glob hands back whatever prefix+// the calling file used (`./locales/`, `../locales/`), so match either.+function localeCodesFromBundlePaths(paths: string[]): string[] {+ return ['en', ...paths.map((path) => path.replace(/^.*\/locales\//, '').replace('.json', ''))]+}++// Each language's endonym (its own name: `Deutsch`, `中文`). `Intl.DisplayNames`+// answers in the language's own convention, so some come back lowercase+// (`français`, `polski`); capitalize the first letter by THAT language's casing+// rules rather than the current locale's. Scripts without case are unaffected,+// and an unknown code falls back to itself.+function localeEndonym(code: string): string {+ const name = intlDisplayName('language', code, code) ?? code++ return name.charAt(0).toLocaleUpperCase(code) + name.slice(1)+}++// The languages the running panel can display, as it declared them. `null`+// until a panel does, which accepts every code — the behaviour before panels+// declared anything.+let uiLocaleCodes: readonly string[] | null = null++/**+ * Declares the languages this panel can display, so a saved preference for one+ * it does not ship is never applied.+ *+ * The account's language is shared by every panel a person signs in to, and+ * panels ship different sets: a language picked in one may not exist in the+ * other. Applied anyway, the framework's own strings would switch while the+ * panel's stayed in English. Call once at boot with the panel's own list.+ *+ * @param codes locale codes the panel ships a bundle for, e.g. `['en', 'de']`+ */+export function setUiLocales(codes: readonly string[]): void {+ uiLocaleCodes = codes+}++/** @returns whether the running panel can display `code` */+export function isUiLocale(code: string): boolean {+ return uiLocaleCodes === null || uiLocaleCodes.includes(code)+}++/**+ * The language a new session should switch the page to, or `null` when the+ * page is already right.+ *+ * The account's saved language wins when the panel can display it. When it+ * cannot, the page keeps the language it booted in — unless that one is not+ * displayable either, which a panel reached before this check existed can be+ * left in, and then it goes back to English.+ *+ * @param saved the account's `selected_locale`+ * @param stored the language the page booted in+ */+export function sessionLocale(saved: string | null | undefined, stored: string): string | null {+ const target = saved && isUiLocale(saved) ? saved : isUiLocale(stored) ? stored : 'en'++ return target === stored ? null : target}/**diff --git a/packages/dashboard-core/src/providers/auth-provider.tsx b/packages/dashboard-core/src/providers/auth-provider.tsxindex 24abc03c19..5716ca09fc 100644--- a/packages/dashboard-core/src/providers/auth-provider.tsx+++ b/packages/dashboard-core/src/providers/auth-provider.tsx@@ -7,7 +7,7 @@ import type {} from '@spree/admin-sdk'import { createContext, type ReactNode, useCallback, useEffect, useRef, useState } from 'react'import { getApiClient, type PanelSession } from '../api-client'-import { ADMIN_LOCALE_STORAGE_KEY, switchLocale } from '../lib/i18n'+import { ADMIN_LOCALE_STORAGE_KEY, sessionLocale, switchLocale } from '../lib/i18n'import { queryClient } from '../lib/query-client'interface AuthContextValue {@@ -95,12 +95,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {// Compare against the persisted choice (not the live i18n.language): if they// already agree, the page booted in the right language and no reload is// needed — this also prevents a reload loop on the periodic token refresh.- const code = authUser.selected_localeconst stored =typeof localStorage !== 'undefined'? (localStorage.getItem(ADMIN_LOCALE_STORAGE_KEY) ?? 'en'): 'en'- if (code && code !== stored) switchLocale(code)+ const target = sessionLocale(authUser.selected_locale, stored)+ if (target) switchLocale(target)}, [])const updateUser = useCallback((changes: Partial<AdminUser>) => {diff --git a/packages/dashboard-core/tests/i18n-init.test.ts b/packages/dashboard-core/tests/i18n-init.test.tsindex 869096eb87..c8a92b8232 100644--- a/packages/dashboard-core/tests/i18n-init.test.ts+++ b/packages/dashboard-core/tests/i18n-init.test.ts@@ -63,3 +63,54 @@ describe('i18n initialization ordering', () => {expect(i18n.resolvedLanguage ?? i18n.language).toBe('pl')})})++/**+ * A person's saved language is shared by every panel they sign in to, and+ * panels ship different languages. `sessionLocale` decides what a new session+ * switches to, given what the panel declared it can display.+ */+describe('sessionLocale', () => {+ async function load(declared?: string[]) {+ vi.resetModules()+ vi.stubGlobal('localStorage', {+ getItem: () => null,+ setItem: () => undefined,+ removeItem: () => undefined,+ })+ const mod = await import('../src/lib/i18n')+ if (declared) mod.setUiLocales(declared)+ return mod+ }++ it('adopts the saved language when the panel ships it', async () => {+ const { sessionLocale } = await load(['en', 'de'])++ expect(sessionLocale('de', 'en')).toBe('de')+ })++ it('stays put when the page is already in the saved language', async () => {+ const { sessionLocale } = await load(['en', 'de'])++ expect(sessionLocale('de', 'de')).toBeNull()+ })++ it('ignores a saved language the panel does not ship', async () => {+ const { sessionLocale, isUiLocale } = await load(['en', 'de'])++ expect(isUiLocale('es')).toBe(false)+ expect(sessionLocale('es', 'de')).toBeNull()+ })++ it('returns to English when neither the saved nor the booted language is shipped', async () => {+ const { sessionLocale } = await load(['en', 'de'])++ expect(sessionLocale('es', 'es')).toBe('en')+ })++ it('accepts every language until a panel declares its own', async () => {+ const { sessionLocale, isUiLocale } = await load()++ expect(isUiLocale('es')).toBe(true)+ expect(sessionLocale('es', 'en')).toBe('es')+ })+})diff --git a/packages/dashboard/src/api-client-setup.ts b/packages/dashboard/src/api-client-setup.tsindex ff8fce5178..5e37cffc04 100644--- a/packages/dashboard/src/api-client-setup.ts+++ b/packages/dashboard/src/api-client-setup.ts@@ -18,6 +18,9 @@ setApiClient({return { rules: response.permissions, keys: response.permission_keys ?? [] }},+ // The account menu's language switcher writes through this, so the one+ // shared component does not have to know which API it is talking to.+ updateAccount: (params) => adminClient.me.update(params),listCountries: () => adminClient.countries.list({ expand: ['states'] }),createDirectUpload: (params) => adminClient.directUploads.create(params),// Backs the shared CSV import wizard, which both panels render. Thediff --git a/packages/dashboard/src/components/spree/profile-dialog.tsx b/packages/dashboard/src/components/spree/profile-dialog.tsxindex 9fcd989970..57690428c9 100644--- a/packages/dashboard/src/components/spree/profile-dialog.tsx+++ b/packages/dashboard/src/components/spree/profile-dialog.tsx@@ -1,5 +1,5 @@import { zodResolver } from '@hookform/resolvers/zod'-import { type MeResponse, SpreeError } from '@spree/admin-sdk'+import type { MeResponse } from '@spree/admin-sdk'import {ImageUploadField,i18n,@@ -147,12 +147,9 @@ function ProfileForm({const code = values.selected_localeif (code && code !== i18n.language) switchLocale(code)} catch (err) {- if (mapSpreeErrorsToForm(err, form.setError)) return- if (err instanceof SpreeError) throw err- toastManager.add({- type: 'error',- title: err instanceof Error ? err.message : t('admin.errors.failed_to_update_profile'),- })+ // Anything that is not a field error has already been toasted by the+ // mutation hook.+ mapSpreeErrorsToForm(err, form.setError)}}diff --git a/packages/dashboard/src/hooks/use-profile.ts b/packages/dashboard/src/hooks/use-profile.tsindex fcbd926588..f652c3dfd2 100644--- a/packages/dashboard/src/hooks/use-profile.ts+++ b/packages/dashboard/src/hooks/use-profile.ts@@ -1,6 +1,7 @@import type { MeResponse, MeUpdateParams } from '@spree/admin-sdk'import { adminClient, useResourceKey, useResourceMutation } from '@spree/dashboard-core'import { useQuery, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'/*** @param enabled Defer the request until it's needed. The edit-profile dialog@@ -15,6 +16,7 @@ export function useProfile(enabled = true) {}export function useUpdateProfile() {+ const { t } = useTranslation()const queryClient = useQueryClient()const profileKey = useResourceKey('profile')@@ -24,7 +26,9 @@ export function useUpdateProfile() {// and avatar there go stale on a self-edit unless that list is refetched.invalidate: [['profile'], ['staff']],successMessage: false, // the dialog toasts success itself- errorMessage: false, // the dialog maps 422s inline via mapSpreeErrorsToForm+ // Field-level 422s never toast — the dialog shows them inline — so this+ // covers everything else: a refusal, a server error, a lost connection.+ errorMessage: t('admin.errors.failed_to_update_profile'),// Write the response into the cache instead of leaning on the invalidation// alone. The dialog disables the profile query while closed, and an// invalidated query with no enabled observer goes stale without refetchingdiff --git a/packages/dashboard/src/i18n-setup.ts b/packages/dashboard/src/i18n-setup.tsindex 870bdd976b..8da4b695c9 100644--- a/packages/dashboard/src/i18n-setup.ts+++ b/packages/dashboard/src/i18n-setup.ts@@ -15,7 +15,7 @@//// `deep: true` + `overwrite: true` merge nested objects without dropping// keys the framework already provided; plugin keys win on collision.-import { i18n, intlDisplayName } from '@spree/dashboard-core'+import { i18n, localesFromBundlePaths, setUiLocales } from '@spree/dashboard-core'import en from './locales/en.json'i18n.addResourceBundle('en', 'translation', en, true, true)@@ -43,21 +43,12 @@ for (const [path, mod] of Object.entries(appLocales)) {i18n.addResourceBundle(codeFromPath(path), 'translation', mod.default, true, true)}-// Each language's endonym (its own name: `Deutsch`, `日本語`). `Intl.DisplayNames`-// returns it in the language's own convention, so some are lowercase-// (`français`, `polski`); capitalize the first letter — per the language's own-// casing rules — for a uniform, title-cased list. Scripts without case-// (`日本語`) are unaffected. Falls back to the code on no coverage.-function localeName(code: string): string {- const name = intlDisplayName('language', code, code) ?? code- return name.charAt(0).toLocaleUpperCase(code) + name.slice(1)-}+setUiLocales(getAvailableUiLocales().map(({ code }) => code))/*** Admin UI languages the dashboard can display, as `{ code, name }` pairs for* the language picker. Derived from the shipped locale bundles, not the API.*/export function getAvailableUiLocales(): Array<{ code: string; name: string }> {- const codes = ['en', ...Object.keys(appLocales).map(codeFromPath)]- return codes.map((code) => ({ code, name: localeName(code) }))+ return localesFromBundlePaths(Object.keys(appLocales))}diff --git a/packages/dashboard/src/schemas/me.ts b/packages/dashboard/src/schemas/me.tsindex cb07058cee..2a6fde0f9d 100644--- a/packages/dashboard/src/schemas/me.ts+++ b/packages/dashboard/src/schemas/me.ts@@ -1,4 +1,5 @@import type { MeResponse, MeUpdateParams } from '@spree/admin-sdk'+import { accountFormToParams, isUiLocale } from '@spree/dashboard-core'import { z } from 'zod/v4'// Profile form for the signed-in admin (PATCH /me). All fields optional —@@ -28,7 +29,12 @@ export function meToForm(me: MeResponse, fallbackLocale: string): MeFormValues {return {first_name: me.user.first_name ?? '',last_name: me.user.last_name ?? '',- selected_locale: me.user.selected_locale || fallbackLocale,+ // A language saved from another panel may not be one this panel ships;+ // preselecting it would show a raw code and save it straight back.+ selected_locale:+ me.user.selected_locale && isUiLocale(me.user.selected_locale)+ ? me.user.selected_locale+ : fallbackLocale,avatar_signed_id: null,avatar_preview_url: null,avatar_cleared: false,@@ -37,18 +43,5 @@ export function meToForm(me: MeResponse, fallbackLocale: string): MeFormValues {/** Map the form to the PATCH /me params (drops frontend-only fields). */export function meToParams(values: MeFormValues): MeUpdateParams {- return {- first_name: values.first_name || undefined,- last_name: values.last_name || undefined,- selected_locale: values.selected_locale || undefined,- ...avatarParam(values.avatar_signed_id, values.avatar_cleared),- }-}--// Three-state mapping: a fresh upload sends the signed_id, an explicit clear-// sends null (purges the attachment), and an untouched field is omitted.-function avatarParam(signedId: string | null, cleared: boolean) {- if (signedId) return { avatar: signedId }- if (cleared) return { avatar: null }- return {}+ return accountFormToParams(values)}diff --git a/packages/seller-dashboard/src/api-client.ts b/packages/seller-dashboard/src/api-client.tsindex b5b19825da..6ea7cec053 100644--- a/packages/seller-dashboard/src/api-client.ts+++ b/packages/seller-dashboard/src/api-client.ts@@ -64,6 +64,10 @@ export function createSellerApiClient({// did) left every `<Can>` on the panel answering false — silently.return { rules: response.permissions ?? [], keys: response.permission_keys ?? [] }},+ // The account menu's language switcher and the profile dialog both write+ // through this, so neither reaches for the Admin API from a panel holding+ // only a seller credential.+ updateAccount: (params) => sellerClient().me.update(params),// The shared address form reads countries through the registered client,// so it works in a panel that has no admin credential.listCountries: () => sellerClient().countries.list(),