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
More translations in admin spa
Damian Legawiec8dcd167d96ab
diff --git a/packages/admin/e2e/customers.spec.ts b/packages/admin/e2e/customers.spec.tsindex dfa90845e7..827a8411a7 100644--- a/packages/admin/e2e/customers.spec.ts+++ b/packages/admin/e2e/customers.spec.ts@@ -95,7 +95,10 @@ test.describe('customers', () => {await page.locator('#sc-category').click()await page.getByRole('option').first().click()- await page.getByRole('button', { name: /^issue store credit$/i }).click()+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^issue store credit$/i })+ .click()await expect(page.getByText(/25\.00/).first()).toBeVisible({ timeout: 15_000 })})diff --git a/packages/admin/e2e/gift-cards.spec.ts b/packages/admin/e2e/gift-cards.spec.tsindex 38f38e30cf..5f301fcfb5 100644--- a/packages/admin/e2e/gift-cards.spec.ts+++ b/packages/admin/e2e/gift-cards.spec.ts@@ -30,11 +30,16 @@ test.describe('gift cards', () => {const creds = await login(page)await gotoIndex(page, GIFT_CARDS_PATH(creds.store_id), CTA)- await createGiftCard(page, { amount: '25.00' })+ // Per-test unique amount so leftover rows from earlier tests don't+ // satisfy this assertion accidentally (suite is serial — see CLAUDE.md).+ const cents = Date.now() % 9000 + 100+ const amount = (cents / 100).toFixed(2)+ await createGiftCard(page, { amount })// Auto-generated code is uppercase hex; just confirm a row with the// freshly-issued amount appears in the table.- await expect(page.getByText(/\$25\.00/).first()).toBeVisible({ timeout: 15_000 })+ const re = new RegExp(`\\$${amount.replace('.', '\\.')}`)+ await expect(page.getByText(re).first()).toBeVisible({ timeout: 15_000 })})test('creates a gift card with a custom code and edits it', async ({ page }) => {diff --git a/packages/admin/src/components/spree/address-form-dialog.tsx b/packages/admin/src/components/spree/address-form-dialog.tsxindex 8f8134d967..75fb175416 100644--- a/packages/admin/src/components/spree/address-form-dialog.tsx+++ b/packages/admin/src/components/spree/address-form-dialog.tsx@@ -1,7 +1,9 @@+import { zodResolver } from '@hookform/resolvers/zod'import type { Address } from '@spree/admin-sdk'-import { useEffect } from 'react'+import { useEffect, useRef } from 'react'import { Controller, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'+import { z } from 'zod/v4'import { CountryCombobox } from '@/components/spree/country-combobox'import { StateCombobox, useCountryStates } from '@/components/spree/country-state-fields'import { Button } from '@/components/ui/button'@@ -16,6 +18,8 @@ import {SheetHeader,SheetTitle,} from '@/components/ui/sheet'+import { mapSpreeErrorsToForm } from '@/lib/form-errors'+import { requiredMessage } from '@/lib/validation-messages'export interface AddressParams {first_name: string@@ -32,20 +36,40 @@ export interface AddressParams {is_default_shipping?: boolean}-interface AddressFormValues {- first_name: string- last_name: string- address1: string- address2: string- city: string- postal_code: string- country_iso: string- state_abbr: string- phone: string- label: string- is_default_billing: boolean- is_default_shipping: boolean-}+const addressFormSchema = z.object({+ first_name: z+ .string()+ .trim()+ .min(1, { error: requiredMessage('first_name') }),+ last_name: z+ .string()+ .trim()+ .min(1, { error: requiredMessage('last_name') }),+ address1: z+ .string()+ .trim()+ .min(1, { error: requiredMessage('address.address1') }),+ address2: z.string(),+ city: z+ .string()+ .trim()+ .min(1, { error: requiredMessage('city') }),+ postal_code: z+ .string()+ .trim()+ .min(1, { error: requiredMessage('address.postal_code') }),+ country_iso: z+ .string()+ .trim()+ .min(1, { error: requiredMessage('country_iso') }),+ state_abbr: z.string(),+ phone: z.string(),+ label: z.string(),+ is_default_billing: z.boolean(),+ is_default_shipping: z.boolean(),+})++type AddressFormValues = z.infer<typeof addressFormSchema>function buildDefaults(address: Address | null | undefined): AddressFormValues {return {@@ -77,21 +101,30 @@ export function AddressFormDialog({address: Address | null | undefinedopen: booleanonOpenChange: (open: boolean) => void- onSave: (address: AddressParams) => void+ onSave: (address: AddressParams) => void | Promise<void>title?: stringisPending?: booleanshowLabel?: booleanshowDefaultFlags?: boolean}) {const { t } = useTranslation()- const form = useForm<AddressFormValues>({ defaultValues: buildDefaults(address) })+ const form = useForm<AddressFormValues>({+ defaultValues: buildDefaults(address),+ resolver: zodResolver(addressFormSchema),+ })const { errors } = form.formState// The parent keys the dialog on the address id so a fresh instance mounts// for each open, but `address` can also stream in async (loaded after the- // sheet mounts). Reset the form when a new record arrives.+ // sheet mounts). Reset only when the *record identity* changes — otherwise a+ // re-render that creates a new `address` object literal would clobber edits+ // mid-flow.+ const prevAddressIdRef = useRef<string | null | undefined>(address?.id)useEffect(() => {- form.reset(buildDefaults(address))+ if (address?.id !== prevAddressIdRef.current) {+ prevAddressIdRef.current = address?.id+ form.reset(buildDefaults(address))+ }}, [address, form])const countryIso = form.watch('country_iso')@@ -99,22 +132,29 @@ export function AddressFormDialog({const useStateCombobox = statesRequired && states.length > 0async function onSubmit(values: AddressFormValues) {- onSave({- first_name: values.first_name,- last_name: values.last_name,- address1: values.address1,- address2: values.address2,- city: values.city,- postal_code: values.postal_code,- country_iso: values.country_iso,- state_abbr: values.state_abbr,- phone: values.phone,- ...(showLabel && { label: values.label || undefined }),- ...(showDefaultFlags && {- is_default_billing: values.is_default_billing,- is_default_shipping: values.is_default_shipping,- }),- })+ try {+ await onSave({+ first_name: values.first_name,+ last_name: values.last_name,+ address1: values.address1,+ address2: values.address2,+ city: values.city,+ postal_code: values.postal_code,+ country_iso: values.country_iso,+ state_abbr: values.state_abbr,+ phone: values.phone,+ ...(showLabel && { label: values.label || undefined }),+ ...(showDefaultFlags && {+ is_default_billing: values.is_default_billing,+ is_default_shipping: values.is_default_shipping,+ }),+ })+ } catch (err) {+ // Surface server-side 422 validation errors on the matching fields so+ // the dialog reflects whatever the API rejected (e.g. "phone is too+ // short"). Non-validation errors bubble to the parent's toast.+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err+ }}// Prevent Enter in combobox inputs from submitting the form. RHF's@@ -210,6 +250,7 @@ export function AddressFormDialog({/>)}/>+ <FieldError errors={[errors.country_iso]} /></Field><div className="grid grid-cols-2 gap-3"><Field>@@ -236,6 +277,7 @@ export function AddressFormDialog({/>)}/>+ <FieldError errors={[errors.state_abbr]} /></Field>) : (<Field>diff --git a/packages/admin/src/components/spree/color-picker.tsx b/packages/admin/src/components/spree/color-picker.tsxindex 088c2963a5..c61571693d 100644--- a/packages/admin/src/components/spree/color-picker.tsx+++ b/packages/admin/src/components/spree/color-picker.tsx@@ -180,7 +180,7 @@ export function ColorPicker({{compact && <div className="mt-3">{hexInput}</div>}<div className="mt-3 flex items-center justify-between gap-2"><span className="font-mono text-xs text-muted-foreground">- {normalizedValue ?? 'No color'}+ {normalizedValue ?? t('admin.color_picker.no_color')}</span>{normalizedValue && (<button@@ -191,7 +191,7 @@ export function ColorPicker({}}className="text-xs text-muted-foreground underline-offset-2 hover:underline">- Clear+ {t('admin.actions.clear')}</button>)}</div>diff --git a/packages/admin/src/components/spree/country-combobox.tsx b/packages/admin/src/components/spree/country-combobox.tsxindex 6fcd6ae8cc..5d9ea1798e 100644--- a/packages/admin/src/components/spree/country-combobox.tsx+++ b/packages/admin/src/components/spree/country-combobox.tsx@@ -86,6 +86,7 @@ export function CountryCombobox({onValueChange={(c: CountryOption | null) => onValueChange(c?.iso ?? '')}itemToStringLabel={(c: CountryOption | null) => c?.name ?? ''}itemToStringValue={(c: CountryOption | null) => c?.iso ?? ''}+ disabled={disabled}// Default filter matches name only via `itemToStringLabel`. Widen it so// typing the ISO code ("US", "USA") also matches.filter={countryFilter}diff --git a/packages/admin/src/components/spree/currency-select.tsx b/packages/admin/src/components/spree/currency-select.tsxindex a521fdf224..7d8981f6bd 100644--- a/packages/admin/src/components/spree/currency-select.tsx+++ b/packages/admin/src/components/spree/currency-select.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useState } from 'react'+import { useMemo, useState } from 'react'import {Select,SelectContent,@@ -65,17 +65,13 @@ export function CurrencySelect({const { currencies, defaultCurrency, defaultLocale } = useStore()const [internalValue, setInternalValue] = useState(defaultValue ?? defaultCurrency)const isControlled = controlledValue !== undefined- const value = isControlled ? controlledValue : internalValue+ // Controlled callers that pass an empty value still see the store default+ // in the dropdown. Derive it here without emitting onChange — committing the+ // fallback during render dirties forms and re-triggers effects. The caller+ // gets the real value the first time the merchant interacts.+ const value = isControlled ? controlledValue || defaultCurrency : internalValueconst displayNameFor = useCurrencyDisplayName(defaultLocale)- // Controlled callers that pass an empty value want the dropdown to *display*- // the store default — but without a matching `onChange` they end up with a- // mismatch between what the merchant sees ("USD") and what gets submitted- // (""). Commit the fallback once so display and payload agree.- useEffect(() => {- if (isControlled && !controlledValue && defaultCurrency) onChange?.(defaultCurrency)- }, [isControlled, controlledValue, defaultCurrency, onChange])-const handleChange = (next: string) => {if (!isControlled) setInternalValue(next)onChange?.(next)diff --git a/packages/admin/src/components/spree/custom-fields/definition-form.tsx b/packages/admin/src/components/spree/custom-fields/definition-form.tsxindex 452c52a214..3715f5c7f0 100644--- a/packages/admin/src/components/spree/custom-fields/definition-form.tsx+++ b/packages/admin/src/components/spree/custom-fields/definition-form.tsx@@ -17,24 +17,24 @@ import {import { Switch } from '@/components/ui/switch'import { useCreateCustomFieldDefinition } from '@/hooks/use-custom-fields'import { mapSpreeErrorsToForm } from '@/lib/form-errors'+import { i18n } from '@/lib/i18n'+import { requiredMessage } from '@/lib/validation-messages'-const FIELD_TYPES = [- { value: 'short_text', label: 'Short text' },- { value: 'long_text', label: 'Long text' },- { value: 'rich_text', label: 'Rich text' },- { value: 'number', label: 'Number' },- { value: 'boolean', label: 'Boolean' },- { value: 'json', label: 'JSON' },-] as const+// Labels live in `en.json` under+// `admin.fields.custom_field_definition.field_type.options.*` — consumers+// translate at render time.+const FIELD_TYPES = ['short_text', 'long_text', 'rich_text', 'number', 'boolean', 'json'] as constconst definitionSchema = z.object({- label: z.string().min(1, 'Required'),- namespace: z.string().min(1, 'Required'),+ label: z.string().min(1, { error: requiredMessage('custom_field_definition.label') }),+ namespace: z.string().min(1, { error: requiredMessage('custom_field_definition.namespace') }),key: z.string()- .min(1, 'Required')- .regex(/^[a-z0-9_]+$/i, 'Letters, numbers, underscore only'),- field_type: z.enum(['short_text', 'long_text', 'rich_text', 'number', 'boolean', 'json']),+ .min(1, { error: requiredMessage('custom_field_definition.key') })+ .regex(/^[a-z0-9_]+$/i, {+ error: () => i18n.t('admin.fields.custom_field_definition.key.invalid_format'),+ }),+ field_type: z.enum(FIELD_TYPES),storefront_visible: z.boolean(),})@@ -80,7 +80,14 @@ export function DefinitionForm({const result = await create.mutateAsync({ ...values, resource_type: resourceType })onSuccess(result.id)} catch (err) {- if (!mapSpreeErrorsToForm(err, form.setError)) throw err+ // 422s map to inline field errors; anything else (network, 5xx) lands+ // on the form-level `root` so the user gets feedback inside the sheet.+ if (!mapSpreeErrorsToForm(err, form.setError)) {+ form.setError('root', {+ type: 'server',+ message: err instanceof Error ? err.message : t('admin.errors.unexpected'),+ })+ }}}@@ -138,24 +145,26 @@ export function DefinitionForm({<Controllername="field_type"control={form.control}- render={({ field }) => (- <Select- items={FIELD_TYPES as unknown as { value: string; label: string }[]}- value={field.value}- onValueChange={field.onChange}- >- <SelectTrigger id="cfd-field-type" aria-invalid={!!errors.field_type || undefined}>- <SelectValue />- </SelectTrigger>- <SelectContent>- {FIELD_TYPES.map((o) => (- <SelectItem key={o.value} value={o.value}>- {o.label}- </SelectItem>- ))}- </SelectContent>- </Select>- )}+ render={({ field }) => {+ const items = FIELD_TYPES.map((value) => ({+ value,+ label: t(`admin.fields.custom_field_definition.field_type.options.${value}`),+ }))+ return (+ <Select items={items} value={field.value} onValueChange={field.onChange}>+ <SelectTrigger id="cfd-field-type" aria-invalid={!!errors.field_type || undefined}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {items.map((o) => (+ <SelectItem key={o.value} value={o.value}>+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+ }}/></Field><Field>diff --git a/packages/admin/src/components/spree/payment-method-editors/payment-method-form.tsx b/packages/admin/src/components/spree/payment-method-editors/payment-method-form.tsxindex f797c4333a..713d491445 100644--- a/packages/admin/src/components/spree/payment-method-editors/payment-method-form.tsx+++ b/packages/admin/src/components/spree/payment-method-editors/payment-method-form.tsx@@ -107,7 +107,13 @@ export function PaymentMethodForm({}}><SelectTrigger id="type" aria-invalid={!!form.formState.errors.type}>- <SelectValue placeholder={loadingTypes ? 'Loading…' : 'Select a provider'}>+ <SelectValue+ placeholder={+ loadingTypes+ ? t('admin.common.loading')+ : t('admin.fields.payment_method.type.placeholder')+ }+ >{(value) =>providerTypes.find((t) => t.type === value)?.label ?? (value as string)}diff --git a/packages/admin/src/components/spree/payment-method-editors/types.ts b/packages/admin/src/components/spree/payment-method-editors/types.tsindex 3d14828e93..038f414315 100644--- a/packages/admin/src/components/spree/payment-method-editors/types.ts+++ b/packages/admin/src/components/spree/payment-method-editors/types.ts@@ -1,23 +1,15 @@import type { PaymentMethod, PreferenceField } from '@spree/admin-sdk'import type { UseFormReturn } from 'react-hook-form'+import type { PaymentMethodFormValues } from '@/schemas/payment-method'/*** Form-state row for a payment method — the in-flight values an editor* cares about whether the sheet is in `create` or `edit` mode.*- * `create` mode has no server `id` and the provider type is still being- * picked; `edit` mode carries the loaded record (id, original schema,- * timestamps, etc.).+ * Inferred from `paymentMethodBaseFormSchema` so the runtime contract and+ * compile-time type stay in lockstep.*/-export interface PaymentMethodFormValues {- name: string- description: string- storefront_visible: boolean- active: boolean- auto_capture: boolean- /** Provider STI shorthand (e.g. `stripe`). Only set in create mode. */- type?: string-}+export type { PaymentMethodFormValues }export type PaymentMethodFormMode = 'create' | 'edit'diff --git a/packages/admin/src/components/spree/products/media-edit-sheet.tsx b/packages/admin/src/components/spree/products/media-edit-sheet.tsxindex 63e42e9d0a..8cbf8bacd7 100644--- a/packages/admin/src/components/spree/products/media-edit-sheet.tsx+++ b/packages/admin/src/components/spree/products/media-edit-sheet.tsx@@ -123,13 +123,13 @@ export function MediaEditSheet({ productId, mediaItem, variants, open, onOpenCha</div><Field>- <FieldLabel htmlFor="media-alt">Alt text</FieldLabel>+ <FieldLabel htmlFor="media-alt">{t('admin.fields.media.alt.label')}</FieldLabel><Textareaid="media-alt"value={alt}onChange={(e) => setAlt(e.target.value)}rows={3}- placeholder={t('admin.components.media.alt_placeholder')}+ placeholder={t('admin.fields.media.alt.placeholder')}/></Field>diff --git a/packages/admin/src/components/spree/promotion-editors/promotion-form.tsx b/packages/admin/src/components/spree/promotion-editors/promotion-form.tsxindex 43cfafccfb..5b6d7c9804 100644--- a/packages/admin/src/components/spree/promotion-editors/promotion-form.tsx+++ b/packages/admin/src/components/spree/promotion-editors/promotion-form.tsx@@ -147,6 +147,7 @@ export function PromotionForm({onDelete,deletePending = false,}: PromotionFormProps) {+ const { t } = useTranslation()const form = useForm<PromotionFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-anyresolver: zodResolver(promotionFormSchema) as any,@@ -204,8 +205,10 @@ export function PromotionForm({if (isLoading) {return (<ResourceLayout- header={<PageHeader title="Loading…" backTo="promotions" />}- main={<div className="text-sm text-muted-foreground">Loading promotion…</div>}+ header={<PageHeader title={t('admin.common.loading')} backTo="promotions" />}+ main={+ <div className="text-sm text-muted-foreground">{t('admin.pages.promotions.loading')}</div>+ }/>)}@@ -215,7 +218,9 @@ export function PromotionForm({<ResourceLayoutheader={<PageHeader- title={mode === 'create' ? 'New promotion' : (promotion?.name ?? '')}+ title={+ mode === 'create' ? t('admin.pages.promotions.new_title') : (promotion?.name ?? '')+ }backTo="promotions"actions={<div className="flex gap-2">@@ -229,7 +234,7 @@ export function PromotionForm({disabled={deletePending}className="text-destructive hover:bg-destructive/10 hover:text-destructive">- Delete+ {t('admin.actions.delete')}</Button></Can>)}@@ -242,11 +247,11 @@ export function PromotionForm({>{form.formState.isSubmitting? mode === 'create'- ? 'Creating…'- : 'Saving…'+ ? t('admin.actions.creating')+ : t('admin.actions.saving'): mode === 'create'- ? 'Create promotion'- : 'Save'}+ ? t('admin.pages.promotions.create_cta')+ : t('admin.actions.save')}</Button></div>}@@ -425,10 +430,10 @@ function TriggerCard({form.setValue('code', randomCouponCode(), { shouldDirty: true })form.clearErrors('code')}}- title="Generate a random code"+ title={t('admin.promotions.generate_code.title')}><SparklesIcon className="size-4" />- Generate+ {t('admin.actions.generate')}</Button></div><FieldError errors={[errors.code]} />@@ -445,10 +450,7 @@ function TriggerCard({min={1}placeholder={t('admin.fields.promotion.number_of_codes.placeholder')}aria-invalid={!!errors.number_of_codes || undefined}- {...form.register('number_of_codes', {- setValueAs: (v) =>- v === '' || v === null || v === undefined ? undefined : Number(v),- })}+ {...form.register('number_of_codes')}/><FieldError errors={[errors.number_of_codes]} /></Field>@@ -567,11 +569,7 @@ function ScheduleCard({ form }: { form: UseFormReturn<PromotionFormValues> }) {min={1}placeholder={t('admin.fields.promotion.usage_limit.placeholder')}aria-invalid={!!errors.usage_limit || undefined}- {...form.register('usage_limit', {- // Optional number — empty input means "no cap", not "0".- setValueAs: (v) =>- v === '' || v === null || v === undefined ? undefined : Number(v),- })}+ {...form.register('usage_limit')}/><FieldError errors={[errors.usage_limit]} /></Field>diff --git a/packages/admin/src/components/spree/resource-combobox.tsx b/packages/admin/src/components/spree/resource-combobox.tsxindex 0b80205d1f..0c244bccfa 100644--- a/packages/admin/src/components/spree/resource-combobox.tsx+++ b/packages/admin/src/components/spree/resource-combobox.tsx@@ -1,5 +1,6 @@import { useQuery } from '@tanstack/react-query'import { type ReactNode, useDeferredValue, useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'import {Combobox,ComboboxContent,@@ -75,10 +76,13 @@ export function ResourceCombobox<T extends ComboboxOption>({queryKey,getOptionLabel,renderOption,- placeholder = 'Search…',- emptyText = 'No results',+ placeholder,+ emptyText,disabled,}: ResourceComboboxProps<T>) {+ const { t } = useTranslation()+ const placeholderLabel = placeholder ?? t('admin.common.search_placeholder')+ const emptyLabel = emptyText ?? t('admin.common.no_results')// Base UI's Combobox owns the input element so it can write the selected// option's label into it on pick. We observe the typed query via// `onInputValueChange` on the Root rather than controlling@@ -88,10 +92,11 @@ export function ResourceCombobox<T extends ComboboxOption>({// Defer the search query so a fast typist doesn't fire one request per// keystroke — React batches the search to the next idle paint.const deferredInput = useDeferredValue(input)+ const trimmedQuery = deferredInput.trim()const { data: searchData } = useQuery({- queryKey: [queryKey, 'search', deferredInput],- queryFn: () => search(deferredInput),+ queryKey: [queryKey, 'search', trimmedQuery],+ queryFn: () => search(trimmedQuery),staleTime: 30_000,})@@ -132,9 +137,9 @@ export function ResourceCombobox<T extends ComboboxOption>({// hide rows whose label doesn't substring-match the typed query.filter={null}>- <ComboboxInput placeholder={placeholder} disabled={disabled} showClear />+ <ComboboxInput placeholder={placeholderLabel} disabled={disabled} showClear /><ComboboxContent>- <ComboboxEmpty>{emptyText}</ComboboxEmpty>+ <ComboboxEmpty>{emptyLabel}</ComboboxEmpty><ComboboxList>{(record: T) => (<ComboboxItem key={record.id} value={record}>diff --git a/packages/admin/src/components/ui/date-picker.tsx b/packages/admin/src/components/ui/date-picker.tsxindex 87e9257116..d8812ee1b0 100644--- a/packages/admin/src/components/ui/date-picker.tsx+++ b/packages/admin/src/components/ui/date-picker.tsx@@ -137,7 +137,13 @@ function DatePicker({}const handleTimeChange = (e: React.ChangeEvent<HTMLInputElement>) => {- const [hours, minutes] = e.target.value.split(':').map(Number)+ const raw = e.target.value+ if (!raw) {+ onChange?.(null)+ return+ }+ const [hours, minutes] = raw.split(':').map(Number)+ if (!Number.isFinite(hours) || !Number.isFinite(minutes)) returnconst d = date && isValidDate ? new Date(date) : new Date()d.setHours(hours, minutes, 0, 0)onChange?.(fromZonedTime(d, tz).toISOString())diff --git a/packages/admin/src/hooks/use-admin-users.ts b/packages/admin/src/hooks/use-admin-users.tsindex 02581d1631..fd3d1a947a 100644--- a/packages/admin/src/hooks/use-admin-users.ts+++ b/packages/admin/src/hooks/use-admin-users.ts@@ -1,5 +1,6 @@import type { AdminUser } from '@spree/admin-sdk'import { adminClient } from '@/client'+import { i18n } from '@/lib/i18n'/*** Shared config for any `<ResourceCombobox>` / `<ResourceMultiAutocomplete>`@@ -13,7 +14,7 @@ export function adminUserAutocompleteProps(queryKey: string) {search: (q: string) => adminClient.adminUsers.list({ email_cont: q, limit: 10 }),hydrate: (ids: string[]) => adminClient.adminUsers.list({ id_in: ids, limit: ids.length }),getOptionLabel: (a: AdminUser) => a.email ?? a.id,- placeholder: 'Search staff…',- emptyText: 'No staff match',+ placeholder: i18n.t('admin.staff.autocomplete.placeholder'),+ emptyText: i18n.t('admin.staff.autocomplete.empty'),}}diff --git a/packages/admin/src/hooks/use-customers.ts b/packages/admin/src/hooks/use-customers.tsindex dc0aea8ba9..e612d98792 100644--- a/packages/admin/src/hooks/use-customers.ts+++ b/packages/admin/src/hooks/use-customers.ts@@ -53,6 +53,7 @@ export function useUpdateCustomer(customerId: string) {export function useDeleteCustomer(customerId: string) {return useResourceMutation({mutationFn: () => adminClient.customers.delete(customerId),+ invalidate: [['customers'], customerQueryKey(customerId)],successMessage: i18n.t('admin.messages.customer_deleted'),})}@@ -107,3 +108,26 @@ export function useDeleteCustomerAddress(customerId: string) {successMessage: i18n.t('admin.messages.address_removed'),})}++// ---------------------------------------------------------------------------+// Bulk operations — index page bulk-action bar consumes these via its `run`+// hook. No success toast because BulkActionBar renders its own with the count.+// ---------------------------------------------------------------------------++type BulkGroupsParams = Parameters<typeof adminClient.customers.bulkAddToGroups>[0]++export function useBulkAddCustomersToGroups() {+ return useResourceMutation({+ mutationFn: (params: BulkGroupsParams) => adminClient.customers.bulkAddToGroups(params),+ successMessage: false,+ errorMessage: false,+ })+}++export function useBulkRemoveCustomersFromGroups() {+ return useResourceMutation({+ mutationFn: (params: BulkGroupsParams) => adminClient.customers.bulkRemoveFromGroups(params),+ successMessage: false,+ errorMessage: false,+ })+}diff --git a/packages/admin/src/hooks/use-gift-cards.ts b/packages/admin/src/hooks/use-gift-cards.tsindex 26518858c1..d7b8b2822f 100644--- a/packages/admin/src/hooks/use-gift-cards.ts+++ b/packages/admin/src/hooks/use-gift-cards.ts@@ -8,6 +8,7 @@ import type {import { useQuery, useQueryClient } from '@tanstack/react-query'import { adminClient } from '@/client'import { useResourceMutation } from '@/hooks/use-resource-mutation'+import { i18n } from '@/lib/i18n'export const giftCardsQueryKey = ['gift-cards'] as const@@ -31,8 +32,8 @@ export function useCreateGiftCard() {return useResourceMutation<GiftCard, Error, GiftCardCreateParams>({mutationFn: (params) => adminClient.giftCards.create(params),invalidate: [giftCardsQueryKey],- successMessage: 'Gift card created',- errorMessage: 'Failed to create gift card',+ successMessage: i18n.t('admin.gift_cards.messages.created'),+ errorMessage: i18n.t('admin.gift_cards.messages.create_failed'),})}@@ -40,8 +41,8 @@ export function useUpdateGiftCard(id: string) {return useResourceMutation<GiftCard, Error, GiftCardUpdateParams>({mutationFn: (params) => adminClient.giftCards.update(id, params),invalidate: [giftCardsQueryKey, giftCardQueryKey(id)],- successMessage: 'Gift card updated',- errorMessage: 'Failed to update gift card',+ successMessage: i18n.t('admin.gift_cards.messages.updated'),+ errorMessage: i18n.t('admin.gift_cards.messages.update_failed'),})}@@ -51,8 +52,8 @@ export function useDeleteGiftCard() {return useResourceMutation<void, Error, string>({mutationFn: (id) => adminClient.giftCards.delete(id),invalidate: [giftCardsQueryKey],- successMessage: 'Gift card deleted',- errorMessage: 'Failed to delete gift card',+ successMessage: i18n.t('admin.gift_cards.messages.deleted'),+ errorMessage: i18n.t('admin.gift_cards.messages.delete_failed'),onSuccess: (_data, id) => {queryClient.removeQueries({ queryKey: giftCardQueryKey(id) })},@@ -72,8 +73,8 @@ export function useCreateGiftCardBatch() {// larger batches), so the gift cards list is the surface that needs to// refetch — not the batches collection itself.invalidate: [giftCardsQueryKey, giftCardBatchesQueryKey],- successMessage: 'Gift card batch created',- errorMessage: 'Failed to create gift card batch',+ successMessage: i18n.t('admin.gift_cards.messages.batch_created'),+ errorMessage: i18n.t('admin.gift_cards.messages.batch_create_failed'),})}@@ -90,7 +91,7 @@ export function giftCardBatchAutocompleteProps(queryKey: string) {adminClient.giftCardBatches.list({ prefix_cont: q, limit: 20, sort: '-created_at' }),hydrate: (ids: string[]) => adminClient.giftCardBatches.list({ id_in: ids, limit: ids.length }),getOptionLabel: (b: GiftCardBatch) => b.prefix ?? b.id,- placeholder: 'Search batches by prefix…',- emptyText: 'No batches match',+ placeholder: i18n.t('admin.gift_cards.batch_autocomplete.placeholder'),+ emptyText: i18n.t('admin.gift_cards.batch_autocomplete.empty'),}}diff --git a/packages/admin/src/lib/form-mappers.ts b/packages/admin/src/lib/form-mappers.tsindex 6a202b80ee..40651cce76 100644--- a/packages/admin/src/lib/form-mappers.ts+++ b/packages/admin/src/lib/form-mappers.ts@@ -2,12 +2,29 @@* 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`* (omit the field) or `null` (clear the server value) rather than passing the- * empty string through.+ * empty string through. Returns the trimmed value when present.*/export function blankToUndefined(s: string | null | undefined): string | undefined {- return s && s.length > 0 ? s : undefined+ const trimmed = s?.trim()+ return trimmed ? trimmed : undefined}export function blankToNull(s: string | null | undefined): string | null {- return s && s.length > 0 ? s : null+ const trimmed = s?.trim()+ return trimmed ? trimmed : null+}++/**+ * Preprocessor for Zod optional-number fields backed by `<input type="number">`.+ * Empty inputs return `''`, which `z.coerce.number()` would coerce to `0` —+ * tripping `.positive()` / `.min()` on otherwise-optional fields. Map empty+ * to `undefined` so the optional branch wins.+ *+ * ```ts+ * usage_limit: z.preprocess(emptyToUndefined, z.coerce.number().int().positive().optional())+ * ```+ */+export function emptyToUndefined(value: unknown): unknown {+ if (value === '' || value === null) return undefined+ return value}diff --git a/packages/admin/src/locales/en.json b/packages/admin/src/locales/en.jsonindex b0ec493f6f..fa24a94d5a 100644--- a/packages/admin/src/locales/en.json+++ b/packages/admin/src/locales/en.json@@ -3,6 +3,8 @@"actions": {"add": "Add","cancel": "Cancel",+ "clear": "Clear",+ "revoke": "Revoke","close": "Close","confirm": "Confirm","create": "Create",@@ -84,6 +86,45 @@"deleted": "Deleted","unsaved_changes": "You have unsaved changes."},+ "color_picker": {+ "no_color": "No color"+ },+ "gift_cards": {+ "statuses": {+ "active": "Active",+ "partially_redeemed": "Partially redeemed",+ "redeemed": "Redeemed",+ "canceled": "Canceled",+ "expired": "Expired"+ },+ "columns": {+ "used": "Used",+ "remaining": "Remaining",+ "batch": "Batch",+ "customer": "Customer",+ "issued_by": "Issued by",+ "expires": "Expires",+ "created": "Created"+ },+ "table": {+ "search_placeholder": "Search by code…",+ "empty": "No gift cards yet"+ },+ "messages": {+ "created": "Gift card created",+ "create_failed": "Failed to create gift card",+ "updated": "Gift card updated",+ "update_failed": "Failed to update gift card",+ "deleted": "Gift card deleted",+ "delete_failed": "Failed to delete gift card",+ "batch_created": "Gift card batch created",+ "batch_create_failed": "Failed to create gift card batch"+ },+ "batch_autocomplete": {+ "placeholder": "Search batches by prefix…",+ "empty": "No batches match"+ }+ },"messages": {"saved": "Saved","created": "Created",@@ -96,6 +137,7 @@"invitation_accepted": "Welcome to Spree","key_created": "Key created","key_revoked": "Key revoked",+ "key_deleted": "Key deleted","product_saved": "Product saved","product_created": "Product created","product_deleted": "Product deleted",@@ -118,6 +160,7 @@"errors": {"required": "This field is required","generic": "Something went wrong",+ "unexpected": "An unexpected error occurred","failed_to_load": "Failed to load","failed_to_save": "Failed to save","failed_to_update": "Failed to update",@@ -219,8 +262,22 @@"custom_field_definition": {"label": { "label": "Label", "placeholder": "e.g. Material" },"namespace": { "label": "Namespace", "placeholder": "custom" },- "key": { "label": "Key", "placeholder": "e.g. material" },- "field_type": { "label": "Type" },+ "key": {+ "label": "Key",+ "placeholder": "e.g. material",+ "invalid_format": "Letters, numbers, underscore only"+ },+ "field_type": {+ "label": "Type",+ "options": {+ "short_text": "Short text",+ "long_text": "Long text",+ "rich_text": "Rich text",+ "number": "Number",+ "boolean": "Boolean",+ "json": "JSON"+ }+ },"storefront_visible": { "label": "Visible on storefront" }},"tax_category": {@@ -278,7 +335,7 @@}},"payment_method": {- "type": { "label": "Provider" },+ "type": { "label": "Provider", "placeholder": "Select a provider" },"name": { "placeholder": "e.g. Credit card (Stripe)" },"description": { "placeholder": "Customer-facing description shown at checkout" },"storefront_visible": { "label": "Visible on storefront" },@@ -382,6 +439,12 @@"customer_note": { "label": "Customer note (visible to customer)" },"internal_note": { "label": "Internal note (staff only)" },"coupon_code": { "label": "Coupon code", "placeholder": "Optional" }+ },+ "media": {+ "alt": {+ "label": "Alt text",+ "placeholder": "Describe the image for accessibility and SEO"+ }}},"components": {@@ -412,12 +475,14 @@"filters_button": "Filters"},"media": {- "alt_placeholder": "Describe the image for accessibility and SEO","remove_tooltip": "Remove image"},"custom_fields": { "json_placeholder": "{ \"example\": \"value\" }" }},"promotions": {+ "generate_code": {+ "title": "Generate a random code"+ },"kinds": {"coupon_code": "Coupon code","automatic": "Automatic (no code)"@@ -627,8 +692,13 @@"on_backorder": "On backorder","in_stock": "{{count}} in stock"},+ "variants_one": "{{count}} variant",+ "variants_other": "{{count}} variants","transfers": {"sheet_title": "New stock transfer",+ "edit_sheet_title": "Transfer {{number}}",+ "description_internal": "Inventory moved from <strong>{{source}}</strong> to <strong>{{destination}}</strong>.",+ "description_external": "External receive into <strong>{{destination}}</strong>.","section_from": "From","section_to": "To","section_items": "Items",@@ -687,9 +757,13 @@}},"promotions": {+ "new_title": "New promotion",+ "create_cta": "Create promotion",+ "loading": "Loading promotion…","gift_cards": {"new_sheet_title": "New gift card","edit_sheet_title": "Gift card",+ "not_found": "Gift card not found.","new_cta": "New gift card","create_label": "Create gift card","batch_section": "Batch",@@ -727,6 +801,7 @@},"validation": {"required": "{{field}} is required",+ "positive_number": "{{field}} must be greater than 0","min_length": "{{field}} must be at least {{count}} characters","passwords_dont_match": "Passwords do not match","invalid_email_or_password": "Invalid email or password",@@ -761,6 +836,10 @@"copy_invitation_link": "Copy invitation link","invitation_link_copied": "Invitation link copied"},+ "autocomplete": {+ "placeholder": "Search staff…",+ "empty": "No staff match"+ },"confirm": {"remove_title": "Remove from store?","remove_message": "{{name}} will lose access to this store.",@@ -839,6 +918,7 @@"create_label": "Create customer group","create_description": "Create a customer group to segment your customers for promotions, analytics, or marketing.","edit_description": "Update the name or description.",+ "default_name": "This group","delete_confirm": {"title": "Delete customer group?","message": "{{name}} will be removed. Customers in this group are not deleted."@@ -920,7 +1000,15 @@"resumed": "Order resumed","shipped": "Fulfillment shipped","captured": "Payment captured",- "voided": "Payment voided"+ "voided": "Payment voided",+ "confirmation_sent": "Confirmation sent"+ },+ "errors": {+ "cancel_failed": "Failed to cancel order",+ "complete_failed": "Failed to complete order",+ "approve_failed": "Failed to approve order",+ "resume_failed": "Failed to resume order",+ "confirmation_send_failed": "Failed to send confirmation"},"variant_search": {"description": "Search for a product variant to add to this order.",@@ -1054,6 +1142,7 @@"create_description": "Pick a provider and configure its credentials.","edit_description": "Update name, visibility, or status.","create_label": "Create payment method",+ "provider_description": "Provider: {{provider}}","delete_confirm": {"title": "Delete payment method?","message": "{{name}} will no longer be available at checkout."@@ -1071,6 +1160,10 @@},"stock_locations": {"add_cta": "Add stock location",+ "stock_items": {+ "empty": "No stock items at this location yet.",+ "empty_search": "No stock items match your search."+ },"create_label": "Create stock location","create_description": "Add a warehouse, store, or pickup point to fulfill orders from.","edit_description": "Update name, address, pickup, or stock policies.",diff --git a/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx b/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsxindex d863ca7666..5b64744039 100644--- a/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx@@ -10,7 +10,7 @@ import {StarIcon,TrashIcon,} from 'lucide-react'-import { type ReactNode, useMemo, useState } from 'react'+import { type ReactNode, useEffect, useMemo, useState } from 'react'import { Controller, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { AddressFormDialog, type AddressParams } from '@/components/spree/address-form-dialog'@@ -79,6 +79,12 @@ import {import { useStoreCreditCategories } from '@/hooks/use-store-credit-categories'import { mapSpreeErrorsToForm } from '@/lib/form-errors'import { type CustomerProfileFormValues, customerProfileFormSchema } from '@/schemas/customer'+import {+ type EditStoreCreditFormValues,+ editStoreCreditFormSchema,+ type IssueStoreCreditFormValues,+ issueStoreCreditFormSchema,+} from '@/schemas/store-credit'export const Route = createFileRoute('/_authenticated/$storeId/customers/$customerId')({component: CustomerDetailPage,@@ -262,6 +268,22 @@ function EditProfileSheet({const { errors } = form.formStateconst mutation = useUpdateCustomer(customer.id)+ // Sheet stays mounted across opens; re-seed form with the latest server+ // values whenever the dialog re-opens or the underlying record refreshes,+ // so stale edits from a previous session are discarded.+ useEffect(() => {+ if (open) {+ form.reset({+ email: customer.email,+ first_name: customer.first_name ?? '',+ last_name: customer.last_name ?? '',+ phone: customer.phone ?? '',+ tags: customer.tags ?? [],+ accepts_email_marketing: customer.accepts_email_marketing,+ })+ }+ }, [open, customer, form])+async function onSubmit(values: CustomerProfileFormValues) {try {await mutation.mutateAsync(values)@@ -842,11 +864,15 @@ function CustomerAddressDialog({const updateMutation = useUpdateCustomerAddress(customer.id)const mutation = isEdit ? updateMutation : createMutation- function handleSave(params: AddressParams) {- const promise = isEdit- ? updateMutation.mutateAsync({ id: address.id, params })- : createMutation.mutateAsync(params)- promise.then(() => onOpenChange(false))+ // Returns the promise so `AddressFormDialog` can map 422 errors onto fields.+ // Closes the sheet only on success.+ async function handleSave(params: AddressParams) {+ if (isEdit) {+ await updateMutation.mutateAsync({ id: address.id, params })+ } else {+ await createMutation.mutateAsync(params)+ }+ onOpenChange(false)}// Wait for countries before mounting so the country/state lazy initializer@@ -1035,12 +1061,6 @@ function StoreCreditCategorySelect({)}-interface EditStoreCreditFormValues {- amount: string- category_id: string- memo: string-}-function EditStoreCreditDialog({customerId,credit,@@ -1057,6 +1077,8 @@ function EditStoreCreditDialog({const amountLocked = Number(credit.amount_used ?? 0) > 0const form = useForm<EditStoreCreditFormValues>({+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ resolver: zodResolver(editStoreCreditFormSchema) as any,defaultValues: {amount: credit.amount ?? '',category_id: credit.category_id ?? '',@@ -1187,12 +1209,22 @@ function IssueStoreCreditDialog({}) {const { t } = useTranslation()const form = useForm<IssueStoreCreditFormValues>({+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ resolver: zodResolver(issueStoreCreditFormSchema) as any,defaultValues: { amount: '', currency: '', category_id: '', memo: '' },})const { errors } = form.formStateconst mutation = useCreateCustomerStoreCredit(customerId)+ // Clear any prior submission state when the dialog re-opens so a fresh form+ // is presented (otherwise stale "Issue $20" values linger across opens).+ useEffect(() => {+ if (open) {+ form.reset({ amount: '', currency: '', category_id: '', memo: '' })+ }+ }, [open, form])+async function onSubmit(values: IssueStoreCreditFormValues) {try {await mutation.mutateAsync({@@ -1304,10 +1336,3 @@ function IssueStoreCreditDialog({</Dialog>)}--interface IssueStoreCreditFormValues {- amount: string- currency: string- category_id: string- memo: string-}diff --git a/packages/admin/src/routes/_authenticated/$storeId/customers/groups.tsx b/packages/admin/src/routes/_authenticated/$storeId/customers/groups.tsxindex bab8681c9c..895f3b6945 100644--- a/packages/admin/src/routes/_authenticated/$storeId/customers/groups.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/customers/groups.tsx@@ -209,7 +209,7 @@ function EditCustomerGroupSheet({const ok = await confirm({title: t('admin.customers.groups.delete_confirm.title'),message: t('admin.customers.groups.delete_confirm.message', {- name: group?.name ?? 'This group',+ name: group?.name ?? t('admin.customers.groups.default_name'),}),variant: 'destructive',confirmLabel: t('admin.actions.delete'),diff --git a/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx b/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsxindex 7917f73d8c..7cfd485f36 100644--- a/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx@@ -26,6 +26,10 @@ import {} from '@/components/ui/sheet'import { Textarea } from '@/components/ui/textarea'import { customerGroupAutocompleteProps } from '@/hooks/use-customer-groups'+import {+ useBulkAddCustomersToGroups,+ useBulkRemoveCustomersFromGroups,+} from '@/hooks/use-customers'import { mapSpreeErrorsToForm } from '@/lib/form-errors'import { Subject } from '@/lib/permissions'import {@@ -56,6 +60,8 @@ function CustomersPage() {const { t } = useTranslation()const search = Route.useSearch() as z.infer<typeof customersSearchSchema>const navigate = useNavigate()+ const bulkAddToGroups = useBulkAddCustomersToGroups()+ const bulkRemoveFromGroups = useBulkRemoveCustomersFromGroups()// BulkActionBar's `successMessage` runs through a `{n}` interpolation in the// bar itself; we pass i18next `{{count}}` as the literal `{n}` token so the@@ -68,7 +74,7 @@ function CustomersPage() {subject: Subject.Customer,form: (props) => <GroupPickerSheet {...props} mode="add" />,run: ({ ids, formValues }) =>- adminClient.customers.bulkAddToGroups({+ bulkAddToGroups.mutateAsync({ids,customer_group_ids: formValues?.customer_group_ids ?? [],}),@@ -83,7 +89,7 @@ function CustomersPage() {subject: Subject.Customer,form: (props) => <GroupPickerSheet {...props} mode="remove" />,run: ({ ids, formValues }) =>- adminClient.customers.bulkRemoveFromGroups({+ bulkRemoveFromGroups.mutateAsync({ids,customer_group_ids: formValues?.customer_group_ids ?? [],}),diff --git a/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx b/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsxindex 9ff6440e4c..7d0a9e941f 100644--- a/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx@@ -158,30 +158,30 @@ function OrderHeader({ order }: { order: Order }) {mutationFn: () => adminClient.orders.cancel(orderId),invalidate: [orderQueryKey(orderId)],successMessage: t('admin.orders.detail.messages.canceled'),- errorMessage: 'Failed to cancel order',+ errorMessage: t('admin.orders.detail.errors.cancel_failed'),})const completeMutation = useResourceMutation({mutationFn: () => adminClient.orders.complete(orderId),invalidate: [orderQueryKey(orderId)],successMessage: t('admin.orders.detail.messages.completed'),- errorMessage: 'Failed to complete order',+ errorMessage: t('admin.orders.detail.errors.complete_failed'),})const approveMutation = useResourceMutation({mutationFn: () => adminClient.orders.approve(orderId),invalidate: [orderQueryKey(orderId)],successMessage: t('admin.orders.detail.messages.approved'),- errorMessage: 'Failed to approve order',+ errorMessage: t('admin.orders.detail.errors.approve_failed'),})const resumeMutation = useResourceMutation({mutationFn: () => adminClient.orders.resume(orderId),invalidate: [orderQueryKey(orderId)],successMessage: t('admin.orders.detail.messages.resumed'),- errorMessage: 'Failed to resume order',+ errorMessage: t('admin.orders.detail.errors.resume_failed'),})const resendMutation = useResourceMutation({mutationFn: () => adminClient.orders.resendConfirmation(orderId, {}),- successMessage: 'Confirmation sent',- errorMessage: 'Failed to send confirmation',+ successMessage: t('admin.orders.detail.messages.confirmation_sent'),+ errorMessage: t('admin.orders.detail.errors.confirmation_send_failed'),})const badges = (@@ -1293,7 +1293,7 @@ function OrderSummaryCard({ order }: { order: Order }) {{order.created_by && (<SummaryRowlabel={t('admin.pages.orders.detail.summary.created_by')}- value={order.created_by.full_name}+ value={order.created_by.full_name || order.created_by.email}/>)}<SummaryRow@@ -1317,7 +1317,7 @@ function OrderSummaryCard({ order }: { order: Order }) {{order.canceler && (<SummaryRowlabel={t('admin.orders.detail.summary.canceler')}- value={order.canceler.full_name}+ value={order.canceler.full_name || order.canceler.email}/>)}</>@@ -1326,7 +1326,7 @@ function OrderSummaryCard({ order }: { order: Order }) {{order.approved_at && order.approver && (<SummaryRowlabel={t('admin.orders.detail.summary.approved_by')}- value={order.approver.full_name}+ value={order.approver.full_name || order.approver.email}/>)}diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/transfers.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/transfers.tsxindex f49633fba6..fc1c1e3976 100644--- a/packages/admin/src/routes/_authenticated/$storeId/products/transfers.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/products/transfers.tsx@@ -3,7 +3,7 @@ import { useQuery } from '@tanstack/react-query'import { createFileRoute, useNavigate } from '@tanstack/react-router'import { ArrowLeftRightIcon, PlusIcon, TrashIcon } from 'lucide-react'import { useMemo, useState } from 'react'-import { useTranslation } from 'react-i18next'+import { Trans, useTranslation } from 'react-i18next'import { z } from 'zod/v4'import { adminClient } from '@/client'import { Can } from '@/components/spree/can'@@ -410,19 +410,22 @@ function ViewStockTransferSheet({<SheetHeader><SheetTitle>{transfer- ? `Transfer ${transfer.number}`+ ? t('admin.pages.products.transfers.edit_sheet_title', { number: transfer.number }): t('admin.pages.products.transfers.sheet_title')}</SheetTitle><SheetDescription>{transfer?.source_location_id ? (- <>- Inventory moved from <span className="font-medium">{sourceName}</span> to{' '}- <span className="font-medium">{destinationName}</span>.- </>+ <Trans+ i18nKey="admin.pages.products.transfers.description_internal"+ values={{ source: sourceName, destination: destinationName }}+ components={{ strong: <span className="font-medium" /> }}+ />) : (- <>- External receive into <span className="font-medium">{destinationName}</span>.- </>+ <Trans+ i18nKey="admin.pages.products.transfers.description_external"+ values={{ destination: destinationName }}+ components={{ strong: <span className="font-medium" /> }}+ />)}</SheetDescription></SheetHeader>diff --git a/packages/admin/src/routes/_authenticated/$storeId/promotions/gift-cards.tsx b/packages/admin/src/routes/_authenticated/$storeId/promotions/gift-cards.tsxindex 660826ca0e..242d188b26 100644--- a/packages/admin/src/routes/_authenticated/$storeId/promotions/gift-cards.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/promotions/gift-cards.tsx@@ -2,7 +2,7 @@ import { zodResolver } from '@hookform/resolvers/zod'import type { Customer, GiftCard } from '@spree/admin-sdk'import { createFileRoute, useNavigate } from '@tanstack/react-router'import { PlusIcon } from 'lucide-react'-import { useEffect } from 'react'+import { useEffect, useRef } from 'react'import { Controller, type UseFormReturn, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { z } from 'zod/v4'@@ -243,8 +243,14 @@ function EditGiftCardSheet({},})+ // Reset only when the *record identity* changes (or the form is pristine)+ // so a background refetch can't clobber unsaved edits in the sheet.+ const prevGiftCardIdRef = useRef<string | undefined>(undefined)useEffect(() => {- if (giftCard) {+ if (!giftCard) return+ const idChanged = giftCard.id !== prevGiftCardIdRef.current+ if (idChanged || !form.formState.isDirty) {+ prevGiftCardIdRef.current = giftCard.idform.reset({code: giftCard.code,amount: Number(giftCard.amount),@@ -295,6 +301,10 @@ function EditGiftCardSheet({</SheetHeader>{isLoading ? (<div className="p-4 text-sm text-muted-foreground">{t('admin.common.loading')}</div>+ ) : !giftCard ? (+ <div className="p-4 text-sm text-muted-foreground">+ {t('admin.pages.promotions.gift_cards.not_found')}+ </div>) : (<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col"><div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">@@ -497,14 +507,16 @@ function CreateGiftCardFormFields({/>)}/>+ <FieldError errors={[form.formState.errors.expires_at]} /></Field>{/* A single customer can't be attached to a whole batch — hide thefield in batch mode to make the difference obvious. */}{!isBatch && (<Field>- <FieldLabel>{t('admin.fields.gift_card.customer_id.label')} (optional)</FieldLabel>+ <FieldLabel>{`${t('admin.fields.gift_card.customer_id.label')} (${t('admin.common.optional').toLowerCase()})`}</FieldLabel><CustomerPickerController form={form} />+ <FieldError errors={[errors.customer_id]} /></Field>)}</FieldGroup>@@ -538,11 +550,17 @@ function EditGiftCardFormFields({/>)}/>+ <FieldError errors={[form.formState.errors.expires_at]} /></Field><Field>- <FieldLabel>{t('admin.fields.gift_card.customer_id.label')} (optional)</FieldLabel>+ <FieldLabel>{`${t('admin.fields.gift_card.customer_id.label')} (${t('admin.common.optional').toLowerCase()})`}</FieldLabel><CustomerPickerController form={form} readOnly={readOnly} />+ <FieldError+ errors={[+ (form.formState.errors as Record<string, { message?: string } | undefined>).customer_id,+ ]}+ /></Field></FieldGroup>)diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/api-keys.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/api-keys.tsxindex c2670ed2b2..9a0dcec9f2 100644--- a/packages/admin/src/routes/_authenticated/$storeId/settings/api-keys.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/api-keys.tsx@@ -249,7 +249,7 @@ function ApiKeyRow({ apiKey, showScopes }: { apiKey: ApiKey; showScopes: booleantitle: t('admin.api_keys.revoke_confirm.title'),message: t('admin.api_keys.revoke_confirm.message'),variant: 'destructive',- confirmLabel: 'Revoke',+ confirmLabel: t('admin.actions.revoke'),})if (!ok) return@@ -266,13 +266,13 @@ function ApiKeyRow({ apiKey, showScopes }: { apiKey: ApiKey; showScopes: booleantitle: t('admin.api_keys.delete_confirm.title'),message: t('admin.api_keys.delete_confirm.message'),variant: 'destructive',- confirmLabel: 'Delete',+ confirmLabel: t('admin.actions.delete'),})if (!ok) returntry {await deleteMutation.mutateAsync(apiKey.id)- toast.success('Key deleted')+ toast.success(t('admin.messages.key_deleted'))} catch (err) {toast.error(err instanceof Error ? err.message : t('admin.api_keys.errors.failed_to_delete'))}diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsxindex 6a8977ccfc..f0f15f4a07 100644--- a/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx@@ -303,7 +303,7 @@ function EditPaymentMethodSheet({</SheetTitle><SheetDescription>{providerLabel- ? `Provider: ${providerLabel}`+ ? t('admin.payment_methods.provider_description', { provider: providerLabel }): t('admin.payment_methods.edit_description')}</SheetDescription></SheetHeader>diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/staff.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/staff.tsxindex 1effcedd12..3c95c37b18 100644--- a/packages/admin/src/routes/_authenticated/$storeId/settings/staff.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/staff.tsx@@ -495,9 +495,7 @@ function InviteDialog({)}}/>- {form.formState.errors.role_id && (- <p className="text-sm text-destructive">{form.formState.errors.role_id.message}</p>- )}+ <FieldError errors={[form.formState.errors.role_id]} /></Field></DialogBody><DialogFooter>@@ -638,9 +636,7 @@ function EditStaffDialog({/>)}/>- {form.formState.errors.role_ids && (- <p className="text-sm text-destructive">{form.formState.errors.role_ids.message}</p>- )}+ <FieldError errors={[form.formState.errors.role_ids]} /></Field></DialogBody><DialogFooter>diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsxindex e0cd2c6757..471ae90e1e 100644--- a/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsx@@ -251,8 +251,13 @@ function EditStockLocationSheet({confirmLabel: t('admin.actions.delete'),})if (!ok) return- await deleteMutation.mutateAsync(id)- onOpenChange(false)+ try {+ await deleteMutation.mutateAsync(id)+ onOpenChange(false)+ } catch {+ // `useResourceMutation` already surfaces a toast for non-422 errors.+ // Keep the sheet open so the user can retry or cancel.+ }}return (@@ -350,10 +355,12 @@ function StockItemsPanel({ stockLocationId }: { stockLocationId: string }) {/></div>{isFetching && items.length === 0 ? (- <div className="px-4 py-6 text-sm text-muted-foreground">Loading…</div>+ <div className="px-4 py-6 text-sm text-muted-foreground">{t('admin.common.loading')}</div>) : items.length === 0 ? (<div className="px-4 py-6 text-sm text-muted-foreground">- No stock items {search ? 'match your search' : 'at this location yet'}.+ {search+ ? t('admin.stock_locations.stock_items.empty_search')+ : t('admin.stock_locations.stock_items.empty')}</div>) : (<div className="divide-y">@@ -365,7 +372,7 @@ function StockItemsPanel({ stockLocationId }: { stockLocationId: string }) {{totalPages > 1 && (<div className="flex items-center justify-between border-t px-4 py-2"><span className="text-xs text-muted-foreground">- Page {page} of {totalPages}+ {t('admin.common.page_of', { page, total: totalPages })}</span><div className="flex gap-1"><Button@@ -375,7 +382,7 @@ function StockItemsPanel({ stockLocationId }: { stockLocationId: string }) {onClick={() => setPage((p) => Math.max(1, p - 1))}disabled={page === 1 || isFetching}>- Prev+ {t('admin.common.prev')}</Button><Buttontype="button"@@ -384,7 +391,7 @@ function StockItemsPanel({ stockLocationId }: { stockLocationId: string }) {onClick={() => setPage((p) => Math.min(totalPages, p + 1))}disabled={page === totalPages || isFetching}>- Next+ {t('admin.common.next')}</Button></div></div>@@ -473,6 +480,7 @@ function ProductGroup({ group, defaultOpen }: { group: StockItemGroup; defaultOp}function StockItemRow({ item }: { item: StockItem }) {+ const { t } = useTranslation()const { storeId } = Route.useParams()const updateMutation = useUpdateStockItem(item.id)const [count, setCount] = useState<number>(item.count_on_hand)@@ -541,7 +549,7 @@ function StockItemRow({ item }: { item: StockItem }) {onClick={save}disabled={!dirty || updateMutation.isPending}>- {updateMutation.isPending ? '…' : 'Save'}+ {updateMutation.isPending ? '…' : t('admin.actions.save')}</Button></td></tr>@@ -618,6 +626,7 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<StockLocationFo)}}/>+ <FieldError errors={[errors.kind]} /></Field><BooleanRow@@ -708,6 +717,7 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<StockLocationFo/>)}/>+ <FieldError errors={[errors.country_iso]} /></Field>{states.length > 0 ? (<Field>@@ -724,6 +734,7 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<StockLocationFo/>)}/>+ <FieldError errors={[errors.state_abbr]} /></Field>) : (<Field>@@ -801,6 +812,7 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<StockLocationFo)}}/>+ <FieldError errors={[errors.pickup_stock_policy]} /></Field><Field><FieldLabel htmlFor="pickup-ready-in-minutes">@@ -813,13 +825,7 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<StockLocationFostep={5}placeholder={t('admin.fields.stock_location.pickup_ready_in_minutes.placeholder')}aria-invalid={!!errors.pickup_ready_in_minutes || undefined}- {...form.register('pickup_ready_in_minutes', {- // Empty number inputs read as '' on the DOM; valueAsNumber turns- // that into NaN, which the optional/nullable Zod schema rejects- // and the form won't submit. Map empty → null instead.- setValueAs: (v) =>- v === '' || v === null || v === undefined ? null : Number(v),- })}+ {...form.register('pickup_ready_in_minutes')}/><FieldError errors={[errors.pickup_ready_in_minutes]} /></Field>diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/tax-categories.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/tax-categories.tsxindex d21dadf747..96f02ce77e 100644--- a/packages/admin/src/routes/_authenticated/$storeId/settings/tax-categories.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/tax-categories.tsx@@ -12,7 +12,7 @@ import { useConfirm } from '@/components/spree/confirm-dialog'import { ResourceTable, resourceSearchSchema } from '@/components/spree/resource-table'import { useRowClickBridge } from '@/components/spree/row-click-bridge'import { Button } from '@/components/ui/button'-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'+import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'import { Input } from '@/components/ui/input'import {Sheet,@@ -213,8 +213,13 @@ function EditTaxCategorySheet({confirmLabel: t('admin.actions.delete'),})if (!ok) return- await deleteMutation.mutateAsync(id)- onOpenChange(false)+ try {+ await deleteMutation.mutateAsync(id)+ onOpenChange(false)+ } catch {+ // `useResourceMutation` already toasts non-422 errors; keep the sheet+ // open so the user can retry.+ }}return (@@ -289,7 +294,7 @@ function TaxCategoryFormFields({ form }: { form: UseFormReturn<TaxCategoryFormVaaria-invalid={!!errors.name || undefined}{...form.register('name')}/>- {errors.name && <p className="text-sm text-destructive">{errors.name.message}</p>}+ <FieldError errors={[errors.name]} /></Field><Field>@@ -300,7 +305,7 @@ function TaxCategoryFormFields({ form }: { form: UseFormReturn<TaxCategoryFormVaaria-invalid={!!errors.tax_code || undefined}{...form.register('tax_code')}/>- {errors.tax_code && <p className="text-sm text-destructive">{errors.tax_code.message}</p>}+ <FieldError errors={[errors.tax_code]} /></Field><Field>@@ -312,9 +317,7 @@ function TaxCategoryFormFields({ form }: { form: UseFormReturn<TaxCategoryFormVaaria-invalid={!!errors.description || undefined}{...form.register('description')}/>- {errors.description && (- <p className="text-sm text-destructive">{errors.description.message}</p>- )}+ <FieldError errors={[errors.description]} /></Field><Field>diff --git a/packages/admin/src/schemas/customer-group.ts b/packages/admin/src/schemas/customer-group.tsindex 0f0d952636..d91a1bd3c7 100644--- a/packages/admin/src/schemas/customer-group.ts+++ b/packages/admin/src/schemas/customer-group.ts@@ -1,10 +1,14 @@import type { CustomerGroupCreateParams, CustomerGroupUpdateParams } from '@spree/admin-sdk'import { z } from 'zod/v4'+import { blankToNull } from '@/lib/form-mappers'import { requiredMessage } from '@/lib/validation-messages'export const customerGroupFormSchema = z.object({- name: z.string().min(1, { error: requiredMessage('name') }),- description: z.string().optional(),+ name: z+ .string()+ .trim()+ .min(1, { error: requiredMessage('name') }),+ description: z.string().trim().optional(),})export type CustomerGroupFormValues = z.infer<typeof customerGroupFormSchema>@@ -16,6 +20,6 @@ export function customerGroupValuesToParams(): CustomerGroupCreateParams & CustomerGroupUpdateParams {return {name: v.name,- description: v.description && v.description.length > 0 ? v.description : null,+ description: blankToNull(v.description),}}diff --git a/packages/admin/src/schemas/gift-card.ts b/packages/admin/src/schemas/gift-card.tsindex f7f719dabb..2646c9f53b 100644--- a/packages/admin/src/schemas/gift-card.ts+++ b/packages/admin/src/schemas/gift-card.ts@@ -74,7 +74,7 @@ export function giftCardBatchValuesToParams(): GiftCardBatchCreateParams {// `code` carries the prefix in batch mode; required, validated above.return {- prefix: v.code ?? '',+ prefix: v.code?.trim() ?? '',amount: v.amount,currency: v.currency,codes_count: v.quantity,diff --git a/packages/admin/src/schemas/payment-method.ts b/packages/admin/src/schemas/payment-method.tsindex 56be9704f4..6d34f02e5b 100644--- a/packages/admin/src/schemas/payment-method.ts+++ b/packages/admin/src/schemas/payment-method.ts@@ -1,6 +1,5 @@import type { PaymentMethodCreateParams, PaymentMethodUpdateParams } from '@spree/admin-sdk'import { z } from 'zod/v4'-import type { PaymentMethodFormValues } from '@/components/spree/payment-method-editors/types'import { requiredMessage } from '@/lib/validation-messages'export const paymentMethodBaseFormSchema = z.object({@@ -9,12 +8,18 @@ export const paymentMethodBaseFormSchema = z.object({storefront_visible: z.boolean(),active: z.boolean(),auto_capture: z.boolean(),+ // Provider STI shorthand (e.g. `stripe`). Only set in create mode; the+ // top-level type is optional on the shared shape and required on the+ // create-only schema below.+ type: z.string().optional(),})export const paymentMethodCreateFormSchema = paymentMethodBaseFormSchema.extend({type: z.string().min(1, { error: requiredMessage('payment_method.type') }),})+export type PaymentMethodFormValues = z.infer<typeof paymentMethodBaseFormSchema>+export const PAYMENT_METHOD_BASE_DEFAULTS: PaymentMethodFormValues = {name: '',description: '',@@ -32,8 +37,11 @@ export function paymentMethodValuesToCreateParams(v: PaymentMethodFormValues,preferences: Record<string, unknown>,): PaymentMethodCreateParams {+ // Schema should have already rejected this — guard against a misuse path+ // that would otherwise send an empty `type` and let the server 422.+ if (!v.type) throw new Error('payment method type is required')return {- type: v.type ?? '',+ type: v.type,name: v.name,description: v.description?.length ? v.description : null,active: v.active,diff --git a/packages/admin/src/schemas/promotion.ts b/packages/admin/src/schemas/promotion.tsindex debd6ad020..ea9592c822 100644--- a/packages/admin/src/schemas/promotion.ts+++ b/packages/admin/src/schemas/promotion.ts@@ -3,6 +3,7 @@ import type {PromotionActionFormDraft,PromotionRuleFormDraft,} from '@/components/spree/promotion-editors/types'+import { emptyToUndefined } from '@/lib/form-mappers'import { i18n } from '@/lib/i18n'import { requiredMessage } from '@/lib/validation-messages'@@ -42,11 +43,14 @@ export const promotionFormSchema = zkind: z.enum(['coupon_code', 'automatic']),code: z.string(),multi_codes: z.boolean(),- number_of_codes: z.coerce.number().int().positive().optional(),+ number_of_codes: z.preprocess(+ emptyToUndefined,+ z.coerce.number().int().positive().optional(),+ ),code_prefix: z.string(),starts_at: z.string(),expires_at: z.string(),- usage_limit: z.coerce.number().int().positive().optional(),+ usage_limit: z.preprocess(emptyToUndefined, z.coerce.number().int().positive().optional()),match_policy: z.enum(['all', 'any']),// Rule/action drafts are owned by the editor components; we accept whatever// shape they emit and let the server's rule/action serializers validate.diff --git a/packages/admin/src/schemas/stock-location.ts b/packages/admin/src/schemas/stock-location.tsindex 7d08d6a863..5ba826ca64 100644--- a/packages/admin/src/schemas/stock-location.ts+++ b/packages/admin/src/schemas/stock-location.ts@@ -4,7 +4,7 @@ import type {StockLocationUpdateParams,} from '@spree/admin-sdk'import { z } from 'zod/v4'-import { blankToUndefined } from '@/lib/form-mappers'+import { blankToUndefined, emptyToUndefined } from '@/lib/form-mappers'import { requiredMessage } from '@/lib/validation-messages'// Labels live in `en.json` under `admin.stock_locations.kinds.*` and@@ -12,11 +12,15 @@ import { requiredMessage } from '@/lib/validation-messages'// values to translated labels at render time.export const STOCK_LOCATION_KINDS = ['warehouse', 'store', 'fulfillment_center'] as constexport const PICKUP_STOCK_POLICIES = ['local', 'any'] as const+export type PickupStockPolicy = (typeof PICKUP_STOCK_POLICIES)[number]export const stockLocationFormSchema = z.object({- name: z.string().min(1, { error: requiredMessage('name') }),+ name: z+ .string()+ .trim()+ .min(1, { error: requiredMessage('name') }),admin_name: z.string().optional(),- kind: z.string().min(1),+ kind: z.enum(STOCK_LOCATION_KINDS),active: z.boolean(),default: z.boolean(),propagate_all_variants: z.boolean(),@@ -31,8 +35,11 @@ export const stockLocationFormSchema = z.object({state_abbr: z.string().optional(),state_name: z.string().optional(),pickup_enabled: z.boolean(),- pickup_stock_policy: z.enum(['local', 'any']),- pickup_ready_in_minutes: z.coerce.number().int().min(0).optional().nullable(),+ pickup_stock_policy: z.enum(PICKUP_STOCK_POLICIES),+ pickup_ready_in_minutes: z.preprocess(+ emptyToUndefined,+ z.coerce.number().int().min(0).optional().nullable(),+ ),pickup_instructions: z.string().optional(),})@@ -65,7 +72,9 @@ export function stockLocationToFormValues(sl: StockLocation): StockLocationFormVreturn {name: sl.name,admin_name: sl.admin_name ?? '',- kind: sl.kind ?? 'warehouse',+ kind: STOCK_LOCATION_KINDS.includes(sl.kind as (typeof STOCK_LOCATION_KINDS)[number])+ ? (sl.kind as (typeof STOCK_LOCATION_KINDS)[number])+ : 'warehouse',active: sl.active,default: sl.default,propagate_all_variants: sl.propagate_all_variants,@@ -80,7 +89,9 @@ export function stockLocationToFormValues(sl: StockLocation): StockLocationFormVstate_abbr: sl.state_abbr ?? '',state_name: sl.state_name ?? '',pickup_enabled: sl.pickup_enabled,- pickup_stock_policy: (sl.pickup_stock_policy as 'local' | 'any') ?? 'local',+ pickup_stock_policy: PICKUP_STOCK_POLICIES.includes(sl.pickup_stock_policy as PickupStockPolicy)+ ? (sl.pickup_stock_policy as PickupStockPolicy)+ : 'local',pickup_ready_in_minutes: sl.pickup_ready_in_minutes ?? null,pickup_instructions: sl.pickup_instructions ?? '',}diff --git a/packages/admin/src/schemas/store-credit.ts b/packages/admin/src/schemas/store-credit.tsnew file mode 100644index 0000000000..1206afde93--- /dev/null+++ b/packages/admin/src/schemas/store-credit.ts@@ -0,0 +1,41 @@+import { z } from 'zod/v4'+import { i18n } from '@/lib/i18n'+import { requiredMessage } from '@/lib/validation-messages'++const amountPositive = () =>+ i18n.t('admin.validation.positive_number', {+ field: i18n.t('admin.fields.store_credit.amount.label'),+ })++// Amount stays a string in the form (Input value), validated against+// "positive numeric" without coercing — the submit handler does the coercion+// so we can preserve trim/blank semantics.+const amountField = z+ .string()+ .trim()+ .refine((v) => v !== '' && Number.isFinite(Number(v)) && Number(v) > 0, {+ error: amountPositive,+ })++export const issueStoreCreditFormSchema = z.object({+ amount: amountField,+ currency: z.string().min(1, { error: requiredMessage('currency') }),+ category_id: z.string().min(1, { error: requiredMessage('store_credit.category_id') }),+ memo: z.string(),+})++export type IssueStoreCreditFormValues = z.infer<typeof issueStoreCreditFormSchema>++// Edit allows blank amount (means "no change") but if provided must be > 0.+export const editStoreCreditFormSchema = z.object({+ amount: z+ .string()+ .trim()+ .refine((v) => v === '' || (Number.isFinite(Number(v)) && Number(v) > 0), {+ error: amountPositive,+ }),+ category_id: z.string(),+ memo: z.string(),+})++export type EditStoreCreditFormValues = z.infer<typeof editStoreCreditFormSchema>diff --git a/packages/admin/src/schemas/store.ts b/packages/admin/src/schemas/store.tsindex 6e395f0761..d928487ba7 100644--- a/packages/admin/src/schemas/store.ts+++ b/packages/admin/src/schemas/store.ts@@ -1,14 +1,22 @@import { z } from 'zod/v4'import { requiredMessage } from '@/lib/validation-messages'+// Labels live in `en.json` under `admin.store.unit_systems.*` and+// `admin.store.weight_units.*`. Consumers translate at render time.+export type UnitSystem = 'metric' | 'imperial'+export const UNIT_SYSTEMS: readonly UnitSystem[] = ['metric', 'imperial']+export const WEIGHT_UNITS: Record<UnitSystem, readonly string[]> = {+ metric: ['kg', 'g'],+ imperial: ['lb', 'oz'],+}+const ALL_WEIGHT_UNITS = [...WEIGHT_UNITS.metric, ...WEIGHT_UNITS.imperial] as const+export const storeSettingsFormSchema = z.object({name: z.string().min(1, { error: requiredMessage('store.name') }),preferred_admin_locale: z.string().nullable().optional(),preferred_timezone: z.string().min(1, { error: requiredMessage('store.preferred_timezone') }),preferred_unit_system: z.enum(['metric', 'imperial']),- preferred_weight_unit: z- .string()- .min(1, { error: requiredMessage('store.preferred_weight_unit') }),+ preferred_weight_unit: z.enum(ALL_WEIGHT_UNITS),})export type StoreSettingsFormValues = z.infer<typeof storeSettingsFormSchema>@@ -25,12 +33,3 @@ export const ADMIN_LOCALE_OPTIONS: Array<{ value: string; label: string }> = [{ value: 'ja', label: '日本語' },{ value: 'zh-CN', label: '中文 (简体)' },]--// Labels live in `en.json` under `admin.store.unit_systems.*` and-// `admin.store.weight_units.*`. Consumers translate at render time.-export type UnitSystem = 'metric' | 'imperial'-export const UNIT_SYSTEMS: readonly UnitSystem[] = ['metric', 'imperial']-export const WEIGHT_UNITS: Record<UnitSystem, readonly string[]> = {- metric: ['kg', 'g'],- imperial: ['lb', 'oz'],-}diff --git a/packages/admin/src/tables/customers.tsx b/packages/admin/src/tables/customers.tsxindex 6959c42611..bd862e17b5 100644--- a/packages/admin/src/tables/customers.tsx+++ b/packages/admin/src/tables/customers.tsx@@ -35,7 +35,7 @@ defineTable('customers', {sortable: true,filterable: true,default: true,- render: (c) => c.full_name ?? '—',+ render: (c) => c.full_name ?? ([c.first_name, c.last_name].filter(Boolean).join(' ') || '—'),},{key: 'phone',diff --git a/packages/admin/src/tables/gift-cards.tsx b/packages/admin/src/tables/gift-cards.tsxindex dec14b5c75..3f6bb5f1aa 100644--- a/packages/admin/src/tables/gift-cards.tsx+++ b/packages/admin/src/tables/gift-cards.tsx@@ -1,4 +1,5 @@import type { GiftCard } from '@spree/admin-sdk'+import i18n from 'i18next'import { GiftIcon } from 'lucide-react'import { RelativeTime } from '@/components/spree/relative-time'import { ResourceNameCell } from '@/components/spree/resource-name-cell'@@ -13,10 +14,10 @@ import { defineTable } from '@/lib/table-registry'// "active" — keep this list in sync with the state machine + display_state// override in `app/models/spree/gift_card.rb`.const STATUS_OPTIONS = [- { value: 'active', label: 'Active' },- { value: 'partially_redeemed', label: 'Partially redeemed' },- { value: 'redeemed', label: 'Redeemed' },- { value: 'canceled', label: 'Canceled' },+ { value: 'active', label: i18n.t('admin.gift_cards.statuses.active') },+ { value: 'partially_redeemed', label: i18n.t('admin.gift_cards.statuses.partially_redeemed') },+ { value: 'redeemed', label: i18n.t('admin.gift_cards.statuses.redeemed') },+ { value: 'canceled', label: i18n.t('admin.gift_cards.statuses.canceled') },] as constconst STATUS_VARIANT: Record<@@ -30,21 +31,23 @@ const STATUS_VARIANT: Record<expired: 'destructive',}-function formatStatus(value: string): string {- return value.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())+function statusLabel(value: string): string {+ return i18n.exists(`admin.gift_cards.statuses.${value}`)+ ? i18n.t(`admin.gift_cards.statuses.${value}`)+ : value.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())}defineTable<GiftCard>('gift-cards', {- title: 'Gift Cards',+ title: i18n.t('admin.nav.gift_cards'),searchParam: 'code_cont',- searchPlaceholder: 'Search by code…',+ searchPlaceholder: i18n.t('admin.gift_cards.table.search_placeholder'),defaultSort: { field: 'created_at', direction: 'desc' },emptyIcon: <GiftIcon className="size-8 text-muted-foreground" />,- emptyMessage: 'No gift cards yet',+ emptyMessage: i18n.t('admin.gift_cards.table.empty'),columns: [{key: 'code',- label: 'Code',+ label: i18n.t('admin.fields.gift_card.code.label'),sortable: true,filterable: true,default: true,@@ -59,7 +62,7 @@ defineTable<GiftCard>('gift-cards', {},{key: 'status',- label: 'Status',+ label: i18n.t('admin.fields.status.label'),// Ransack filters off the underlying `state` column — `display_state`// is a presentation-only override that returns 'expired' for active// cards past their `expires_at`. Server still indexes `state`.@@ -71,33 +74,33 @@ defineTable<GiftCard>('gift-cards', {default: true,render: (g) => {const status = g.status ?? 'active'- return <Badge variant={STATUS_VARIANT[status] ?? 'secondary'}>{formatStatus(status)}</Badge>+ return <Badge variant={STATUS_VARIANT[status] ?? 'secondary'}>{statusLabel(status)}</Badge>},},{key: 'display_amount',- label: 'Amount',+ label: i18n.t('admin.fields.gift_card.amount.label'),default: true,className: 'text-right tabular-nums whitespace-nowrap font-medium',render: (g) => g.display_amount,},{key: 'display_amount_used',- label: 'Used',+ label: i18n.t('admin.gift_cards.columns.used'),default: true,className: 'text-right tabular-nums whitespace-nowrap',render: (g) => g.display_amount_used,},{key: 'display_amount_remaining',- label: 'Remaining',+ label: i18n.t('admin.gift_cards.columns.remaining'),default: true,className: 'text-right tabular-nums whitespace-nowrap',render: (g) => g.display_amount_remaining,},{key: 'currency',- label: 'Currency',+ label: i18n.t('admin.fields.gift_card.currency.label'),sortable: true,filterable: true,filterType: 'currency',@@ -106,7 +109,7 @@ defineTable<GiftCard>('gift-cards', {},{key: 'gift_card_batch',- label: 'Batch',+ label: i18n.t('admin.gift_cards.columns.batch'),// Filter narrows to cards belonging to one or more batches via the// `gift_card_batch_id_in` Ransack predicate (whitelisted on the// GiftCard model). Picker renders inline batch prefixes.@@ -124,7 +127,7 @@ defineTable<GiftCard>('gift-cards', {},{key: 'customer',- label: 'Customer',+ label: i18n.t('admin.gift_cards.columns.customer'),// Whitelisted `user_id` on the GiftCard model.ransackAttribute: 'user_id',filterable: true,@@ -135,7 +138,7 @@ defineTable<GiftCard>('gift-cards', {},{key: 'created_by',- label: 'Issued by',+ label: i18n.t('admin.gift_cards.columns.issued_by'),// GiftCard whitelists `code`, `user_id`, `state`, `gift_card_batch_id`.// `created_by_id` is not whitelisted yet — Ransack will reject the// predicate without it; we add it server-side alongside this column.@@ -148,7 +151,7 @@ defineTable<GiftCard>('gift-cards', {},{key: 'expires_at',- label: 'Expires',+ label: i18n.t('admin.gift_cards.columns.expires'),sortable: true,filterable: true,filterType: 'date',@@ -158,7 +161,7 @@ defineTable<GiftCard>('gift-cards', {},{key: 'created_at',- label: 'Created',+ label: i18n.t('admin.gift_cards.columns.created'),sortable: true,filterType: 'date',default: false,diff --git a/packages/admin/src/tables/products.tsx b/packages/admin/src/tables/products.tsxindex c3d9cedeba..c365629210 100644--- a/packages/admin/src/tables/products.tsx+++ b/packages/admin/src/tables/products.tsx@@ -87,7 +87,9 @@ defineTable('products', {{variantCount > 1 ? (<> – - <span className="text-sm text-muted-foreground">{variantCount} variants</span>+ <span className="text-sm text-muted-foreground">+ {i18n.t('admin.pages.products.variants', { count: variantCount })}+ </span></>) : (''