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
Implement translations and extract queries to hooks
Damian Legawiec81417fc0ee34
diff --git a/packages/admin/e2e/auth.spec.ts b/packages/admin/e2e/auth.spec.tsindex 4f67913501..cf7012ba84 100644--- a/packages/admin/e2e/auth.spec.ts+++ b/packages/admin/e2e/auth.spec.ts@@ -10,7 +10,7 @@ test.describe('admin authentication', () => {await page.getByLabel(/email/i).fill(creds.admin_email)await page.getByLabel(/password/i).fill(creds.admin_password)- await page.getByRole('button', { name: /^login$/i }).click()+ await page.getByRole('button', { name: /^sign in$/i }).click()// The /_authenticated/ index resolves the active store and redirects to// /$storeId. We just need to leave /login.@@ -23,7 +23,7 @@ test.describe('admin authentication', () => {await page.getByLabel(/email/i).fill('[email protected]')await page.getByLabel(/password/i).fill('wrong-password-123')- await page.getByRole('button', { name: /^login$/i }).click()+ await page.getByRole('button', { name: /^sign in$/i }).click()await expect(page.getByText(/invalid email or password/i)).toBeVisible()expect(page.url()).toContain('/login')diff --git a/packages/admin/e2e/customer-groups.spec.ts b/packages/admin/e2e/customer-groups.spec.tsindex 30c4cd02c4..e6b96fe286 100644--- a/packages/admin/e2e/customer-groups.spec.ts+++ b/packages/admin/e2e/customer-groups.spec.ts@@ -62,10 +62,10 @@ test.describe('customer groups', () => {await rowButton(page, name).click()await expect(page.getByRole('heading', { name })).toBeVisible({ timeout: 15_000 })- // Members summary shows "0 customers in this group" (empty by default) +- // a View members link that deep-links to the customers index with a- // Ransack filter on `customer_groups_id_in`.- await expect(page.getByText(/0 customers in this group/i)).toBeVisible()+ // Members summary shows "0 customers" (empty by default) + a View members+ // link that deep-links to the customers index with a Ransack filter on+ // `customer_groups_id_in`.+ await expect(page.getByText(/^0 customers$/i)).toBeVisible()const link = page.getByRole('link', { name: /view members/i })await expect(link).toHaveAttribute('href', /customer_groups_id/)})diff --git a/packages/admin/e2e/customers.spec.ts b/packages/admin/e2e/customers.spec.tsindex 4849c4421a..dfa90845e7 100644--- a/packages/admin/e2e/customers.spec.ts+++ b/packages/admin/e2e/customers.spec.ts@@ -87,7 +87,7 @@ test.describe('customers', () => {const email = `e2e-credit-${Date.now()}@example.com`await createCustomer(page, email)- await page.getByRole('button', { name: /issue credit/i }).click()+ await page.getByRole('button', { name: /issue store credit/i }).click()await expect(page.getByRole('heading', { name: /issue store credit/i })).toBeVisible()await page.locator('#sc-amount').fill('25.00')@@ -95,7 +95,7 @@ test.describe('customers', () => {await page.locator('#sc-category').click()await page.getByRole('option').first().click()- await page.getByRole('button', { name: /^issue credit$/i }).click()+ await page.getByRole('button', { name: /^issue store credit$/i }).click()await expect(page.getByText(/25\.00/).first()).toBeVisible({ timeout: 15_000 })})@@ -128,7 +128,7 @@ test.describe('customers', () => {await page.getByRole('button', { name: /add to group/i }).click()// Picker sheet opens — pick the seeded group, then confirm.- await expect(page.getByRole('heading', { name: /add 2 customers to groups/i })).toBeVisible()+ await expect(page.getByRole('heading', { name: /add to groups/i })).toBeVisible()await page.getByRole('dialog').getByPlaceholder(/search customer groups/i)diff --git a/packages/admin/e2e/gift-cards.spec.ts b/packages/admin/e2e/gift-cards.spec.tsindex 4d58a03f9d..38f38e30cf 100644--- a/packages/admin/e2e/gift-cards.spec.ts+++ b/packages/admin/e2e/gift-cards.spec.ts@@ -13,7 +13,9 @@ async function createGiftCard(if (attrs.code) await page.locator('#code').fill(attrs.code)await page.locator('#amount').fill(attrs.amount)- if (attrs.expiresAt) await page.locator('#expires_at').fill(attrs.expiresAt)+ // Note: expires_at is a `<StoreDatePicker>` (button + popover), not a native+ // input — can't be `.fill()`ed. Specs needing an expiry should drive the+ // picker UI instead of passing `expiresAt` here.await page.getByRole('button', { name: /create gift card/i }).click()}@@ -40,7 +42,7 @@ test.describe('gift cards', () => {await gotoIndex(page, GIFT_CARDS_PATH(creds.store_id), CTA)const code = `E2E${Date.now().toString().slice(-6)}`- await createGiftCard(page, { amount: '50.00', code, expiresAt: '2030-12-31' })+ await createGiftCard(page, { amount: '50.00', code })await expect(rowButton(page, code)).toBeVisible({ timeout: 15_000 })@@ -66,7 +68,7 @@ test.describe('gift cards', () => {// Quantity > 1 flips the sheet into batch mode — the Code field// relabels to Prefix and the customer picker disappears.await page.locator('#quantity').fill('3')- await expect(page.getByText(/Bulk-issue 3 gift cards/i)).toBeVisible()+ await expect(page.getByText(/^prefix$/i).first()).toBeVisible()await page.locator('#code').fill(prefix)await page.locator('#amount').fill('20.00')diff --git a/packages/admin/e2e/helpers.ts b/packages/admin/e2e/helpers.tsindex 546812462f..cf8d4ef4ff 100644--- a/packages/admin/e2e/helpers.ts+++ b/packages/admin/e2e/helpers.ts@@ -44,7 +44,7 @@ export async function login(page: Page): Promise<E2ECredentials> {await page.goto('/login')await page.getByLabel(/email/i).fill(creds.admin_email)await page.getByLabel(/password/i).fill(creds.admin_password)- await page.getByRole('button', { name: /^login$/i }).click()+ await page.getByRole('button', { name: /^sign in$/i }).click()await expect(page).not.toHaveURL(/\/login/, { timeout: 15_000 })return creds}@@ -104,11 +104,11 @@ export async function fillAddressForm(page: Page, address: AddressInput) {if (address.postalCode !== undefined) await page.locator('#addr-zip').fill(address.postalCode)if (address.phone !== undefined) await page.locator('#addr-phone').fill(address.phone)if (address.country) {- await page.getByPlaceholder('Search countries...').fill(address.country)+ await page.getByPlaceholder(/^search countries/i).fill(address.country)await page.getByRole('option', { name: address.country }).first().click()}if (address.state) {- await page.getByPlaceholder('Search states...').fill(address.state)+ await page.getByPlaceholder(/^search states/i).fill(address.state)await page.getByRole('option', { name: address.state }).first().click()}}diff --git a/packages/admin/e2e/option-types.spec.ts b/packages/admin/e2e/option-types.spec.tsindex 5d25b70552..17e7bc4ac5 100644--- a/packages/admin/e2e/option-types.spec.ts+++ b/packages/admin/e2e/option-types.spec.ts@@ -9,7 +9,7 @@ async function createOptionType(attrs: { internalName: string; label: string; values?: Array<{ name: string; label: string }> },) {await page.getByRole('button', { name: /add option type/i }).click()- await expect(page.getByRole('heading', { name: /add option type/i })).toBeVisible()+ await expect(page.getByRole('heading', { name: /create option type/i })).toBeVisible()// Use `#label` / `#name` directly — row-level option-value inputs also// expose accessible names of "Label" / "Internal name", and `getByLabel`'sdiff --git a/packages/admin/src/components/spree/address-form-dialog.tsx b/packages/admin/src/components/spree/address-form-dialog.tsxindex 9f2667366e..8f8134d967 100644--- a/packages/admin/src/components/spree/address-form-dialog.tsx+++ b/packages/admin/src/components/spree/address-form-dialog.tsx@@ -155,22 +155,18 @@ export function AddressFormDialog({)}<div className="grid grid-cols-2 gap-3"><Field>- <FieldLabel htmlFor="addr-first-name">- {t('admin.fields.first_name.label')}- </FieldLabel>+ <FieldLabel htmlFor="addr-fn">{t('admin.fields.first_name.label')}</FieldLabel><Input- id="addr-first-name"+ id="addr-fn"aria-invalid={!!errors.first_name || undefined}{...form.register('first_name')}/><FieldError errors={[errors.first_name]} /></Field><Field>- <FieldLabel htmlFor="addr-last-name">- {t('admin.fields.last_name.label')}- </FieldLabel>+ <FieldLabel htmlFor="addr-ln">{t('admin.fields.last_name.label')}</FieldLabel><Input- id="addr-last-name"+ id="addr-ln"aria-invalid={!!errors.last_name || undefined}{...form.register('last_name')}/>@@ -178,22 +174,22 @@ export function AddressFormDialog({</Field></div><Field>- <FieldLabel htmlFor="addr-address1">+ <FieldLabel htmlFor="addr-a1">{t('admin.fields.address.address1.label')}</FieldLabel><Input- id="addr-address1"+ id="addr-a1"aria-invalid={!!errors.address1 || undefined}{...form.register('address1')}/><FieldError errors={[errors.address1]} /></Field><Field>- <FieldLabel htmlFor="addr-address2">+ <FieldLabel htmlFor="addr-a2">{t('admin.fields.address.address2.label')}</FieldLabel><Input- id="addr-address2"+ id="addr-a2"aria-invalid={!!errors.address2 || undefined}{...form.register('address2')}/>@@ -256,11 +252,11 @@ export function AddressFormDialog({)}</div><Field>- <FieldLabel htmlFor="addr-postal-code">+ <FieldLabel htmlFor="addr-zip">{t('admin.fields.address.postal_code.label')}</FieldLabel><Input- id="addr-postal-code"+ id="addr-zip"aria-invalid={!!errors.postal_code || undefined}{...form.register('postal_code')}/>diff --git a/packages/admin/src/components/spree/back-button.tsx b/packages/admin/src/components/spree/back-button.tsxindex b5f314dd67..8e0800bfcf 100644--- a/packages/admin/src/components/spree/back-button.tsx+++ b/packages/admin/src/components/spree/back-button.tsx@@ -1,5 +1,6 @@import { useParams, useRouter } from '@tanstack/react-router'import { ArrowLeftIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'interface BackButtonProps {/**@@ -16,6 +17,7 @@ interface BackButtonProps {* when there's nothing to go back to (e.g. deep-link, new tab).*/export function BackButton({ fallback, className }: BackButtonProps) {+ const { t } = useTranslation()const router = useRouter()const { storeId } = useParams({ strict: false }) as { storeId?: string }@@ -38,7 +40,7 @@ export function BackButton({ fallback, className }: BackButtonProps) {className ??'inline-flex items-center justify-center rounded-lg p-1.5 text-muted-foreground hover:bg-accent hover:text-foreground transition-colors'}- aria-label="Back"+ aria-label={t('admin.actions.back')}><ArrowLeftIcon className="size-5" /></button>diff --git a/packages/admin/src/components/spree/color-picker.tsx b/packages/admin/src/components/spree/color-picker.tsxindex 222f4563e5..088c2963a5 100644--- a/packages/admin/src/components/spree/color-picker.tsx+++ b/packages/admin/src/components/spree/color-picker.tsx@@ -1,5 +1,6 @@import { useEffect, useRef, useState } from 'react'import { HexColorPicker } from 'react-colorful'+import { useTranslation } from 'react-i18next'import { Input } from '@/components/ui/input'import { cn } from '@/lib/utils'@@ -64,6 +65,7 @@ export function ColorPicker({compact = false,panelAlign = 'start',}: ColorPickerProps) {+ const { t } = useTranslation()const normalizedValue = normalizeHex(value)const [open, setOpen] = useState(false)// Local text mirrors `value` but lets the user type freely (including@@ -139,7 +141,11 @@ export function ColorPicker({<buttontype="button"disabled={disabled}- aria-label={normalizedValue ? `Change color (${normalizedValue})` : 'Pick a color'}+ aria-label={+ normalizedValue+ ? t('admin.a11y.change_color', { value: normalizedValue })+ : t('admin.a11y.pick_color')+ }aria-haspopup="dialog"aria-expanded={open}onClick={() => setOpen((v) => !v)}@@ -155,7 +161,7 @@ export function ColorPicker({{open && (<divrole="dialog"- aria-label="Pick a color"+ aria-label={t('admin.a11y.pick_color')}className={cn('absolute top-full z-50 mt-2 min-w-min rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-md',panelAlign === 'end' ? 'right-0' : 'left-0',diff --git a/packages/admin/src/components/spree/custom-fields/custom-fields-drawer.tsx b/packages/admin/src/components/spree/custom-fields/custom-fields-drawer.tsxindex dd2995ea86..958182d3e0 100644--- a/packages/admin/src/components/spree/custom-fields/custom-fields-drawer.tsx+++ b/packages/admin/src/components/spree/custom-fields/custom-fields-drawer.tsx@@ -2,6 +2,7 @@ import type { CustomFieldOwnerType } from '@spree/admin-sdk'import { ArrowLeftIcon, CheckCircle2Icon, Loader2Icon, PlusIcon } from 'lucide-react'import { type ReactNode, useEffect, useMemo, useState } from 'react'import { useForm } from 'react-hook-form'+import { useTranslation } from 'react-i18next'import { toast } from 'sonner'import { Button } from '@/components/ui/button'import {@@ -42,6 +43,7 @@ export function CustomFieldsDrawer({ownerId,resourceLabel,}: CustomFieldsDrawerProps) {+ const { t } = useTranslation()const [view, setView] = useState<View>('values')const [lastCreatedDefinitionId, setLastCreatedDefinitionId] = useState<string | null>(null)@@ -60,7 +62,7 @@ export function CustomFieldsDrawer({variant="ghost"size="icon-sm"onClick={() => setView('values')}- aria-label="Back"+ aria-label={t('admin.actions.back')}><ArrowLeftIcon className="size-4" /></Button>diff --git a/packages/admin/src/components/spree/drag-handle.tsx b/packages/admin/src/components/spree/drag-handle.tsxindex a8a6bf6761..1ce000a667 100644--- a/packages/admin/src/components/spree/drag-handle.tsx+++ b/packages/admin/src/components/spree/drag-handle.tsx@@ -1,6 +1,7 @@import type { DraggableAttributes, DraggableSyntheticListeners } from '@dnd-kit/core'import { GripVerticalIcon } from 'lucide-react'import type { ComponentProps } from 'react'+import { useTranslation } from 'react-i18next'import { cn } from '@/lib/utils'interface DragHandleProps extends Omit<ComponentProps<'button'>, 'type'> {@@ -31,10 +32,11 @@ interface DragHandleProps extends Omit<ComponentProps<'button'>, 'type'> {* surrounding cell (typically `w-8 touch-none p-0`).*/export function DragHandle({ attributes, listeners, className, ...props }: DragHandleProps) {+ const { t } = useTranslation()return (<buttontype="button"- aria-label="Drag to reorder"+ aria-label={t('admin.a11y.drag_to_reorder')}className={cn('flex h-full w-full items-center justify-center rounded-lg p-2 text-muted-foreground cursor-grab active:cursor-grabbing hover:bg-accent',className,diff --git a/packages/admin/src/components/spree/json-preview-drawer.tsx b/packages/admin/src/components/spree/json-preview-drawer.tsxindex 60bf76fb8b..6138d2a90c 100644--- a/packages/admin/src/components/spree/json-preview-drawer.tsx+++ b/packages/admin/src/components/spree/json-preview-drawer.tsx@@ -14,6 +14,7 @@ import {} from 'lucide-react'import type { ComponentProps } from 'react'import { useMemo, useState } from 'react'+import { useTranslation } from 'react-i18next'import { Button } from '@/components/ui/button'import {Sheet,@@ -76,6 +77,7 @@ export function JsonPreviewDrawer({endpoint,storeId,}: JsonPreviewDrawerProps) {+ const { t } = useTranslation()const { data, isLoading, isFetching, error, refetch } = useQuery({queryKey,queryFn,@@ -106,7 +108,7 @@ export function JsonPreviewDrawer({size="icon-xs"className="absolute top-3 right-3"onClick={() => onOpenChange(false)}- aria-label="Close"+ aria-label={t('admin.actions.close')}><XIcon className="size-4" /></ToolbarButton>@@ -116,16 +118,16 @@ export function JsonPreviewDrawer({<ToolbarButtonsize="icon-xs"onClick={() => setCollapsed(false)}- aria-label="Expand all"- title="Expand all"+ aria-label={t('admin.a11y.expand_all')}+ title={t('admin.a11y.expand_all')}><ChevronDownIcon className="size-4" /></ToolbarButton><ToolbarButtonsize="icon-xs"onClick={() => setCollapsed(true)}- aria-label="Collapse all"- title="Collapse all"+ aria-label={t('admin.a11y.collapse_all')}+ title={t('admin.a11y.collapse_all')}><ChevronRightIcon className="size-4" /></ToolbarButton>@@ -139,8 +141,8 @@ export function JsonPreviewDrawer({<ToolbarButtonsize="icon-xs"onClick={() => refetch()}- aria-label="Refetch"- title="Refetch"+ aria-label={t('admin.a11y.refetch')}+ title={t('admin.a11y.refetch')}disabled={isFetching}>{isFetching ? (diff --git a/packages/admin/src/components/spree/page-header.tsx b/packages/admin/src/components/spree/page-header.tsxindex b164ea0002..af3d27f130 100644--- a/packages/admin/src/components/spree/page-header.tsx+++ b/packages/admin/src/components/spree/page-header.tsx@@ -1,6 +1,7 @@import { useParams } from '@tanstack/react-router'import { BracesIcon, CheckIcon, CopyIcon, EllipsisVerticalIcon, TrashIcon } from 'lucide-react'import { lazy, type ReactNode, Suspense, useState } from 'react'+import { useTranslation } from 'react-i18next'import { BackButton } from '@/components/spree/back-button'import { useConfirm } from '@/components/spree/confirm-dialog'import type { JsonPreviewDrawerProps } from '@/components/spree/json-preview-drawer'@@ -203,12 +204,13 @@ function PageActionsDropdown({deleteLabel,onOpenJson,}: PageActionsDropdownProps) {+ const { t } = useTranslation()const confirm = useConfirm()return (<DropdownMenu><DropdownMenuTrigger asChild>- <Button size="icon-sm" variant="outline" aria-label="More actions">+ <Button size="icon-sm" variant="outline" aria-label={t('admin.actions.more_actions')}><EllipsisVerticalIcon className="size-4" /></Button></DropdownMenuTrigger>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 60114e8946..f797c4333a 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@@ -161,9 +161,9 @@ function PaymentMethodTopFields({ form }: { form: UseFormReturn<PaymentMethodForreturn (<FieldGroup><Field>- <FieldLabel htmlFor="pm-name">{t('admin.fields.name.label')}</FieldLabel>+ <FieldLabel htmlFor="name">{t('admin.fields.name.label')}</FieldLabel><Input- id="pm-name"+ id="name"placeholder={t('admin.fields.payment_method.name.placeholder')}aria-invalid={!!errors.name || undefined}{...form.register('name')}@@ -171,9 +171,9 @@ function PaymentMethodTopFields({ form }: { form: UseFormReturn<PaymentMethodFor<FieldError errors={[errors.name]} /></Field><Field>- <FieldLabel htmlFor="pm-description">{t('admin.fields.description.label')}</FieldLabel>+ <FieldLabel htmlFor="description">{t('admin.fields.description.label')}</FieldLabel><Textarea- id="pm-description"+ id="description"rows={2}placeholder={t('admin.fields.payment_method.description.placeholder')}aria-invalid={!!errors.description || undefined}@@ -185,7 +185,7 @@ function PaymentMethodTopFields({ form }: { form: UseFormReturn<PaymentMethodFor<Field><div className="flex items-start justify-between gap-4"><div className="flex flex-col">- <FieldLabel htmlFor="pm-active" className="cursor-pointer">+ <FieldLabel htmlFor="active" className="cursor-pointer">{t('admin.fields.payment_method.active.label')}</FieldLabel><span className="text-xs text-muted-foreground">@@ -196,7 +196,7 @@ function PaymentMethodTopFields({ form }: { form: UseFormReturn<PaymentMethodForname="active"control={form.control}render={({ field }) => (- <Switch id="pm-active" checked={!!field.value} onCheckedChange={field.onChange} />+ <Switch id="active" checked={!!field.value} onCheckedChange={field.onChange} />)}/></div>@@ -204,7 +204,7 @@ function PaymentMethodTopFields({ form }: { form: UseFormReturn<PaymentMethodFor<Field><div className="flex items-start justify-between gap-4"><div className="flex flex-col">- <FieldLabel htmlFor="pm-auto-capture" className="cursor-pointer">+ <FieldLabel htmlFor="auto_capture" className="cursor-pointer">{t('admin.fields.payment_method.auto_capture.label')}</FieldLabel><span className="text-xs text-muted-foreground">@@ -215,11 +215,7 @@ function PaymentMethodTopFields({ form }: { form: UseFormReturn<PaymentMethodForname="auto_capture"control={form.control}render={({ field }) => (- <Switch- id="pm-auto-capture"- checked={!!field.value}- onCheckedChange={field.onChange}- />+ <Switch id="auto_capture" checked={!!field.value} onCheckedChange={field.onChange} />)}/></div>diff --git a/packages/admin/src/components/spree/products/inventory-section.tsx b/packages/admin/src/components/spree/products/inventory-section.tsxindex 2cc6a5f7b0..59cb755f84 100644--- a/packages/admin/src/components/spree/products/inventory-section.tsx+++ b/packages/admin/src/components/spree/products/inventory-section.tsx@@ -3,6 +3,7 @@ import type { ColumnDef } from '@tanstack/react-table'import { ExternalLinkIcon } from 'lucide-react'import { useMemo } from 'react'import { Controller, type UseFormReturn, useWatch } from 'react-hook-form'+import { useTranslation } from 'react-i18next'import { DataGrid, NumberCell, ReadOnlyCell, SwitchCell } from '@/components/spree/data-grid'import type { ProductFormValues } from '@/schemas/product'@@ -29,6 +30,7 @@ interface InventorySectionProps {}export function InventorySection({ form, storeId, hasVariants }: InventorySectionProps) {+ const { t } = useTranslation()// Subscribe to the array so the rows recompute when the user adds/removes// a variant. We don't need finer reactivity here — individual cell values// are wired via Controllers below, which re-render only their own cell.@@ -168,7 +170,7 @@ export function InventorySection({ form, storeId, hasVariants }: InventorySectio</div>) : null}- aria-label="Stock at locations"+ aria-label={t('admin.a11y.stock_at_locations')}/>)}diff --git a/packages/admin/src/components/spree/promotion-editors/promotion-form.tsx b/packages/admin/src/components/spree/promotion-editors/promotion-form.tsxindex 5ae1048c2b..43cfafccfb 100644--- a/packages/admin/src/components/spree/promotion-editors/promotion-form.tsx+++ b/packages/admin/src/components/spree/promotion-editors/promotion-form.tsx@@ -76,10 +76,10 @@ import { mapSpreeErrorsToForm } from '@/lib/form-errors'import { Subject } from '@/lib/permissions'import { useStore } from '@/providers/store-provider'import {- KIND_OPTIONS,- MATCH_POLICY_OPTIONS,+ MATCH_POLICIES,type MatchPolicy,PROMOTION_DEFAULTS,+ PROMOTION_KINDS,type PromotionFormValues,type PromotionKind,promotionFormSchema,@@ -297,9 +297,9 @@ function BasicsCard({ form }: { form: UseFormReturn<PromotionFormValues> }) {<CardContent><FieldGroup><Field>- <FieldLabel htmlFor="promo-name">{t('admin.fields.name.label')}</FieldLabel>+ <FieldLabel htmlFor="name">{t('admin.fields.name.label')}</FieldLabel><Input- id="promo-name"+ id="name"placeholder={t('admin.fields.promotion.name.placeholder')}aria-invalid={!!errors.name || undefined}{...form.register('name')}@@ -307,11 +307,9 @@ function BasicsCard({ form }: { form: UseFormReturn<PromotionFormValues> }) {<FieldError errors={[errors.name]} /></Field><Field>- <FieldLabel htmlFor="promo-description">- {t('admin.fields.description.label')}- </FieldLabel>+ <FieldLabel htmlFor="description">{t('admin.fields.description.label')}</FieldLabel><Textarea- id="promo-description"+ id="description"rows={3}placeholder={t('admin.fields.promotion.description.placeholder')}aria-invalid={!!errors.description || undefined}@@ -350,28 +348,34 @@ function TriggerCard({) : (<FieldGroup><Field>- <FieldLabel htmlFor="promo-kind">{t('admin.fields.promotion.kind.label')}</FieldLabel>+ <FieldLabel htmlFor="kind">{t('admin.fields.promotion.kind.label')}</FieldLabel><Controllername="kind"control={form.control}- render={({ field }) => (- <Select- items={KIND_OPTIONS as never}- value={field.value}- onValueChange={field.onChange}- >- <SelectTrigger id="promo-kind">- <SelectValue />- </SelectTrigger>- <SelectContent>- {KIND_OPTIONS.map((o) => (- <SelectItem key={o.value} value={o.value}>- {o.label}- </SelectItem>- ))}- </SelectContent>- </Select>- )}+ render={({ field }) => {+ const items = PROMOTION_KINDS.map((value) => ({+ value,+ label: t(`admin.promotions.kinds.${value}`),+ }))+ return (+ <Select+ items={items as never}+ value={field.value}+ onValueChange={field.onChange}+ >+ <SelectTrigger id="kind">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {items.map((o) => (+ <SelectItem key={o.value} value={o.value}>+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+ }}/></Field>@@ -380,7 +384,7 @@ function TriggerCard({<Field><div className="flex items-start justify-between gap-4"><div className="flex flex-col">- <FieldLabel htmlFor="promo-multi-codes" className="cursor-pointer">+ <FieldLabel htmlFor="multi_codes" className="cursor-pointer">{t('admin.fields.promotion.multi_codes.label')}</FieldLabel><span className="text-xs text-muted-foreground">@@ -392,7 +396,7 @@ function TriggerCard({control={form.control}render={({ field }) => (<Switch- id="promo-multi-codes"+ id="multi_codes"checked={!!field.value}onCheckedChange={field.onChange}/>@@ -403,10 +407,10 @@ function TriggerCard({{!multiCodes ? (<Field>- <FieldLabel htmlFor="promo-code">{t('admin.fields.code.label')}</FieldLabel>+ <FieldLabel htmlFor="code">{t('admin.fields.code.label')}</FieldLabel><div className="flex items-center gap-2"><Input- id="promo-code"+ id="code"placeholder={t('admin.fields.promotion.code.placeholder')}aria-invalid={!!errors.code || undefined}{...form.register('code')}@@ -432,25 +436,28 @@ function TriggerCard({) : (<><Field>- <FieldLabel htmlFor="promo-number-of-codes">+ <FieldLabel htmlFor="number_of_codes">{t('admin.fields.promotion.number_of_codes.label')}</FieldLabel><Input- id="promo-number-of-codes"+ id="number_of_codes"type="number"min={1}placeholder={t('admin.fields.promotion.number_of_codes.placeholder')}aria-invalid={!!errors.number_of_codes || undefined}- {...form.register('number_of_codes')}+ {...form.register('number_of_codes', {+ setValueAs: (v) =>+ v === '' || v === null || v === undefined ? undefined : Number(v),+ })}/><FieldError errors={[errors.number_of_codes]} /></Field><Field>- <FieldLabel htmlFor="promo-code-prefix">+ <FieldLabel htmlFor="code_prefix">{t('admin.fields.promotion.code_prefix.label')}</FieldLabel><Input- id="promo-code-prefix"+ id="code_prefix"placeholder={t('admin.fields.promotion.code_prefix.placeholder')}aria-invalid={!!errors.code_prefix || undefined}{...form.register('code_prefix')}@@ -551,16 +558,20 @@ function ScheduleCard({ form }: { form: UseFormReturn<PromotionFormValues> }) {/></Field><Field>- <FieldLabel htmlFor="promo-usage-limit">+ <FieldLabel htmlFor="usage_limit">{t('admin.fields.promotion.usage_limit.label')}</FieldLabel><Input- id="promo-usage-limit"+ id="usage_limit"type="number"min={1}placeholder={t('admin.fields.promotion.usage_limit.placeholder')}aria-invalid={!!errors.usage_limit || undefined}- {...form.register('usage_limit')}+ {...form.register('usage_limit', {+ // Optional number — empty input means "no cap", not "0".+ setValueAs: (v) =>+ v === '' || v === null || v === undefined ? undefined : Number(v),+ })}/><FieldError errors={[errors.usage_limit]} /></Field>@@ -587,6 +598,7 @@ function RulesCard({rulesArray: RulesArraymatchPolicy: MatchPolicy}) {+ const { t } = useTranslation()const { data: typesData } = usePromotionRuleTypes()const { defaultCurrency } = useStore()const [pickerOpen, setPickerOpen] = useState(false)@@ -609,34 +621,36 @@ function RulesCard({<CardHeader><div className="flex flex-wrap items-start justify-between gap-3"><div>- <CardTitle>Rules</CardTitle>+ <CardTitle>{t('admin.promotions.rules_card.title')}</CardTitle><p className="text-sm text-muted-foreground">- Conditions that decide whether the promotion applies.{' '}- {matchPolicy === 'all' ? 'All rules must match.' : 'Any rule may match.'}+ {t('admin.promotions.rules_card.description')}{' '}+ {t(`admin.promotions.match_policies.${matchPolicy}_hint`)}</p></div>{showMatchPolicy && (<Controllername="match_policy"control={form.control}- render={({ field }) => (- <Select- items={MATCH_POLICY_OPTIONS}- value={field.value}- onValueChange={field.onChange}- >- <SelectTrigger id="match_policy" data-size="sm" className="w-auto">- <SelectValue />- </SelectTrigger>- <SelectContent>- {MATCH_POLICY_OPTIONS.map((o) => (- <SelectItem key={o.value} value={o.value}>- {o.label}- </SelectItem>- ))}- </SelectContent>- </Select>- )}+ render={({ field }) => {+ const items = MATCH_POLICIES.map((value) => ({+ value,+ label: t(`admin.promotions.match_policies.${value}`),+ }))+ return (+ <Select items={items as never} value={field.value} onValueChange={field.onChange}>+ <SelectTrigger id="match_policy" data-size="sm" className="w-auto">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {items.map((o) => (+ <SelectItem key={o.value} value={o.value}>+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+ }}/>)}</div>diff --git a/packages/admin/src/components/spree/resource-table.tsx b/packages/admin/src/components/spree/resource-table.tsxindex 5b3f4d2ba5..b8c861a191 100644--- a/packages/admin/src/components/spree/resource-table.tsx+++ b/packages/admin/src/components/spree/resource-table.tsx@@ -26,6 +26,7 @@ import {useMemo,useState,} from 'react'+import { useTranslation } from 'react-i18next'import { z } from 'zod/v4'import { type BulkAction, BulkActionBar } from '@/components/spree/bulk-action-bar'import { DragHandle } from '@/components/spree/drag-handle'@@ -175,6 +176,7 @@ export function ResourceTable<T extends Record<string, any>>({bulkActions,}: ResourceTableProps<T>) {const table = getTable<T>(tableKey)+ const { t } = useTranslation()const { token } = useAuth()const navigate = useNavigate()const queryClient = useQueryClient()@@ -452,7 +454,7 @@ export function ResourceTable<T extends Record<string, any>>({checked={allPageSelected}indeterminate={somePageSelected}onCheckedChange={togglePage}- aria-label="Select all rows on this page"+ aria-label={t('admin.a11y.select_all_rows')}/></TableHead>)}@@ -494,7 +496,7 @@ export function ResourceTable<T extends Record<string, any>>({<Checkboxchecked={isSelected}onCheckedChange={() => toggleRow(rowId)}- aria-label="Select row"+ aria-label={t('admin.a11y.select_row')}/></TableCell>)}diff --git a/packages/admin/src/components/spree/secret-input.tsx b/packages/admin/src/components/spree/secret-input.tsxindex 21ab61bc3a..1e9b5944d3 100644--- a/packages/admin/src/components/spree/secret-input.tsx+++ b/packages/admin/src/components/spree/secret-input.tsx@@ -1,6 +1,7 @@import { isMaskedSecret } from '@spree/admin-sdk'import { EyeIcon, EyeOffIcon } from 'lucide-react'import { useState } from 'react'+import { useTranslation } from 'react-i18next'import { Button } from '@/components/ui/button'import { Field, FieldLabel } from '@/components/ui/field'import { Input } from '@/components/ui/input'@@ -45,6 +46,7 @@ export function SecretInput({helpText,placeholder,}: SecretInputProps) {+ const { t } = useTranslation()const storedMask = isMaskedSecret(value) ? value : null// Captured at click time so Cancel can restore the original mask even// after `onChange('')` has cleared the parent value.@@ -97,7 +99,7 @@ export function SecretInput({/><buttontype="button"- aria-label={revealed ? 'Hide value' : 'Show value'}+ aria-label={revealed ? t('admin.a11y.hide_value') : t('admin.a11y.show_value')}aria-pressed={revealed}onClick={() => setRevealed((v) => !v)}className="absolute inset-y-0 right-0 flex items-center px-2.5 text-muted-foreground hover:text-foreground"diff --git a/packages/admin/src/components/spree/settings-sidebar.tsx b/packages/admin/src/components/spree/settings-sidebar.tsxindex 534a08e2b9..00d5323828 100644--- a/packages/admin/src/components/spree/settings-sidebar.tsx+++ b/packages/admin/src/components/spree/settings-sidebar.tsx@@ -1,5 +1,6 @@import { Link, useParams, useRouterState } from '@tanstack/react-router'import { PackageIcon } from 'lucide-react'+import { useTranslation } from 'react-i18next'import { NavIcon } from '@/components/spree/nav-main'import { Badge } from '@/components/ui/badge'import {@@ -34,6 +35,7 @@ import '@/nav/settings'* still need a separate solution.*/export function SettingsSidebar({ open }: { open: boolean }) {+ const { t } = useTranslation()const { storeId } = useParams({ strict: false }) as { storeId?: string }const id = storeId ?? 'default'const snapshot = useSettingsNav()@@ -46,7 +48,7 @@ export function SettingsSidebar({ open }: { open: boolean }) {// while closed prevents screen-reader and keyboard access to hidden links.return (<aside- aria-label="Settings navigation"+ aria-label={t('admin.a11y.settings_navigation')}aria-hidden={!open}data-state={open ? 'open' : 'closed'}className={cn(diff --git a/packages/admin/src/components/spree/top-bar.tsx b/packages/admin/src/components/spree/top-bar.tsxindex c7259c3f32..829baa8f73 100644--- a/packages/admin/src/components/spree/top-bar.tsx+++ b/packages/admin/src/components/spree/top-bar.tsx@@ -7,6 +7,7 @@ import {SearchIcon,UserIcon,} from 'lucide-react'+import { useTranslation } from 'react-i18next'import { ThemeMenuItems } from '@/components/spree/theme-toggle'import { Avatar, AvatarFallback } from '@/components/ui/avatar'import { Button } from '@/components/ui/button'@@ -98,6 +99,7 @@ function ViewStoreLink() {// ---------------------------------------------------------------------------function TopBarUser() {+ const { t } = useTranslation()const { user, logout } = useAuth()if (!user) return null@@ -108,7 +110,7 @@ function TopBarUser() {<DropdownMenuTrigger asChild><buttontype="button"- aria-label="User menu"+ aria-label={t('admin.a11y.user_menu')}className="flex items-center gap-2 rounded-lg p-1 transition-colors hover:bg-accent"><Avatar className="size-7">diff --git a/packages/admin/src/components/ui/breadcrumb.tsx b/packages/admin/src/components/ui/breadcrumb.tsxindex 47d37a8088..2b2e06fcdb 100644--- a/packages/admin/src/components/ui/breadcrumb.tsx+++ b/packages/admin/src/components/ui/breadcrumb.tsx@@ -1,10 +1,18 @@import { ChevronRightIcon, MoreHorizontalIcon } from 'lucide-react'import type * as React from 'react'import { Slot } from '@/components/ui/slot'+import { i18n } from '@/lib/i18n'import { cn } from '@/lib/utils'function Breadcrumb({ className, ...props }: React.ComponentProps<'nav'>) {- return <nav aria-label="breadcrumb" data-slot="breadcrumb" className={cn(className)} {...props} />+ return (+ <nav+ aria-label={i18n.t('admin.a11y.breadcrumb')}+ data-slot="breadcrumb"+ className={cn(className)}+ {...props}+ />+ )}function BreadcrumbList({ className, ...props }: React.ComponentProps<'ol'>) {diff --git a/packages/admin/src/components/ui/sidebar.tsx b/packages/admin/src/components/ui/sidebar.tsxindex 906b633fb6..d9c9dbd154 100644--- a/packages/admin/src/components/ui/sidebar.tsx+++ b/packages/admin/src/components/ui/sidebar.tsx@@ -15,6 +15,7 @@ import { Skeleton } from '@/components/ui/skeleton'import { Slot } from '@/components/ui/slot'import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'import { useIsMobile } from '@/hooks/use-mobile'+import { i18n } from '@/lib/i18n'import { cn } from '@/lib/utils'const SIDEBAR_COOKIE_NAME = 'sidebar_state'@@ -273,10 +274,10 @@ function SidebarRail({ className, ...props }: React.ComponentProps<'button'>) {<buttondata-sidebar="rail"data-slot="sidebar-rail"- aria-label="Toggle Sidebar"+ aria-label={i18n.t('admin.a11y.toggle_sidebar')}tabIndex={-1}onClick={toggleSidebar}- title="Toggle Sidebar"+ title={i18n.t('admin.a11y.toggle_sidebar')}className={cn('absolute inset-y-0 z-20 hidden w-4 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:start-1/2 after:w-[2px] hover:after:bg-sidebar-border sm:flex ltr:-translate-x-1/2 rtl:-translate-x-1/2','in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize',diff --git a/packages/admin/src/hooks/use-customer-store-credits.ts b/packages/admin/src/hooks/use-customer-store-credits.tsnew file mode 100644index 0000000000..c7eab7a89e--- /dev/null+++ b/packages/admin/src/hooks/use-customer-store-credits.ts@@ -0,0 +1,35 @@+import { adminClient } from '@/client'+import { customerQueryKey } from '@/hooks/use-customers'+import { useResourceMutation } from '@/hooks/use-resource-mutation'+import { i18n } from '@/lib/i18n'++type StoreCreditCreateParams = Parameters<typeof adminClient.customers.storeCredits.create>[1]+type StoreCreditUpdateParams = Parameters<typeof adminClient.customers.storeCredits.update>[2]++export type { StoreCreditUpdateParams }++export function useCreateCustomerStoreCredit(customerId: string) {+ return useResourceMutation({+ mutationFn: (params: StoreCreditCreateParams) =>+ adminClient.customers.storeCredits.create(customerId, params),+ invalidate: [customerQueryKey(customerId)],+ successMessage: i18n.t('admin.messages.store_credit_saved'),+ })+}++export function useUpdateCustomerStoreCredit(customerId: string, creditId: string) {+ return useResourceMutation({+ mutationFn: (params: StoreCreditUpdateParams) =>+ adminClient.customers.storeCredits.update(customerId, creditId, params),+ invalidate: [customerQueryKey(customerId)],+ successMessage: i18n.t('admin.messages.store_credit_saved'),+ })+}++export function useDeleteCustomerStoreCredit(customerId: string) {+ return useResourceMutation({+ mutationFn: (id: string) => adminClient.customers.storeCredits.delete(customerId, id),+ invalidate: [customerQueryKey(customerId)],+ successMessage: i18n.t('admin.messages.store_credit_removed'),+ })+}diff --git a/packages/admin/src/hooks/use-customers.ts b/packages/admin/src/hooks/use-customers.tsindex 626c99d0da..dc0aea8ba9 100644--- a/packages/admin/src/hooks/use-customers.ts+++ b/packages/admin/src/hooks/use-customers.ts@@ -1,5 +1,9 @@import type { Customer } from '@spree/admin-sdk'+import { useQuery } from '@tanstack/react-query'import { adminClient } from '@/client'+import { useAuth } from '@/hooks/use-auth'+import { useResourceMutation } from '@/hooks/use-resource-mutation'+import { i18n } from '@/lib/i18n'/*** Shared config for any `<ResourceCombobox>` / `<ResourceMultiAutocomplete>`@@ -21,3 +25,85 @@ export function customerAutocompleteProps(queryKey: string) {emptyText: 'No customers match',}}++export function customerQueryKey(customerId: string) {+ return ['customer', customerId] as const+}++export function useCustomer(customerId: string) {+ const { isAuthenticated } = useAuth()+ return useQuery({+ queryKey: customerQueryKey(customerId),+ queryFn: () =>+ adminClient.customers.get(customerId, { expand: ['addresses', 'store_credits'] }),+ enabled: isAuthenticated,+ })+}++type CustomerUpdateParams = Parameters<typeof adminClient.customers.update>[1]++export function useUpdateCustomer(customerId: string) {+ return useResourceMutation({+ mutationFn: (params: CustomerUpdateParams) => adminClient.customers.update(customerId, params),+ invalidate: [customerQueryKey(customerId)],+ successMessage: i18n.t('admin.messages.customer_saved'),+ })+}++export function useDeleteCustomer(customerId: string) {+ return useResourceMutation({+ mutationFn: () => adminClient.customers.delete(customerId),+ successMessage: i18n.t('admin.messages.customer_deleted'),+ })+}++// `params` is spread into the queryKey so callers passing a fresh `{}` each+// render don't force a JSON-equality rehash on every paint.+export function useCustomerOrders(customerId: string, params: { limit: number; status?: string }) {+ const { isAuthenticated } = useAuth()+ return useQuery({+ queryKey: ['customer-orders', customerId, params.limit, params.status ?? null] as const,+ queryFn: () =>+ adminClient.orders.list({+ user_id_eq: customerId,+ ...(params.status ? { status_eq: params.status } : {}),+ limit: params.limit,+ sort: '-completed_at',+ expand: ['items'],+ }),+ enabled: isAuthenticated,+ })+}++// ---------------------------------------------------------------------------+// Addresses+// ---------------------------------------------------------------------------++type AddressCreateParams = Parameters<typeof adminClient.customers.addresses.create>[1]+type AddressUpdateParams = Parameters<typeof adminClient.customers.addresses.update>[2]++export function useCreateCustomerAddress(customerId: string) {+ return useResourceMutation({+ mutationFn: (params: AddressCreateParams) =>+ adminClient.customers.addresses.create(customerId, params),+ invalidate: [customerQueryKey(customerId)],+ successMessage: i18n.t('admin.messages.address_saved'),+ })+}++export function useUpdateCustomerAddress(customerId: string) {+ return useResourceMutation({+ mutationFn: ({ id, params }: { id: string; params: AddressUpdateParams }) =>+ adminClient.customers.addresses.update(customerId, id, params),+ invalidate: [customerQueryKey(customerId)],+ successMessage: i18n.t('admin.messages.address_saved'),+ })+}++export function useDeleteCustomerAddress(customerId: string) {+ return useResourceMutation({+ mutationFn: (id: string) => adminClient.customers.addresses.delete(customerId, id),+ invalidate: [customerQueryKey(customerId)],+ successMessage: i18n.t('admin.messages.address_removed'),+ })+}diff --git a/packages/admin/src/hooks/use-gift-cards.ts b/packages/admin/src/hooks/use-gift-cards.tsindex 28a5618f99..26518858c1 100644--- a/packages/admin/src/hooks/use-gift-cards.ts+++ b/packages/admin/src/hooks/use-gift-cards.ts@@ -23,6 +23,10 @@ export function useGiftCard(id: string | undefined, expand?: string[]) {})}+export function listGiftCards(params: Parameters<typeof adminClient.giftCards.list>[0]) {+ return adminClient.giftCards.list(params)+}+export function useCreateGiftCard() {return useResourceMutation<GiftCard, Error, GiftCardCreateParams>({mutationFn: (params) => adminClient.giftCards.create(params),diff --git a/packages/admin/src/lib/form-mappers.ts b/packages/admin/src/lib/form-mappers.tsnew file mode 100644index 0000000000..6a202b80ee--- /dev/null+++ b/packages/admin/src/lib/form-mappers.ts@@ -0,0 +1,13 @@+/**+ * 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.+ */+export function blankToUndefined(s: string | null | undefined): string | undefined {+ return s && s.length > 0 ? s : undefined+}++export function blankToNull(s: string | null | undefined): string | null {+ return s && s.length > 0 ? s : null+}diff --git a/packages/admin/src/lib/validation-messages.ts b/packages/admin/src/lib/validation-messages.tsnew file mode 100644index 0000000000..b03b5bd044--- /dev/null+++ b/packages/admin/src/lib/validation-messages.ts@@ -0,0 +1,19 @@+import { i18n } from '@/lib/i18n'++/**+ * Lazy "<Field> is required" message for Zod v4 schemas. Wrap in `{ error: ... }`+ * so the message is resolved per validation (not at module load) — keeps the+ * literal out of the schema and lets locale changes pick up.+ *+ * ```ts+ * z.string().min(1, { error: requiredMessage('name') })+ * z.string().min(1, { error: requiredMessage('payment_method.type') })+ * ```+ *+ * `field` is a dot-path under `admin.fields.*` resolving to a `.label` key —+ * `'name'` → `admin.fields.name.label`, `'payment_method.type'` →+ * `admin.fields.payment_method.type.label`.+ */+export function requiredMessage(field: string): () => string {+ return () => i18n.t('admin.validation.required', { field: i18n.t(`admin.fields.${field}.label`) })+}diff --git a/packages/admin/src/locales/en.json b/packages/admin/src/locales/en.jsonindex daa4a6a731..b0ec493f6f 100644--- a/packages/admin/src/locales/en.json+++ b/packages/admin/src/locales/en.json@@ -30,7 +30,36 @@"sending": "Sending…","reset": "Reset","show": "Show",- "hide": "Hide"+ "hide": "Hide",+ "back": "Back",+ "actions_menu": "Actions",+ "more_actions": "More actions"+ },+ "a11y": {+ "breadcrumb": "Breadcrumb",+ "toggle_sidebar": "Toggle sidebar",+ "settings_navigation": "Settings navigation",+ "user_menu": "User menu",+ "drag_to_reorder": "Drag to reorder",+ "reorder": "Reorder",+ "select_all_rows": "Select all rows on this page",+ "select_row": "Select row",+ "clear_date": "Clear date",+ "clear_selection": "Clear selection",+ "expand_all": "Expand all",+ "collapse_all": "Collapse all",+ "refetch": "Refetch",+ "hide_value": "Hide value",+ "show_value": "Show value",+ "pick_color": "Pick a color",+ "change_color": "Change color ({{value}})",+ "stock_at_locations": "Stock at locations",+ "edit_media": "Edit media",+ "delete_image": "Delete image",+ "remove_image": "Remove image",+ "view_image": "View image",+ "upload_image": "Upload image",+ "remove_value": "Remove value"},"common": {"loading": "Loading…",@@ -81,6 +110,9 @@"promotion_deleted": "Promotion deleted","gift_card_created": "Gift card created","address_saved": "Address saved",+ "address_removed": "Address removed",+ "store_credit_saved": "Store credit saved",+ "store_credit_removed": "Store credit removed","copied_to_clipboard": "Copied to clipboard"},"errors": {@@ -386,6 +418,26 @@"custom_fields": { "json_placeholder": "{ \"example\": \"value\" }" }},"promotions": {+ "kinds": {+ "coupon_code": "Coupon code",+ "automatic": "Automatic (no code)"+ },+ "match_policies": {+ "all": "All rules must match",+ "any": "Any rule may match",+ "all_hint": "All rules must match.",+ "any_hint": "Any rule may match."+ },+ "rules_card": {+ "title": "Rules",+ "description": "Conditions that decide whether the promotion applies."+ },+ "validation": {+ "code_required": "Code is required (or click Generate)",+ "prefix_required": "Prefix is required for multi-code batches",+ "number_of_codes_required": "Pick how many codes to generate",+ "expiry_after_start": "Expiry must be after the start date"+ },"rules": {"country": {"label": "Countries",@@ -473,6 +525,8 @@},"customers": {"new_cta": "New Customer",+ "create_label": "Create customer",+ "edit_sheet_title": "Edit customer","groups_cta": "Customer groups","groups": {"title": "Customer groups",@@ -574,7 +628,7 @@"in_stock": "{{count}} in stock"},"transfers": {- "sheet_title": "Stock transfer",+ "sheet_title": "New stock transfer","section_from": "From","section_to": "To","section_items": "Items",@@ -585,7 +639,7 @@"sheet_title_edit": "Edit option type","values_section": "Values","values_empty": "No values yet.",- "add_value": "Add value",+ "add_value": "Add option value","table": { "values": "Values" }}},@@ -637,6 +691,7 @@"new_sheet_title": "New gift card","edit_sheet_title": "Gift card","new_cta": "New gift card",+ "create_label": "Create gift card","batch_section": "Batch","create_batch_cta": "Create {{count}} gift cards","status_options": { "redeemed": "Redeemed", "expired": "Expired", "void": "Void" },@@ -651,7 +706,21 @@"validation": {"amount_positive": "Amount must be greater than zero","amount_required": "Amount is required",- "prefix_required": "Prefix is required for batches"+ "prefix_required": "Prefix is required for batches",+ "currency_required": "Currency is required"+ },+ "prefix": {+ "label": "Prefix",+ "placeholder": "e.g. WELCOME — codes will be WELCOME-abc123",+ "auto_placeholder": "Auto-generated when blank"+ },+ "no_customer": "No customer attached",+ "usage": {+ "title": "Usage",+ "amount": "Amount",+ "used": "Used",+ "remaining": "Remaining",+ "issued_by": "Issued by"}}}@@ -661,6 +730,8 @@"min_length": "{{field}} must be at least {{count}} characters","passwords_dont_match": "Passwords do not match","invalid_email_or_password": "Invalid email or password",+ "invalid_email": "Enter a valid email",+ "invalid_hex_color": "Invalid hex color","invalid_password": "Invalid password","password_required": "Password is required","first_name_required": "First name is required",@@ -675,7 +746,6 @@"generic_error_title": "Could not load invitation","generic_error_message": "Something went wrong. Please try again.","join_store": "Join {{store}}",- "join_default": "Join this store","invited_by": "{{email}} invited you","invited_generic": "You have been invited","invited_as_role": " as {{role}}",@@ -766,6 +836,7 @@"view_members": "View members","count_one": "{{count}} customer","count_other": "{{count}} customers",+ "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.","delete_confirm": {@@ -963,6 +1034,8 @@},"options": {"kinds": { "dropdown": "Dropdown", "color_swatch": "Color swatch", "buttons": "Buttons" },+ "add_cta": "Add option type",+ "create_label": "Create option type","create_description": "Define an option that variants can use (e.g. size, color).","edit_description": "Edit the option type and its values.","delete_confirm": {@@ -998,8 +1071,18 @@},"stock_locations": {"add_cta": "Add stock location",+ "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.",+ "kinds": {+ "warehouse": "Warehouse",+ "store": "Store",+ "fulfillment_center": "Fulfillment center"+ },+ "pickup_stock_policies": {+ "local": "Only items at this location",+ "any": "Allow transfers from other locations"+ },"delete_confirm": {"title": "Delete stock location?","message": "{{name}} will be removed. Stock items at this location are not deleted."@@ -1012,6 +1095,15 @@"table": { "variant": "Variant", "on_hand": "On hand", "backorder": "Backorder" }}},- "store": { "load_failed_title": "Failed to load store settings" }+ "store": {+ "load_failed_title": "Failed to load store settings",+ "unit_systems": { "metric": "Metric", "imperial": "Imperial" },+ "weight_units": {+ "kg": "Kilogram (kg)",+ "g": "Gram (g)",+ "lb": "Pound (lb)",+ "oz": "Ounce (oz)"+ }+ }}}diff --git a/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx b/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsxindex 602eb76ba7..d863ca7666 100644--- a/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx@@ -1,5 +1,5 @@+import { zodResolver } from '@hookform/resolvers/zod'import type { Address, Customer, Order, StoreCredit } from '@spree/admin-sdk'-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'import {EllipsisVerticalIcon,@@ -10,10 +10,9 @@ import {StarIcon,TrashIcon,} from 'lucide-react'-import { type ReactNode, useState } from 'react'+import { type ReactNode, useMemo, useState } from 'react'import { Controller, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'-import { adminClient } from '@/client'import { AddressFormDialog, type AddressParams } from '@/components/spree/address-form-dialog'import { useConfirm } from '@/components/spree/confirm-dialog'import { CurrencySelect } from '@/components/spree/currency-select'@@ -61,36 +60,30 @@ import {SheetTitle,} from '@/components/ui/sheet'import { Textarea } from '@/components/ui/textarea'-import { useAuth } from '@/hooks/use-auth'import { useCountries } from '@/hooks/use-countries'+import {+ type StoreCreditUpdateParams,+ useCreateCustomerStoreCredit,+ useDeleteCustomerStoreCredit,+ useUpdateCustomerStoreCredit,+} from '@/hooks/use-customer-store-credits'+import {+ useCreateCustomerAddress,+ useCustomer,+ useCustomerOrders,+ useDeleteCustomer,+ useDeleteCustomerAddress,+ useUpdateCustomer,+ useUpdateCustomerAddress,+} from '@/hooks/use-customers'import { useStoreCreditCategories } from '@/hooks/use-store-credit-categories'import { mapSpreeErrorsToForm } from '@/lib/form-errors'+import { type CustomerProfileFormValues, customerProfileFormSchema } from '@/schemas/customer'export const Route = createFileRoute('/_authenticated/$storeId/customers/$customerId')({component: CustomerDetailPage,})-function useCustomer(customerId: string) {- const { isAuthenticated } = useAuth()- return useQuery({- queryKey: ['customer', customerId],- queryFn: () =>- adminClient.customers.get(customerId, { expand: ['addresses', 'store_credits'] }),- enabled: isAuthenticated,- })-}--function useCustomerMutation<TParams>(- customerId: string,- mutationFn: (params: TParams) => Promise<unknown>,-) {- const queryClient = useQueryClient()- return useMutation({- mutationFn,- onSuccess: () => queryClient.invalidateQueries({ queryKey: ['customer', customerId] }),- })-}-function CustomerDetailPage() {const { t } = useTranslation()const { customerId } = Route.useParams()@@ -125,10 +118,12 @@ function CustomerBody({ customer }: { customer: Customer }) {// The server hard-deletes only when the customer has no completed orders// (Spree::Core::DestroyWithOrdersError → 422 `customer_has_orders`). We// surface the API error message inline rather than swallowing the failure.- const deleteMutation = useMutation({- mutationFn: () => adminClient.customers.delete(customer.id),- onSuccess: () => navigate({ to: '/$storeId/customers', params: { storeId } }),- })+ const deleteMutation = useDeleteCustomer(customer.id)++ async function handleDelete() {+ await deleteMutation.mutateAsync()+ navigate({ to: '/$storeId/customers', params: { storeId } })+ }return (<ResourceLayout@@ -140,12 +135,14 @@ function CustomerBody({ customer }: { customer: Customer }) {backTo="customers"badges={customer.tags?.map((tag) => <Badge key={tag}>{tag}</Badge>)}resource={{ id: customer.id }}- onDelete={() => deleteMutation.mutateAsync()}+ onDelete={handleDelete}deleteLabel={t('admin.customers.detail.delete_label')}jsonPreview={{title: `Customer ${customer.email}`,queryKey: ['json', 'customer', customer.id],- queryFn: () => adminClient.customers.get(customer.id),+ // Reuse what `useCustomer` already loaded — opening the drawer+ // shouldn't trigger a duplicate fetch.+ queryFn: () => Promise.resolve(customer),endpoint: `/api/v3/admin/customers/${customer.id}`,}}/>@@ -177,7 +174,9 @@ function CustomerBody({ customer }: { customer: Customer }) {<><ProfileCard customer={customer} /><AddressesCard customer={customer} />- <InternalNoteCard customer={customer} />+ {/* Key on `updated_at` so the textarea's local state resets after a+ refetch (e.g. another mutation invalidates the customer). */}+ <InternalNoteCard key={customer.updated_at} customer={customer} /></>}/>@@ -238,15 +237,6 @@ function ProfileCard({ customer }: { customer: Customer }) {)}-interface EditProfileFormValues {- email: string- first_name: string- last_name: string- phone: string- tags: string[]- accepts_email_marketing: boolean-}-function EditProfileSheet({customer,open,@@ -257,7 +247,9 @@ function EditProfileSheet({onOpenChange: (open: boolean) => void}) {const { t } = useTranslation()- const form = useForm<EditProfileFormValues>({+ const form = useForm<CustomerProfileFormValues>({+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ resolver: zodResolver(customerProfileFormSchema) as any,defaultValues: {email: customer.email,first_name: customer.first_name ?? '',@@ -268,11 +260,9 @@ function EditProfileSheet({},})const { errors } = form.formState- const mutation = useCustomerMutation(customer.id, (params: EditProfileFormValues) =>- adminClient.customers.update(customer.id, params),- )+ const mutation = useUpdateCustomer(customer.id)- async function onSubmit(values: EditProfileFormValues) {+ async function onSubmit(values: CustomerProfileFormValues) {try {await mutation.mutateAsync(values)onOpenChange(false)@@ -285,7 +275,7 @@ function EditProfileSheet({<Sheet open={open} onOpenChange={onOpenChange}><SheetContent><SheetHeader>- <SheetTitle>{t('admin.pages.customers.detail.section_profile')}</SheetTitle>+ <SheetTitle>{t('admin.pages.customers.edit_sheet_title')}</SheetTitle><SheetDescription>{t('admin.customers.detail.edit_profile_description')}</SheetDescription>@@ -299,9 +289,9 @@ function EditProfileSheet({)}<FieldGroup><Field>- <FieldLabel htmlFor="cust-email">{t('admin.fields.email.label')}</FieldLabel>+ <FieldLabel htmlFor="email">{t('admin.fields.email.label')}</FieldLabel><Input- id="cust-email"+ id="email"type="email"aria-invalid={!!errors.email || undefined}{...form.register('email')}@@ -309,31 +299,27 @@ function EditProfileSheet({<FieldError errors={[errors.email]} /></Field><Field>- <FieldLabel htmlFor="cust-first-name">- {t('admin.fields.first_name.label')}- </FieldLabel>+ <FieldLabel htmlFor="first_name">{t('admin.fields.first_name.label')}</FieldLabel><Input- id="cust-first-name"+ id="first_name"aria-invalid={!!errors.first_name || undefined}{...form.register('first_name')}/><FieldError errors={[errors.first_name]} /></Field><Field>- <FieldLabel htmlFor="cust-last-name">- {t('admin.fields.last_name.label')}- </FieldLabel>+ <FieldLabel htmlFor="last_name">{t('admin.fields.last_name.label')}</FieldLabel><Input- id="cust-last-name"+ id="last_name"aria-invalid={!!errors.last_name || undefined}{...form.register('last_name')}/><FieldError errors={[errors.last_name]} /></Field><Field>- <FieldLabel htmlFor="cust-phone">{t('admin.fields.phone.label')}</FieldLabel>+ <FieldLabel htmlFor="phone">{t('admin.fields.phone.label')}</FieldLabel><Input- id="cust-phone"+ id="phone"aria-invalid={!!errors.phone || undefined}{...form.register('phone')}/>@@ -355,7 +341,7 @@ function EditProfileSheet({</Field><Field><div className="flex items-start justify-between gap-4">- <FieldLabel htmlFor="cust-marketing" className="cursor-pointer">+ <FieldLabel htmlFor="accepts_email_marketing" className="cursor-pointer">{t('admin.fields.customer.accepts_email_marketing.label')}</FieldLabel><Controller@@ -363,7 +349,7 @@ function EditProfileSheet({control={form.control}render={({ field }) => (<Checkbox- id="cust-marketing"+ id="accepts_email_marketing"checked={!!field.value}onCheckedChange={field.onChange}/>@@ -445,22 +431,6 @@ function Stat({ label, value }: { label: string; value: ReactNode }) {// Last Order// ----------------------------------------------------------------------------function useCustomerOrders(customerId: string, params: { limit: number; status?: string }) {- const { isAuthenticated } = useAuth()- return useQuery({- queryKey: ['customer-orders', customerId, params],- queryFn: () =>- adminClient.orders.list({- user_id_eq: customerId,- ...(params.status ? { status_eq: params.status } : {}),- limit: params.limit,- sort: '-completed_at',- expand: ['items'],- }),- enabled: isAuthenticated,- })-}-function LastOrderCard({ order }: { order: Order }) {const { t } = useTranslation()return (@@ -631,9 +601,7 @@ function InternalNoteCard({ customer }: { customer: Customer }) {const [editing, setEditing] = useState(false)const [note, setNote] = useState(customer.internal_note_html ?? '')- const mutation = useCustomerMutation(customer.id, (params: { internal_note: string }) =>- adminClient.customers.update(customer.id, params),- )+ const mutation = useUpdateCustomer(customer.id)return (<Card>@@ -706,22 +674,24 @@ function AddressesCard({ customer }: { customer: Customer }) {const [addOpen, setAddOpen] = useState(false)const [editing, setEditing] = useState<Address | null>(null)const confirm = useConfirm()- const isDefault = (a: Address) => a.is_default_billing || a.is_default_shipping- const addresses = [...(customer.addresses ?? [])].sort(- (a, b) => Number(isDefault(b)) - Number(isDefault(a)),- )+ const addresses = useMemo(() => {+ const isDefault = (a: Address) => a.is_default_billing || a.is_default_shipping+ return [...(customer.addresses ?? [])].sort(+ (a, b) => Number(isDefault(b)) - Number(isDefault(a)),+ )+ }, [customer.addresses])- const deleteMutation = useCustomerMutation(customer.id, (id: string) =>- adminClient.customers.addresses.delete(customer.id, id),- )+ const deleteMutation = useDeleteCustomerAddress(customer.id)- const setDefaultMutation = useCustomerMutation(- customer.id,- (params: { id: string; kind: 'billing' | 'shipping' }) =>- adminClient.customers.addresses.update(customer.id, params.id, {+ const updateMutation = useUpdateCustomerAddress(customer.id)+ function setDefault(params: { id: string; kind: 'billing' | 'shipping' }) {+ return updateMutation.mutate({+ id: params.id,+ params: {[params.kind === 'billing' ? 'is_default_billing' : 'is_default_shipping']: true,- }),- )+ },+ })+ }return (<>@@ -788,14 +758,14 @@ function AddressesCard({ customer }: { customer: Customer }) {</DropdownMenuItem>{!addr.is_default_billing && (<DropdownMenuItem- onClick={() => setDefaultMutation.mutate({ id: addr.id, kind: 'billing' })}+ onClick={() => setDefault({ id: addr.id, kind: 'billing' })}>{t('admin.customers.detail.address.set_default_billing')}</DropdownMenuItem>)}{!addr.is_default_shipping && (<DropdownMenuItem- onClick={() => setDefaultMutation.mutate({ id: addr.id, kind: 'shipping' })}+ onClick={() => setDefault({ id: addr.id, kind: 'shipping' })}>{t('admin.customers.detail.address.set_default_shipping')}</DropdownMenuItem>@@ -868,11 +838,16 @@ function CustomerAddressDialog({}) {const { isLoading: countriesLoading } = useCountries()const isEdit = Boolean(address.id)- const mutation = useCustomerMutation(customer.id, (params: AddressParams) =>- isEdit- ? adminClient.customers.addresses.update(customer.id, address.id, params)- : adminClient.customers.addresses.create(customer.id, params),- )+ const createMutation = useCreateCustomerAddress(customer.id)+ 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))+ }// Wait for countries before mounting so the country/state lazy initializer// can resolve the address's country_iso/state_abbr to a real option.@@ -883,7 +858,7 @@ function CustomerAddressDialog({address={address}openonOpenChange={onOpenChange}- onSave={(params) => mutation.mutate(params, { onSuccess: () => onOpenChange(false) })}+ onSave={handleSave}title={title}isPending={mutation.isPending}showLabel@@ -903,9 +878,7 @@ function StoreCreditsCard({ customer }: { customer: Customer }) {const confirm = useConfirm()const credits = customer.store_credits ?? []- const deleteMutation = useCustomerMutation(customer.id, (id: string) =>- adminClient.customers.storeCredits.delete(customer.id, id),- )+ const deleteMutation = useDeleteCustomerStoreCredit(customer.id)return (<>@@ -1092,14 +1065,10 @@ function EditStoreCreditDialog({})const { errors } = form.formState- const mutation = useCustomerMutation(- customerId,- (params: Parameters<typeof adminClient.customers.storeCredits.update>[2]) =>- adminClient.customers.storeCredits.update(customerId, credit.id, params),- )+ const mutation = useUpdateCustomerStoreCredit(customerId, credit.id)async function onSubmit(values: EditStoreCreditFormValues) {- const params: Parameters<typeof adminClient.customers.storeCredits.update>[2] = {}+ const params: StoreCreditUpdateParams = {}if (!amountLocked) {const amountValue = values.amount.toString().trim()@@ -1222,11 +1191,7 @@ function IssueStoreCreditDialog({})const { errors } = form.formState- const mutation = useCustomerMutation(- customerId,- (params: Parameters<typeof adminClient.customers.storeCredits.create>[1]) =>- adminClient.customers.storeCredits.create(customerId, params),- )+ const mutation = useCreateCustomerStoreCredit(customerId)async function onSubmit(values: IssueStoreCreditFormValues) {try {@@ -1284,7 +1249,7 @@ function IssueStoreCreditDialog({render={({ field }) => (<CurrencySelectid="sc-currency"- value={field.value || undefined}+ value={field.value || ''}onChange={field.onChange}required/>diff --git a/packages/admin/src/routes/_authenticated/$storeId/customers/groups.tsx b/packages/admin/src/routes/_authenticated/$storeId/customers/groups.tsxindex 54f57c4981..bab8681c9c 100644--- a/packages/admin/src/routes/_authenticated/$storeId/customers/groups.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/customers/groups.tsx@@ -1,9 +1,5 @@import { zodResolver } from '@hookform/resolvers/zod'-import type {- CustomerGroup,- CustomerGroupCreateParams,- CustomerGroupUpdateParams,-} from '@spree/admin-sdk'+import type { CustomerGroup, CustomerGroupCreateParams } from '@spree/admin-sdk'import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'import { PlusIcon, UsersIcon } from 'lucide-react'import { useEffect } from 'react'@@ -35,6 +31,12 @@ import {} from '@/hooks/use-customer-groups'import { mapSpreeErrorsToForm } from '@/lib/form-errors'import { Subject } from '@/lib/permissions'+import {+ CUSTOMER_GROUP_DEFAULTS,+ type CustomerGroupFormValues,+ customerGroupFormSchema,+ customerGroupValuesToParams,+} from '@/schemas/customer-group'import '@/tables/customer-groups'const customerGroupsSearchSchema = resourceSearchSchema.extend({@@ -96,22 +98,6 @@ function CustomerGroupsPage() {)}-const formSchema = z.object({- name: z.string().min(1, 'Name is required'),- description: z.string().optional(),-})--type FormValues = z.infer<typeof formSchema>--const DEFAULT_VALUES: FormValues = { name: '', description: '' }--function valuesToParams(v: FormValues): CustomerGroupCreateParams & CustomerGroupUpdateParams {- return {- name: v.name,- description: v.description && v.description.length > 0 ? v.description : null,- }-}-function CreateCustomerGroupSheet({open,onOpenChange,@@ -121,16 +107,18 @@ function CreateCustomerGroupSheet({}) {const { t } = useTranslation()const createMutation = useCreateCustomerGroup()- const form = useForm<FormValues>({+ const form = useForm<CustomerGroupFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(formSchema) as any,- defaultValues: DEFAULT_VALUES,+ resolver: zodResolver(customerGroupFormSchema) as any,+ defaultValues: CUSTOMER_GROUP_DEFAULTS,})- async function onSubmit(values: FormValues) {+ async function onSubmit(values: CustomerGroupFormValues) {try {- await createMutation.mutateAsync(valuesToParams(values) as CustomerGroupCreateParams)- form.reset(DEFAULT_VALUES)+ await createMutation.mutateAsync(+ customerGroupValuesToParams(values) as CustomerGroupCreateParams,+ )+ form.reset(CUSTOMER_GROUP_DEFAULTS)onOpenChange(false)} catch (err) {if (!mapSpreeErrorsToForm(err, form.setError)) throw err@@ -141,7 +129,7 @@ function CreateCustomerGroupSheet({<Sheetopen={open}onOpenChange={(next) => {- if (!next) form.reset(DEFAULT_VALUES)+ if (!next) form.reset(CUSTOMER_GROUP_DEFAULTS)onOpenChange(next)}}>@@ -167,7 +155,7 @@ function CreateCustomerGroupSheet({<Button type="submit" size="sm" disabled={form.formState.isSubmitting}>{form.formState.isSubmitting? t('admin.actions.creating')- : t('admin.actions.create')}+ : t('admin.customers.groups.create_label')}</Button></SheetFooter></form>@@ -192,10 +180,10 @@ function EditCustomerGroupSheet({const deleteMutation = useDeleteCustomerGroup()const confirm = useConfirm()- const form = useForm<FormValues>({+ const form = useForm<CustomerGroupFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(formSchema) as any,- defaultValues: DEFAULT_VALUES,+ resolver: zodResolver(customerGroupFormSchema) as any,+ defaultValues: CUSTOMER_GROUP_DEFAULTS,})useEffect(() => {@@ -207,9 +195,9 @@ function EditCustomerGroupSheet({}}, [group, form])- async function onSubmit(values: FormValues) {+ async function onSubmit(values: CustomerGroupFormValues) {try {- await updateMutation.mutateAsync(valuesToParams(values))+ await updateMutation.mutateAsync(customerGroupValuesToParams(values))form.reset(values)onOpenChange(false)} catch (err) {@@ -294,7 +282,7 @@ function EditCustomerGroupSheet({)}-function NameDescriptionFields({ form }: { form: UseFormReturn<FormValues> }) {+function NameDescriptionFields({ form }: { form: UseFormReturn<CustomerGroupFormValues> }) {const { t } = useTranslation()const { errors } = form.formStatereturn (diff --git a/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx b/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsxindex 5f8f2471c4..7917f73d8c 100644--- a/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx@@ -1,3 +1,4 @@+import { zodResolver } from '@hookform/resolvers/zod'import { useMutation } from '@tanstack/react-query'import { createFileRoute, useNavigate } from '@tanstack/react-router'import { PlusIcon, UserMinusIcon, UserPlusIcon } from 'lucide-react'@@ -27,6 +28,11 @@ import { Textarea } from '@/components/ui/textarea'import { customerGroupAutocompleteProps } from '@/hooks/use-customer-groups'import { mapSpreeErrorsToForm } from '@/lib/form-errors'import { Subject } from '@/lib/permissions'+import {+ NEW_CUSTOMER_DEFAULTS,+ type NewCustomerFormValues,+ newCustomerFormSchema,+} from '@/schemas/customer'import '@/tables/customers'// Adds `?new=1` on top of the standard table search schema so the create sheet@@ -189,26 +195,6 @@ function GroupPickerSheet({// Create Sheet// ============================================================================-interface NewCustomerFormValues {- email: string- first_name: string- last_name: string- phone: string- tags: string[]- accepts_email_marketing: boolean- internal_note: string-}--const NEW_CUSTOMER_DEFAULTS: NewCustomerFormValues = {- email: '',- first_name: '',- last_name: '',- phone: '',- tags: [],- accepts_email_marketing: false,- internal_note: '',-}-function NewCustomerSheet({open,onOpenChange,@@ -220,7 +206,11 @@ function NewCustomerSheet({const { storeId } = Route.useParams()const navigate = useNavigate()- const form = useForm<NewCustomerFormValues>({ defaultValues: NEW_CUSTOMER_DEFAULTS })+ const form = useForm<NewCustomerFormValues>({+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ resolver: zodResolver(newCustomerFormSchema) as any,+ defaultValues: NEW_CUSTOMER_DEFAULTS,+ })const createMutation = useMutation({mutationFn: (params: Parameters<typeof adminClient.customers.create>[0]) =>@@ -269,11 +259,9 @@ function NewCustomerSheet({)}<FieldGroup><Field>- <FieldLabel htmlFor="new-customer-email">- {t('admin.fields.email.label')}- </FieldLabel>+ <FieldLabel htmlFor="email">{t('admin.fields.email.label')}</FieldLabel><Input- id="new-customer-email"+ id="email"type="email"autoFocusaria-invalid={!!form.formState.errors.email || undefined}@@ -283,22 +271,18 @@ function NewCustomerSheet({</Field><div className="grid grid-cols-2 gap-3"><Field>- <FieldLabel htmlFor="new-customer-first-name">- {t('admin.fields.first_name.label')}- </FieldLabel>+ <FieldLabel htmlFor="first_name">{t('admin.fields.first_name.label')}</FieldLabel><Input- id="new-customer-first-name"+ id="first_name"aria-invalid={!!form.formState.errors.first_name || undefined}{...form.register('first_name')}/><FieldError errors={[form.formState.errors.first_name]} /></Field><Field>- <FieldLabel htmlFor="new-customer-last-name">- {t('admin.fields.last_name.label')}- </FieldLabel>+ <FieldLabel htmlFor="last_name">{t('admin.fields.last_name.label')}</FieldLabel><Input- id="new-customer-last-name"+ id="last_name"aria-invalid={!!form.formState.errors.last_name || undefined}{...form.register('last_name')}/>@@ -306,11 +290,9 @@ function NewCustomerSheet({</Field></div><Field>- <FieldLabel htmlFor="new-customer-phone">- {t('admin.fields.phone.label')}- </FieldLabel>+ <FieldLabel htmlFor="phone">{t('admin.fields.phone.label')}</FieldLabel><Input- id="new-customer-phone"+ id="phone"aria-invalid={!!form.formState.errors.phone || undefined}{...form.register('phone')}/>@@ -332,7 +314,7 @@ function NewCustomerSheet({</Field><Field><div className="flex items-start justify-between gap-4">- <FieldLabel htmlFor="new-customer-marketing" className="cursor-pointer">+ <FieldLabel htmlFor="accepts_email_marketing" className="cursor-pointer">{t('admin.fields.customer.accepts_email_marketing.label')}</FieldLabel><Controller@@ -340,7 +322,7 @@ function NewCustomerSheet({control={form.control}render={({ field }) => (<Checkbox- id="new-customer-marketing"+ id="accepts_email_marketing"checked={!!field.value}onCheckedChange={field.onChange}/>@@ -349,11 +331,11 @@ function NewCustomerSheet({</div></Field><Field>- <FieldLabel htmlFor="new-customer-note">+ <FieldLabel htmlFor="internal_note">{t('admin.fields.customer.internal_note.label')}</FieldLabel><Textarea- id="new-customer-note"+ id="internal_note"rows={4}placeholder={t('admin.fields.customer.internal_note.placeholder')}aria-invalid={!!form.formState.errors.internal_note || undefined}@@ -374,7 +356,9 @@ function NewCustomerSheet({{t('admin.actions.cancel')}</Button><Button type="submit" size="sm" disabled={createMutation.isPending}>- {createMutation.isPending ? t('admin.actions.creating') : t('admin.actions.create')}+ {createMutation.isPending+ ? t('admin.actions.creating')+ : t('admin.pages.customers.create_label')}</Button></SheetFooter></form>diff --git a/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx b/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsxindex 1a5429d169..9ff6440e4c 100644--- a/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/orders/$orderId.tsx@@ -429,7 +429,7 @@ function AddLineItemDialog({type="button"onClick={() => setSelectedVariant(null)}className="rounded p-1 text-muted-foreground hover:bg-accent hover:text-foreground"- aria-label="Clear selected variant"+ aria-label={t('admin.a11y.clear_selection')}><XCircleIcon className="size-4" /></button>diff --git a/packages/admin/src/routes/_authenticated/$storeId/orders/new.tsx b/packages/admin/src/routes/_authenticated/$storeId/orders/new.tsxindex be95427fc2..ee67b11ba7 100644--- a/packages/admin/src/routes/_authenticated/$storeId/orders/new.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/orders/new.tsx@@ -80,7 +80,8 @@ function NewOrderPage() {})const email = form.watch('email')- const canSubmit = (Boolean(customer) || email.length > 0) && !createMutation.isPending+ const canSubmit =+ (Boolean(customer) || email.length > 0) && items.length > 0 && !createMutation.isPendingasync function onSubmit(values: NewOrderFormValues) {if (!canSubmit) returndiff --git a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsxindex 0979ec83a2..dfddbd67a5 100644--- a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx@@ -537,6 +537,7 @@ function SortableMediaThumbnail({onEdit: () => voidonDelete: () => void}) {+ const { t } = useTranslation()// The whole thumbnail is the drag source — listeners/attributes attach to// the wrapper. PointerSensor's distance:5 on the parent DndContext lets// brief clicks on the action buttons fall through without starting a drag.@@ -578,7 +579,7 @@ function SortableMediaThumbnail({type="button"variant="outline"size="icon-sm"- aria-label="Edit media"+ aria-label={t('admin.a11y.edit_media')}onPointerDown={(e) => e.stopPropagation()}onClick={(e) => {e.stopPropagation()@@ -592,7 +593,7 @@ function SortableMediaThumbnail({type="button"variant="outline"size="icon-sm"- aria-label="Delete image"+ aria-label={t('admin.a11y.delete_image')}onPointerDown={(e) => e.stopPropagation()}onClick={(e) => {e.stopPropagation()diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/options.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/options.tsxindex 7d481b9a0a..f5142ced8a 100644--- a/packages/admin/src/routes/_authenticated/$storeId/products/options.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/products/options.tsx@@ -15,12 +15,7 @@ import {} from '@dnd-kit/sortable'import { CSS } from '@dnd-kit/utilities'import { zodResolver } from '@hookform/resolvers/zod'-import type {- OptionType,- OptionTypeCreateParams,- OptionValue,- OptionValueParams,-} from '@spree/admin-sdk'+import type { OptionType, OptionTypeCreateParams } from '@spree/admin-sdk'import { useQueryClient } from '@tanstack/react-query'import { createFileRoute, useNavigate } from '@tanstack/react-router'import { ImageIcon, PlusIcon, Trash2Icon, UploadCloudIcon, XIcon } from 'lucide-react'@@ -82,6 +77,15 @@ import {import { mapSpreeErrorsToForm } from '@/lib/form-errors'import { Subject } from '@/lib/permissions'import { cn } from '@/lib/utils'+import {+ OPTION_TYPE_DEFAULTS,+ OPTION_TYPE_KINDS,+ type OptionTypeFormValues,+ type OptionValueFormValue,+ optionTypeFormSchema,+ optionValueToFormRow,+ valueToParam,+} from '@/schemas/option-type'import '@/tables/option-types'const optionTypesSearchSchema = resourceSearchSchema.extend({@@ -130,7 +134,7 @@ function OptionTypesPage() {<Can I="create" a={Subject.OptionType}><Button size="sm" className="h-[2.125rem]" onClick={openCreate}><PlusIcon className="size-4" />- {t('admin.actions.add')}+ {t('admin.products.options.add_cta')}</Button></Can>}@@ -148,87 +152,6 @@ function OptionTypesPage() {)}-// ----------------------------------------------------------------------------// Form schema-// -----------------------------------------------------------------------------// NOTE: kind labels are translated at render time via i18n (see-// `OptionTypeFormFields`); the `label` here is the i18n key suffix used by-// `kindLabel(value)` below.-const KIND_OPTIONS = [- { value: 'dropdown', label: 'dropdown' },- { value: 'color_swatch', label: 'color_swatch' },- { value: 'buttons', label: 'buttons' },-] as const--const HEX_RE = /^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$/--const optionValueSchema = z.object({- id: z.string().optional(),- name: z.string().min(1, 'Name is required'),- label: z.string().min(1, 'Label is required'),- color_code: z- .string()- .nullable()- .optional()- .refine((v) => !v || HEX_RE.test(v), 'Invalid hex color'),- /** Active Storage signed_id from a fresh direct upload. Frontend-only state. */- image_signed_id: z.string().nullable().optional(),- /** Existing image URL (for preview only — never sent back). Frontend-only state. */- image_url: z.string().nullable().optional(),- /** True when the user clicks the trash icon next to an existing image. Frontend-only state. */- image_cleared: z.boolean().optional(),-})--const formSchema = z.object({- name: z.string().min(1, 'Name is required'),- label: z.string().min(1, 'Label is required'),- kind: z.enum(['dropdown', 'color_swatch', 'buttons']),- filterable: z.boolean(),- option_values: z.array(optionValueSchema),-})--type FormValues = z.infer<typeof formSchema>-type OptionValueFormValue = z.infer<typeof optionValueSchema>--const DEFAULT_VALUES: FormValues = {- name: '',- label: '',- kind: 'dropdown',- filterable: false,- option_values: [],-}--/**- * Hydrate the form from an API option_value row. Spreads all API fields 1:1 and- * attaches the frontend-only image upload-state fields (`image_signed_id`,- * `image_cleared`) initialized to their resting values.- */-function optionValueToFormRow(ov: OptionValue): OptionValueFormValue {- return {- ...ov,- image_signed_id: null,- image_cleared: false,- }-}--/**- * Build the API payload for a single option_value row. `index` is the row's- * current array position; we send `position: index + 1` (1-indexed) so- * `acts_as_list` persists the drag-reordered order. The frontend-only image- * upload state collapses into the API's `image` field: a fresh signed_id is- * sent, an explicit clear sends `null`, and an untouched row omits `image`- * entirely so the existing attachment stays.- */-function valueToParam(v: OptionValueFormValue, index: number): OptionValueParams {- const { image_signed_id, image_url: _imageUrl, image_cleared, ...rest } = v- return {- ...rest,- position: index + 1,- ...(image_signed_id ? { image: image_signed_id } : image_cleared ? { image: null } : {}),- }-}-// ---------------------------------------------------------------------------// Create// ---------------------------------------------------------------------------@@ -242,19 +165,19 @@ function CreateOptionTypeSheet({}) {const { t } = useTranslation()const createMutation = useCreateOptionType()- const form = useForm<FormValues>({+ const form = useForm<OptionTypeFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(formSchema) as any,- defaultValues: DEFAULT_VALUES,+ resolver: zodResolver(optionTypeFormSchema) as any,+ defaultValues: OPTION_TYPE_DEFAULTS,})- async function onSubmit(values: FormValues) {+ async function onSubmit(values: OptionTypeFormValues) {try {await createMutation.mutateAsync({...values,option_values: values.option_values.map(valueToParam),} as OptionTypeCreateParams)- form.reset(DEFAULT_VALUES)+ form.reset(OPTION_TYPE_DEFAULTS)onOpenChange(false)} catch (err) {if (!mapSpreeErrorsToForm(err, form.setError)) throw err@@ -265,7 +188,7 @@ function CreateOptionTypeSheet({<Sheetopen={open}onOpenChange={(next) => {- if (!next) form.reset(DEFAULT_VALUES)+ if (!next) form.reset(OPTION_TYPE_DEFAULTS)onOpenChange(next)}}>@@ -297,7 +220,7 @@ function CreateOptionTypeSheet({<Button type="submit" size="sm" disabled={form.formState.isSubmitting}>{form.formState.isSubmitting? t('admin.actions.creating')- : t('admin.actions.create')}+ : t('admin.products.options.create_label')}</Button></SheetFooter></form>@@ -325,23 +248,23 @@ function EditOptionTypeSheet({const deleteMutation = useDeleteOptionType()const confirm = useConfirm()- const form = useForm<FormValues>({+ const form = useForm<OptionTypeFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(formSchema) as any,- defaultValues: DEFAULT_VALUES,+ resolver: zodResolver(optionTypeFormSchema) as any,+ defaultValues: OPTION_TYPE_DEFAULTS,})useEffect(() => {if (optionType) {form.reset({...optionType,- kind: optionType.kind as FormValues['kind'],+ kind: optionType.kind as OptionTypeFormValues['kind'],option_values: (optionType.option_values ?? []).map(optionValueToFormRow),})}}, [optionType, form])- async function onSubmit(values: FormValues) {+ async function onSubmit(values: OptionTypeFormValues) {try {await updateMutation.mutateAsync({...values,@@ -433,16 +356,16 @@ function EditOptionTypeSheet({// Top-level fields// ----------------------------------------------------------------------------function OptionTypeFormFields({ form }: { form: UseFormReturn<FormValues> }) {+function OptionTypeFormFields({ form }: { form: UseFormReturn<OptionTypeFormValues> }) {const { t } = useTranslation()const { errors } = form.formStatereturn (<FieldGroup><div className="grid grid-cols-1 gap-4 sm:grid-cols-2"><Field>- <FieldLabel htmlFor="ot-label">{t('admin.fields.option_type.label.label')}</FieldLabel>+ <FieldLabel htmlFor="label">{t('admin.fields.option_type.label.label')}</FieldLabel><Input- id="ot-label"+ id="label"autoFocusplaceholder={t('admin.fields.option_type.label.placeholder')}aria-invalid={!!errors.label || undefined}@@ -454,9 +377,9 @@ function OptionTypeFormFields({ form }: { form: UseFormReturn<FormValues> }) {<FieldError errors={[errors.label]} /></Field><Field>- <FieldLabel htmlFor="ot-name">{t('admin.fields.option_type.name.label')}</FieldLabel>+ <FieldLabel htmlFor="name">{t('admin.fields.option_type.name.label')}</FieldLabel><Input- id="ot-name"+ id="name"placeholder={t('admin.fields.option_type.name.placeholder')}aria-invalid={!!errors.name || undefined}{...form.register('name')}@@ -466,18 +389,18 @@ function OptionTypeFormFields({ form }: { form: UseFormReturn<FormValues> }) {</Field></div><Field>- <FieldLabel htmlFor="ot-kind">{t('admin.fields.option_type.kind.label')}</FieldLabel>+ <FieldLabel htmlFor="kind">{t('admin.fields.option_type.kind.label')}</FieldLabel><Controllername="kind"control={form.control}render={({ field }) => {- const items = KIND_OPTIONS.map((o) => ({- value: o.value,- label: t(`admin.products.options.kinds.${o.value}`),+ const items = OPTION_TYPE_KINDS.map((value) => ({+ value,+ label: t(`admin.products.options.kinds.${value}`),}))return (<Select items={items as never} value={field.value} onValueChange={field.onChange}>- <SelectTrigger id="ot-kind">+ <SelectTrigger id="kind"><SelectValue /></SelectTrigger><SelectContent>@@ -496,7 +419,7 @@ function OptionTypeFormFields({ form }: { form: UseFormReturn<FormValues> }) {<Field><div className="flex items-start justify-between gap-4"><div className="flex flex-col">- <FieldLabel htmlFor="ot-filterable" className="cursor-pointer">+ <FieldLabel htmlFor="filterable" className="cursor-pointer">{t('admin.fields.option_type.filterable.label')}</FieldLabel><span className="text-xs text-muted-foreground">@@ -507,7 +430,7 @@ function OptionTypeFormFields({ form }: { form: UseFormReturn<FormValues> }) {name="filterable"control={form.control}render={({ field }) => (- <Switch id="ot-filterable" checked={!!field.value} onCheckedChange={field.onChange} />+ <Switch id="filterable" checked={!!field.value} onCheckedChange={field.onChange} />)}/></div>@@ -527,12 +450,12 @@ function OptionValuesFieldArray({form: any}) {const { t } = useTranslation()- const valuesArray = useFieldArray<FormValues, 'option_values', '_key'>({- control: form.control as Control<FormValues>,+ const valuesArray = useFieldArray<OptionTypeFormValues, 'option_values', '_key'>({+ control: form.control as Control<OptionTypeFormValues>,name: 'option_values',keyName: '_key',})- const kind = form.watch('kind') as FormValues['kind']+ const kind = form.watch('kind') as OptionTypeFormValues['kind']const showColor = kind === 'color_swatch'const showImage = kind === 'color_swatch' || kind === 'buttons'@@ -579,14 +502,14 @@ function OptionValuesFieldArray({<Table><TableHeader><TableRow>- <TableHead className="w-8" aria-label="Reorder" />+ <TableHead className="w-8" aria-label={t('admin.a11y.reorder')} /><TableHead>{t('admin.fields.option_value.name.label')}</TableHead><TableHead>{t('admin.fields.option_value.label.label')}</TableHead>{showColor && (<TableHead>{t('admin.fields.option_value.color_code.label')}</TableHead>)}{showImage && <TableHead>{t('admin.fields.option_value.image.label')}</TableHead>}- <TableHead aria-label="Actions" />+ <TableHead aria-label={t('admin.actions.actions_menu')} /></TableRow></TableHeader><TableBody>@@ -736,7 +659,7 @@ function SortableOptionValueRow({type="button"variant="ghost"size="icon-sm"- aria-label="Remove value"+ aria-label={t('admin.a11y.remove_value')}onPointerDown={(e) => e.stopPropagation()}onClick={onRemove}className="text-destructive hover:bg-destructive/10 hover:text-destructive"@@ -756,9 +679,10 @@ function OptionValueImageField({form,index,}: {- form: UseFormReturn<FormValues>+ form: UseFormReturn<OptionTypeFormValues>index: number}) {+ const { t } = useTranslation()const fileInputId = useId()const fileInputRef = useRef<HTMLInputElement>(null)const directUpload = useDirectUpload()@@ -826,7 +750,7 @@ function OptionValueImageField({'disabled:cursor-not-allowed disabled:opacity-50',preview && 'cursor-zoom-in',)}- aria-label={preview ? 'View image' : 'Upload image'}+ aria-label={t(preview ? 'admin.a11y.view_image' : 'admin.a11y.upload_image')}>{preview ? (<img src={preview} alt="" className="size-full object-cover" />@@ -857,7 +781,7 @@ function OptionValueImageField({onPointerDown={(e) => e.stopPropagation()}onClick={clear}disabled={uploading}- aria-label="Remove image"+ aria-label={t('admin.a11y.remove_image')}className={cn('absolute -right-1.5 -top-1.5 flex size-4 items-center justify-center rounded-full','border border-border bg-background text-muted-foreground shadow-xs',diff --git a/packages/admin/src/routes/_authenticated/$storeId/promotions/gift-cards.tsx b/packages/admin/src/routes/_authenticated/$storeId/promotions/gift-cards.tsxindex fd6e84bc38..660826ca0e 100644--- a/packages/admin/src/routes/_authenticated/$storeId/promotions/gift-cards.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/promotions/gift-cards.tsx@@ -1,18 +1,11 @@import { zodResolver } from '@hookform/resolvers/zod'-import type {- Customer,- GiftCard,- GiftCardBatchCreateParams,- GiftCardCreateParams,- GiftCardUpdateParams,-} from '@spree/admin-sdk'+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 { Controller, type UseFormReturn, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { z } from 'zod/v4'-import { adminClient } from '@/client'import { Can } from '@/components/spree/can'import { useConfirm } from '@/components/spree/confirm-dialog'import { CurrencySelect } from '@/components/spree/currency-select'@@ -33,6 +26,7 @@ import {} from '@/components/ui/sheet'import { customerAutocompleteProps } from '@/hooks/use-customers'import {+ listGiftCards,useCreateGiftCard,useCreateGiftCardBatch,useDeleteGiftCard,@@ -40,9 +34,18 @@ import {useUpdateGiftCard,} from '@/hooks/use-gift-cards'import { mapSpreeErrorsToForm } from '@/lib/form-errors'-import { i18n } from '@/lib/i18n'import { Subject } from '@/lib/permissions'import { useStore } from '@/providers/store-provider'+import {+ BATCH_LIMIT,+ type GiftCardCreateFormValues,+ type GiftCardEditFormValues,+ giftCardBatchValuesToParams,+ giftCardCreateFormSchema,+ giftCardEditFormSchema,+ giftCardEditValuesToParams,+ giftCardSingleValuesToParams,+} from '@/schemas/gift-card'import '@/tables/gift-cards'const giftCardsSearchSchema = resourceSearchSchema.extend({@@ -90,7 +93,7 @@ function GiftCardsPage() {<ResourceTable<GiftCard>tableKey="gift-cards"queryKey="gift-cards"- queryFn={(params) => adminClient.giftCards.list(params)}+ queryFn={listGiftCards}searchParams={search}defaultParams={{ expand: LIST_EXPAND }}actions={@@ -109,75 +112,6 @@ function GiftCardsPage() {)}-// -----------------------------------------------------------------------------// Form schemas — separate for create (with `quantity`) vs edit (no quantity,-// no code-prefix branching).-// ------------------------------------------------------------------------------// Mirrors `Spree::Config[:gift_card_batch_limit]`. Hardcoded for now; if the-// merchant overrides it we'll surface it via a store-settings endpoint later.-const BATCH_LIMIT = 50_000--const createFormSchema = z.object({- // When `quantity === 1` this is the optional caller-supplied code.- // When `quantity > 1` it becomes the required batch `prefix`.- code: z.string().optional(),- amount: z.coerce- .number()- .positive(i18n.t('admin.pages.promotions.gift_cards.validation.amount_positive')),- currency: z.string().min(1, 'Currency is required'),- expires_at: z.string().optional(),- customer_id: z.string().optional(),- quantity: z.coerce.number().int().min(1).max(BATCH_LIMIT),-})--type CreateFormValues = z.infer<typeof createFormSchema>--const editFormSchema = z.object({- code: z.string().optional(),- amount: z.coerce- .number()- .positive(i18n.t('admin.pages.promotions.gift_cards.validation.amount_positive')),- currency: z.string().min(1, 'Currency is required'),- expires_at: z.string().optional(),- customer_id: z.string().optional(),-})--type EditFormValues = z.infer<typeof editFormSchema>--function blank(s: string | undefined): string | undefined {- return s && s.length > 0 ? s : undefined-}--function editValuesToParams(v: EditFormValues): GiftCardUpdateParams {- return {- amount: v.amount,- expires_at: v.expires_at || null,- user_id: blank(v.customer_id) ?? null,- }-}--function singleValuesToParams(v: CreateFormValues): GiftCardCreateParams {- return {- code: blank(v.code),- amount: v.amount,- currency: v.currency,- expires_at: v.expires_at || null,- user_id: blank(v.customer_id) ?? null,- }-}--function batchValuesToParams(v: CreateFormValues): GiftCardBatchCreateParams {- // `code` carries the prefix in batch mode; required, validated below.- return {- prefix: v.code ?? '',- amount: v.amount,- currency: v.currency,- codes_count: v.quantity,- expires_at: v.expires_at || null,- }-}-// ----------------------------------------------------------------------------// Create sheet — single sheet for both single-issue and batch-issue. The// flow branches off `quantity`: `1` posts to `/gift_cards`; `>1` posts to@@ -198,9 +132,9 @@ function CreateGiftCardSheet({// seed `currency` here too so react-hook-form's validator doesn't reject// the submit on a blank string before `mutate` ever runs.const { defaultCurrency } = useStore()- const form = useForm<CreateFormValues>({+ const form = useForm<GiftCardCreateFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(createFormSchema) as any,+ resolver: zodResolver(giftCardCreateFormSchema) as any,defaultValues: {code: '',// Empty so the input shows its placeholder; zod's `z.coerce.number()`@@ -216,21 +150,12 @@ function CreateGiftCardSheet({const quantity = form.watch('quantity')const isBatch = Number(quantity) > 1- async function onSubmit(values: CreateFormValues) {+ async function onSubmit(values: GiftCardCreateFormValues) {try {if (Number(values.quantity) > 1) {- // Batches require a prefix; surface the validation error inline rather- // than letting the server 422.- if (!values.code?.trim()) {- form.setError('code', {- type: 'required',- message: t('admin.pages.promotions.gift_cards.validation.prefix_required'),- })- return- }- await createBatchMutation.mutateAsync(batchValuesToParams(values))+ await createBatchMutation.mutateAsync(giftCardBatchValuesToParams(values))} else {- await createMutation.mutateAsync(singleValuesToParams(values))+ await createMutation.mutateAsync(giftCardSingleValuesToParams(values))}form.reset()onOpenChange(false)@@ -278,7 +203,7 @@ function CreateGiftCardSheet({? t('admin.actions.creating'): isBatch? t('admin.pages.promotions.gift_cards.create_batch_cta', { count: quantity })- : t('admin.actions.create')}+ : t('admin.pages.promotions.gift_cards.create_label')}</Button></SheetFooter></form>@@ -306,9 +231,9 @@ function EditGiftCardSheet({const deleteMutation = useDeleteGiftCard()const confirm = useConfirm()- const form = useForm<EditFormValues>({+ const form = useForm<GiftCardEditFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(editFormSchema) as any,+ resolver: zodResolver(giftCardEditFormSchema) as any,defaultValues: {code: '',amount: 0,@@ -330,9 +255,9 @@ function EditGiftCardSheet({}}, [giftCard, form])- async function onSubmit(values: EditFormValues) {+ async function onSubmit(values: GiftCardEditFormValues) {try {- await updateMutation.mutateAsync(editValuesToParams(values))+ await updateMutation.mutateAsync(giftCardEditValuesToParams(values))form.reset(values)onOpenChange(false)} catch (err) {@@ -431,6 +356,7 @@ function CustomerPickerController({form: anyreadOnly?: boolean}) {+ const { t } = useTranslation()return (<Controllername="customer_id"@@ -438,7 +364,7 @@ function CustomerPickerController({render={({ field }) =>readOnly ? (<div className="text-sm text-muted-foreground">- {field.value || 'No customer attached'}+ {field.value || t('admin.pages.promotions.gift_cards.no_customer')}</div>) : (<ResourceCombobox<Customer>@@ -460,7 +386,7 @@ function CustomerPickerController({)}-function AmountCurrencyRow<T extends CreateFormValues | EditFormValues>({+function AmountCurrencyRow<T extends GiftCardCreateFormValues | GiftCardEditFormValues>({form,readOnly,currencyLocked,@@ -475,9 +401,9 @@ function AmountCurrencyRow<T extends CreateFormValues | EditFormValues>({return (<div className="grid grid-cols-2 gap-3"><Field>- <FieldLabel htmlFor="gc-amount">{t('admin.fields.gift_card.amount.label')}</FieldLabel>+ <FieldLabel htmlFor="amount">{t('admin.fields.gift_card.amount.label')}</FieldLabel><Input- id="gc-amount"+ id="amount"type="number"step="0.01"min={0}@@ -489,13 +415,13 @@ function AmountCurrencyRow<T extends CreateFormValues | EditFormValues>({</Field><Field>- <FieldLabel htmlFor="gc-currency">{t('admin.fields.gift_card.currency.label')}</FieldLabel>+ <FieldLabel htmlFor="currency">{t('admin.fields.gift_card.currency.label')}</FieldLabel><Controllername={'currency' as never}control={form.control}render={({ field }) => (<CurrencySelect- id="gc-currency"+ id="currency"value={(field.value as string) || undefined}onChange={field.onChange}disabled={readOnly || currencyLocked}@@ -511,7 +437,7 @@ function CreateGiftCardFormFields({form,isBatch,}: {- form: UseFormReturn<CreateFormValues>+ form: UseFormReturn<GiftCardCreateFormValues>isBatch: boolean}) {const { t } = useTranslation()@@ -519,9 +445,9 @@ function CreateGiftCardFormFields({return (<FieldGroup><Field>- <FieldLabel htmlFor="gc-quantity">{t('admin.fields.gift_card.quantity.label')}</FieldLabel>+ <FieldLabel htmlFor="quantity">{t('admin.fields.gift_card.quantity.label')}</FieldLabel><Input- id="gc-quantity"+ id="quantity"type="number"min={1}max={BATCH_LIMIT}@@ -529,21 +455,23 @@ function CreateGiftCardFormFields({aria-invalid={!!errors.quantity || undefined}{...form.register('quantity')}/>- <p className="text-xs text-muted-foreground">- {`Issue 1 card or bulk-issue up to ${BATCH_LIMIT.toLocaleString()} as a batch.`}- </p>+ <p className="text-xs text-muted-foreground">{t('admin.fields.gift_card.quantity.help')}</p><FieldError errors={[errors.quantity]} /></Field><Field>- <FieldLabel htmlFor="gc-code">- {isBatch ? 'Prefix' : t('admin.fields.gift_card.code.label')}+ <FieldLabel htmlFor="code">+ {isBatch+ ? t('admin.pages.promotions.gift_cards.prefix.label')+ : t('admin.fields.gift_card.code.label')}</FieldLabel><Input- id="gc-code"- placeholder={- isBatch ? 'e.g. WELCOME — codes will be WELCOME-abc123' : 'Auto-generated when blank'- }+ id="code"+ placeholder={t(+ isBatch+ ? 'admin.pages.promotions.gift_cards.prefix.placeholder'+ : 'admin.pages.promotions.gift_cards.prefix.auto_placeholder',+ )}aria-invalid={!!errors.code || undefined}{...form.register('code')}/>@@ -556,9 +484,7 @@ function CreateGiftCardFormFields({<AmountCurrencyRow form={form} readOnly={false} currencyLocked={false} /><Field>- <FieldLabel htmlFor="gc-expires-at">- {t('admin.fields.gift_card.expires_at.label')}- </FieldLabel>+ <FieldLabel htmlFor="expires_at">{t('admin.fields.gift_card.expires_at.label')}</FieldLabel><Controllername="expires_at"control={form.control}@@ -589,7 +515,7 @@ function EditGiftCardFormFields({form,readOnly = false,}: {- form: UseFormReturn<EditFormValues>+ form: UseFormReturn<GiftCardEditFormValues>readOnly?: boolean}) {const { t } = useTranslation()@@ -598,9 +524,7 @@ function EditGiftCardFormFields({<AmountCurrencyRow form={form} readOnly={readOnly} currencyLocked /><Field>- <FieldLabel htmlFor="gc-expires-at">- {t('admin.fields.gift_card.expires_at.label')}- </FieldLabel>+ <FieldLabel htmlFor="expires_at">{t('admin.fields.gift_card.expires_at.label')}</FieldLabel><Controllername="expires_at"control={form.control}@@ -630,23 +554,24 @@ function EditGiftCardFormFields({// ----------------------------------------------------------------------------function GiftCardUsageSummary({ giftCard }: { giftCard: GiftCard }) {+ const { t } = useTranslation()return (<div className="rounded-md border bg-muted/30 p-3 text-sm">- <div className="mb-2 font-medium">Usage</div>+ <div className="mb-2 font-medium">{t('admin.pages.promotions.gift_cards.usage.title')}</div><div className="grid grid-cols-2 gap-1 text-muted-foreground">- <span>Amount</span>+ <span>{t('admin.pages.promotions.gift_cards.usage.amount')}</span><span className="text-right text-foreground tabular-nums">{giftCard.display_amount}</span>- <span>Used</span>+ <span>{t('admin.pages.promotions.gift_cards.usage.used')}</span><span className="text-right text-foreground tabular-nums">{giftCard.display_amount_used}</span>- <span>Remaining</span>+ <span>{t('admin.pages.promotions.gift_cards.usage.remaining')}</span><span className="text-right text-foreground tabular-nums">{giftCard.display_amount_remaining}</span>{giftCard.created_by && (<>- <span>Issued by</span>+ <span>{t('admin.pages.promotions.gift_cards.usage.issued_by')}</span><span className="text-right text-foreground">{giftCard.created_by.email}</span></>)}diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsxindex 4911e160c5..6a8977ccfc 100644--- a/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx@@ -1,10 +1,5 @@import { zodResolver } from '@hookform/resolvers/zod'-import type {- PaymentMethod,- PaymentMethodCreateParams,- PaymentMethodUpdateParams,- PreferenceField,-} from '@spree/admin-sdk'+import type { PaymentMethod, PreferenceField } from '@spree/admin-sdk'import { useQueryClient } from '@tanstack/react-query'import { createFileRoute, useNavigate } from '@tanstack/react-router'import { PlusIcon } from 'lucide-react'@@ -38,6 +33,14 @@ import {} from '@/hooks/use-payment-methods'import { mapSpreeErrorsToForm } from '@/lib/form-errors'import { Subject } from '@/lib/permissions'+import {+ PAYMENT_METHOD_BASE_DEFAULTS,+ PAYMENT_METHOD_CREATE_DEFAULTS,+ paymentMethodBaseFormSchema,+ paymentMethodCreateFormSchema,+ paymentMethodValuesToCreateParams,+ paymentMethodValuesToUpdateParams,+} from '@/schemas/payment-method'import '@/tables/payment-methods'const paymentMethodsSearchSchema = resourceSearchSchema.extend({@@ -106,53 +109,6 @@ function PaymentMethodsPage() {)}-const baseFormSchema = z.object({- name: z.string().min(1, 'Name is required'),- description: z.string().optional(),- storefront_visible: z.boolean(),- active: z.boolean(),- auto_capture: z.boolean(),-})--const createFormSchema = baseFormSchema.extend({- type: z.string().min(1, 'Pick a provider'),-})--const BASE_DEFAULTS: PaymentMethodFormValues = {- name: '',- description: '',- storefront_visible: true,- active: true,- auto_capture: false,-}--const CREATE_DEFAULTS: PaymentMethodFormValues = { ...BASE_DEFAULTS, type: '' }--function valuesToCreateParams(- v: PaymentMethodFormValues,- preferences: Record<string, unknown>,-): PaymentMethodCreateParams {- return {- type: v.type ?? '',- name: v.name,- description: v.description?.length ? v.description : null,- active: v.active,- auto_capture: v.auto_capture,- storefront_visible: v.storefront_visible,- ...(Object.keys(preferences).length > 0 ? { preferences } : {}),- }-}--function valuesToUpdateParams(v: PaymentMethodFormValues): PaymentMethodUpdateParams {- return {- name: v.name,- description: v.description?.length ? v.description : null,- active: v.active,- auto_capture: v.auto_capture,- storefront_visible: v.storefront_visible,- }-}-function CreatePaymentMethodSheet({open,onOpenChange,@@ -167,8 +123,8 @@ function CreatePaymentMethodSheet({const form = useForm<PaymentMethodFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(createFormSchema) as any,- defaultValues: CREATE_DEFAULTS,+ resolver: zodResolver(paymentMethodCreateFormSchema) as any,+ defaultValues: PAYMENT_METHOD_CREATE_DEFAULTS,})const [preferences, setPreferences] = useState<Record<string, unknown>>({})@@ -185,8 +141,8 @@ function CreatePaymentMethodSheet({async function onSubmit(values: PaymentMethodFormValues) {try {- await createMutation.mutateAsync(valuesToCreateParams(values, preferences))- form.reset(CREATE_DEFAULTS)+ await createMutation.mutateAsync(paymentMethodValuesToCreateParams(values, preferences))+ form.reset(PAYMENT_METHOD_CREATE_DEFAULTS)setPreferences({})onOpenChange(false)} catch (err) {@@ -199,7 +155,7 @@ function CreatePaymentMethodSheet({open={open}onOpenChange={(next) => {if (!next) {- form.reset(CREATE_DEFAULTS)+ form.reset(PAYMENT_METHOD_CREATE_DEFAULTS)setPreferences({})}onOpenChange(next)@@ -269,8 +225,8 @@ function EditPaymentMethodSheet({const form = useForm<PaymentMethodFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(baseFormSchema) as any,- defaultValues: BASE_DEFAULTS,+ resolver: zodResolver(paymentMethodBaseFormSchema) as any,+ defaultValues: PAYMENT_METHOD_BASE_DEFAULTS,})const [preferences, setPreferences] = useState<Record<string, unknown>>({})// Snapshot of the preferences last loaded from the server. Derive the@@ -302,7 +258,7 @@ function EditPaymentMethodSheet({)async function onSubmit(values: PaymentMethodFormValues) {- const params = valuesToUpdateParams(values)+ const params = paymentMethodValuesToUpdateParams(values)if (preferencesDirty) params.preferences = preferencestry {await updateMutation.mutateAsync(params)diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsxindex f055f58ab4..e0cd2c6757 100644--- a/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsx@@ -48,6 +48,15 @@ import {} from '@/hooks/use-stock-locations'import { mapSpreeErrorsToForm } from '@/lib/form-errors'import { Subject } from '@/lib/permissions'+import {+ formValuesToParams,+ PICKUP_STOCK_POLICIES,+ STOCK_LOCATION_DEFAULTS,+ STOCK_LOCATION_KINDS,+ type StockLocationFormValues,+ stockLocationFormSchema,+ stockLocationToFormValues,+} from '@/schemas/stock-location'import '@/tables/stock-locations'// Adds `?edit=<id>` and `?new=1` on top of the standard table search schema@@ -62,17 +71,6 @@ export const Route = createFileRoute('/_authenticated/$storeId/settings/stock-locomponent: StockLocationsPage,})-const KIND_OPTIONS = [- { value: 'warehouse', label: 'Warehouse' },- { value: 'store', label: 'Store' },- { value: 'fulfillment_center', label: 'Fulfillment center' },-] as const--const PICKUP_POLICY_OPTIONS = [- { value: 'local', label: 'Only items at this location' },- { value: 'any', label: 'Allow transfers from other locations' },-] as const-function StockLocationsPage() {const { t } = useTranslation()// Cast: Route.useSearch's inferred type unions with the parent layout's@@ -129,110 +127,6 @@ function StockLocationsPage() {)}-// ============================================================================-// Form-// ============================================================================--const formSchema = z.object({- name: z.string().min(1, 'Name is required'),- admin_name: z.string().optional(),- kind: z.string().min(1),- active: z.boolean(),- default: z.boolean(),- propagate_all_variants: z.boolean(),- backorderable_default: z.boolean(),- address1: z.string().optional(),- address2: z.string().optional(),- city: z.string().optional(),- zipcode: z.string().optional(),- phone: z.string().optional(),- company: z.string().optional(),- country_iso: z.string().optional(),- 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_instructions: z.string().optional(),-})--type FormValues = z.infer<typeof formSchema>--const DEFAULT_VALUES: FormValues = {- name: '',- admin_name: '',- kind: 'warehouse',- active: true,- default: false,- propagate_all_variants: false,- backorderable_default: false,- address1: '',- address2: '',- city: '',- zipcode: '',- phone: '',- company: '',- country_iso: '',- state_abbr: '',- state_name: '',- pickup_enabled: false,- pickup_stock_policy: 'local',- pickup_ready_in_minutes: null,- pickup_instructions: '',-}--function stockLocationToFormValues(sl: StockLocation): FormValues {- return {- name: sl.name,- admin_name: sl.admin_name ?? '',- kind: sl.kind ?? 'warehouse',- active: sl.active,- default: sl.default,- propagate_all_variants: sl.propagate_all_variants,- backorderable_default: sl.backorderable_default,- address1: sl.address1 ?? '',- address2: sl.address2 ?? '',- city: sl.city ?? '',- zipcode: sl.zipcode ?? '',- phone: sl.phone ?? '',- company: sl.company ?? '',- country_iso: sl.country_iso ?? '',- state_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_ready_in_minutes: sl.pickup_ready_in_minutes ?? null,- pickup_instructions: sl.pickup_instructions ?? '',- }-}--// Drops blank strings → undefined so we don't overwrite null fields with "".-function formValuesToParams(v: FormValues): StockLocationCreateParams & StockLocationUpdateParams {- const blank = (s: string | null | undefined) => (s && s.length > 0 ? s : undefined)- return {- name: v.name,- admin_name: blank(v.admin_name),- kind: v.kind,- active: v.active,- default: v.default,- propagate_all_variants: v.propagate_all_variants,- backorderable_default: v.backorderable_default,- address1: blank(v.address1),- address2: blank(v.address2),- city: blank(v.city),- zipcode: blank(v.zipcode),- phone: blank(v.phone),- company: blank(v.company),- country_iso: blank(v.country_iso),- state_abbr: blank(v.state_abbr),- state_name: blank(v.state_name),- pickup_enabled: v.pickup_enabled,- pickup_stock_policy: v.pickup_stock_policy,- pickup_ready_in_minutes: v.pickup_ready_in_minutes ?? null,- pickup_instructions: blank(v.pickup_instructions),- }-}-// ============================================================================// Create Sheet// ============================================================================@@ -247,17 +141,17 @@ function CreateStockLocationSheet({const { t } = useTranslation()const createMutation = useCreateStockLocation()- const form = useForm<FormValues>({+ const form = useForm<StockLocationFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(formSchema) as any,- defaultValues: DEFAULT_VALUES,+ resolver: zodResolver(stockLocationFormSchema) as any,+ defaultValues: STOCK_LOCATION_DEFAULTS,})- async function onSubmit(values: FormValues) {+ async function onSubmit(values: StockLocationFormValues) {try {const params = formValuesToParams(values) as StockLocationCreateParamsawait createMutation.mutateAsync(params)- form.reset(DEFAULT_VALUES)+ form.reset(STOCK_LOCATION_DEFAULTS)onOpenChange(false)} catch (err) {if (!mapSpreeErrorsToForm(err, form.setError)) throw err@@ -268,7 +162,7 @@ function CreateStockLocationSheet({<Sheetopen={open}onOpenChange={(next) => {- if (!next) form.reset(DEFAULT_VALUES)+ if (!next) form.reset(STOCK_LOCATION_DEFAULTS)onOpenChange(next)}}>@@ -294,7 +188,7 @@ function CreateStockLocationSheet({<Button type="submit" size="sm" disabled={form.formState.isSubmitting}>{form.formState.isSubmitting? t('admin.actions.creating')- : t('admin.actions.create')}+ : t('admin.stock_locations.create_label')}</Button></SheetFooter></form>@@ -322,10 +216,10 @@ function EditStockLocationSheet({const deleteMutation = useDeleteStockLocation()const confirm = useConfirm()- const form = useForm<FormValues>({+ const form = useForm<StockLocationFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(formSchema) as any,- defaultValues: DEFAULT_VALUES,+ resolver: zodResolver(stockLocationFormSchema) as any,+ defaultValues: STOCK_LOCATION_DEFAULTS,})// Reset form when the loaded resource arrives — keeps the inputs in sync@@ -336,7 +230,7 @@ function EditStockLocationSheet({}}, [stockLocation, form])- async function onSubmit(values: FormValues) {+ async function onSubmit(values: StockLocationFormValues) {try {const params = formValuesToParams(values) as StockLocationUpdateParamsawait updateMutation.mutateAsync(params)@@ -658,7 +552,7 @@ function StockItemRow({ item }: { item: StockItem }) {// Shared form fields// ============================================================================-function StockLocationFormFields({ form }: { form: UseFormReturn<FormValues> }) {+function StockLocationFormFields({ form }: { form: UseFormReturn<StockLocationFormValues> }) {const { t } = useTranslation()const { errors } = form.formStateconst countryIso = form.watch('country_iso')@@ -674,9 +568,9 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<FormValues> }))}<Field>- <FieldLabel htmlFor="sl-name">{t('admin.fields.name.label')}</FieldLabel>+ <FieldLabel htmlFor="name">{t('admin.fields.name.label')}</FieldLabel><Input- id="sl-name"+ id="name"autoFocusplaceholder={t('admin.fields.stock_location.name.placeholder')}aria-invalid={!!errors.name || undefined}@@ -686,11 +580,11 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<FormValues> })</Field><Field>- <FieldLabel htmlFor="sl-admin-name">+ <FieldLabel htmlFor="admin-name">{t('admin.fields.stock_location.admin_name.label')}</FieldLabel><Input- id="sl-admin-name"+ id="admin-name"placeholder={t('admin.fields.stock_location.admin_name.placeholder')}aria-invalid={!!errors.admin_name || undefined}{...form.register('admin_name')}@@ -699,54 +593,56 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<FormValues> })</Field><Field>- <FieldLabel htmlFor="sl-kind">{t('admin.fields.stock_location.kind.label')}</FieldLabel>+ <FieldLabel htmlFor="kind">{t('admin.fields.stock_location.kind.label')}</FieldLabel><Controllername="kind"control={form.control}- render={({ field }) => (- <Select- items={KIND_OPTIONS as never}- value={field.value}- onValueChange={field.onChange}- >- <SelectTrigger id="sl-kind">- <SelectValue />- </SelectTrigger>- <SelectContent>- {KIND_OPTIONS.map((o) => (- <SelectItem key={o.value} value={o.value}>- {o.label}- </SelectItem>- ))}- </SelectContent>- </Select>- )}+ render={({ field }) => {+ const items = STOCK_LOCATION_KINDS.map((value) => ({+ value,+ label: t(`admin.stock_locations.kinds.${value}`),+ }))+ return (+ <Select items={items as never} value={field.value} onValueChange={field.onChange}>+ <SelectTrigger id="kind">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {items.map((o) => (+ <SelectItem key={o.value} value={o.value}>+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+ }}/></Field><BooleanRow- id="sl-active"+ id="active"label={t('admin.fields.stock_location.active.label')}help={t('admin.fields.stock_location.active.help')}form={form}name="active"/><BooleanRow- id="sl-default"+ id="default"label={t('admin.fields.stock_location.default.label')}help={t('admin.fields.stock_location.default.help')}form={form}name="default"/><BooleanRow- id="sl-backorderable-default"+ id="backorderable-default"label={t('admin.fields.stock_location.backorderable_default.label')}help={t('admin.fields.stock_location.backorderable_default.help')}form={form}name="backorderable_default"/><BooleanRow- id="sl-propagate-all-variants"+ id="propagate-all-variants"label={t('admin.fields.stock_location.propagate_all_variants.label')}help={t('admin.fields.stock_location.propagate_all_variants.help')}form={form}@@ -759,18 +655,18 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<FormValues> })</h3><FieldGroup><Field>- <FieldLabel htmlFor="sl-address1">{t('admin.fields.address1.label')}</FieldLabel>+ <FieldLabel htmlFor="address1">{t('admin.fields.address1.label')}</FieldLabel><Input- id="sl-address1"+ id="address1"aria-invalid={!!errors.address1 || undefined}{...form.register('address1')}/><FieldError errors={[errors.address1]} /></Field><Field>- <FieldLabel htmlFor="sl-address2">{t('admin.fields.address2.label')}</FieldLabel>+ <FieldLabel htmlFor="address2">{t('admin.fields.address2.label')}</FieldLabel><Input- id="sl-address2"+ id="address2"aria-invalid={!!errors.address2 || undefined}{...form.register('address2')}/>@@ -778,18 +674,18 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<FormValues> })</Field><div className="grid grid-cols-2 gap-3"><Field>- <FieldLabel htmlFor="sl-city">{t('admin.fields.city.label')}</FieldLabel>+ <FieldLabel htmlFor="city">{t('admin.fields.city.label')}</FieldLabel><Input- id="sl-city"+ id="city"aria-invalid={!!errors.city || undefined}{...form.register('city')}/><FieldError errors={[errors.city]} /></Field><Field>- <FieldLabel htmlFor="sl-zipcode">{t('admin.fields.zipcode.label')}</FieldLabel>+ <FieldLabel htmlFor="zipcode">{t('admin.fields.zipcode.label')}</FieldLabel><Input- id="sl-zipcode"+ id="zipcode"aria-invalid={!!errors.zipcode || undefined}{...form.register('zipcode')}/>@@ -831,9 +727,9 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<FormValues> })</Field>) : (<Field>- <FieldLabel htmlFor="sl-state-name">{t('admin.fields.state_name.label')}</FieldLabel>+ <FieldLabel htmlFor="state-name">{t('admin.fields.state_name.label')}</FieldLabel><Input- id="sl-state-name"+ id="state-name"aria-invalid={!!errors.state_name || undefined}{...form.register('state_name')}/>@@ -841,18 +737,18 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<FormValues> })</Field>)}<Field>- <FieldLabel htmlFor="sl-phone">{t('admin.fields.phone.label')}</FieldLabel>+ <FieldLabel htmlFor="phone">{t('admin.fields.phone.label')}</FieldLabel><Input- id="sl-phone"+ id="phone"aria-invalid={!!errors.phone || undefined}{...form.register('phone')}/><FieldError errors={[errors.phone]} /></Field><Field>- <FieldLabel htmlFor="sl-company">{t('admin.fields.company.label')}</FieldLabel>+ <FieldLabel htmlFor="company">{t('admin.fields.company.label')}</FieldLabel><Input- id="sl-company"+ id="company"aria-invalid={!!errors.company || undefined}{...form.register('company')}/>@@ -865,7 +761,7 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<FormValues> })<h3 className="mb-3 text-sm font-medium">{t('admin.stock_locations.section_pickup')}</h3><FieldGroup><BooleanRow- id="sl-pickup-enabled"+ id="pickup-enabled"label={t('admin.fields.stock_location.pickup_enabled.label')}help={t('admin.fields.stock_location.pickup_enabled.help')}form={form}@@ -874,53 +770,65 @@ function StockLocationFormFields({ form }: { form: UseFormReturn<FormValues> }){pickupEnabled && (<><Field>- <FieldLabel htmlFor="sl-pickup-stock-policy">+ <FieldLabel htmlFor="pickup-stock-policy">{t('admin.fields.stock_location.pickup_stock_policy.label')}</FieldLabel><Controllername="pickup_stock_policy"control={form.control}- render={({ field }) => (- <Select- items={PICKUP_POLICY_OPTIONS as never}- value={field.value}- onValueChange={field.onChange}- >- <SelectTrigger id="sl-pickup-stock-policy">- <SelectValue />- </SelectTrigger>- <SelectContent>- {PICKUP_POLICY_OPTIONS.map((o) => (- <SelectItem key={o.value} value={o.value}>- {o.label}- </SelectItem>- ))}- </SelectContent>- </Select>- )}+ render={({ field }) => {+ const items = PICKUP_STOCK_POLICIES.map((value) => ({+ value,+ label: t(`admin.stock_locations.pickup_stock_policies.${value}`),+ }))+ return (+ <Select+ items={items as never}+ value={field.value}+ onValueChange={field.onChange}+ >+ <SelectTrigger id="pickup-stock-policy">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {items.map((o) => (+ <SelectItem key={o.value} value={o.value}>+ {o.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+ }}/></Field><Field>- <FieldLabel htmlFor="sl-pickup-ready-in-minutes">+ <FieldLabel htmlFor="pickup-ready-in-minutes">{t('admin.fields.stock_location.pickup_ready_in_minutes.label')}</FieldLabel><Input- id="sl-pickup-ready-in-minutes"+ id="pickup-ready-in-minutes"type="number"min={0}step={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', { valueAsNumber: true })}+ {...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),+ })}/><FieldError errors={[errors.pickup_ready_in_minutes]} /></Field><Field>- <FieldLabel htmlFor="sl-pickup-instructions">+ <FieldLabel htmlFor="pickup-instructions">{t('admin.fields.stock_location.pickup_instructions.label')}</FieldLabel><Textarea- id="sl-pickup-instructions"+ id="pickup-instructions"rows={3}placeholder={t('admin.fields.stock_location.pickup_instructions.placeholder')}aria-invalid={!!errors.pickup_instructions || undefined}@@ -946,8 +854,8 @@ function BooleanRow({id: stringlabel: stringhelp?: string- form: UseFormReturn<FormValues>- name: keyof FormValues+ form: UseFormReturn<StockLocationFormValues>+ name: keyof StockLocationFormValues}) {return (<Field>diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/store.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/store.tsxindex 4e5eeafbc2..b86dc75312 100644--- a/packages/admin/src/routes/_authenticated/$storeId/settings/store.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/store.tsx@@ -2,7 +2,13 @@ import { zodResolver } from '@hookform/resolvers/zod'import { SpreeError, type Store } from '@spree/admin-sdk'import { createFileRoute } from '@tanstack/react-router'import { useEffect, useMemo } from 'react'-import { Controller, useForm } from 'react-hook-form'+import {+ type Control,+ Controller,+ type FieldPath,+ type FieldValues,+ useForm,+} from 'react-hook-form'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'import { FormActions, useFormSubmitShortcut } from '@/components/spree/form-actions'@@ -26,8 +32,8 @@ import {ADMIN_LOCALE_OPTIONS,type StoreSettingsFormValues,storeSettingsFormSchema,- UNIT_SYSTEM_OPTIONS,- WEIGHT_UNIT_OPTIONS,+ UNIT_SYSTEMS,+ WEIGHT_UNITS,} from '@/schemas/store'export const Route = createFileRoute('/_authenticated/$storeId/settings/store')({@@ -108,7 +114,7 @@ function StoreSettingsForm({ store }: { store: Store }) {// that system so the form never holds an inconsistent pair.const unitSystem = form.watch('preferred_unit_system')useEffect(() => {- const validUnits = WEIGHT_UNIT_OPTIONS[unitSystem]?.map((u) => u.value) ?? []+ const validUnits = WEIGHT_UNITS[unitSystem] ?? []const current = form.getValues('preferred_weight_unit')if (current && !validUnits.includes(current)) {form.setValue('preferred_weight_unit', validUnits[0] ?? '', { shouldDirty: true })@@ -138,7 +144,18 @@ function StoreSettingsForm({ store }: { store: Store }) {// Compute the dynamic timezone option list once. `Intl.supportedValuesOf`// can be expensive on some browsers; memo keeps re-renders cheap.const timezoneOptions = useMemo(() => TIMEZONES.map((tz) => ({ value: tz, label: tz })), [])- const weightOptions = WEIGHT_UNIT_OPTIONS[unitSystem] ?? WEIGHT_UNIT_OPTIONS.metric+ const unitSystemOptions = useMemo(+ () => UNIT_SYSTEMS.map((value) => ({ value, label: t(`admin.store.unit_systems.${value}`) })),+ [t],+ )+ const weightOptions = useMemo(+ () =>+ (WEIGHT_UNITS[unitSystem] ?? WEIGHT_UNITS.metric).map((value) => ({+ value,+ label: t(`admin.store.weight_units.${value}`),+ })),+ [t, unitSystem],+ )const { errors } = form.formState@@ -207,7 +224,7 @@ function StoreSettingsForm({ store }: { store: Store }) {label={t('admin.fields.store.preferred_unit_system.label')}name="preferred_unit_system"control={form.control}- options={UNIT_SYSTEM_OPTIONS as never}+ options={unitSystemOptions}/><SelectFieldid="store-weight-unit"@@ -226,27 +243,32 @@ function StoreSettingsForm({ store }: { store: Store }) {)}-interface SelectFieldProps {+interface SelectFieldProps<TValues extends FieldValues> {id: stringlabel: stringplaceholder?: string- // eslint-disable-next-line @typescript-eslint/no-explicit-any- name: any- // eslint-disable-next-line @typescript-eslint/no-explicit-any- control: any+ name: FieldPath<TValues>+ control: Control<TValues>options: ReadonlyArray<{ value: string; label: string }>}-function SelectField({ id, label, placeholder, name, control, options }: SelectFieldProps) {+function SelectField<TValues extends FieldValues>({+ id,+ label,+ placeholder,+ name,+ control,+ options,+}: SelectFieldProps<TValues>) {return (- <Field>- <FieldLabel htmlFor={id}>{label}</FieldLabel>- <Controller- name={name}- control={control}- render={({ field }) => (+ <Controller+ name={name}+ control={control}+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel htmlFor={id}>{label}</FieldLabel><Select items={options as never} value={field.value} onValueChange={field.onChange}>- <SelectTrigger id={id}>+ <SelectTrigger id={id} aria-invalid={!!fieldState.error || undefined}><SelectValue placeholder={placeholder} /></SelectTrigger><SelectContent>@@ -257,8 +279,9 @@ function SelectField({ id, label, placeholder, name, control, options }: SelectF))}</SelectContent></Select>- )}- />- </Field>+ <FieldError errors={[fieldState.error]} />+ </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 8372a8fd91..d21dadf747 100644--- a/packages/admin/src/routes/_authenticated/$storeId/settings/tax-categories.tsx+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/tax-categories.tsx@@ -1,9 +1,5 @@import { zodResolver } from '@hookform/resolvers/zod'-import type {- TaxCategory,- TaxCategoryCreateParams,- TaxCategoryUpdateParams,-} from '@spree/admin-sdk'+import type { TaxCategory, TaxCategoryCreateParams } from '@spree/admin-sdk'import { createFileRoute, useNavigate } from '@tanstack/react-router'import { PlusIcon } from 'lucide-react'import { useEffect } from 'react'@@ -36,6 +32,12 @@ import {} from '@/hooks/use-tax-categories'import { mapSpreeErrorsToForm } from '@/lib/form-errors'import { Subject } from '@/lib/permissions'+import {+ TAX_CATEGORY_DEFAULTS,+ type TaxCategoryFormValues,+ taxCategoryFormSchema,+ taxCategoryValuesToParams,+} from '@/schemas/tax-category'import '@/tables/tax-categories'const taxCategoriesSearchSchema = resourceSearchSchema.extend({@@ -95,27 +97,6 @@ function TaxCategoriesPage() {)}-const formSchema = z.object({- name: z.string().min(1, 'Name is required'),- tax_code: z.string().optional(),- description: z.string().optional(),- is_default: z.boolean(),-})--type FormValues = z.infer<typeof formSchema>--const DEFAULT_VALUES: FormValues = { name: '', tax_code: '', description: '', is_default: false }--function valuesToParams(v: FormValues): TaxCategoryCreateParams & TaxCategoryUpdateParams {- const blank = (s: string | undefined) => (s && s.length > 0 ? s : undefined)- return {- name: v.name,- tax_code: blank(v.tax_code) ?? null,- description: blank(v.description) ?? null,- is_default: v.is_default,- }-}-function CreateTaxCategorySheet({open,onOpenChange,@@ -125,16 +106,16 @@ function CreateTaxCategorySheet({}) {const { t } = useTranslation()const createMutation = useCreateTaxCategory()- const form = useForm<FormValues>({+ const form = useForm<TaxCategoryFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(formSchema) as any,- defaultValues: DEFAULT_VALUES,+ resolver: zodResolver(taxCategoryFormSchema) as any,+ defaultValues: TAX_CATEGORY_DEFAULTS,})- async function onSubmit(values: FormValues) {+ async function onSubmit(values: TaxCategoryFormValues) {try {- await createMutation.mutateAsync(valuesToParams(values) as TaxCategoryCreateParams)- form.reset(DEFAULT_VALUES)+ await createMutation.mutateAsync(taxCategoryValuesToParams(values) as TaxCategoryCreateParams)+ form.reset(TAX_CATEGORY_DEFAULTS)onOpenChange(false)} catch (err) {if (!mapSpreeErrorsToForm(err, form.setError)) throw err@@ -145,7 +126,7 @@ function CreateTaxCategorySheet({<Sheetopen={open}onOpenChange={(next) => {- if (!next) form.reset(DEFAULT_VALUES)+ if (!next) form.reset(TAX_CATEGORY_DEFAULTS)onOpenChange(next)}}>@@ -195,10 +176,10 @@ function EditTaxCategorySheet({const deleteMutation = useDeleteTaxCategory()const confirm = useConfirm()- const form = useForm<FormValues>({+ const form = useForm<TaxCategoryFormValues>({// eslint-disable-next-line @typescript-eslint/no-explicit-any- resolver: zodResolver(formSchema) as any,- defaultValues: DEFAULT_VALUES,+ resolver: zodResolver(taxCategoryFormSchema) as any,+ defaultValues: TAX_CATEGORY_DEFAULTS,})useEffect(() => {@@ -212,9 +193,9 @@ function EditTaxCategorySheet({}}, [taxCategory, form])- async function onSubmit(values: FormValues) {+ async function onSubmit(values: TaxCategoryFormValues) {try {- await updateMutation.mutateAsync(valuesToParams(values))+ await updateMutation.mutateAsync(taxCategoryValuesToParams(values))form.reset(values)onOpenChange(false)} catch (err) {@@ -289,7 +270,7 @@ function EditTaxCategorySheet({)}-function TaxCategoryFormFields({ form }: { form: UseFormReturn<FormValues> }) {+function TaxCategoryFormFields({ form }: { form: UseFormReturn<TaxCategoryFormValues> }) {const { t } = useTranslation()const { errors } = form.formStatereturn (diff --git a/packages/admin/src/routes/login.tsx b/packages/admin/src/routes/login.tsxindex df7d8333b2..6d35ea323a 100644--- a/packages/admin/src/routes/login.tsx+++ b/packages/admin/src/routes/login.tsx@@ -2,21 +2,13 @@ import { zodResolver } from '@hookform/resolvers/zod'import { createFileRoute, Navigate } from '@tanstack/react-router'import { useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'-import { z } from 'zod/v4'import { Button } from '@/components/ui/button'import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'import { Input } from '@/components/ui/input'import { Label } from '@/components/ui/label'import { useAuth } from '@/hooks/use-auth'-import { i18n } from '@/lib/i18n'import { cn } from '@/lib/utils'--const loginSchema = z.object({- email: z.email(),- password: z.string().min(1, i18n.t('admin.validation.password_required')),-})--type LoginForm = z.infer<typeof loginSchema>+import { type LoginFormValues, loginFormSchema } from '@/schemas/auth'export const Route = createFileRoute('/login')({component: LoginPage,@@ -26,12 +18,12 @@ function LoginPage() {const { t } = useTranslation()const { login, isLoading, isAuthenticated } = useAuth()- const form = useForm<LoginForm>({- resolver: zodResolver(loginSchema),+ const form = useForm<LoginFormValues>({+ resolver: zodResolver(loginFormSchema),defaultValues: { email: '', password: '' },})- const onSubmit = async (data: LoginForm) => {+ const onSubmit = async (data: LoginFormValues) => {try {await login(data.email, data.password)} catch {@@ -62,8 +54,8 @@ function LoginFormCard({isLoading,className,}: {- form: ReturnType<typeof useForm<LoginForm>>- onSubmit: (data: LoginForm) => Promise<void>+ form: ReturnType<typeof useForm<LoginFormValues>>+ onSubmit: (data: LoginFormValues) => Promise<void>isLoading: booleanclassName?: string}) {diff --git a/packages/admin/src/schemas/auth.ts b/packages/admin/src/schemas/auth.tsnew file mode 100644index 0000000000..d7bd483a6a--- /dev/null+++ b/packages/admin/src/schemas/auth.ts@@ -0,0 +1,43 @@+import { z } from 'zod/v4'+import { i18n } from '@/lib/i18n'++// Lazy message factories — Zod v4 accepts `{ error: () => string }` as an+// error map, which it invokes per validation. Module-scope `i18n.t(...)`+// would lock the English string in at import time, breaking locale switches+// once we ship a second translation.+const passwordRequired = () => i18n.t('admin.validation.password_required')+const firstNameRequired = () => i18n.t('admin.validation.first_name_required')+const lastNameRequired = () => i18n.t('admin.validation.last_name_required')+const passwordsDontMatch = () => i18n.t('admin.validation.passwords_dont_match')+const passwordMinLength = () =>+ i18n.t('admin.validation.min_length', {+ field: i18n.t('admin.fields.password.label'),+ count: 8,+ })++/** Login form — server validates password strength; client only checks presence. */+export const loginFormSchema = z.object({+ email: z.email(),+ password: z.string().min(1, { error: passwordRequired }),+})+export type LoginFormValues = z.infer<typeof loginFormSchema>++/** Existing invitee confirming with their current password. */+export const acceptInvitationSignInFormSchema = z.object({+ password: z.string().min(1, { error: passwordRequired }),+})+export type AcceptInvitationSignInFormValues = z.infer<typeof acceptInvitationSignInFormSchema>++/** New invitee creating an account inline — mirrors the server's `AdminUser` validations. */+export const acceptInvitationSignUpFormSchema = z+ .object({+ first_name: z.string().min(1, { error: firstNameRequired }),+ last_name: z.string().min(1, { error: lastNameRequired }),+ password: z.string().min(8, { error: passwordMinLength }),+ password_confirmation: z.string(),+ })+ .refine((data) => data.password === data.password_confirmation, {+ error: passwordsDontMatch,+ path: ['password_confirmation'],+ })+export type AcceptInvitationSignUpFormValues = z.infer<typeof acceptInvitationSignUpFormSchema>diff --git a/packages/admin/src/schemas/customer-group.ts b/packages/admin/src/schemas/customer-group.tsnew file mode 100644index 0000000000..0f0d952636--- /dev/null+++ b/packages/admin/src/schemas/customer-group.ts@@ -0,0 +1,21 @@+import type { CustomerGroupCreateParams, CustomerGroupUpdateParams } from '@spree/admin-sdk'+import { z } from 'zod/v4'+import { requiredMessage } from '@/lib/validation-messages'++export const customerGroupFormSchema = z.object({+ name: z.string().min(1, { error: requiredMessage('name') }),+ description: z.string().optional(),+})++export type CustomerGroupFormValues = z.infer<typeof customerGroupFormSchema>++export const CUSTOMER_GROUP_DEFAULTS: CustomerGroupFormValues = { name: '', description: '' }++export function customerGroupValuesToParams(+ v: CustomerGroupFormValues,+): CustomerGroupCreateParams & CustomerGroupUpdateParams {+ return {+ name: v.name,+ description: v.description && v.description.length > 0 ? v.description : null,+ }+}diff --git a/packages/admin/src/schemas/customer.ts b/packages/admin/src/schemas/customer.tsnew file mode 100644index 0000000000..934381fb16--- /dev/null+++ b/packages/admin/src/schemas/customer.ts@@ -0,0 +1,38 @@+import { z } from 'zod/v4'+import { i18n } from '@/lib/i18n'+import { requiredMessage } from '@/lib/validation-messages'++const customerProfileBase = z.object({+ // Server requires a valid email; check client-side so the user gets an+ // inline error rather than a 422 round-trip.+ email: z+ .string()+ .trim()+ .min(1, { error: requiredMessage('email') })+ .email({ error: () => i18n.t('admin.validation.invalid_email') }),+ first_name: z.string(),+ last_name: z.string(),+ phone: z.string(),+ tags: z.array(z.string()),+ accepts_email_marketing: z.boolean(),+})++export const customerProfileFormSchema = customerProfileBase+export type CustomerProfileFormValues = z.infer<typeof customerProfileFormSchema>++// New-customer sheet adds an inline `internal_note` — existing customers edit+// the note in its own card, so it's omitted from the profile schema.+export const newCustomerFormSchema = customerProfileBase.extend({+ internal_note: z.string(),+})+export type NewCustomerFormValues = z.infer<typeof newCustomerFormSchema>++export const NEW_CUSTOMER_DEFAULTS: NewCustomerFormValues = {+ email: '',+ first_name: '',+ last_name: '',+ phone: '',+ tags: [],+ accepts_email_marketing: false,+ internal_note: '',+}diff --git a/packages/admin/src/schemas/gift-card.ts b/packages/admin/src/schemas/gift-card.tsnew file mode 100644index 0000000000..f7f719dabb--- /dev/null+++ b/packages/admin/src/schemas/gift-card.ts@@ -0,0 +1,83 @@+import type {+ GiftCardBatchCreateParams,+ GiftCardCreateParams,+ GiftCardUpdateParams,+} from '@spree/admin-sdk'+import { z } from 'zod/v4'+import { blankToNull, blankToUndefined } from '@/lib/form-mappers'+import { i18n } from '@/lib/i18n'++// Mirrors `Spree::Config[:gift_card_batch_limit]`. Hardcoded for now; if the+// merchant overrides it we'll surface it via a store-settings endpoint later.+export const BATCH_LIMIT = 50_000++// Zod accepts a message function for lazy evaluation — important so the i18n+// catalog has had a chance to initialize and so locale changes pick up.+const amountPositive = () => i18n.t('admin.pages.promotions.gift_cards.validation.amount_positive')+const prefixRequired = () => i18n.t('admin.pages.promotions.gift_cards.validation.prefix_required')+const currencyRequired = () =>+ i18n.t('admin.pages.promotions.gift_cards.validation.currency_required')++export const giftCardCreateFormSchema = z+ .object({+ // When `quantity === 1` this is the optional caller-supplied code.+ // When `quantity > 1` it becomes the required batch `prefix`.+ code: z.string().optional(),+ amount: z.coerce.number().positive({ error: amountPositive }),+ currency: z.string().min(1, { error: currencyRequired }),+ expires_at: z.string().optional(),+ customer_id: z.string().optional(),+ quantity: z.coerce.number().int().min(1).max(BATCH_LIMIT),+ })+ .superRefine((values, ctx) => {+ if (values.quantity > 1 && !values.code?.trim()) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ path: ['code'],+ message: prefixRequired(),+ })+ }+ })++export type GiftCardCreateFormValues = z.infer<typeof giftCardCreateFormSchema>++export const giftCardEditFormSchema = z.object({+ code: z.string().optional(),+ amount: z.coerce.number().positive({ error: amountPositive }),+ currency: z.string().min(1, { error: currencyRequired }),+ expires_at: z.string().optional(),+ customer_id: z.string().optional(),+})++export type GiftCardEditFormValues = z.infer<typeof giftCardEditFormSchema>++export function giftCardEditValuesToParams(v: GiftCardEditFormValues): GiftCardUpdateParams {+ return {+ amount: v.amount,+ expires_at: v.expires_at || null,+ user_id: blankToNull(v.customer_id),+ }+}++export function giftCardSingleValuesToParams(v: GiftCardCreateFormValues): GiftCardCreateParams {+ return {+ code: blankToUndefined(v.code),+ amount: v.amount,+ currency: v.currency,+ expires_at: v.expires_at || null,+ user_id: blankToNull(v.customer_id),+ }+}++export function giftCardBatchValuesToParams(+ v: GiftCardCreateFormValues,+): GiftCardBatchCreateParams {+ // `code` carries the prefix in batch mode; required, validated above.+ return {+ prefix: v.code ?? '',+ amount: v.amount,+ currency: v.currency,+ codes_count: v.quantity,+ expires_at: v.expires_at || null,+ }+}diff --git a/packages/admin/src/schemas/option-type.ts b/packages/admin/src/schemas/option-type.tsnew file mode 100644index 0000000000..d80f3d1125--- /dev/null+++ b/packages/admin/src/schemas/option-type.ts@@ -0,0 +1,78 @@+import type { OptionValue, OptionValueParams } from '@spree/admin-sdk'+import { z } from 'zod/v4'+import { i18n } from '@/lib/i18n'+import { requiredMessage } from '@/lib/validation-messages'++// Labels live in `en.json` under `admin.products.options.kinds.*` — consumers+// translate at render time.+export const OPTION_TYPE_KINDS = ['dropdown', 'color_swatch', 'buttons'] as const++const HEX_RE = /^#[0-9A-Fa-f]{6}([0-9A-Fa-f]{2})?$/++export const optionValueSchema = z.object({+ id: z.string().optional(),+ name: z.string().min(1, { error: requiredMessage('name') }),+ label: z.string().min(1, { error: requiredMessage('label') }),+ color_code: z+ .string()+ .nullable()+ .optional()+ .refine((v) => !v || HEX_RE.test(v), {+ error: () => i18n.t('admin.validation.invalid_hex_color'),+ }),+ /** Active Storage signed_id from a fresh direct upload. Frontend-only state. */+ image_signed_id: z.string().nullable().optional(),+ /** Existing image URL (for preview only — never sent back). Frontend-only state. */+ image_url: z.string().nullable().optional(),+ /** True when the user clicks the trash icon next to an existing image. Frontend-only state. */+ image_cleared: z.boolean().optional(),+})++export const optionTypeFormSchema = z.object({+ name: z.string().min(1, { error: requiredMessage('name') }),+ label: z.string().min(1, { error: requiredMessage('label') }),+ kind: z.enum(OPTION_TYPE_KINDS),+ filterable: z.boolean(),+ option_values: z.array(optionValueSchema),+})++export type OptionTypeFormValues = z.infer<typeof optionTypeFormSchema>+export type OptionValueFormValue = z.infer<typeof optionValueSchema>++export const OPTION_TYPE_DEFAULTS: OptionTypeFormValues = {+ name: '',+ label: '',+ kind: 'dropdown',+ filterable: false,+ option_values: [],+}++/**+ * Hydrate the form from an API option_value row. Spreads all API fields 1:1 and+ * attaches the frontend-only image upload-state fields (`image_signed_id`,+ * `image_cleared`) initialized to their resting values.+ */+export function optionValueToFormRow(ov: OptionValue): OptionValueFormValue {+ return {+ ...ov,+ image_signed_id: null,+ image_cleared: false,+ }+}++/**+ * Build the API payload for a single option_value row. `index` is the row's+ * current array position; we send `position: index + 1` (1-indexed) so+ * `acts_as_list` persists the drag-reordered order. The frontend-only image+ * upload state collapses into the API's `image` field: a fresh signed_id is+ * sent, an explicit clear sends `null`, and an untouched row omits `image`+ * entirely so the existing attachment stays.+ */+export function valueToParam(v: OptionValueFormValue, index: number): OptionValueParams {+ const { image_signed_id, image_url: _imageUrl, image_cleared, ...rest } = v+ return {+ ...rest,+ position: index + 1,+ ...(image_signed_id ? { image: image_signed_id } : image_cleared ? { image: null } : {}),+ }+}diff --git a/packages/admin/src/schemas/order.ts b/packages/admin/src/schemas/order.tsindex f8bea77480..c0b0760688 100644--- a/packages/admin/src/schemas/order.ts+++ b/packages/admin/src/schemas/order.ts@@ -1,4 +1,5 @@import { z } from 'zod/v4'+import { i18n } from '@/lib/i18n'/*** New-order form schema. The "customer OR email" rule is enforced at the@@ -11,7 +12,10 @@ import { z } from 'zod/v4'* comes back as a 422 and gets routed through `mapSpreeErrorsToForm`.*/export const newOrderFormSchema = z.object({- email: z.string().email('Enter a valid email').or(z.literal('')),+ email: z+ .string()+ .email({ error: () => i18n.t('admin.validation.invalid_email') })+ .or(z.literal('')),customer_note: z.string(),internal_note: z.string(),coupon_code: z.string(),diff --git a/packages/admin/src/schemas/payment-method.ts b/packages/admin/src/schemas/payment-method.tsnew file mode 100644index 0000000000..56be9704f4--- /dev/null+++ b/packages/admin/src/schemas/payment-method.ts@@ -0,0 +1,56 @@+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({+ name: z.string().min(1, { error: requiredMessage('name') }),+ description: z.string().optional(),+ storefront_visible: z.boolean(),+ active: z.boolean(),+ auto_capture: z.boolean(),+})++export const paymentMethodCreateFormSchema = paymentMethodBaseFormSchema.extend({+ type: z.string().min(1, { error: requiredMessage('payment_method.type') }),+})++export const PAYMENT_METHOD_BASE_DEFAULTS: PaymentMethodFormValues = {+ name: '',+ description: '',+ storefront_visible: true,+ active: true,+ auto_capture: false,+}++export const PAYMENT_METHOD_CREATE_DEFAULTS: PaymentMethodFormValues = {+ ...PAYMENT_METHOD_BASE_DEFAULTS,+ type: '',+}++export function paymentMethodValuesToCreateParams(+ v: PaymentMethodFormValues,+ preferences: Record<string, unknown>,+): PaymentMethodCreateParams {+ return {+ type: v.type ?? '',+ name: v.name,+ description: v.description?.length ? v.description : null,+ active: v.active,+ auto_capture: v.auto_capture,+ storefront_visible: v.storefront_visible,+ ...(Object.keys(preferences).length > 0 ? { preferences } : {}),+ }+}++export function paymentMethodValuesToUpdateParams(+ v: PaymentMethodFormValues,+): PaymentMethodUpdateParams {+ return {+ name: v.name,+ description: v.description?.length ? v.description : null,+ active: v.active,+ auto_capture: v.auto_capture,+ storefront_visible: v.storefront_visible,+ }+}diff --git a/packages/admin/src/schemas/product.ts b/packages/admin/src/schemas/product.tsindex 23fe3fc798..3f4751e1e1 100644--- a/packages/admin/src/schemas/product.ts+++ b/packages/admin/src/schemas/product.ts@@ -1,4 +1,5 @@import { z } from 'zod/v4'+import { requiredMessage } from '@/lib/validation-messages'export const stockItemFormSchema = z.object({stock_location_id: z.string(),@@ -20,7 +21,7 @@ export type VariantInventoryFormValues = z.infer<typeof variantInventoryFormScheexport const productFormSchema = z.object({// General- name: z.string().min(1, 'Name is required'),+ name: z.string().min(1, { error: requiredMessage('name') }),description: z.string().optional(),// Statusdiff --git a/packages/admin/src/schemas/promotion.ts b/packages/admin/src/schemas/promotion.tsindex 821eee5cda..debd6ad020 100644--- a/packages/admin/src/schemas/promotion.ts+++ b/packages/admin/src/schemas/promotion.ts@@ -3,19 +3,19 @@ import type {PromotionActionFormDraft,PromotionRuleFormDraft,} from '@/components/spree/promotion-editors/types'+import { i18n } from '@/lib/i18n'+import { requiredMessage } from '@/lib/validation-messages'export type PromotionKind = 'coupon_code' | 'automatic'export type MatchPolicy = 'all' | 'any'-export const KIND_OPTIONS = [- { value: 'coupon_code', label: 'Coupon code' },- { value: 'automatic', label: 'Automatic (no code)' },-] as const satisfies ReadonlyArray<{ value: PromotionKind; label: string }>--export const MATCH_POLICY_OPTIONS = [- { value: 'all', label: 'All rules must match' },- { value: 'any', label: 'Any rule may match' },-] as const satisfies ReadonlyArray<{ value: MatchPolicy; label: string }>+// Labels live in `en.json` under `admin.promotions.kinds.*` and+// `admin.promotions.match_policies.*`. Consumers translate at render time.+export const PROMOTION_KINDS = [+ 'coupon_code',+ 'automatic',+] as const satisfies ReadonlyArray<PromotionKind>+export const MATCH_POLICIES = ['all', 'any'] as const satisfies ReadonlyArray<MatchPolicy>/*** Promotion form schema.@@ -37,7 +37,7 @@ export const MATCH_POLICY_OPTIONS = [*/export const promotionFormSchema = z.object({- name: z.string().min(1, 'Name is required'),+ name: z.string().min(1, { error: requiredMessage('name') }),description: z.string(),kind: z.enum(['coupon_code', 'automatic']),code: z.string(),@@ -62,14 +62,14 @@ export const promotionFormSchema = zctx.addIssue({code: 'custom',path: ['code_prefix'],- message: 'Prefix is required for multi-code batches',+ message: i18n.t('admin.promotions.validation.prefix_required'),})}if (!v.number_of_codes || v.number_of_codes < 1) {ctx.addIssue({code: 'custom',path: ['number_of_codes'],- message: 'Pick how many codes to generate',+ message: i18n.t('admin.promotions.validation.number_of_codes_required'),})}} else {@@ -77,7 +77,7 @@ export const promotionFormSchema = zctx.addIssue({code: 'custom',path: ['code'],- message: 'Code is required (or click Generate)',+ message: i18n.t('admin.promotions.validation.code_required'),})}}@@ -87,7 +87,7 @@ export const promotionFormSchema = zctx.addIssue({code: 'custom',path: ['expires_at'],- message: 'Expiry must be after the start date',+ message: i18n.t('admin.promotions.validation.expiry_after_start'),})}})diff --git a/packages/admin/src/schemas/stock-location.ts b/packages/admin/src/schemas/stock-location.tsnew file mode 100644index 0000000000..7d08d6a863--- /dev/null+++ b/packages/admin/src/schemas/stock-location.ts@@ -0,0 +1,115 @@+import type {+ StockLocation,+ StockLocationCreateParams,+ StockLocationUpdateParams,+} from '@spree/admin-sdk'+import { z } from 'zod/v4'+import { blankToUndefined } from '@/lib/form-mappers'+import { requiredMessage } from '@/lib/validation-messages'++// Labels live in `en.json` under `admin.stock_locations.kinds.*` and+// `admin.stock_locations.pickup_stock_policies.*`. Consumers map these+// values to translated labels at render time.+export const STOCK_LOCATION_KINDS = ['warehouse', 'store', 'fulfillment_center'] as const+export const PICKUP_STOCK_POLICIES = ['local', 'any'] as const++export const stockLocationFormSchema = z.object({+ name: z.string().min(1, { error: requiredMessage('name') }),+ admin_name: z.string().optional(),+ kind: z.string().min(1),+ active: z.boolean(),+ default: z.boolean(),+ propagate_all_variants: z.boolean(),+ backorderable_default: z.boolean(),+ address1: z.string().optional(),+ address2: z.string().optional(),+ city: z.string().optional(),+ zipcode: z.string().optional(),+ phone: z.string().optional(),+ company: z.string().optional(),+ country_iso: z.string().optional(),+ 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_instructions: z.string().optional(),+})++export type StockLocationFormValues = z.infer<typeof stockLocationFormSchema>++export const STOCK_LOCATION_DEFAULTS: StockLocationFormValues = {+ name: '',+ admin_name: '',+ kind: 'warehouse',+ active: true,+ default: false,+ propagate_all_variants: false,+ backorderable_default: false,+ address1: '',+ address2: '',+ city: '',+ zipcode: '',+ phone: '',+ company: '',+ country_iso: '',+ state_abbr: '',+ state_name: '',+ pickup_enabled: false,+ pickup_stock_policy: 'local',+ pickup_ready_in_minutes: null,+ pickup_instructions: '',+}++export function stockLocationToFormValues(sl: StockLocation): StockLocationFormValues {+ return {+ name: sl.name,+ admin_name: sl.admin_name ?? '',+ kind: sl.kind ?? 'warehouse',+ active: sl.active,+ default: sl.default,+ propagate_all_variants: sl.propagate_all_variants,+ backorderable_default: sl.backorderable_default,+ address1: sl.address1 ?? '',+ address2: sl.address2 ?? '',+ city: sl.city ?? '',+ zipcode: sl.zipcode ?? '',+ phone: sl.phone ?? '',+ company: sl.company ?? '',+ country_iso: sl.country_iso ?? '',+ state_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_ready_in_minutes: sl.pickup_ready_in_minutes ?? null,+ pickup_instructions: sl.pickup_instructions ?? '',+ }+}++// Drops blank strings → undefined so we don't overwrite null fields with "".+export function formValuesToParams(+ v: StockLocationFormValues,+): StockLocationCreateParams & StockLocationUpdateParams {+ return {+ name: v.name,+ admin_name: blankToUndefined(v.admin_name),+ kind: v.kind,+ active: v.active,+ default: v.default,+ propagate_all_variants: v.propagate_all_variants,+ backorderable_default: v.backorderable_default,+ address1: blankToUndefined(v.address1),+ address2: blankToUndefined(v.address2),+ city: blankToUndefined(v.city),+ zipcode: blankToUndefined(v.zipcode),+ phone: blankToUndefined(v.phone),+ company: blankToUndefined(v.company),+ country_iso: blankToUndefined(v.country_iso),+ state_abbr: blankToUndefined(v.state_abbr),+ state_name: blankToUndefined(v.state_name),+ pickup_enabled: v.pickup_enabled,+ pickup_stock_policy: v.pickup_stock_policy,+ pickup_ready_in_minutes: v.pickup_ready_in_minutes ?? null,+ pickup_instructions: blankToUndefined(v.pickup_instructions),+ }+}diff --git a/packages/admin/src/schemas/store.ts b/packages/admin/src/schemas/store.tsindex db57fb2a39..6e395f0761 100644--- a/packages/admin/src/schemas/store.ts+++ b/packages/admin/src/schemas/store.ts@@ -1,11 +1,14 @@import { z } from 'zod/v4'+import { requiredMessage } from '@/lib/validation-messages'export const storeSettingsFormSchema = z.object({- name: z.string().min(1, 'Name is required'),+ name: z.string().min(1, { error: requiredMessage('store.name') }),preferred_admin_locale: z.string().nullable().optional(),- preferred_timezone: z.string().min(1, 'Timezone is required'),+ 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, 'Weight unit is required'),+ preferred_weight_unit: z+ .string()+ .min(1, { error: requiredMessage('store.preferred_weight_unit') }),})export type StoreSettingsFormValues = z.infer<typeof storeSettingsFormSchema>@@ -23,21 +26,11 @@ export const ADMIN_LOCALE_OPTIONS: Array<{ value: string; label: string }> = [{ value: 'zh-CN', label: '中文 (简体)' },]-export const UNIT_SYSTEM_OPTIONS: Array<{ value: 'metric' | 'imperial'; label: string }> = [- { value: 'metric', label: 'Metric' },- { value: 'imperial', label: 'Imperial' },-]--export const WEIGHT_UNIT_OPTIONS: Record<- 'metric' | 'imperial',- Array<{ value: string; label: string }>-> = {- metric: [- { value: 'kg', label: 'Kilogram (kg)' },- { value: 'g', label: 'Gram (g)' },- ],- imperial: [- { value: 'lb', label: 'Pound (lb)' },- { value: 'oz', label: 'Ounce (oz)' },- ],+// 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/schemas/tax-category.ts b/packages/admin/src/schemas/tax-category.tsnew file mode 100644index 0000000000..145bb51ab5--- /dev/null+++ b/packages/admin/src/schemas/tax-category.ts@@ -0,0 +1,31 @@+import type { TaxCategoryCreateParams, TaxCategoryUpdateParams } from '@spree/admin-sdk'+import { z } from 'zod/v4'+import { blankToNull } from '@/lib/form-mappers'+import { requiredMessage } from '@/lib/validation-messages'++export const taxCategoryFormSchema = z.object({+ name: z.string().min(1, { error: requiredMessage('name') }),+ tax_code: z.string().optional(),+ description: z.string().optional(),+ is_default: z.boolean(),+})++export type TaxCategoryFormValues = z.infer<typeof taxCategoryFormSchema>++export const TAX_CATEGORY_DEFAULTS: TaxCategoryFormValues = {+ name: '',+ tax_code: '',+ description: '',+ is_default: false,+}++export function taxCategoryValuesToParams(+ v: TaxCategoryFormValues,+): TaxCategoryCreateParams & TaxCategoryUpdateParams {+ return {+ name: v.name,+ tax_code: blankToNull(v.tax_code),+ description: blankToNull(v.description),+ is_default: v.is_default,+ }+}