Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Standardize forms to expose server validation errors and use translations

Damian Legawiecc53cecbf5892
diff --git a/CLAUDE.md b/CLAUDE.md
index 10fcd10deb..ace7cd8084 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -14,7 +14,7 @@ Use `/project:create-plan` and `/project:update-plan` for plan management.
Current plans:
- `6.0-cart-order-split.md` — Cart/Order model separation, polymorphic LineItem
- `6.0-admin-api.md` — Admin REST API conventions, auth, endpoint list (~300 endpoints)
-- `6.0-admin-spa.md` — React admin architecture, extension points, table registry
+- `6.0-admin-spa.md` — React admin architecture, extension points, table registry, i18n + server-error mapping
- `6.0-product-types.md` — Prototype → ProductType rename, MetafieldDefinition schema enforcement
- `6.0-remove-master-variant.md` — Eliminate is_master, add default_variant_id FK on Product
- `6.0-split-adjustments.md` — Replace polymorphic Adjustment with TaxLine, Discount, Fee
@@ -421,9 +421,7 @@ Same patterns as `@spree/sdk` but for the Admin API. Supports both secret key (s
### @spree/admin — Admin UI (React SPA)
-The Spree 6.0 admin dashboard. A Vite-built React SPA that replaces the legacy Rails `spree/admin` engine entirely. See [`packages/admin/README.md`](packages/admin/README.md) for the full tech stack, project structure, and architecture (auth flow, permissions, multi-store, extension points). Architecture decisions live in `docs/plans/6.0-admin-spa.md`.
-
-**Tech stack at a glance:** Vite, TanStack Router (file-based, type-safe), TanStack Query, React Hook Form + Zod, shadcn/ui + Base UI + Tailwind, Biome, Vitest. All API calls go through `@spree/admin-sdk`.
+The Spree 6.0 admin dashboard — a Vite-built React SPA that replaces the legacy Rails `spree/admin` engine entirely. Tech stack: Vite, TanStack Router (file-based, type-safe), TanStack Query, React Hook Form + Zod, shadcn/ui + Base UI + Tailwind, Biome, Vitest. All API calls go through `@spree/admin-sdk`. See [`packages/admin/README.md`](packages/admin/README.md) and `docs/plans/6.0-admin-spa.md` for the full architecture (auth, permissions, multi-store, extension points).
**Running the admin UI locally:**
@@ -437,26 +435,37 @@ cd packages/admin
pnpm dev # http://localhost:5173 (proxies /api/* to :3000)
```
-`VITE_SPREE_API_URL` overrides the backend URL for both dev and build (defaults to `http://localhost:3000`). Sign in with the seed admin user (`[email protected]` / `spree123` by default — check your server's `db/seeds.rb`).
+`VITE_SPREE_API_URL` overrides the backend URL (default `http://localhost:3000`). Sign in with the seed admin user (`[email protected]` / `spree123` — check `db/seeds.rb`).
**When implementing a new admin feature:**
-1. **Look at the legacy Rails admin in `spree/admin/`** for guidance on what the feature does today (data shape, business rules, edge cases). It's a useful reference for "what does this screen actually need to do."
-2. **Don't port the UX 1:1.** The legacy admin is Rails + Turbo, which constrained UX choices around server round-trips, full page navigations, and form submissions. The React SPA can do better — inline editing, optimistic updates, multi-step flows without page reloads, modal-driven workflows, real-time validation, drag-and-drop, virtualized lists. Use those patterns where they meaningfully improve the experience.
-3. **The Admin API is the only data source.** Never reach into Rails models or import server-rendered HTML.
-4. **Follow `docs/plans/6.0-admin-spa.md`** for the three extension points (table registry, navigation registry, component injection) and the shadcn copy-paste ownership model.
-5. **Wrap SDK calls in custom hooks** under `src/hooks/` (e.g., `useOrders`, `useProduct`) — never call `adminClient` directly from components.
+1. **The Admin API is the only data source.** Never reach into Rails models or import server-rendered HTML. If a needed endpoint or attribute is missing, add it to `spree/api` first (see backend conventions above), regenerate types via the [Type Generation Pipeline](#type-generation-pipeline), then consume it from the SPA.
+2. **Look at the legacy Rails admin in `spree/admin/`** for what the feature does today (data shape, business rules, edge cases) — but don't port the UX 1:1. The SPA can do better than Turbo-era full-page reloads where it meaningfully improves the experience.
+3. **Follow `docs/plans/6.0-admin-spa.md`** for the three extension points (table registry, navigation registry, component injection) and the shadcn copy-paste ownership model.
+4. **Wrap SDK calls in custom hooks** under `src/hooks/` (e.g. `useOrders`, `useProduct`) — never call `adminClient` directly from components.
+
+**Forms.** Raw React Hook Form with `<Field>` / `<Input>` / `<FieldError>` blocks. Drive each input explicitly with `form.register(...)` or a `<Controller>` for custom widgets so the form reads top-to-bottom. Wrap RHF's `handleSubmit` with a try/catch that calls `mapSpreeErrorsToForm` (`@/lib/form-errors`) to route 422 responses onto `form.formState.errors`: flat attribute keys become field errors with `aria-invalid` + `<FieldError>`; `:base` and nested keys land on `errors.root.message` so render a destructive banner at the top of the form.
+
+```tsx
+async function handleSubmit(values: FormValues) {
+ try {
+ await onSubmit(values)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+}
+```
-If a needed Admin API endpoint or attribute is missing, **add it to `spree/api` first** (see backend conventions above), regenerate types via the [Type Generation Pipeline](#type-generation-pipeline), then consume it from the SPA.
+- **Labels/placeholders/help** come from `packages/admin/src/locales/en.json` under `admin.fields.<resource>.<attribute>.{label,placeholder,help}` with cross-resource fallback `admin.fields.<attribute>.<facet>`. Dev mode logs missing keys to the console.
+- **Client validation** lives in the Zod schema (`zodResolver`).
+- **Mutation hooks built on `useResourceMutation` suppress their own toast for 422 responses** — the form already shows the inline message. Non-validation errors (network, 5xx, gateway) still toast. For a plain `useMutation` you want a fallback toast on, layer the catch: try `mapSpreeErrorsToForm` first, re-throw `SpreeError`, otherwise `toast.error(...)`.
-**Base UI vs Radix — `<Select>` does not auto-render labels.** The admin SPA's `<Select>` wraps **Base UI** (`@base-ui/react/select`), not Radix. Unlike Radix, Base UI's `<Select.Value />` defaults to rendering the raw selected `value` (e.g. the ISO code, the slug, the prefixed ID) instead of the matching `<SelectItem>`'s children. A bare `<SelectValue />` next to `<SelectItem value="warehouse">Warehouse</SelectItem>` will display `warehouse`, not `Warehouse`.
+**Form schemas** live in `packages/admin/src/schemas/<resource>.ts` when shared across 2+ files or non-trivial (~30+ lines, nested sub-schemas, companion constants); inline is fine for short single-file forms. The schema file owns the Zod schema, its inferred `FormValues` type, defaults, dropdown option arrays, and regex constants. **Don't add form↔API mappers to paper over field renames** — if you find yourself translating `ot.label → form.presentation`, fix the API instead (read/write symmetry, see "API Controllers" above). Mappers are only for pure frontend state (upload progress, transient UI bookkeeping).
-There are two correct ways to make the trigger show the label:
+**Base UI `<Select>` does not auto-render labels.** Unlike Radix, Base UI's `<Select.Value />` renders the raw selected `value` (the slug, the ISO code, the prefixed ID) instead of the matching `<SelectItem>`'s children. Two fixes:
-1. **Pass `items` to `<Select>` (preferred when option labels are static).** Base UI resolves the trigger label from the items array automatically:
+1. **Static option labels** — pass an `items` array; Base UI resolves the trigger label automatically:
```tsx
- const KIND_OPTIONS = [{ value: 'warehouse', label: 'Warehouse' }, ...] as const
-
<Select items={KIND_OPTIONS} value={...} onValueChange={...}>
<SelectTrigger><SelectValue /></SelectTrigger>
<SelectContent>
@@ -464,41 +473,28 @@ There are two correct ways to make the trigger show the label:
</SelectContent>
</Select>
```
-2. **Use the `<SelectValue>` children render-prop (when labels are dynamic, e.g. fetched options).** Base UI calls the function with the current value:
+2. **Dynamic option labels** — use the children render-prop:
```tsx
- <SelectValue>
- {(value) => roles.find((r) => r.id === value)?.name ?? (value as string)}
- </SelectValue>
+ <SelectValue>{(value) => roles.find((r) => r.id === value)?.name ?? (value as string)}</SelectValue>
```
-For free-text **searchable** pickers, prefer `<Combobox>` over `<Select>` — see `components/spree/country-state-fields.tsx` for the country/state pattern.
-
-**Form schemas live in `packages/admin/src/schemas/<resource>.ts`** when shared across 2+ files or non-trivial (~30+ lines, nested sub-schemas, companion option/constant arrays); inline is fine for single-file routes with a short schema. Filename is the kebab-case singular resource name (`product.ts`, `option-type.ts`, `tax-category.ts`). The schema file owns the entire form contract end-to-end: the Zod schema, its inferred `FormValues` type, default-values constants, dropdown option arrays, regex constants, **and** any form↔API mapper functions. Co-locating the schema with its mappers prevents the two from drifting (editing the schema almost always means editing the mappers). References: `schemas/product.ts`, `schemas/store.ts`.
-
-Mappers should only exist for **pure frontend state** (upload progress flags, transient UI bookkeeping, derived display values). If you find yourself renaming an API field on the way in or out (`ot.label → form.presentation`), **fix the API instead** — see the read/write symmetry rule under "API Controllers" above. Frontend translation layers are a code smell and a maintenance tax; mappers shouldn't paper over inconsistent backend naming.
-
-**`acts_as_list` ⇒ drag-and-drop reorder, never a numeric position input.** Whenever a model uses `acts_as_list` (in Ruby), the admin SPA surface for that model — both top-level list tables and nested collection editors inside forms — must reorder via **dnd-kit**, not via an exposed `position` number field. The user expects to grab a row and drop it, not type a number into a spreadsheet. Two reference patterns ship in the codebase:
-
-1. **Top-level resource tables**: pass `reorder={{ onReorder: (id, position) => adminClient.X.update(id, { position }) }}` to `<ResourceTable>`. The table renders a grip column, owns the `DndContext` + `SortableContext` + `verticalListSortingStrategy` internally, and does optimistic local state with rollback on failure. Reference: `routes/_authenticated/$storeId/settings/payment-methods.tsx`. The position is 1-indexed; the server's `acts_as_list` shifts siblings.
-2. **Nested collection editors inside a form** (e.g. an `option_values[]` array on an option type sheet): wrap the `useFieldArray` rows in `DndContext` + `SortableContext`, give each row a `<GripVerticalIcon>` grip with `{...attributes} {...listeners}` from `useSortable`, and on drag end call `valuesArray.move(from, to)` and rewrite each row's `position` to its new index. The position field is **not rendered** in the form; it's a computed output. Reference: `routes/_authenticated/$storeId/products/options.tsx` (option values) and `routes/_authenticated/$storeId/products/$productId.tsx` (product media — grid layout, uses `rectSortingStrategy`).
-
-Use `verticalListSortingStrategy` for table rows / vertical lists, `rectSortingStrategy` for grids. Always include `KeyboardSensor` with `sortableKeyboardCoordinates` alongside `PointerSensor` for accessibility. Set `activationConstraint: { distance: 5 }` on the pointer sensor so clicks on row content don't hijack as drags.
+For free-text **searchable** pickers, use `<Combobox>` instead — see `components/spree/country-state-fields.tsx`.
-**Always use `<StoreDatePicker>` (with `react-hook-form` `<Controller>`) for date/datetime fields — never `<Input type="date">`, never the raw `<DatePicker>`.** `@/components/spree/store-date-picker` wraps `<DatePicker>` and pulls the store's IANA timezone from `<StoreProvider>` so every datetime in the admin SPA means the same thing for every admin regardless of where they're logged in from. The underlying picker (`@/components/ui/date-picker`) wraps shadcn `<Calendar>` + `<Popover>` and emits:
+**`acts_as_list` ⇒ drag-and-drop reorder, never a numeric position input.** When a model uses `acts_as_list`, both top-level list tables and nested collection editors must reorder via dnd-kit:
-- **Date-only mode** (default): `yyyy-MM-dd` plain strings (timezone-agnostic). Persist as-is — the backend's `date` columns accept these directly via Ransack `*_eq`/`*_gt`/`*_lt`. Don't slice an ISO; the picker no longer emits one.
-- **Datetime mode** (`includeTime`): full UTC ISO string. The user picks a wall-clock time **in the store's timezone**, and the picker converts to the corresponding UTC instant. On read, the picker reinterprets the UTC instant back into store-local wall clock for display.
+1. **Top-level resource tables**: pass `reorder={{ onReorder: (id, position) => adminClient.X.update(id, { position }) }}` to `<ResourceTable>` — it owns the `DndContext` + `SortableContext` internally, optimistic with rollback. Reference: `routes/_authenticated/$storeId/settings/payment-methods.tsx`.
+2. **Nested collection editors** (e.g. `option_values[]` on an option-type sheet): wrap `useFieldArray` rows in `DndContext` + `SortableContext`, give each row a `<GripVerticalIcon>` grip with `{...attributes} {...listeners}` from `useSortable`, and on drag end call `valuesArray.move(from, to)` and rewrite each row's `position` to its new index. The position field is **not rendered**; it's a computed output. Reference: `routes/_authenticated/$storeId/products/options.tsx` (vertical), `routes/_authenticated/$storeId/products/$productId.tsx` (product media grid).
-Two patterns:
+Use `verticalListSortingStrategy` for rows/lists, `rectSortingStrategy` for grids. Always pair `PointerSensor` (with `activationConstraint: { distance: 5 }` so row clicks don't hijack as drags) with `KeyboardSensor` + `sortableKeyboardCoordinates` for accessibility.
-1. **Form fields**: wire through `<Controller name="…" control={form.control} render={({ field }) => <StoreDatePicker value={field.value || null} onChange={(next) => field.onChange(next ?? '')} placeholder="Pick a date" />} />`. Reference: `routes/_authenticated/$storeId/promotions/gift-cards.tsx`.
-2. **Filter panels / ad-hoc inputs**: pass the value through directly. `<StoreDatePicker value={state || null} onChange={(next) => setState(next ?? '')} />`. The toolbar's `filterType: 'date'` branch already routes here.
+**`<StoreDatePicker>` is the only correct way to render a date/datetime field.** Never use `<Input type="date">` (native styling breaks the design system) or the bare `<DatePicker>` in `components/ui/` (skips the store timezone). `@/components/spree/store-date-picker` reads the store's IANA timezone from `<StoreProvider>` so every datetime in the SPA means the same thing for every admin. Modes:
-The picker accepts `includeTime` when you need a time component (`PaymentMethod#starts_at`/`ends_at`, scheduled publishing, etc.) — set it explicitly; default is date-only. Never render a raw `<input type="date">` — browsers render that natively, with platform-specific styling that breaks the design system. If you find one, replace it. Only reach for the bare `<DatePicker>` in `components/ui/` when you need to override the timezone explicitly (very rare — e.g. picking the store's own timezone setting itself).
+- **Date-only** (default): emits `yyyy-MM-dd` strings (timezone-agnostic). Persist as-is — backend `date` columns accept these directly via Ransack.
+- **Datetime** (`includeTime`): the user picks a wall-clock time in the store's timezone; the picker emits the corresponding UTC ISO string and reinterprets it on read.
-**Inside a `<Sheet>`, pass `inline` to `<StoreDatePicker>`.** The default Popover-based path hits the in-Sheet portal mounting bug below; the `inline` prop renders the calendar as an absolute-positioned panel beneath the trigger (with click-outside / Escape close) instead. Filter panels and page-level forms keep the default Popover. Reference: gift card create/edit sheets in `routes/_authenticated/$storeId/promotions/gift-cards.tsx`.
+Wire through `<Controller>` in forms; pass `value`/`onChange` directly in filter panels. **Inside a `<Sheet>`, pass `inline`** — the default Popover path hits the portal bug below.
-**Base UI `<Popover>` is unreliable when nested inside a `<Sheet>`'s portal tree.** Symptom: the trigger button gets `aria-expanded="true"` and `data-popup-open=""` on click, but no `[data-slot="popover-content"]` ever appears in the DOM — the Popup component silently fails to mount its rendered output. Happens in deeply-nested portal trees (Sheet → SortableContext → TableRow → Popover). When clicks fire and state opens but no panel appears, **don't keep poking at Popover** — render the panel inline with `absolute top-full left-0 z-50` + a `document.pointerdown` click-outside listener + Escape-to-close. The picker doesn't need a portal unless it must escape an `overflow: hidden` ancestor; for table cells and form fields, inline is fine. Reference: `components/spree/color-picker.tsx`.
+**Base UI `<Popover>` is unreliable inside a `<Sheet>`'s portal tree.** Symptom: the trigger gets `aria-expanded="true"` and `data-popup-open=""` on click, but no `[data-slot="popover-content"]` ever appears in the DOM. Happens in deeply-nested portal trees (Sheet → SortableContext → TableRow → Popover). Fix: render the panel inline with `absolute top-full left-0 z-50` + a `document.pointerdown` click-outside listener + Escape-to-close. A portal is only needed to escape an `overflow: hidden` ancestor; for table cells and form fields, inline is fine. Reference: `components/spree/color-picker.tsx`, plus `<StoreDatePicker inline>` above.
### @spree/sdk-core — Shared HTTP Layer
diff --git a/docs/plans/6.0-admin-spa.md b/docs/plans/6.0-admin-spa.md
index 5f861fd0e1..4a60238f57 100644
--- a/docs/plans/6.0-admin-spa.md
+++ b/docs/plans/6.0-admin-spa.md
@@ -17,13 +17,15 @@ A new single-page React admin dashboard that replaces the Rails `spree/admin` en
- **No SSR.** Pure client-side, outputs static files.
- **Admin API is the only data source.** Never reach into Rails models, never import Rails-rendered HTML.
- **Route path includes `/$storeId/`** for all authenticated routes (multi-store support). `/` redirects to the current/default store.
-- **Auth via JWT + refresh token.** Access token in React context, refresh token in `localStorage` (or httpOnly cookie when we have a hosted deployment). 401 → auto-refresh via SDK `onUnauthorized` hook → retry.
+- **Auth via JWT + refresh token.** Access token in memory, refresh token in an httpOnly cookie (see `5.5-admin-auth-cookie-refresh.md`). 401 → auto-refresh via SDK `onUnauthorized` hook → retry.
- **Permissions are server-driven.** `GET /api/v3/admin/me` returns the CanCanCan rules serialized; SPA mirrors them via `<Can I="..." a="..." />` and the `usePermissions()` hook. Server still enforces `authorize!` — SPA is UX only.
- **Shadcn/ui copy-paste ownership model** — plugin authors can extend or override components without fighting a component library's abstraction.
- **Table registry + navigation registry + slot registry** are the three extension points. Nothing else is pluggable yet. Slot names mirror Rails admin's `render_admin_partials` slots so plugin authors carry their mental model across.
- **No global state library.** TanStack Query handles server state, React Hook Form handles form state, `AuthProvider` + `PermissionProvider` handle session. Add Zustand only if we hit a legitimate client-state problem.
- **No breadcrumbs.** Legacy admin used breadcrumbs because deep flows (Product → Variants → Variant edit) were full-page navigations. The SPA collapses those into drawers and inline UIs, so the chains shrink to one or two segments — covered by `<BackButton>` (in `<PageHeader>`), the page title itself, and the highlighted sidebar section. Do not reintroduce a breadcrumb component.
- **shipping_category_id is not part of product forms** — dropped in 6.0 per `6.0-fulfillment-and-delivery.md`.
+- **Forms stay as explicit React Hook Form blocks** (`<Field>` / `<Input>` / `<Controller>` / `<FieldError>`) — no field/form wrapper. A `<SpreeForm>` + `<SpreeField>` abstraction was tried and rolled back (rationale in "Forms & i18n"). The compensating utilities — `mapSpreeErrorsToForm` for 422 → RHF translation, and i18n keys under `admin.fields.<resource>.<attribute>` — remain as small primitives that compose with raw RHF.
+- **i18next + react-i18next for admin UI strings.** All form labels, placeholders, help text, button copy, and toast text resolve through `useTranslation()`. Translation keys mirror Rails I18n: `admin.fields.<resource>.<attribute>.<facet>` with fallback to `admin.fields.<attribute>.<facet>`. English-only at launch (`packages/admin/src/locales/en.json`); the infrastructure supports more locales but actually translating the admin UI is a separate, opt-in project. Bundle cost: ~14 KB gzipped.
## Design Details
@@ -44,7 +46,7 @@ A new single-page React admin dashboard that replaces the Rails `spree/admin` en
| Forms | **React Hook Form + Zod** | Schemas mirror API contracts; Zod schemas can be derived from Typelizer-generated types |
| UI | **shadcn/ui + Tailwind** | Copy-paste ownership so extensions can override without fighting component APIs |
| Icons | **lucide-react** | |
-| Auth | **Custom `AuthProvider`** | Token in memory + localStorage; refresh token in localStorage; 58-minute refresh timer; 401 auto-retry via SDK `onUnauthorized` |
+| Auth | **Custom `AuthProvider`** | Access token in memory; refresh token in httpOnly cookie (`5.5-admin-auth-cookie-refresh.md`); 58-minute refresh timer; 401 auto-retry via SDK `onUnauthorized` |
| Permissions | **Custom `PermissionProvider`** | Loads `/api/v3/admin/me` on login, exposes `usePermissions()` + `<Can>` mirroring CanCanCan |
| State (session) | `AuthProvider` + `PermissionProvider` | Small context, no global store |
| Linting/formatting | **Biome** | Single tool, fast |
@@ -54,20 +56,20 @@ A new single-page React admin dashboard that replaces the Rails `spree/admin` en
### Auth flow
```
-Login → POST /auth/login → { token, refresh_token, user }
+Login → POST /auth/login → { token, user } (refresh token set as httpOnly cookie)
↓
-Store in adminClient, AuthProvider state, localStorage
+Store access token in adminClient + AuthProvider state (in memory only)
↓
PermissionProvider fetches /me → { user, permissions: [...] }
↓
Router beforeLoad guards check `context.auth.isAuthenticated`
↓
-Every 58 min: refresh token → new access + rotated refresh
+Every 58 min: refresh → new access token; server rotates the cookie
↓
On 401 from any API call: SDK onUnauthorized → refresh → retry original request
```
-Concurrent refresh calls are serialized via a shared promise to prevent double-rotation.
+Concurrent refresh calls are serialized via a shared promise to prevent double-rotation. Cookie migration plan: `5.5-admin-auth-cookie-refresh.md`.
### Route structure
@@ -374,6 +376,219 @@ Render props give plugins more power but worse UX: they must understand the host
| `content_for :page_actions { ... }` | `<Slot name="page.actions" context={{ resource }} />` |
| `Spree.admin.navigation.sidebar.add :menu, ...` | `nav.add({ key, label, url, icon, position, if })` |
+### Forms & i18n
+
+Admin SPA forms are **raw React Hook Form blocks** — `<Field>` / `<Input>` / `<Controller>` / `<FieldError>` written out per attribute — combined with two small utilities:
+
+1. **`mapSpreeErrorsToForm(error, setError)`** translates 422 SpreeError responses into `form.setError(...)` calls (flat attribute keys onto fields, `:base` and nested keys onto `formState.errors.root`).
+2. **`useTranslation()` + `admin.fields.<resource>.<attribute>.{label,placeholder,help}` keys** in `packages/admin/src/locales/en.json` keep labels translatable.
+
+#### Why not a `<SpreeField>` / `<SpreeForm>` wrapper?
+
+A short-lived branch shipped a Rails-FormBuilder-equivalent (`<SpreeField attribute="name" />` collapsing label + input + error + i18n into one line; `<SpreeForm resource="…">` context provider for the form + resource scope). It got reverted before merging. The win was ~5-10× LOC reduction per field; the cost was readability — every field's behavior (which input element, where the label came from, how errors rendered, how server validation got wired) became implicit, and stacking the layers (form context, key resolution with fallback, `as=` dispatch, error wiring) made forms harder to debug than the verbose original.
+
+The Rails FormBuilder analogy was misleading: FormBuilder works because the model + view + controller share one naming convention and the framework owns all four sides. In a React SPA those layers are decoupled — RHF owns form state, Zod owns validation, the SDK owns API params, react-i18next owns labels — and bridging them through a single component pushed too much logic into implicit defaults.
+
+What survives the rollback: the i18n keys, `mapSpreeErrorsToForm`, and `useResourceMutation`'s 422-toast suppression all stay as small primitives that compose with raw RHF.
+
+#### Translation keys
+
+```jsonc
+// packages/admin/src/locales/en.json
+{
+ "admin": {
+ "fields": {
+ "name": { "label": "Name" },
+ "description": { "label": "Description" },
+ "code": { "label": "Code", "placeholder": "SUMMER2026" },
+ "starts_at": { "label": "Starts" },
+ "expires_at": { "label": "Expires" },
+ "usage_limit": { "label": "Usage limit", "placeholder": "Unlimited" },
+
+ // Per-resource overrides — picked when the consumer passes the resource key explicitly.
+ "promotion": { "name": { "label": "Name", "placeholder": "Summer Sale" } },
+ "option_type": { "name": { "label": "Internal name", "help": "Lowercase identifier. Must be unique across the store." },
+ "label": { "label": "Label", "help": "Shown to customers on the storefront." } },
+ "stock_location": { "name": { "label": "Name", "placeholder": "Brooklyn warehouse" },
+ "admin_name": { "label": "Internal name", "placeholder": "Optional — shown only in the admin" } }
+ },
+ "actions": { "create": "Create", "save": "Save", "saving": "Saving…", "cancel": "Cancel", "delete": "Delete" }
+ }
+}
+```
+
+Resolution is per-call: callers reach for the per-resource key first (`t('admin.fields.promotion.name.label')`), or the cross-resource default when there's no override (`t('admin.fields.name.label')`). Facets are `label | placeholder | help`. Resource names use the snake-case singular API model name (`promotion`, `option_type`, `stock_location`, `payment_method`) so the SPA mirrors the serializer + Rails model layout.
+
+#### Form pattern
+
+```tsx
+function PromotionForm({ form, onSubmit }: Props) {
+ const { t } = useTranslation()
+ const { errors } = form.formState
+
+ async function handleSubmit(values: PromotionFormValues) {
+ try {
+ await onSubmit(values)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
+ }
+
+ return (
+ <form onSubmit={form.handleSubmit(handleSubmit)}>
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">{errors.root.message}</p>
+ )}
+ <FieldGroup>
+ <Field>
+ <FieldLabel htmlFor="promo-name">{t('admin.fields.name.label')}</FieldLabel>
+ <Input
+ id="promo-name"
+ placeholder={t('admin.fields.promotion.name.placeholder')}
+ aria-invalid={!!errors.name || undefined}
+ {...form.register('name')}
+ />
+ <FieldError errors={[errors.name]} />
+ </Field>
+ {/* …more fields follow the same shape… */}
+ </FieldGroup>
+ </form>
+ )
+}
+```
+
+Custom widgets (CurrencySelect, CountryCombobox, ResourceCombobox, TagCombobox, RichTextEditor, StoreDatePicker, ColorPicker, dnd-kit field-arrays) use inline `<Controller>` blocks. Validation lives in the Zod schema (`zodResolver`); per-field rules belong on `z.object({ … })`, not on the input.
+
+#### Server error mapping
+
+```ts
+// packages/admin/src/lib/form-errors.ts
+export function mapSpreeErrorsToForm<T>(error: unknown, setError: UseFormSetError<T>): boolean
+```
+
+Walks `SpreeError.details` (`{ field: string[] }`), calls `setError(field, { type: 'server', message })` for flat keys, and seeds `formState.errors.root.message` with the server's top-level summary so `:base`/nested errors still surface. Returns `true` when a SpreeError was rendered — callers re-throw anything else so the surrounding mutation hook can toast network/5xx errors.
+
+#### Extending forms — per-resource form slots
+
+The legacy Rails admin let plugins inject form fields into a host model's form via `render_admin_partials(:product_form_partials, f:, product:)` and friends. The SPA needs an equivalent — without it, the only way to add a single custom field to e.g. the Order form is to fork the route, which discards all upstream improvements forever.
+
+The lightweight built-in mechanism (`Spree::Metafields` → `<CustomFieldsCard>`) covers ~80% of "add a field" use cases with zero code, but it renders fields in a dedicated card at the bottom of the page — not inline with the form's other fields, and no client-side validation. For the cases where a plugin needs a typed, validated, inline field, **form slots** are the answer.
+
+**Slot taxonomy.** Mirror the existing `<resource>.<surface>` convention already used by promotion / payment-method editors, and align with the legacy Rails partial names (`product_form_partials` → `product.form`):
+
+| Form | Slot points | Context shape |
+|---|---|---|
+| Product detail | `product.form`, `product.form_sidebar`, `product.dropdown`, `product.page_title` | `{ form: UseFormReturn<ProductFormValues>, product: Product, mode: 'edit' }` |
+| Order detail | `order.page_header`, `order.page_body`, `order.page_sidebar`, `order.summary`, `order.dropdown` | `{ order: Order }` (no `form` — the order detail page is mostly read-only with inline edits) |
+| New order | `order_new.form`, `order_new.sidebar` | `{ form: UseFormReturn<NewOrderFormValues>, customer: Customer \| null }` |
+| Customer detail | `customer.page_body`, `customer.page_sidebar`, `customer.dropdown` | `{ customer: Customer }` |
+| Promotion form | `promotion.sidebar`, `promotion.main` | `{ form: UseFormReturn<PromotionFormValues>, mode: 'create' \| 'edit' }` |
+| Store settings | `store.form` | `{ form: UseFormReturn<StoreSettingsFormValues>, store: Store }` |
+| Settings forms (payment_method, tax_category, customer_group, stock_location, …) | `<resource>.form` | `{ form: UseFormReturn<…FormValues>, resource: <Resource> \| null, mode }` |
+
+**Position semantics.** Built-in cards reserve `100`/`200`/`300` (with gaps) so plugin slots can sort relative to them — "before Variants card" = `< 100`, "between Variants and Inventory" = `150`, etc. Document the built-in positions per slot when the host page lands.
+
+**Usage from the host page (today):**
+
+```tsx
+// routes/_authenticated/$storeId/products/$productId.tsx
+<ResourceLayout
+ main={
+ <>
+ <GeneralCard form={form} />
+ <MediaCard productId={productId} variants={product.variants ?? []} />
+ <InventoryCard form={form} storeId={storeId} hasVariants={hasVariants} />
+ <CustomFieldsCard ownerType="Spree::Product" ownerId={productId} resourceLabel="products" />
+ <Slot<ProductFormSlotContext>
+ name="product.form"
+ context={{ form, product, mode: 'edit' }}
+ />
+ <MetadataCard metadata={product.metadata} />
+ </>
+ }
+ sidebar={
+ <>
+ <StatusCard form={form} />
+ <CategorizationCard form={form} />
+ <TaxCard form={form} />
+ <SEOCard form={form} product={product} />
+ <Slot<ProductFormSlotContext>
+ name="product.form_sidebar"
+ context={{ form, product, mode: 'edit' }}
+ />
+ </>
+ }
+/>
+```
+
+**Plugin code (downstream `@my-co/spree-warehouse-plugin`):**
+
+```tsx
+// src/index.tsx — imported once from the app's main.tsx
+import { registerSlot } from '@spree/admin/lib/slot-registry'
+import type { ProductFormSlotContext } from '@spree/admin/components/spree/products/slots'
+import { WarehouseCard } from './warehouse-card'
+
+registerSlot<ProductFormSlotContext>('product.form_sidebar', {
+ id: 'warehouse-plugin/preferred-location',
+ position: 250, // after Tax (200), before SEO (300)
+ component: ({ form, product }) => <WarehouseCard form={form} product={product} />,
+})
+```
+
+```tsx
+// src/warehouse-card.tsx
+import { Controller, type UseFormReturn } from 'react-hook-form'
+import type { Product } from '@spree/admin-sdk'
+import { useTranslation } from 'react-i18next'
+import { Card, CardContent, CardHeader, CardTitle } from '@spree/admin/components/ui/card'
+import { Field, FieldError, FieldLabel } from '@spree/admin/components/ui/field'
+
+interface Props {
+ form: UseFormReturn<{ preferred_warehouse_id?: string; [k: string]: unknown }>
+ product: Product
+}
+
+export function WarehouseCard({ form, product }: Props) {
+ const { t } = useTranslation()
+ return (
+ <Card>
+ <CardHeader><CardTitle>{t('warehouse.title')}</CardTitle></CardHeader>
+ <CardContent>
+ <Field>
+ <FieldLabel>{t('warehouse.preferred_location')}</FieldLabel>
+ <Controller
+ name="preferred_warehouse_id"
+ control={form.control}
+ render={({ field }) => <WarehouseCombobox {...field} />}
+ />
+ <FieldError errors={[form.formState.errors.preferred_warehouse_id]} />
+ </Field>
+ </CardContent>
+ </Card>
+ )
+}
+```
+
+The field's value flows through RHF, gets submitted alongside the host form's values (the Admin API accepts unknown keys — extending the JSON payload is enough; the plugin's Ruby side reads it from `params[:preferred_warehouse_id]` and stores it on the new column it added). Server-side validation errors come back as `details: { preferred_warehouse_id: [...] }` and `mapSpreeErrorsToForm` routes them onto the inline field automatically — no host-page changes needed.
+
+**Schema augmentation is deferred.** Injecting Zod refinements into a schema already wired into `useForm` has no clean answer (the host page would need to know about the plugin, breaking the one-way registration model). For now, plugin fields skip client-side validation and rely on the server — the 422 path already renders the error inline. We'll revisit when a concrete plugin asks for cross-field client rules.
+
+**Slot naming + ownership rules.** Same as the existing slot API:
+- New slots cost forever — once published, removing or renaming them breaks plugins. Add one only when at least one real plugin needs it.
+- Slot keys live in a per-form `slots.ts` module (`components/spree/products/slots.ts`, `components/spree/orders/slots.ts`, …) that exports both the slot name **and** the context type. Plugins import both.
+- Document every new slot in the table above in the same PR that adds it.
+
+**What we ship in this plan (Phase 4):**
+- `slots.ts` files for Product / Order / Customer / Promotion / Store / New Order
+- `<Slot>` placements in each host page at the documented positions
+- Reference plugin example in `packages/admin/examples/` (a no-op "extra field" plugin so plugin authors have something to copy)
+
+**What we explicitly defer:**
+- Schema augmentation helper (`useResolverWith`) — wait for a concrete plugin asking for it
+- Slot `priority`/`replace`/`exclusive` semantics — current `position`-only model is enough
+- Per-field injection (between two existing fields in the same `<Card>`) — slots inject whole cards/rows. If a plugin needs to interleave fields, it owns its whole card.
+
### Component library (`src/components/spree/`)
The shadcn copy-paste model is preserved for primitives (`src/components/ui/`). On top of those primitives we maintain a Spree compound layer at `src/components/spree/` that supplies the page chrome, drawers, and form widgets used across resources. Plugin authors can fork any `spree/*` component into their own override file the same way they fork shadcn primitives — no framework lock-in.
@@ -406,6 +621,7 @@ All drawer-based, opened from `<PageHeader>`'s actions dropdown.
| Component | Replaces |
|---|---|
+| `mapSpreeErrorsToForm(error, setError)` | `ActiveModel::Errors` → form-builder error rendering; translates a thrown SpreeError into `form.setError(...)` calls so 422 responses light up `aria-invalid` + `<FieldError>` inline (and `:base` / nested keys land on `formState.errors.root.message` for a top-of-form banner). |
| `<MoneyInput>` | `money_field_controller.js`; currency-aware decimal input. |
| `<SlugInput>` | `slug_form_controller.js`; auto-generates from a watched field until edited manually. |
| `<SeoFields>` | `_seo.html.erb` + `seo_form_controller.js`; meta_title + meta_description + slug + SERP preview + character counts. |
@@ -508,6 +724,8 @@ packages/admin/
│ ├── schemas/
│ │ ├── product.ts # Zod form schemas
│ │ └── ...
+│ ├── locales/
+│ │ └── en.json # admin.fields.* + admin.actions.* + …
│ └── lib/
│ ├── query-client.ts
│ ├── table-registry.ts # defineTable, getTable, tables proxy
@@ -515,6 +733,8 @@ packages/admin/
│ ├── nav-registry.ts # nav.add, nav.remove, nav.update
│ ├── permissions.ts # Subject + Action constants
│ ├── formatters.ts # formatPrice, formatRelativeTime
+│ ├── i18n.ts # i18next init + locale loading
+│ ├── form-errors.ts # mapSpreeErrorsToForm
│ └── utils.ts
```
@@ -575,7 +795,7 @@ Build remaining resource pages on top of the chrome and Tier 3 form primitives (
- **Always use SDK types.** Never hand-write API response shapes. If a type is wrong, fix the Rails serializer + run Typelizer, don't cast in the SPA.
- **No `useMemo`/`useCallback` without reason.** Keep components small and readable; optimize only when profiling says so.
- **No imperative navigation hacks.** Use TanStack Router `Link` and `navigate`.
-- **All forms use React Hook Form + Zod.** Never use uncontrolled forms or manual `useState` for form state.
+- **Forms use React Hook Form + Zod with raw `<Field>` / `<Input>` / `<Controller>` / `<FieldError>` blocks.** No `<SpreeField>` / `<SpreeForm>` wrapper (see "Forms & i18n"). Labels come from i18n. Server validation errors route onto fields via `mapSpreeErrorsToForm`.
- **All data fetching goes through TanStack Query hooks in `src/hooks/`.** Never call `adminClient` directly from components.
- **Permission-gate UI optimistically.** Show the button, handle 403 with a toast. Only hide when there's a clear `read` denial.
- **All nav items, routes, and action buttons that correspond to Admin API resources must pass a `subject` to `<Can>` or the equivalent check.** Sidebar filtering already does this — keep it consistent.
diff --git a/packages/admin/src/components/spree/address-form-dialog.tsx b/packages/admin/src/components/spree/address-form-dialog.tsx
index f913c2a895..9f2667366e 100644
--- a/packages/admin/src/components/spree/address-form-dialog.tsx
+++ b/packages/admin/src/components/spree/address-form-dialog.tsx
@@ -1,10 +1,12 @@
import type { Address } from '@spree/admin-sdk'
-import { type FormEvent, useCallback, useState } from 'react'
+import { useEffect } from 'react'
+import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
import { CountryCombobox } from '@/components/spree/country-combobox'
import { StateCombobox, useCountryStates } from '@/components/spree/country-state-fields'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import {
Sheet,
@@ -30,6 +32,38 @@ export interface AddressParams {
is_default_shipping?: boolean
}
+interface AddressFormValues {
+ first_name: string
+ last_name: string
+ address1: string
+ address2: string
+ city: string
+ postal_code: string
+ country_iso: string
+ state_abbr: string
+ phone: string
+ label: string
+ is_default_billing: boolean
+ is_default_shipping: boolean
+}
+
+function buildDefaults(address: Address | null | undefined): AddressFormValues {
+ return {
+ first_name: address?.first_name ?? '',
+ last_name: address?.last_name ?? '',
+ address1: address?.address1 ?? '',
+ address2: address?.address2 ?? '',
+ city: address?.city ?? '',
+ postal_code: address?.postal_code ?? '',
+ country_iso: address?.country_iso ?? '',
+ state_abbr: address?.state_abbr ?? '',
+ phone: address?.phone ?? '',
+ label: address?.label ?? '',
+ is_default_billing: address?.is_default_billing ?? false,
+ is_default_shipping: address?.is_default_shipping ?? false,
+ }
+}
+
export function AddressFormDialog({
address,
open,
@@ -49,44 +83,43 @@ export function AddressFormDialog({
showLabel?: boolean
showDefaultFlags?: boolean
}) {
+ const { t } = useTranslation()
+ const form = useForm<AddressFormValues>({ defaultValues: buildDefaults(address) })
+ const { errors } = form.formState
+
// The parent keys the dialog on the address id so a fresh instance mounts
- // for each open — that's what lets us seed `countryIso` from the address
- // once and forget about it.
- const [countryIso, setCountryIso] = useState<string>(() => address?.country_iso ?? '')
- const [stateAbbr, setStateAbbr] = useState<string>(() => address?.state_abbr ?? '')
+ // for each open, but `address` can also stream in async (loaded after the
+ // sheet mounts). Reset the form when a new record arrives.
+ useEffect(() => {
+ form.reset(buildDefaults(address))
+ }, [address, form])
+ const countryIso = form.watch('country_iso')
const { states, statesRequired } = useCountryStates(countryIso)
const useStateCombobox = statesRequired && states.length > 0
- const handleCountryChange = useCallback((iso: string) => {
- setCountryIso(iso)
- // Clear the previously selected state — the combobox is keyed on the
- // country, but we still need the form field to reset across countries.
- setStateAbbr('')
- }, [])
-
- function handleSubmit(e: FormEvent<HTMLFormElement>) {
- e.preventDefault()
- const fd = new FormData(e.currentTarget)
+ async function onSubmit(values: AddressFormValues) {
onSave({
- first_name: fd.get('first_name') as string,
- last_name: fd.get('last_name') as string,
- address1: fd.get('address1') as string,
- address2: fd.get('address2') as string,
- city: fd.get('city') as string,
- postal_code: fd.get('postal_code') as string,
- country_iso: countryIso,
- state_abbr: useStateCombobox ? stateAbbr : (fd.get('state_abbr') as string),
- phone: fd.get('phone') as string,
- ...(showLabel && { label: (fd.get('label') as string) || undefined }),
+ first_name: values.first_name,
+ last_name: values.last_name,
+ address1: values.address1,
+ address2: values.address2,
+ city: values.city,
+ postal_code: values.postal_code,
+ country_iso: values.country_iso,
+ state_abbr: values.state_abbr,
+ phone: values.phone,
+ ...(showLabel && { label: values.label || undefined }),
...(showDefaultFlags && {
- is_default_billing: fd.get('is_default_billing') === 'on',
- is_default_shipping: fd.get('is_default_shipping') === 'on',
+ is_default_billing: values.is_default_billing,
+ is_default_shipping: values.is_default_shipping,
}),
})
}
- // Prevent Enter in combobox inputs from submitting the form
+ // Prevent Enter in combobox inputs from submitting the form. RHF's
+ // handleSubmit fires on submit events, so swallow Enter inside any
+ // role=combobox before it bubbles into the form.
function handleKeyDown(e: React.KeyboardEvent) {
const target = e.target as HTMLElement
if (e.key === 'Enter' && target.getAttribute('role') === 'combobox') {
@@ -102,7 +135,7 @@ export function AddressFormDialog({
<SheetDescription>Update the address details.</SheetDescription>
</SheetHeader>
<form
- onSubmit={handleSubmit}
+ onSubmit={form.handleSubmit(onSubmit)}
onKeyDown={handleKeyDown}
className="flex flex-col flex-1 overflow-hidden"
>
@@ -110,95 +143,175 @@ export function AddressFormDialog({
<FieldGroup>
{showLabel && (
<Field>
- <FieldLabel htmlFor="addr-label">Label</FieldLabel>
+ <FieldLabel htmlFor="addr-label">
+ {t('admin.fields.address.label.label')}
+ </FieldLabel>
<Input
id="addr-label"
- name="label"
- placeholder="e.g. Home, Office"
- defaultValue={address?.label ?? ''}
+ placeholder={t('admin.fields.address.label.placeholder')}
+ {...form.register('label')}
/>
</Field>
)}
<div className="grid grid-cols-2 gap-3">
<Field>
- <FieldLabel htmlFor="addr-fn">First name</FieldLabel>
- <Input id="addr-fn" name="first_name" defaultValue={address?.first_name ?? ''} />
+ <FieldLabel htmlFor="addr-first-name">
+ {t('admin.fields.first_name.label')}
+ </FieldLabel>
+ <Input
+ id="addr-first-name"
+ aria-invalid={!!errors.first_name || undefined}
+ {...form.register('first_name')}
+ />
+ <FieldError errors={[errors.first_name]} />
</Field>
<Field>
- <FieldLabel htmlFor="addr-ln">Last name</FieldLabel>
- <Input id="addr-ln" name="last_name" defaultValue={address?.last_name ?? ''} />
+ <FieldLabel htmlFor="addr-last-name">
+ {t('admin.fields.last_name.label')}
+ </FieldLabel>
+ <Input
+ id="addr-last-name"
+ aria-invalid={!!errors.last_name || undefined}
+ {...form.register('last_name')}
+ />
+ <FieldError errors={[errors.last_name]} />
</Field>
</div>
<Field>
- <FieldLabel htmlFor="addr-a1">Address</FieldLabel>
- <Input id="addr-a1" name="address1" defaultValue={address?.address1 ?? ''} />
+ <FieldLabel htmlFor="addr-address1">
+ {t('admin.fields.address.address1.label')}
+ </FieldLabel>
+ <Input
+ id="addr-address1"
+ aria-invalid={!!errors.address1 || undefined}
+ {...form.register('address1')}
+ />
+ <FieldError errors={[errors.address1]} />
</Field>
<Field>
- <FieldLabel htmlFor="addr-a2">Apartment, suite, etc.</FieldLabel>
- <Input id="addr-a2" name="address2" defaultValue={address?.address2 ?? ''} />
+ <FieldLabel htmlFor="addr-address2">
+ {t('admin.fields.address.address2.label')}
+ </FieldLabel>
+ <Input
+ id="addr-address2"
+ aria-invalid={!!errors.address2 || undefined}
+ {...form.register('address2')}
+ />
+ <FieldError errors={[errors.address2]} />
</Field>
<Field>
- <FieldLabel>Country</FieldLabel>
- <CountryCombobox value={countryIso} onValueChange={handleCountryChange} />
+ <FieldLabel>{t('admin.fields.country_iso.label')}</FieldLabel>
+ <Controller
+ name="country_iso"
+ control={form.control}
+ render={({ field }) => (
+ <CountryCombobox
+ value={field.value}
+ onValueChange={(iso) => {
+ field.onChange(iso)
+ form.setValue('state_abbr', '', { shouldDirty: true })
+ }}
+ />
+ )}
+ />
</Field>
<div className="grid grid-cols-2 gap-3">
<Field>
- <FieldLabel htmlFor="addr-city">City</FieldLabel>
- <Input id="addr-city" name="city" defaultValue={address?.city ?? ''} />
+ <FieldLabel htmlFor="addr-city">{t('admin.fields.city.label')}</FieldLabel>
+ <Input
+ id="addr-city"
+ aria-invalid={!!errors.city || undefined}
+ {...form.register('city')}
+ />
+ <FieldError errors={[errors.city]} />
</Field>
- <Field>
- <FieldLabel>State / Province</FieldLabel>
- {useStateCombobox ? (
- <StateCombobox
- countryIso={countryIso}
- states={states}
- value={stateAbbr}
- onValueChange={setStateAbbr}
+ {useStateCombobox ? (
+ <Field>
+ <FieldLabel>{t('admin.fields.state_abbr.label')}</FieldLabel>
+ <Controller
+ name="state_abbr"
+ control={form.control}
+ render={({ field }) => (
+ <StateCombobox
+ countryIso={countryIso}
+ states={states}
+ value={field.value}
+ onValueChange={field.onChange}
+ />
+ )}
/>
- ) : (
+ </Field>
+ ) : (
+ <Field>
+ <FieldLabel htmlFor="addr-state-abbr">
+ {t('admin.fields.state_abbr.label')}
+ </FieldLabel>
<Input
- id="addr-state"
- name="state_abbr"
- defaultValue={address?.state_abbr ?? ''}
+ id="addr-state-abbr"
+ aria-invalid={!!errors.state_abbr || undefined}
+ {...form.register('state_abbr')}
/>
- )}
- </Field>
+ <FieldError errors={[errors.state_abbr]} />
+ </Field>
+ )}
</div>
<Field>
- <FieldLabel htmlFor="addr-zip">Postal code</FieldLabel>
- <Input id="addr-zip" name="postal_code" defaultValue={address?.postal_code ?? ''} />
+ <FieldLabel htmlFor="addr-postal-code">
+ {t('admin.fields.address.postal_code.label')}
+ </FieldLabel>
+ <Input
+ id="addr-postal-code"
+ aria-invalid={!!errors.postal_code || undefined}
+ {...form.register('postal_code')}
+ />
+ <FieldError errors={[errors.postal_code]} />
</Field>
<Field>
- <FieldLabel htmlFor="addr-phone">Phone</FieldLabel>
- <Input id="addr-phone" name="phone" defaultValue={address?.phone ?? ''} />
+ <FieldLabel htmlFor="addr-phone">{t('admin.fields.phone.label')}</FieldLabel>
+ <Input
+ id="addr-phone"
+ aria-invalid={!!errors.phone || undefined}
+ {...form.register('phone')}
+ />
+ <FieldError errors={[errors.phone]} />
</Field>
{showDefaultFlags && (
<>
<Field>
- <label
- htmlFor="addr-default-billing"
- className="flex items-center gap-2 text-sm"
- >
- <Checkbox
- id="addr-default-billing"
+ <div className="flex items-start justify-between gap-4">
+ <FieldLabel htmlFor="addr-default-billing" className="cursor-pointer">
+ {t('admin.fields.address.is_default_billing.label')}
+ </FieldLabel>
+ <Controller
name="is_default_billing"
- defaultChecked={address?.is_default_billing}
+ control={form.control}
+ render={({ field }) => (
+ <Checkbox
+ id="addr-default-billing"
+ checked={!!field.value}
+ onCheckedChange={field.onChange}
+ />
+ )}
/>
- Default billing address
- </label>
+ </div>
</Field>
<Field>
- <label
- htmlFor="addr-default-shipping"
- className="flex items-center gap-2 text-sm"
- >
- <Checkbox
- id="addr-default-shipping"
+ <div className="flex items-start justify-between gap-4">
+ <FieldLabel htmlFor="addr-default-shipping" className="cursor-pointer">
+ {t('admin.fields.address.is_default_shipping.label')}
+ </FieldLabel>
+ <Controller
name="is_default_shipping"
- defaultChecked={address?.is_default_shipping}
+ control={form.control}
+ render={({ field }) => (
+ <Checkbox
+ id="addr-default-shipping"
+ checked={!!field.value}
+ onCheckedChange={field.onChange}
+ />
+ )}
/>
- Default shipping address
- </label>
+ </div>
</Field>
</>
)}
diff --git a/packages/admin/src/components/spree/custom-fields/definition-form.tsx b/packages/admin/src/components/spree/custom-fields/definition-form.tsx
index f6b096e404..452c52a214 100644
--- a/packages/admin/src/components/spree/custom-fields/definition-form.tsx
+++ b/packages/admin/src/components/spree/custom-fields/definition-form.tsx
@@ -2,6 +2,7 @@ import { zodResolver } from '@hookform/resolvers/zod'
import { Loader2Icon } from 'lucide-react'
import type { ReactNode } from 'react'
import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
import { z } from 'zod/v4'
import { Button } from '@/components/ui/button'
import { Field, FieldLabel } from '@/components/ui/field'
@@ -15,6 +16,7 @@ import {
} from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { useCreateCustomFieldDefinition } from '@/hooks/use-custom-fields'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
const FIELD_TYPES = [
{ value: 'short_text', label: 'Short text' },
@@ -58,6 +60,7 @@ export function DefinitionForm({
onSuccess,
renderShell,
}: DefinitionFormProps) {
+ const { t } = useTranslation()
const create = useCreateCustomFieldDefinition(resourceType)
const form = useForm<DefinitionFormValues>({
@@ -70,66 +73,84 @@ export function DefinitionForm({
storefront_visible: false,
},
})
+ const { errors } = form.formState
const onSubmit = async (values: DefinitionFormValues) => {
try {
const result = await create.mutateAsync({ ...values, resource_type: resourceType })
onSuccess(result.id)
} catch (err) {
- const message = err instanceof Error ? err.message : 'Failed to create definition'
- form.setError('root', { message })
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
}
}
const fields = (
<div className="flex flex-col gap-4">
- {form.formState.errors.root && (
- <div className="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive">
- {form.formState.errors.root.message}
- </div>
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
)}
-
<Field>
- <FieldLabel htmlFor="label">Label</FieldLabel>
- <Input id="label" placeholder="e.g. Material" {...form.register('label')} />
- {form.formState.errors.label && (
- <p className="text-xs text-destructive">{form.formState.errors.label.message}</p>
- )}
+ <FieldLabel htmlFor="cfd-label">
+ {t('admin.fields.custom_field_definition.label.label')}
+ </FieldLabel>
+ <Input
+ id="cfd-label"
+ placeholder={t('admin.fields.custom_field_definition.label.placeholder')}
+ aria-invalid={!!errors.label || undefined}
+ {...form.register('label')}
+ />
+ {errors.label && <p className="text-sm text-destructive">{errors.label.message}</p>}
</Field>
-
<div className="grid grid-cols-3 gap-3">
<Field className="col-span-1">
- <FieldLabel htmlFor="namespace">Namespace</FieldLabel>
- <Input id="namespace" placeholder="custom" {...form.register('namespace')} />
- {form.formState.errors.namespace && (
- <p className="text-xs text-destructive">{form.formState.errors.namespace.message}</p>
+ <FieldLabel htmlFor="cfd-namespace">
+ {t('admin.fields.custom_field_definition.namespace.label')}
+ </FieldLabel>
+ <Input
+ id="cfd-namespace"
+ placeholder={t('admin.fields.custom_field_definition.namespace.placeholder')}
+ aria-invalid={!!errors.namespace || undefined}
+ {...form.register('namespace')}
+ />
+ {errors.namespace && (
+ <p className="text-sm text-destructive">{errors.namespace.message}</p>
)}
</Field>
<Field className="col-span-2">
- <FieldLabel htmlFor="key">Key</FieldLabel>
- <Input id="key" placeholder="e.g. material" {...form.register('key')} />
- {form.formState.errors.key && (
- <p className="text-xs text-destructive">{form.formState.errors.key.message}</p>
- )}
+ <FieldLabel htmlFor="cfd-key">
+ {t('admin.fields.custom_field_definition.key.label')}
+ </FieldLabel>
+ <Input
+ id="cfd-key"
+ placeholder={t('admin.fields.custom_field_definition.key.placeholder')}
+ aria-invalid={!!errors.key || undefined}
+ {...form.register('key')}
+ />
+ {errors.key && <p className="text-sm text-destructive">{errors.key.message}</p>}
</Field>
</div>
-
<Field>
- <FieldLabel>Type</FieldLabel>
+ <FieldLabel htmlFor="cfd-field-type">
+ {t('admin.fields.custom_field_definition.field_type.label')}
+ </FieldLabel>
<Controller
name="field_type"
control={form.control}
render={({ field }) => (
- <Select value={field.value} onValueChange={field.onChange}>
- <SelectTrigger className="w-full">
- <SelectValue>
- {(value) => FIELD_TYPES.find((t) => t.value === value)?.label ?? value}
- </SelectValue>
+ <Select
+ items={FIELD_TYPES as unknown as { value: string; label: string }[]}
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger id="cfd-field-type" aria-invalid={!!errors.field_type || undefined}>
+ <SelectValue />
</SelectTrigger>
<SelectContent>
- {FIELD_TYPES.map((t) => (
- <SelectItem key={t.value} value={t.value}>
- {t.label}
+ {FIELD_TYPES.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
</SelectItem>
))}
</SelectContent>
@@ -137,20 +158,23 @@ export function DefinitionForm({
)}
/>
</Field>
-
- <Field orientation="horizontal">
- <Controller
- name="storefront_visible"
- control={form.control}
- render={({ field }) => (
- <Switch
- id="storefront_visible"
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- )}
- />
- <FieldLabel htmlFor="storefront_visible">Visible on storefront</FieldLabel>
+ <Field>
+ <div className="flex items-start justify-between gap-4">
+ <FieldLabel htmlFor="cfd-storefront-visible" className="cursor-pointer">
+ {t('admin.fields.custom_field_definition.storefront_visible.label')}
+ </FieldLabel>
+ <Controller
+ name="storefront_visible"
+ control={form.control}
+ render={({ field }) => (
+ <Switch
+ id="cfd-storefront-visible"
+ checked={!!field.value}
+ onCheckedChange={field.onChange}
+ />
+ )}
+ />
+ </div>
</Field>
</div>
)
@@ -162,18 +186,14 @@ export function DefinitionForm({
</Button>
)
- const handleSubmit = form.handleSubmit(onSubmit)
-
return (
<form
- onSubmit={(e) => {
- // The drawer is portaled out of the DOM but React bubbles synthetic
- // events through the React tree, so without this guard the outer
- // product form's onSubmit also fires. Hard-stop here.
- e.stopPropagation()
- handleSubmit(e)
- }}
+ onSubmit={form.handleSubmit(onSubmit)}
className="flex h-full flex-col"
+ // The drawer is portaled out of the DOM but React bubbles synthetic
+ // events through the React tree, so without this guard the outer
+ // product form's onSubmit also fires. Hard-stop here.
+ onSubmitCapture={(e) => e.stopPropagation()}
>
{renderShell({ fields, submitButton })}
</form>
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.tsx
index f7ca4ac9a1..60114e8946 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
@@ -1,9 +1,10 @@
import type { PaymentMethod, PreferenceField } from '@spree/admin-sdk'
import { Controller, type UseFormReturn } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
import { PreferencesForm } from '@/components/spree/preferences-form'
import { Slot } from '@/components/spree/slot'
import { StorefrontVisibleSwitch } from '@/components/spree/storefront-visible-switch'
-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import {
Select,
@@ -64,6 +65,7 @@ export function PaymentMethodForm({
onPreferencesChange,
onProviderTypeChange,
}: PaymentMethodFormProps) {
+ const { t } = useTranslation()
// Per-provider slot lookups. If a plugin has registered a `form` slot
// for this provider (e.g. Stripe OAuth Connect), we render that
// instead of the generic `<PreferencesForm>`. Guide/actions slots are
@@ -85,7 +87,7 @@ export function PaymentMethodForm({
<div className="flex flex-1 flex-col gap-4">
{mode === 'create' && (
<Field>
- <FieldLabel htmlFor="type">Provider</FieldLabel>
+ <FieldLabel htmlFor="type">{t('admin.fields.payment_method.type.label')}</FieldLabel>
<Controller
name="type"
control={form.control}
@@ -121,9 +123,7 @@ export function PaymentMethodForm({
</Select>
)}
/>
- {form.formState.errors.type && (
- <p className="text-sm text-destructive">{form.formState.errors.type.message}</p>
- )}
+ <FieldError errors={[form.formState.errors.type]} />
</Field>
)}
@@ -156,68 +156,70 @@ export function PaymentMethodForm({
}
function PaymentMethodTopFields({ form }: { form: UseFormReturn<PaymentMethodFormValues> }) {
+ const { t } = useTranslation()
+ const { errors } = form.formState
return (
<FieldGroup>
<Field>
- <FieldLabel htmlFor="name">Name</FieldLabel>
+ <FieldLabel htmlFor="pm-name">{t('admin.fields.name.label')}</FieldLabel>
<Input
- id="name"
- placeholder="e.g. Credit card (Stripe)"
+ id="pm-name"
+ placeholder={t('admin.fields.payment_method.name.placeholder')}
+ aria-invalid={!!errors.name || undefined}
{...form.register('name')}
- aria-invalid={!!form.formState.errors.name}
/>
- {form.formState.errors.name && (
- <p className="text-sm text-destructive">{form.formState.errors.name.message}</p>
- )}
+ <FieldError errors={[errors.name]} />
</Field>
-
<Field>
- <FieldLabel htmlFor="description">Description</FieldLabel>
+ <FieldLabel htmlFor="pm-description">{t('admin.fields.description.label')}</FieldLabel>
<Textarea
- id="description"
+ id="pm-description"
rows={2}
- placeholder="Customer-facing description shown at checkout"
+ placeholder={t('admin.fields.payment_method.description.placeholder')}
+ aria-invalid={!!errors.description || undefined}
{...form.register('description')}
/>
+ <FieldError errors={[errors.description]} />
</Field>
-
<StorefrontVisibleSwitch control={form.control} name="storefront_visible" />
-
<Field>
<div className="flex items-start justify-between gap-4">
<div className="flex flex-col">
- <FieldLabel htmlFor="active" className="cursor-pointer">
- Active
+ <FieldLabel htmlFor="pm-active" className="cursor-pointer">
+ {t('admin.fields.payment_method.active.label')}
</FieldLabel>
<span className="text-xs text-muted-foreground">
- Inactive methods are hidden from checkout.
+ {t('admin.fields.payment_method.active.help')}
</span>
</div>
<Controller
name="active"
control={form.control}
render={({ field }) => (
- <Switch id="active" checked={!!field.value} onCheckedChange={field.onChange} />
+ <Switch id="pm-active" checked={!!field.value} onCheckedChange={field.onChange} />
)}
/>
</div>
</Field>
-
<Field>
<div className="flex items-start justify-between gap-4">
<div className="flex flex-col">
- <FieldLabel htmlFor="auto_capture" className="cursor-pointer">
- Auto-capture
+ <FieldLabel htmlFor="pm-auto-capture" className="cursor-pointer">
+ {t('admin.fields.payment_method.auto_capture.label')}
</FieldLabel>
<span className="text-xs text-muted-foreground">
- Capture funds automatically on authorization. When off, you must capture manually.
+ {t('admin.fields.payment_method.auto_capture.help')}
</span>
</div>
<Controller
name="auto_capture"
control={form.control}
render={({ field }) => (
- <Switch id="auto_capture" checked={!!field.value} onCheckedChange={field.onChange} />
+ <Switch
+ id="pm-auto-capture"
+ checked={!!field.value}
+ onCheckedChange={field.onChange}
+ />
)}
/>
</div>
diff --git a/packages/admin/src/components/spree/preferences-form.tsx b/packages/admin/src/components/spree/preferences-form.tsx
index db153e0fbd..faf413ed38 100644
--- a/packages/admin/src/components/spree/preferences-form.tsx
+++ b/packages/admin/src/components/spree/preferences-form.tsx
@@ -16,13 +16,23 @@ import { Textarea } from '@/components/ui/textarea'
*
* `:password` fields are always skipped — the server returns their
* defaults as `null`, and even when it doesn't, autofilling a password
- * field is hostile UX.
+ * field is hostile UX. `contextDefaults` fills schema-declared keys whose
+ * own default is null/undefined — used by callers that know about runtime
+ * context the schema can't express (e.g. the store's default currency).
*/
-export function defaultPreferences(schema: PreferenceFieldDef[]): Record<string, unknown> {
+export function defaultPreferences(
+ schema: PreferenceFieldDef[],
+ contextDefaults: Record<string, unknown> = {},
+): Record<string, unknown> {
const out: Record<string, unknown> = {}
for (const field of schema) {
if (field.type === 'password') continue
- if (field.default !== null && field.default !== undefined) out[field.key] = field.default
+ if (field.default !== null && field.default !== undefined) {
+ out[field.key] = field.default
+ continue
+ }
+ const ctx = contextDefaults[field.key]
+ if (ctx !== undefined && ctx !== null && ctx !== '') out[field.key] = ctx
}
return out
}
@@ -104,7 +114,7 @@ export function PreferenceField({
return (
<Field>
<FieldLabel htmlFor={id}>{displayLabel}</FieldLabel>
- <CurrencySelect id={id} value={(value as string) || undefined} onChange={onChange} />
+ <CurrencySelect id={id} value={(value as string) || ''} onChange={onChange} />
</Field>
)
}
diff --git a/packages/admin/src/components/spree/promotion-editors/promotion-form.tsx b/packages/admin/src/components/spree/promotion-editors/promotion-form.tsx
index 66fe658b83..5ae1048c2b 100644
--- a/packages/admin/src/components/spree/promotion-editors/promotion-form.tsx
+++ b/packages/admin/src/components/spree/promotion-editors/promotion-form.tsx
@@ -1,3 +1,4 @@
+import { zodResolver } from '@hookform/resolvers/zod'
import type {
Customer,
Promotion,
@@ -7,15 +8,17 @@ import type {
PromotionRuleDraft,
ResourceTypeDefinition,
} from '@spree/admin-sdk'
-import { DownloadIcon, PlusIcon, TrashIcon } from 'lucide-react'
+import { DownloadIcon, PlusIcon, SparklesIcon, TrashIcon } from 'lucide-react'
import { useEffect, useState } from 'react'
-import { Controller, useFieldArray, useForm } from 'react-hook-form'
+import { Controller, type UseFormReturn, useFieldArray, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
import { formatCalculatorSummary } from '@/components/spree/calculator-summary'
import { Can } from '@/components/spree/can'
import { useConfirm } from '@/components/spree/confirm-dialog'
import { PageHeader } from '@/components/spree/page-header'
import { PreferencesForm } from '@/components/spree/preferences-form'
import { EditorShell } from '@/components/spree/promotion-editors/editor-shell'
+import { StoreDatePicker } from '@/components/spree/store-date-picker'
import '@/components/spree/promotion-editors/register'
import {
actionDraftFromAction,
@@ -33,7 +36,6 @@ import {
} from '@/components/spree/promotion-editors/types'
import { ResourceLayout } from '@/components/spree/resource-layout'
import { Slot } from '@/components/spree/slot'
-import { StoreDatePicker } from '@/components/spree/store-date-picker'
import { ActiveBadge, Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
@@ -45,7 +47,7 @@ import {
TableHeader,
TableRow,
} from '@/components/ui/data-table'
-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import {
Select,
@@ -70,15 +72,23 @@ import {
usePromotionCouponCodes,
usePromotionRuleTypes,
} from '@/hooks/use-promotions'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
import { Subject } from '@/lib/permissions'
+import { useStore } from '@/providers/store-provider'
+import {
+ KIND_OPTIONS,
+ MATCH_POLICY_OPTIONS,
+ type MatchPolicy,
+ PROMOTION_DEFAULTS,
+ type PromotionFormValues,
+ type PromotionKind,
+ promotionFormSchema,
+} from '@/schemas/promotion'
// =============================================================================
// Types
// =============================================================================
-type PromotionKind = 'coupon_code' | 'automatic'
-type MatchPolicy = 'all' | 'any'
-
/**
* Form values for the unified promotion form. Both create and edit use the
* same shape; the create page sends the full set on POST, the edit page
@@ -89,21 +99,7 @@ type MatchPolicy = 'all' | 'any'
* accept changes to them after creation — see `permitted_params` in
* Spree::Api::V3::Admin::PromotionsController).
*/
-export interface PromotionFormValues {
- name: string
- description: string
- kind: PromotionKind
- code: string
- multi_codes: boolean
- number_of_codes: number | undefined
- code_prefix: string
- starts_at: string
- expires_at: string
- usage_limit: number | undefined
- match_policy: MatchPolicy
- rules: PromotionRuleFormDraft[]
- actions: PromotionActionFormDraft[]
-}
+export type { PromotionFormValues } from '@/schemas/promotion'
export interface PromotionFormPayload {
name: string
@@ -138,32 +134,6 @@ interface PromotionFormProps {
deletePending?: boolean
}
-const KIND_OPTIONS = [
- { value: 'coupon_code', label: 'Coupon code' },
- { value: 'automatic', label: 'Automatic (no code)' },
-] as const
-
-const MATCH_POLICY_OPTIONS = [
- { value: 'all', label: 'All rules must match' },
- { value: 'any', label: 'Any rule may match' },
-] as const
-
-const CREATE_DEFAULTS: PromotionFormValues = {
- name: '',
- description: '',
- kind: 'coupon_code',
- code: '',
- multi_codes: false,
- number_of_codes: undefined,
- code_prefix: '',
- starts_at: '',
- expires_at: '',
- usage_limit: undefined,
- match_policy: 'all',
- rules: [],
- actions: [],
-}
-
// =============================================================================
// Root component
// =============================================================================
@@ -177,7 +147,11 @@ export function PromotionForm({
onDelete,
deletePending = false,
}: PromotionFormProps) {
- const form = useForm<PromotionFormValues>({ defaultValues: CREATE_DEFAULTS })
+ const form = useForm<PromotionFormValues>({
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ resolver: zodResolver(promotionFormSchema) as any,
+ defaultValues: PROMOTION_DEFAULTS,
+ })
const rulesArray = useFieldArray({ control: form.control, name: 'rules', keyName: '_key' })
const actionsArray = useFieldArray({ control: form.control, name: 'actions', keyName: '_key' })
@@ -219,7 +193,11 @@ export function PromotionForm({
if (mode === 'create') {
Object.assign(payload, couponFieldsForKind(values))
}
- await onSubmit(payload)
+ try {
+ await onSubmit(payload)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
const isLoading = mode === 'edit' && (!promotion || !initialRules || !initialActions)
@@ -276,6 +254,14 @@ export function PromotionForm({
}
main={
<>
+ {form.formState.errors.root?.message && (
+ <p
+ className="rounded-md bg-destructive/10 px-3 py-2 text-sm text-destructive"
+ role="alert"
+ >
+ {form.formState.errors.root.message}
+ </p>
+ )}
<RulesCard
form={form}
rulesArray={rulesArray}
@@ -300,8 +286,9 @@ export function PromotionForm({
// Sidebar cards
// =============================================================================
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function BasicsCard({ form }: { form: any }) {
+function BasicsCard({ form }: { form: UseFormReturn<PromotionFormValues> }) {
+ const { t } = useTranslation()
+ const { errors } = form.formState
return (
<Card>
<CardHeader>
@@ -310,22 +297,27 @@ function BasicsCard({ form }: { form: any }) {
<CardContent>
<FieldGroup>
<Field>
- <FieldLabel htmlFor="name">Name</FieldLabel>
+ <FieldLabel htmlFor="promo-name">{t('admin.fields.name.label')}</FieldLabel>
<Input
- id="name"
- placeholder="Summer Sale"
- {...form.register('name', { required: true })}
- aria-invalid={!!form.formState.errors.name}
+ id="promo-name"
+ placeholder={t('admin.fields.promotion.name.placeholder')}
+ aria-invalid={!!errors.name || undefined}
+ {...form.register('name')}
/>
+ <FieldError errors={[errors.name]} />
</Field>
<Field>
- <FieldLabel htmlFor="description">Description</FieldLabel>
+ <FieldLabel htmlFor="promo-description">
+ {t('admin.fields.description.label')}
+ </FieldLabel>
<Textarea
- id="description"
+ id="promo-description"
rows={3}
- placeholder="Internal description (optional)"
+ placeholder={t('admin.fields.promotion.description.placeholder')}
+ aria-invalid={!!errors.description || undefined}
{...form.register('description')}
/>
+ <FieldError errors={[errors.description]} />
</Field>
</FieldGroup>
</CardContent>
@@ -339,10 +331,11 @@ function TriggerCard({
promotion,
}: {
mode: 'create' | 'edit'
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- form: any
+ form: UseFormReturn<PromotionFormValues>
promotion?: Promotion
}) {
+ const { t } = useTranslation()
+ const { errors } = form.formState
const kind = form.watch('kind')
const multiCodes = form.watch('multi_codes')
@@ -357,13 +350,17 @@ function TriggerCard({
) : (
<FieldGroup>
<Field>
- <FieldLabel htmlFor="kind">How is this promotion applied?</FieldLabel>
+ <FieldLabel htmlFor="promo-kind">{t('admin.fields.promotion.kind.label')}</FieldLabel>
<Controller
name="kind"
control={form.control}
render={({ field }) => (
- <Select items={KIND_OPTIONS} value={field.value} onValueChange={field.onChange}>
- <SelectTrigger id="kind">
+ <Select
+ items={KIND_OPTIONS as never}
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger id="promo-kind">
<SelectValue />
</SelectTrigger>
<SelectContent>
@@ -383,11 +380,11 @@ function TriggerCard({
<Field>
<div className="flex items-start justify-between gap-4">
<div className="flex flex-col">
- <FieldLabel htmlFor="multi_codes" className="cursor-pointer">
- Generate a batch of unique codes
+ <FieldLabel htmlFor="promo-multi-codes" className="cursor-pointer">
+ {t('admin.fields.promotion.multi_codes.label')}
</FieldLabel>
<span className="text-xs text-muted-foreground">
- Useful for one-time-use codes — each customer redeems a different code.
+ {t('admin.fields.promotion.multi_codes.help')}
</span>
</div>
<Controller
@@ -395,7 +392,7 @@ function TriggerCard({
control={form.control}
render={({ field }) => (
<Switch
- id="multi_codes"
+ id="promo-multi-codes"
checked={!!field.value}
onCheckedChange={field.onChange}
/>
@@ -406,27 +403,62 @@ function TriggerCard({
{!multiCodes ? (
<Field>
- <FieldLabel htmlFor="code">Code</FieldLabel>
- <Input id="code" placeholder="SUMMER2026" {...form.register('code')} />
+ <FieldLabel htmlFor="promo-code">{t('admin.fields.code.label')}</FieldLabel>
+ <div className="flex items-center gap-2">
+ <Input
+ id="promo-code"
+ placeholder={t('admin.fields.promotion.code.placeholder')}
+ aria-invalid={!!errors.code || undefined}
+ {...form.register('code')}
+ />
+ <Button
+ type="button"
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ // Clear any "required" error left from a prior submit so the field
+ // doesn't stay red after we fill it in.
+ form.setValue('code', randomCouponCode(), { shouldDirty: true })
+ form.clearErrors('code')
+ }}
+ title="Generate a random code"
+ >
+ <SparklesIcon className="size-4" />
+ Generate
+ </Button>
+ </div>
+ <FieldError errors={[errors.code]} />
</Field>
) : (
<>
<Field>
- <FieldLabel htmlFor="number_of_codes">Number of codes</FieldLabel>
+ <FieldLabel htmlFor="promo-number-of-codes">
+ {t('admin.fields.promotion.number_of_codes.label')}
+ </FieldLabel>
<Input
- id="number_of_codes"
+ id="promo-number-of-codes"
type="number"
min={1}
- placeholder="100"
+ placeholder={t('admin.fields.promotion.number_of_codes.placeholder')}
+ aria-invalid={!!errors.number_of_codes || undefined}
{...form.register('number_of_codes')}
/>
+ <FieldError errors={[errors.number_of_codes]} />
</Field>
<Field>
- <FieldLabel htmlFor="code_prefix">Code prefix (optional)</FieldLabel>
- <Input id="code_prefix" placeholder="VIP" {...form.register('code_prefix')} />
- <span className="text-xs text-muted-foreground">
- Each generated code will start with this prefix.
- </span>
+ <FieldLabel htmlFor="promo-code-prefix">
+ {t('admin.fields.promotion.code_prefix.label')}
+ </FieldLabel>
+ <Input
+ id="promo-code-prefix"
+ placeholder={t('admin.fields.promotion.code_prefix.placeholder')}
+ aria-invalid={!!errors.code_prefix || undefined}
+ {...form.register('code_prefix')}
+ />
+ <p className="text-xs text-muted-foreground">
+ {t('admin.fields.promotion.code_prefix.help')}
+ </p>
+ <FieldError errors={[errors.code_prefix]} />
</Field>
</>
)}
@@ -466,7 +498,9 @@ function ReadOnlyTriggerSummary({ promotion }: { promotion: Promotion }) {
) : (
<div>
Single coupon code:{' '}
- <code className="rounded bg-muted px-1 py-0.5 text-xs">{promotion.code ?? '—'}</code>
+ <code className="rounded bg-muted px-1 py-0.5 text-xs">
+ {promotion.code?.toUpperCase() || '—'}
+ </code>
</div>
)}
<p className="text-xs text-muted-foreground">
@@ -476,8 +510,9 @@ function ReadOnlyTriggerSummary({ promotion }: { promotion: Promotion }) {
)
}
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-function ScheduleCard({ form }: { form: any }) {
+function ScheduleCard({ form }: { form: UseFormReturn<PromotionFormValues> }) {
+ const { t } = useTranslation()
+ const { errors } = form.formState
return (
<Card>
<CardHeader>
@@ -486,44 +521,48 @@ function ScheduleCard({ form }: { form: any }) {
<CardContent>
<FieldGroup>
<Field>
- <FieldLabel>Starts</FieldLabel>
+ <FieldLabel htmlFor="promo-starts-at">{t('admin.fields.starts_at.label')}</FieldLabel>
<Controller
name="starts_at"
control={form.control}
render={({ field }) => (
<StoreDatePicker
value={field.value || null}
- onChange={(v) => field.onChange(v ?? '')}
- placeholder="No start date"
+ onChange={(next) => field.onChange(next ?? '')}
+ placeholder={t('admin.fields.promotion.starts_at.placeholder')}
includeTime
/>
)}
/>
</Field>
<Field>
- <FieldLabel>Expires</FieldLabel>
+ <FieldLabel htmlFor="promo-expires-at">{t('admin.fields.expires_at.label')}</FieldLabel>
<Controller
name="expires_at"
control={form.control}
render={({ field }) => (
<StoreDatePicker
value={field.value || null}
- onChange={(v) => field.onChange(v ?? '')}
- placeholder="No expiry"
+ onChange={(next) => field.onChange(next ?? '')}
+ placeholder={t('admin.fields.promotion.expires_at.placeholder')}
includeTime
/>
)}
/>
</Field>
<Field>
- <FieldLabel htmlFor="usage_limit">Usage limit</FieldLabel>
+ <FieldLabel htmlFor="promo-usage-limit">
+ {t('admin.fields.promotion.usage_limit.label')}
+ </FieldLabel>
<Input
- id="usage_limit"
+ id="promo-usage-limit"
type="number"
min={1}
- placeholder="Unlimited"
+ placeholder={t('admin.fields.promotion.usage_limit.placeholder')}
+ aria-invalid={!!errors.usage_limit || undefined}
{...form.register('usage_limit')}
/>
+ <FieldError errors={[errors.usage_limit]} />
</Field>
</FieldGroup>
</CardContent>
@@ -549,6 +588,7 @@ function RulesCard({
matchPolicy: MatchPolicy
}) {
const { data: typesData } = usePromotionRuleTypes()
+ const { defaultCurrency } = useStore()
const [pickerOpen, setPickerOpen] = useState(false)
const [editingIndex, setEditingIndex] = useState<number | null>(null)
@@ -632,7 +672,7 @@ function RulesCard({
open
onOpenChange={(o) => !o && setPickerOpen(false)}
onPicked={(type) => {
- const draft = ruleDraftFromType(type)
+ const draft = ruleDraftFromType(type, { currency: defaultCurrency })
rulesArray.append(draft)
setPickerOpen(false)
setEditingIndex(rulesArray.fields.length)
@@ -922,6 +962,7 @@ function ActionsCard({
actionsArray: ActionsArray
}) {
const { data: typesData } = usePromotionActionTypes()
+ const { defaultCurrency } = useStore()
const [pickerOpen, setPickerOpen] = useState(false)
const [editingIndex, setEditingIndex] = useState<number | null>(null)
@@ -967,7 +1008,7 @@ function ActionsCard({
open
onOpenChange={(o) => !o && setPickerOpen(false)}
onPicked={(type) => {
- const draft = actionDraftFromType(type)
+ const draft = actionDraftFromType(type, { currency: defaultCurrency })
actionsArray.append(draft)
setPickerOpen(false)
setEditingIndex(actionsArray.fields.length)
@@ -1286,6 +1327,21 @@ function CouponCodesSheet({
// Helpers
// =============================================================================
+/**
+ * 8-char uppercase alphanumeric (digits + A–Z, excluding ambiguous 0/O/1/I/L).
+ * Mirrors `Spree::Promotion#random_code`'s rough alphabet — but generated
+ * client-side so the merchant sees what they're about to save before they
+ * click Create.
+ */
+function randomCouponCode(): string {
+ const alphabet = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789'
+ const bytes = new Uint32Array(8)
+ crypto.getRandomValues(bytes)
+ let out = ''
+ for (const b of bytes) out += alphabet[b % alphabet.length]
+ return out
+}
+
/**
* Server expects a coherent trigger set: automatic clears all coupon
* fields, single-code sets `code`, multi-code sets `number_of_codes` +
diff --git a/packages/admin/src/components/spree/promotion-editors/rule-category.tsx b/packages/admin/src/components/spree/promotion-editors/rule-category.tsx
index b70101bb93..8eaddd79fb 100644
--- a/packages/admin/src/components/spree/promotion-editors/rule-category.tsx
+++ b/packages/admin/src/components/spree/promotion-editors/rule-category.tsx
@@ -1,25 +1,15 @@
import type { Category } from '@spree/admin-sdk'
-import { useState } from 'react'
+import { useMemo, useState } from 'react'
import { adminClient } from '@/client'
import { ResourceMultiAutocomplete } from '@/components/spree/resource-multi-autocomplete'
import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { useTranslation } from '@/lib/i18n'
import { EditorShell } from './editor-shell'
import { MatchPolicyPicker } from './match-policy-picker'
import type { PromotionRuleEditorContext } from './types'
type MatchPolicy = 'any' | 'all'
-const MATCH_POLICIES: readonly { value: MatchPolicy; label: string; description: string }[] = [
- {
- value: 'any',
- label: 'Any of these categories',
- description: 'Order must contain a product in at least one.',
- },
- {
- value: 'all',
- label: 'All of these categories',
- description: 'Order must contain a product in every category.',
- },
-]
+const MATCH_POLICY_VALUES: readonly MatchPolicy[] = ['any', 'all']
/**
* Surfaced as "Category(ies)" per the 6.0 Taxon→Category rename.
@@ -27,10 +17,21 @@ const MATCH_POLICIES: readonly { value: MatchPolicy; label: string; description:
* ships; descendant categories match implicitly server-side.
*/
export function CategoryRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {
+ const { t } = useTranslation()
+ const matchPolicies = useMemo(
+ () =>
+ MATCH_POLICY_VALUES.map((value) => ({
+ value,
+ label: t(`admin.promotions.rules.category.match_policy.${value}.label`),
+ description: t(`admin.promotions.rules.category.match_policy.${value}.description`),
+ })),
+ [t],
+ )
+
const initialMatchPolicy = ((draft.preferences?.match_policy as MatchPolicy) ??
'any') as MatchPolicy
const [matchPolicy, setMatchPolicy] = useState<MatchPolicy>(
- MATCH_POLICIES.some((p) => p.value === initialMatchPolicy) ? initialMatchPolicy : 'any',
+ MATCH_POLICY_VALUES.includes(initialMatchPolicy) ? initialMatchPolicy : 'any',
)
const [categoryIds, setCategoryIds] = useState<string[]>(draft.category_ids ?? [])
const [categories, setCategories] = useState<Category[]>(draft.categories ?? [])
@@ -47,11 +48,11 @@ export function CategoryRuleEditor({ draft, onSave, onClose }: PromotionRuleEdit
return (
<EditorShell onSave={handleSave} onCancel={onClose} pending={false}>
- <MatchPolicyPicker policies={MATCH_POLICIES} value={matchPolicy} onChange={setMatchPolicy} />
+ <MatchPolicyPicker policies={matchPolicies} value={matchPolicy} onChange={setMatchPolicy} />
<FieldGroup>
<Field>
- <FieldLabel>Categories</FieldLabel>
+ <FieldLabel>{t('admin.promotions.rules.category.label')}</FieldLabel>
<ResourceMultiAutocomplete
queryKey="promotion-rule-categories"
value={categoryIds}
@@ -62,8 +63,8 @@ export function CategoryRuleEditor({ draft, onSave, onClose }: PromotionRuleEdit
}
hydrate={(ids) => adminClient.categories.list({ id_in: ids, limit: ids.length })}
getOptionLabel={(c) => c.pretty_name ?? c.name ?? c.id}
- placeholder="Search categories…"
- emptyText="No categories match"
+ placeholder={t('admin.promotions.rules.category.search_placeholder')}
+ emptyText={t('admin.promotions.rules.category.empty')}
/>
</Field>
</FieldGroup>
diff --git a/packages/admin/src/components/spree/promotion-editors/rule-customer-group.tsx b/packages/admin/src/components/spree/promotion-editors/rule-customer-group.tsx
index c1d9a644a1..7df4011e9a 100644
--- a/packages/admin/src/components/spree/promotion-editors/rule-customer-group.tsx
+++ b/packages/admin/src/components/spree/promotion-editors/rule-customer-group.tsx
@@ -3,10 +3,12 @@ import { useState } from 'react'
import { ResourceMultiAutocomplete } from '@/components/spree/resource-multi-autocomplete'
import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
import { customerGroupAutocompleteProps } from '@/hooks/use-customer-groups'
+import { useTranslation } from '@/lib/i18n'
import { EditorShell } from './editor-shell'
import type { PromotionRuleEditorContext } from './types'
export function CustomerGroupRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {
+ const { t } = useTranslation()
const [groupIds, setGroupIds] = useState<string[]>(
() => (draft.preferences?.customer_group_ids ?? []) as string[],
)
@@ -25,12 +27,14 @@ export function CustomerGroupRuleEditor({ draft, onSave, onClose }: PromotionRul
<EditorShell onSave={handleSave} onCancel={onClose} pending={false}>
<FieldGroup>
<Field>
- <FieldLabel>Customer groups</FieldLabel>
+ <FieldLabel>{t('admin.promotions.rules.customer_group.label')}</FieldLabel>
<ResourceMultiAutocomplete
{...customerGroupAutocompleteProps('promotion-rule-customer-groups')}
value={groupIds}
onChange={setGroupIds}
onResolvedOptionsChange={setCustomerGroups}
+ placeholder={t('admin.promotions.rules.customer_group.search_placeholder')}
+ emptyText={t('admin.promotions.rules.customer_group.empty')}
/>
</Field>
</FieldGroup>
diff --git a/packages/admin/src/components/spree/promotion-editors/rule-product.tsx b/packages/admin/src/components/spree/promotion-editors/rule-product.tsx
index c3907f13d3..46a1e60159 100644
--- a/packages/admin/src/components/spree/promotion-editors/rule-product.tsx
+++ b/packages/admin/src/components/spree/promotion-editors/rule-product.tsx
@@ -1,32 +1,32 @@
import type { Product } from '@spree/admin-sdk'
-import { useState } from 'react'
+import { useMemo, useState } from 'react'
import { adminClient } from '@/client'
import { ResourceMultiAutocomplete } from '@/components/spree/resource-multi-autocomplete'
import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { useTranslation } from '@/lib/i18n'
import { EditorShell } from './editor-shell'
import { MatchPolicyPicker } from './match-policy-picker'
import type { PromotionRuleEditorContext } from './types'
type MatchPolicy = 'any' | 'all' | 'none'
-const MATCH_POLICIES: readonly { value: MatchPolicy; label: string; description: string }[] = [
- { value: 'any', label: 'Any of these products', description: 'Order must contain at least one.' },
- {
- value: 'all',
- label: 'All of these products',
- description: 'Order must contain every product.',
- },
- {
- value: 'none',
- label: 'None of these products',
- description: 'Order must not contain any of them.',
- },
-]
+const MATCH_POLICY_VALUES: readonly MatchPolicy[] = ['any', 'all', 'none']
export function ProductRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {
+ const { t } = useTranslation()
+ const matchPolicies = useMemo(
+ () =>
+ MATCH_POLICY_VALUES.map((value) => ({
+ value,
+ label: t(`admin.promotions.rules.product.match_policy.${value}.label`),
+ description: t(`admin.promotions.rules.product.match_policy.${value}.description`),
+ })),
+ [t],
+ )
+
const initialMatchPolicy = ((draft.preferences?.match_policy as MatchPolicy) ??
'any') as MatchPolicy
const [matchPolicy, setMatchPolicy] = useState<MatchPolicy>(
- MATCH_POLICIES.some((p) => p.value === initialMatchPolicy) ? initialMatchPolicy : 'any',
+ MATCH_POLICY_VALUES.includes(initialMatchPolicy) ? initialMatchPolicy : 'any',
)
const [productIds, setProductIds] = useState<string[]>(draft.product_ids ?? [])
const [products, setProducts] = useState<Product[]>(draft.products ?? [])
@@ -43,11 +43,11 @@ export function ProductRuleEditor({ draft, onSave, onClose }: PromotionRuleEdito
return (
<EditorShell onSave={handleSave} onCancel={onClose} pending={false}>
- <MatchPolicyPicker policies={MATCH_POLICIES} value={matchPolicy} onChange={setMatchPolicy} />
+ <MatchPolicyPicker policies={matchPolicies} value={matchPolicy} onChange={setMatchPolicy} />
<FieldGroup>
<Field>
- <FieldLabel>Products</FieldLabel>
+ <FieldLabel>{t('admin.promotions.rules.product.label')}</FieldLabel>
<ResourceMultiAutocomplete
queryKey="promotion-rule-products"
value={productIds}
@@ -56,8 +56,8 @@ export function ProductRuleEditor({ draft, onSave, onClose }: PromotionRuleEdito
search={(q) => adminClient.products.list({ name_cont: q, limit: 10, sort: 'name' })}
hydrate={(ids) => adminClient.products.list({ id_in: ids, limit: ids.length })}
getOptionLabel={(p) => p.name ?? p.id}
- placeholder="Search products by name…"
- emptyText="No products match"
+ placeholder={t('admin.promotions.rules.product.search_placeholder')}
+ emptyText={t('admin.promotions.rules.product.empty')}
/>
</Field>
</FieldGroup>
diff --git a/packages/admin/src/components/spree/promotion-editors/rule-user.tsx b/packages/admin/src/components/spree/promotion-editors/rule-user.tsx
index 6bd753f768..35870f018a 100644
--- a/packages/admin/src/components/spree/promotion-editors/rule-user.tsx
+++ b/packages/admin/src/components/spree/promotion-editors/rule-user.tsx
@@ -3,10 +3,12 @@ import { useState } from 'react'
import { adminClient } from '@/client'
import { ResourceMultiAutocomplete } from '@/components/spree/resource-multi-autocomplete'
import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { useTranslation } from '@/lib/i18n'
import { EditorShell } from './editor-shell'
import type { PromotionRuleEditorContext } from './types'
export function UserRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorContext) {
+ const { t } = useTranslation()
const [customerIds, setCustomerIds] = useState<string[]>(draft.customer_ids ?? [])
const [customers, setCustomers] = useState<Customer[]>(draft.customers ?? [])
@@ -19,7 +21,7 @@ export function UserRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorCo
<EditorShell onSave={handleSave} onCancel={onClose} pending={false}>
<FieldGroup>
<Field>
- <FieldLabel>Customers</FieldLabel>
+ <FieldLabel>{t('admin.promotions.rules.customer.label')}</FieldLabel>
<ResourceMultiAutocomplete
queryKey="promotion-rule-customers"
value={customerIds}
@@ -28,8 +30,8 @@ export function UserRuleEditor({ draft, onSave, onClose }: PromotionRuleEditorCo
search={(q) => adminClient.customers.list({ search: q, limit: 10 })}
hydrate={(ids) => adminClient.customers.list({ id_in: ids, limit: ids.length })}
getOptionLabel={(c) => c.full_name || c.email || c.id}
- placeholder="Search customers by name or email…"
- emptyText="No customers match"
+ placeholder={t('admin.promotions.rules.customer.search_placeholder')}
+ emptyText={t('admin.promotions.rules.customer.empty')}
/>
</Field>
</FieldGroup>
diff --git a/packages/admin/src/components/spree/promotion-editors/types.ts b/packages/admin/src/components/spree/promotion-editors/types.ts
index 532c46ef5b..33c626ef22 100644
--- a/packages/admin/src/components/spree/promotion-editors/types.ts
+++ b/packages/admin/src/components/spree/promotion-editors/types.ts
@@ -130,32 +130,42 @@ export function newLocalId(): string {
* Builds a fresh draft from a registry type definition (e.g. an entry
* returned by `/promotion_rules/types`). The `_localId` lets React
* track the row before the server assigns a real `id`.
+ *
+ * `contextDefaults` lets the picker inject runtime defaults the schema
+ * can't express on its own (e.g. the store's `defaultCurrency` for
+ * `:currency`-typed prefs). Schema defaults still take precedence.
*/
-export function ruleDraftFromType(type: {
- type: string
- label: string
- preference_schema: PreferenceField[]
-}): PromotionRuleFormDraft {
+export function ruleDraftFromType(
+ type: {
+ type: string
+ label: string
+ preference_schema: PreferenceField[]
+ },
+ contextDefaults: Record<string, unknown> = {},
+): PromotionRuleFormDraft {
return {
_localId: newLocalId(),
type: type.type,
label: type.label,
preference_schema: type.preference_schema,
- preferences: defaultPreferences(type.preference_schema),
+ preferences: defaultPreferences(type.preference_schema, contextDefaults),
}
}
-export function actionDraftFromType(type: {
- type: string
- label: string
- preference_schema: PreferenceField[]
-}): PromotionActionFormDraft {
+export function actionDraftFromType(
+ type: {
+ type: string
+ label: string
+ preference_schema: PreferenceField[]
+ },
+ contextDefaults: Record<string, unknown> = {},
+): PromotionActionFormDraft {
return {
_localId: newLocalId(),
type: type.type,
label: type.label,
preference_schema: type.preference_schema,
- preferences: defaultPreferences(type.preference_schema),
+ preferences: defaultPreferences(type.preference_schema, contextDefaults),
}
}
diff --git a/packages/admin/src/hooks/use-resource-mutation.ts b/packages/admin/src/hooks/use-resource-mutation.ts
index 0b6c579d85..69ea433667 100644
--- a/packages/admin/src/hooks/use-resource-mutation.ts
+++ b/packages/admin/src/hooks/use-resource-mutation.ts
@@ -1,3 +1,4 @@
+import { SpreeError } from '@spree/admin-sdk'
import {
type QueryKey,
type UseMutationOptions,
@@ -12,7 +13,14 @@ interface UseResourceMutationOptions<TData, TError, TVariables>
invalidate?: QueryKey[]
/** Toast on success. Pass `false` to disable. Default `'Saved'`. */
successMessage?: string | false
- /** Toast on error. Pass `false` to disable. Default `'Something went wrong'`. */
+ /**
+ * Toast on error. Pass `false` to disable. Default `'Something went wrong'`.
+ *
+ * 422 validation errors never toast — callers that surface them inline via
+ * `mapSpreeErrorsToForm` would otherwise show the same problem twice. The
+ * toast is reserved for failures the form can't render (network, 5xx,
+ * auth, gateway).
+ */
errorMessage?: string | false
/** Forwarded onSuccess callback. Runs after invalidation + toast. */
onSuccess?: UseMutationOptions<TData, TError, TVariables>['onSuccess']
@@ -62,10 +70,17 @@ export function useResourceMutation<TData = unknown, TError = Error, TVariables
return onSuccess?.(data, variables, onMutateResult, ctx)
},
onError: (error, variables, onMutateResult, ctx) => {
- if (errorMessage !== false) {
+ if (errorMessage !== false && !isValidationError(error)) {
toast.error(errorMessage)
}
return onError?.(error, variables, onMutateResult, ctx)
},
})
}
+
+// 422 with `details` means the model rejected the payload (e.g., "Code can't
+// be blank"). The form renders these next to the offending input via
+// `mapSpreeErrorsToForm`, so toasting the same thing would just be noise.
+function isValidationError(error: unknown): boolean {
+ return error instanceof SpreeError && error.status === 422
+}
diff --git a/packages/admin/src/lib/form-errors.ts b/packages/admin/src/lib/form-errors.ts
new file mode 100644
index 0000000000..2f6c2d6841
--- /dev/null
+++ b/packages/admin/src/lib/form-errors.ts
@@ -0,0 +1,103 @@
+import { SpreeError } from '@spree/admin-sdk'
+import type { FieldValues, Path, UseFormSetError } from 'react-hook-form'
+
+/**
+ * Map a thrown error from a Spree Admin API mutation onto a react-hook-form
+ * instance. Two things happen on every call:
+ *
+ * 1. The server's top-level `error.message` (e.g. "Code can't be blank, Name
+ * can't be blank") is set on `formState.errors.root` so `<FormError>`
+ * always renders the full failure summary — even when individual fields
+ * aren't rendered (nested rules, useFieldArray rows, validations on
+ * associations).
+ * 2. Per-key entries from `error.details` are also set as per-field errors
+ * for any key that names a top-level flat attribute (`code`, `name`,
+ * `expires_at`). Nested or dotted keys (`promotion_rules.base`, `rules`
+ * on a useFieldArray, `line_items.0.quantity`) only contribute to the
+ * root summary — we don't pretend to know which of those have rendered
+ * inputs, and "silent" is the worst outcome.
+ *
+ * Return value:
+ * - `true` → the error was rendered into the form, the caller may suppress
+ * its toast
+ * - `false` → not a SpreeError (network / programming bug). Caller should
+ * log + toast as usual.
+ *
+ * Usage:
+ *
+ * ```ts
+ * const create = useCreateThing()
+ *
+ * async function onSubmit(values: FormValues) {
+ * try {
+ * await create.mutateAsync(values)
+ * onSuccess()
+ * } catch (err) {
+ * if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ * }
+ * }
+ * ```
+ *
+ * Server response shape (from `Spree::Api::V3::ErrorHandler#render_validation_error`):
+ *
+ * ```json
+ * { "error": {
+ * "code": "validation_error",
+ * "message": "Code can't be blank, Name can't be blank",
+ * "details": { "code": ["can't be blank"], "name": ["can't be blank"] }
+ * } }
+ * ```
+ *
+ * `details` keys are AR attribute names. `<form-field>.base` is AR's
+ * record-level errors collection on a nested association — we treat both
+ * the bare `base` key and any `*.base` key as record-level and route them
+ * to root.
+ */
+export function mapSpreeErrorsToForm<TFieldValues extends FieldValues>(
+ error: unknown,
+ setError: UseFormSetError<TFieldValues>,
+): boolean {
+ if (!(error instanceof SpreeError)) return false
+
+ const { details, message } = error
+
+ // Always seed the root error with the server's top-level message. Even
+ // when details exist, the top-level message is the readable summary —
+ // and it's the only place nested/association errors will reliably show.
+ if (message) {
+ setError('root' as Path<TFieldValues>, { type: 'server', message })
+ }
+
+ if (!details) return true
+
+ // Per-field errors. Each detail value is `string[]` (one Rails error per
+ // entry). Only top-level flat keys get set as per-field errors; nested
+ // keys (`promotion_rules.base`, `rules`, `line_items.0.x`) stay on root.
+ //
+ // We're conservative on purpose: there's no way to know at this layer
+ // whether a given path has a rendered input, so anything that smells
+ // nested or associative falls back to the root summary that we already
+ // set above. Silently dropping errors onto unrendered field paths is a
+ // worse failure mode than redundant root messages.
+ for (const [field, messages] of Object.entries(details)) {
+ if (!messages?.length) continue
+ if (!isRenderableFieldKey(field)) continue
+
+ setError(field as Path<TFieldValues>, {
+ type: 'server',
+ message: messages.join(', '),
+ })
+ }
+
+ return true
+}
+
+// `base` (bare) and `*.base` are AR's record-level errors. `*.<n>.*` is an
+// association/collection index path. Anything with `.` is too risky to set
+// as a top-level RHF path — it'd either create a phantom nested error or
+// silently miss a rendered field. Stick to flat snake_case keys.
+function isRenderableFieldKey(key: string): boolean {
+ if (key === 'base') return false
+ if (key.includes('.')) return false
+ return true
+}
diff --git a/packages/admin/src/main.tsx b/packages/admin/src/main.tsx
index da651d36e2..fc7e3cd8f7 100644
--- a/packages/admin/src/main.tsx
+++ b/packages/admin/src/main.tsx
@@ -4,6 +4,9 @@ import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { ConfirmProvider } from '@/components/spree/confirm-dialog'
import { TooltipProvider } from '@/components/ui/tooltip'
+// Side-effect import: registers i18next with react-i18next before any component
+// calls useTranslation(). Must come before @/router.
+import '@/lib/i18n'
import { queryClient } from '@/lib/query-client'
import { AuthProvider } from '@/providers/auth-provider'
import { PermissionProvider } from '@/providers/permission-provider'
diff --git a/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx b/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx
index 9d080cd4db..7b09ec4f51 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/customers/$customerId.tsx
@@ -10,7 +10,9 @@ import {
StarIcon,
TrashIcon,
} from 'lucide-react'
-import { type FormEvent, type ReactNode, useState } from 'react'
+import { type ReactNode, 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'
@@ -41,7 +43,7 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import {
Select,
@@ -62,6 +64,7 @@ import { Textarea } from '@/components/ui/textarea'
import { useAuth } from '@/hooks/use-auth'
import { useCountries } from '@/hooks/use-countries'
import { useStoreCreditCategories } from '@/hooks/use-store-credit-categories'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
export const Route = createFileRoute('/_authenticated/$storeId/customers/$customerId')({
component: CustomerDetailPage,
@@ -229,6 +232,15 @@ 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,
@@ -238,26 +250,29 @@ function EditProfileSheet({
open: boolean
onOpenChange: (open: boolean) => void
}) {
- const [tags, setTags] = useState<string[]>(customer.tags ?? [])
- const mutation = useCustomerMutation(customer.id, (params: Record<string, unknown>) =>
- adminClient.customers.update(
- customer.id,
- params as Parameters<typeof adminClient.customers.update>[1],
- ),
+ const { t } = useTranslation()
+ const form = useForm<EditProfileFormValues>({
+ defaultValues: {
+ email: customer.email,
+ first_name: customer.first_name ?? '',
+ last_name: customer.last_name ?? '',
+ phone: customer.phone ?? '',
+ tags: customer.tags ?? [],
+ accepts_email_marketing: customer.accepts_email_marketing,
+ },
+ })
+ const { errors } = form.formState
+ const mutation = useCustomerMutation(customer.id, (params: EditProfileFormValues) =>
+ adminClient.customers.update(customer.id, params),
)
- function handleSubmit(e: FormEvent<HTMLFormElement>) {
- e.preventDefault()
- const fd = new FormData(e.currentTarget)
- const payload: Record<string, unknown> = {
- email: fd.get('email'),
- first_name: fd.get('first_name'),
- last_name: fd.get('last_name'),
- phone: fd.get('phone'),
- accepts_email_marketing: fd.get('accepts_email_marketing') === 'on',
- tags,
+ async function onSubmit(values: EditProfileFormValues) {
+ try {
+ await mutation.mutateAsync(values)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
}
- mutation.mutate(payload, { onSuccess: () => onOpenChange(false) })
}
return (
@@ -267,47 +282,86 @@ function EditProfileSheet({
<SheetTitle>Edit Customer</SheetTitle>
<SheetDescription>Update the customer's profile information.</SheetDescription>
</SheetHeader>
- <form onSubmit={handleSubmit} className="flex min-h-0 flex-1 flex-col">
+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
<div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
<FieldGroup>
<Field>
- <FieldLabel htmlFor="email">Email</FieldLabel>
+ <FieldLabel htmlFor="cust-email">{t('admin.fields.email.label')}</FieldLabel>
<Input
- id="email"
- name="email"
+ id="cust-email"
type="email"
- defaultValue={customer.email}
- required
+ aria-invalid={!!errors.email || undefined}
+ {...form.register('email')}
/>
+ <FieldError errors={[errors.email]} />
</Field>
<Field>
- <FieldLabel htmlFor="first_name">First name</FieldLabel>
- <Input id="first_name" name="first_name" defaultValue={customer.first_name ?? ''} />
+ <FieldLabel htmlFor="cust-first-name">
+ {t('admin.fields.first_name.label')}
+ </FieldLabel>
+ <Input
+ id="cust-first-name"
+ aria-invalid={!!errors.first_name || undefined}
+ {...form.register('first_name')}
+ />
+ <FieldError errors={[errors.first_name]} />
</Field>
<Field>
- <FieldLabel htmlFor="last_name">Last name</FieldLabel>
- <Input id="last_name" name="last_name" defaultValue={customer.last_name ?? ''} />
+ <FieldLabel htmlFor="cust-last-name">
+ {t('admin.fields.last_name.label')}
+ </FieldLabel>
+ <Input
+ id="cust-last-name"
+ aria-invalid={!!errors.last_name || undefined}
+ {...form.register('last_name')}
+ />
+ <FieldError errors={[errors.last_name]} />
</Field>
<Field>
- <FieldLabel htmlFor="phone">Phone</FieldLabel>
- <Input id="phone" name="phone" defaultValue={customer.phone ?? ''} />
+ <FieldLabel htmlFor="cust-phone">{t('admin.fields.phone.label')}</FieldLabel>
+ <Input
+ id="cust-phone"
+ aria-invalid={!!errors.phone || undefined}
+ {...form.register('phone')}
+ />
+ <FieldError errors={[errors.phone]} />
</Field>
<Field>
- <FieldLabel>Tags</FieldLabel>
- <TagCombobox taggableType="Spree::User" value={tags} onChange={setTags} />
+ <FieldLabel>{t('admin.fields.customer.tags.label')}</FieldLabel>
+ <Controller
+ name="tags"
+ control={form.control}
+ render={({ field }) => (
+ <TagCombobox
+ taggableType="Spree::User"
+ value={field.value}
+ onChange={field.onChange}
+ />
+ )}
+ />
</Field>
<Field>
- <label
- htmlFor="accepts_email_marketing"
- className="flex items-center gap-2 text-sm"
- >
- <Checkbox
- id="accepts_email_marketing"
+ <div className="flex items-start justify-between gap-4">
+ <FieldLabel htmlFor="cust-marketing" className="cursor-pointer">
+ {t('admin.fields.customer.accepts_email_marketing.label')}
+ </FieldLabel>
+ <Controller
name="accepts_email_marketing"
- defaultChecked={customer.accepts_email_marketing}
+ control={form.control}
+ render={({ field }) => (
+ <Checkbox
+ id="cust-marketing"
+ checked={!!field.value}
+ onCheckedChange={field.onChange}
+ />
+ )}
/>
- Subscribed to marketing
- </label>
+ </div>
</Field>
</FieldGroup>
</div>
@@ -912,44 +966,45 @@ function StoreCreditsCard({ customer }: { customer: Customer }) {
// matching category's name from the dynamic options list.
function StoreCreditCategorySelect({
id,
- name,
- defaultValue,
+ value,
+ onChange,
required,
}: {
id: string
- name: string
- defaultValue?: string
+ value: string
+ onChange: (next: string) => void
required?: boolean
}) {
const { data, isLoading } = useStoreCreditCategories()
- const [value, setValue] = useState(defaultValue ?? '')
const categories = data?.data ?? []
return (
- <>
- {/* Hidden input keeps the FormData submit path working. */}
- <input type="hidden" name={name} value={value} />
- <Select value={value} onValueChange={setValue}>
- <SelectTrigger id={id} aria-required={required}>
- <SelectValue placeholder={isLoading ? 'Loading categories…' : 'Select a category'}>
- {(v) => {
- const category = categories.find((c) => c.id === v)
- return category ? category.name : (v as string)
- }}
- </SelectValue>
- </SelectTrigger>
- <SelectContent>
- {categories.map((c) => (
- <SelectItem key={c.id} value={c.id}>
- {c.name}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </>
+ <Select value={value} onValueChange={onChange}>
+ <SelectTrigger id={id} aria-required={required}>
+ <SelectValue placeholder={isLoading ? 'Loading categories…' : 'Select a category'}>
+ {(v) => {
+ const category = categories.find((c) => c.id === v)
+ return category ? category.name : (v as string)
+ }}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {categories.map((c) => (
+ <SelectItem key={c.id} value={c.id}>
+ {c.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
)
}
+interface EditStoreCreditFormValues {
+ amount: string
+ category_id: string
+ memo: string
+}
+
function EditStoreCreditDialog({
customerId,
credit,
@@ -959,33 +1014,45 @@ function EditStoreCreditDialog({
credit: StoreCredit
onOpenChange: (open: boolean) => void
}) {
+ const { t } = useTranslation()
// Server rejects amount changes once any of it has been used. Lock the
// field so the merchant doesn't submit a value that will only come back
// as a 422 store_credit_in_use.
const amountLocked = Number(credit.amount_used ?? 0) > 0
+ const form = useForm<EditStoreCreditFormValues>({
+ defaultValues: {
+ amount: credit.amount ?? '',
+ category_id: credit.category_id ?? '',
+ memo: credit.memo ?? '',
+ },
+ })
+ const { errors } = form.formState
+
const mutation = useCustomerMutation(
customerId,
(params: Parameters<typeof adminClient.customers.storeCredits.update>[2]) =>
adminClient.customers.storeCredits.update(customerId, credit.id, params),
)
- function handleSubmit(e: FormEvent<HTMLFormElement>) {
- e.preventDefault()
- const fd = new FormData(e.currentTarget)
+ async function onSubmit(values: EditStoreCreditFormValues) {
const params: Parameters<typeof adminClient.customers.storeCredits.update>[2] = {}
if (!amountLocked) {
- const amountValue = String(fd.get('amount') ?? '').trim()
+ const amountValue = values.amount.toString().trim()
if (amountValue) params.amount = Number(amountValue)
}
- const categoryId = String(fd.get('category_id') ?? '').trim()
- if (categoryId) params.category_id = categoryId
+ if (values.category_id.trim()) params.category_id = values.category_id
- params.memo = String(fd.get('memo') ?? '')
+ params.memo = values.memo
- mutation.mutate(params, { onSuccess: () => onOpenChange(false) })
+ try {
+ await mutation.mutateAsync(params)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
return (
@@ -999,20 +1066,28 @@ function EditStoreCreditDialog({
' The amount cannot be changed because some of it has already been used.'}
</DialogDescription>
</DialogHeader>
- <form onSubmit={handleSubmit}>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
<DialogBody>
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
<FieldGroup>
<div className="grid grid-cols-2 gap-3">
<Field>
- <FieldLabel htmlFor="edit-sc-amount">Amount</FieldLabel>
+ <FieldLabel htmlFor="edit-sc-amount">
+ {t('admin.fields.store_credit.amount.label')}
+ </FieldLabel>
<Input
id="edit-sc-amount"
- name="amount"
type="number"
step="0.01"
- defaultValue={credit.amount ?? ''}
disabled={amountLocked}
+ aria-invalid={!!errors.amount || undefined}
+ {...form.register('amount')}
/>
+ <FieldError errors={[errors.amount]} />
</Field>
<Field>
{/* Currency is locked: the API doesn't accept `currency`
@@ -1020,21 +1095,40 @@ function EditStoreCreditDialog({
would invalidate amount_used / amount_remaining). We
surface it disabled so the merchant always sees which
currency the credit is in. */}
- <FieldLabel htmlFor="edit-sc-currency">Currency</FieldLabel>
+ <FieldLabel htmlFor="edit-sc-currency">
+ {t('admin.fields.store_credit.currency.label')}
+ </FieldLabel>
<CurrencySelect id="edit-sc-currency" value={credit.currency} disabled />
</Field>
</div>
<Field>
- <FieldLabel htmlFor="edit-sc-category">Category</FieldLabel>
- <StoreCreditCategorySelect
- id="edit-sc-category"
+ <FieldLabel htmlFor="edit-sc-category">
+ {t('admin.fields.store_credit.category_id.label')}
+ </FieldLabel>
+ <Controller
name="category_id"
- defaultValue={credit.category_id ?? ''}
+ control={form.control}
+ render={({ field }) => (
+ <StoreCreditCategorySelect
+ id="edit-sc-category"
+ value={field.value}
+ onChange={field.onChange}
+ />
+ )}
/>
</Field>
<Field>
- <FieldLabel htmlFor="edit-sc-memo">Memo</FieldLabel>
- <Textarea id="edit-sc-memo" name="memo" rows={3} defaultValue={credit.memo ?? ''} />
+ <FieldLabel htmlFor="edit-sc-memo">
+ {t('admin.fields.store_credit.memo.label')}
+ </FieldLabel>
+ <Textarea
+ id="edit-sc-memo"
+ rows={3}
+ placeholder={t('admin.fields.store_credit.memo.placeholder')}
+ aria-invalid={!!errors.memo || undefined}
+ {...form.register('memo')}
+ />
+ <FieldError errors={[errors.memo]} />
</Field>
</FieldGroup>
</DialogBody>
@@ -1061,24 +1155,30 @@ function IssueStoreCreditDialog({
open: boolean
onOpenChange: (open: boolean) => void
}) {
+ const { t } = useTranslation()
+ const form = useForm<IssueStoreCreditFormValues>({
+ defaultValues: { amount: '', currency: '', category_id: '', memo: '' },
+ })
+ const { errors } = form.formState
+
const mutation = useCustomerMutation(
customerId,
(params: Parameters<typeof adminClient.customers.storeCredits.create>[1]) =>
adminClient.customers.storeCredits.create(customerId, params),
)
- function handleSubmit(e: FormEvent<HTMLFormElement>) {
- e.preventDefault()
- const fd = new FormData(e.currentTarget)
- mutation.mutate(
- {
- amount: Number(fd.get('amount')),
- currency: String(fd.get('currency') ?? ''),
- category_id: String(fd.get('category_id') ?? ''),
- memo: (fd.get('memo') as string) || undefined,
- },
- { onSuccess: () => onOpenChange(false) },
- )
+ async function onSubmit(values: IssueStoreCreditFormValues) {
+ try {
+ await mutation.mutateAsync({
+ amount: Number(values.amount),
+ currency: values.currency,
+ category_id: values.category_id,
+ memo: values.memo || undefined,
+ })
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
return (
@@ -1088,31 +1188,76 @@ function IssueStoreCreditDialog({
<DialogTitle>Issue Store Credit</DialogTitle>
<DialogDescription>Add store credit to this customer's account.</DialogDescription>
</DialogHeader>
- <form onSubmit={handleSubmit}>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
<DialogBody>
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
<FieldGroup>
<div className="grid grid-cols-2 gap-3">
<Field>
- <FieldLabel htmlFor="sc-amount">Amount</FieldLabel>
- <Input id="sc-amount" name="amount" type="number" step="0.01" required />
+ <FieldLabel htmlFor="sc-amount">
+ {t('admin.fields.store_credit.amount.label')}
+ </FieldLabel>
+ <Input
+ id="sc-amount"
+ type="number"
+ step="0.01"
+ required
+ aria-invalid={!!errors.amount || undefined}
+ {...form.register('amount')}
+ />
+ <FieldError errors={[errors.amount]} />
</Field>
<Field>
- <FieldLabel htmlFor="sc-currency">Currency</FieldLabel>
- <CurrencySelect id="sc-currency" name="currency" required />
+ <FieldLabel htmlFor="sc-currency">
+ {t('admin.fields.store_credit.currency.label')}
+ </FieldLabel>
+ <Controller
+ name="currency"
+ control={form.control}
+ render={({ field }) => (
+ <CurrencySelect
+ id="sc-currency"
+ value={field.value || undefined}
+ onChange={field.onChange}
+ required
+ />
+ )}
+ />
</Field>
</div>
<Field>
- <FieldLabel htmlFor="sc-category">Category</FieldLabel>
- <StoreCreditCategorySelect id="sc-category" name="category_id" required />
+ <FieldLabel htmlFor="sc-category">
+ {t('admin.fields.store_credit.category_id.label')}
+ </FieldLabel>
+ <Controller
+ name="category_id"
+ control={form.control}
+ render={({ field }) => (
+ <StoreCreditCategorySelect
+ id="sc-category"
+ value={field.value}
+ onChange={field.onChange}
+ required
+ />
+ )}
+ />
</Field>
<Field>
- <FieldLabel htmlFor="sc-memo">Memo</FieldLabel>
+ <FieldLabel htmlFor="sc-memo">
+ {t('admin.fields.store_credit.memo.label')}
+ </FieldLabel>
<Textarea
id="sc-memo"
- name="memo"
rows={3}
- placeholder="Reason for issuing this credit"
+ placeholder={t('admin.fields.store_credit.memo.placeholder')}
+ aria-invalid={!!errors.memo || undefined}
+ {...form.register('memo')}
/>
+ <FieldError errors={[errors.memo]} />
</Field>
</FieldGroup>
</DialogBody>
@@ -1129,3 +1274,10 @@ function IssueStoreCreditDialog({
</Dialog>
)
}
+
+interface IssueStoreCreditFormValues {
+ amount: string
+ currency: string
+ category_id: string
+ memo: string
+}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/customers/groups.tsx b/packages/admin/src/routes/_authenticated/$storeId/customers/groups.tsx
index b473dfcebe..5b1dfde62b 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/customers/groups.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/customers/groups.tsx
@@ -7,7 +7,8 @@ import type {
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
import { PlusIcon, UsersIcon } from 'lucide-react'
import { useEffect } from 'react'
-import { useForm } from 'react-hook-form'
+import { 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'
@@ -32,6 +33,7 @@ import {
useDeleteCustomerGroup,
useUpdateCustomerGroup,
} from '@/hooks/use-customer-groups'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
import { Subject } from '@/lib/permissions'
import '@/tables/customer-groups'
@@ -124,9 +126,13 @@ function CreateCustomerGroupSheet({
})
async function onSubmit(values: FormValues) {
- await createMutation.mutateAsync(valuesToParams(values) as CustomerGroupCreateParams)
- form.reset(DEFAULT_VALUES)
- onOpenChange(false)
+ try {
+ await createMutation.mutateAsync(valuesToParams(values) as CustomerGroupCreateParams)
+ form.reset(DEFAULT_VALUES)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
return (
@@ -200,9 +206,13 @@ function EditCustomerGroupSheet({
}, [group, form])
async function onSubmit(values: FormValues) {
- await updateMutation.mutateAsync(valuesToParams(values))
- form.reset(values)
- onOpenChange(false)
+ try {
+ await updateMutation.mutateAsync(valuesToParams(values))
+ form.reset(values)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
async function onDelete() {
@@ -278,36 +288,40 @@ function EditCustomerGroupSheet({
)
}
-function NameDescriptionFields({
- form,
-}: {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- form: any
-}) {
+function NameDescriptionFields({ form }: { form: UseFormReturn<FormValues> }) {
+ const { t } = useTranslation()
+ const { errors } = form.formState
return (
<FieldGroup>
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
<Field>
- <FieldLabel htmlFor="name">Name</FieldLabel>
+ <FieldLabel htmlFor="name">{t('admin.fields.name.label')}</FieldLabel>
<Input
id="name"
autoFocus
- placeholder="e.g. VIP customers"
+ placeholder={t('admin.fields.customer_group.name.placeholder')}
+ aria-invalid={!!errors.name || undefined}
{...form.register('name')}
- aria-invalid={!!form.formState.errors.name}
/>
- {form.formState.errors.name && (
- <p className="text-sm text-destructive">{form.formState.errors.name.message}</p>
- )}
+ {errors.name && <p className="text-sm text-destructive">{errors.name.message}</p>}
</Field>
<Field>
- <FieldLabel htmlFor="description">Description</FieldLabel>
+ <FieldLabel htmlFor="description">{t('admin.fields.description.label')}</FieldLabel>
<Textarea
id="description"
rows={3}
- placeholder="Optional internal description"
+ placeholder={t('admin.fields.customer_group.description.placeholder')}
+ aria-invalid={!!errors.description || undefined}
{...form.register('description')}
/>
+ {errors.description && (
+ <p className="text-sm text-destructive">{errors.description.message}</p>
+ )}
</Field>
</FieldGroup>
)
diff --git a/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx b/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx
index 945c3b1c27..89c1c60179 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/customers/index.tsx
@@ -1,7 +1,9 @@
import { useMutation } from '@tanstack/react-query'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { PlusIcon, UserMinusIcon, UserPlusIcon } from 'lucide-react'
-import { type FormEvent, useState } from 'react'
+import { useState } from 'react'
+import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
import { z } from 'zod/v4'
import { adminClient } from '@/client'
import type { BulkAction, BulkActionFormProps } from '@/components/spree/bulk-action-bar'
@@ -11,7 +13,7 @@ import { ResourceTable, resourceSearchSchema } from '@/components/spree/resource
import { TagCombobox } from '@/components/spree/tag-combobox'
import { Button } from '@/components/ui/button'
import { Checkbox } from '@/components/ui/checkbox'
-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import {
Sheet,
@@ -23,6 +25,7 @@ import {
} from '@/components/ui/sheet'
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 '@/tables/customers'
@@ -179,6 +182,26 @@ 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,
@@ -186,10 +209,11 @@ function NewCustomerSheet({
open: boolean
onOpenChange: (open: boolean) => void
}) {
+ const { t } = useTranslation()
const { storeId } = Route.useParams()
const navigate = useNavigate()
- const [tags, setTags] = useState<string[]>([])
- const [acceptsMarketing, setAcceptsMarketing] = useState(false)
+
+ const form = useForm<NewCustomerFormValues>({ defaultValues: NEW_CUSTOMER_DEFAULTS })
const createMutation = useMutation({
mutationFn: (params: Parameters<typeof adminClient.customers.create>[0]) =>
@@ -204,26 +228,22 @@ function NewCustomerSheet({
},
})
- function handleSubmit(e: FormEvent<HTMLFormElement>) {
- e.preventDefault()
- const fd = new FormData(e.currentTarget)
- const email = String(fd.get('email') ?? '').trim()
- if (!email) return
-
- const payload: Parameters<typeof adminClient.customers.create>[0] = { email }
- const firstName = String(fd.get('first_name') ?? '').trim()
- const lastName = String(fd.get('last_name') ?? '').trim()
- const phone = String(fd.get('phone') ?? '').trim()
- const internalNote = String(fd.get('internal_note') ?? '').trim()
+ async function onSubmit(values: NewCustomerFormValues) {
+ const payload: Parameters<typeof adminClient.customers.create>[0] = {
+ email: values.email.trim(),
+ accepts_email_marketing: values.accepts_email_marketing,
+ }
+ if (values.first_name.trim()) payload.first_name = values.first_name.trim()
+ if (values.last_name.trim()) payload.last_name = values.last_name.trim()
+ if (values.phone.trim()) payload.phone = values.phone.trim()
+ if (values.internal_note.trim()) payload.internal_note = values.internal_note.trim()
+ if (values.tags.length) payload.tags = values.tags
- if (firstName) payload.first_name = firstName
- if (lastName) payload.last_name = lastName
- if (phone) payload.phone = phone
- if (internalNote) payload.internal_note = internalNote
- if (tags.length) payload.tags = tags
- payload.accepts_email_marketing = acceptsMarketing
-
- createMutation.mutate(payload)
+ try {
+ await createMutation.mutateAsync(payload)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
return (
@@ -236,59 +256,107 @@ function NewCustomerSheet({
page if they need to sign in.
</SheetDescription>
</SheetHeader>
- <form onSubmit={handleSubmit} className="flex min-h-0 flex-1 flex-col">
+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
<div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {form.formState.errors.root.message}
+ </p>
+ )}
<FieldGroup>
<Field>
- <FieldLabel htmlFor="email">Email</FieldLabel>
- <Input id="email" name="email" type="email" required autoFocus />
+ <FieldLabel htmlFor="new-customer-email">
+ {t('admin.fields.email.label')}
+ </FieldLabel>
+ <Input
+ id="new-customer-email"
+ type="email"
+ autoFocus
+ aria-invalid={!!form.formState.errors.email || undefined}
+ {...form.register('email')}
+ />
+ <FieldError errors={[form.formState.errors.email]} />
</Field>
<div className="grid grid-cols-2 gap-3">
<Field>
- <FieldLabel htmlFor="first_name">First name</FieldLabel>
- <Input id="first_name" name="first_name" />
+ <FieldLabel htmlFor="new-customer-first-name">
+ {t('admin.fields.first_name.label')}
+ </FieldLabel>
+ <Input
+ id="new-customer-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="last_name">Last name</FieldLabel>
- <Input id="last_name" name="last_name" />
+ <FieldLabel htmlFor="new-customer-last-name">
+ {t('admin.fields.last_name.label')}
+ </FieldLabel>
+ <Input
+ id="new-customer-last-name"
+ aria-invalid={!!form.formState.errors.last_name || undefined}
+ {...form.register('last_name')}
+ />
+ <FieldError errors={[form.formState.errors.last_name]} />
</Field>
</div>
<Field>
- <FieldLabel htmlFor="phone">Phone</FieldLabel>
- <Input id="phone" name="phone" />
+ <FieldLabel htmlFor="new-customer-phone">
+ {t('admin.fields.phone.label')}
+ </FieldLabel>
+ <Input
+ id="new-customer-phone"
+ aria-invalid={!!form.formState.errors.phone || undefined}
+ {...form.register('phone')}
+ />
+ <FieldError errors={[form.formState.errors.phone]} />
</Field>
<Field>
- <FieldLabel>Tags</FieldLabel>
- <TagCombobox taggableType="Spree::User" value={tags} onChange={setTags} />
+ <FieldLabel>{t('admin.fields.customer.tags.label')}</FieldLabel>
+ <Controller
+ name="tags"
+ control={form.control}
+ render={({ field }) => (
+ <TagCombobox
+ taggableType="Spree::User"
+ value={field.value}
+ onChange={field.onChange}
+ />
+ )}
+ />
</Field>
<Field>
- <label
- htmlFor="accepts_email_marketing"
- className="flex items-center gap-2 text-sm"
- >
- <Checkbox
- id="accepts_email_marketing"
+ <div className="flex items-start justify-between gap-4">
+ <FieldLabel htmlFor="new-customer-marketing" className="cursor-pointer">
+ {t('admin.fields.customer.accepts_email_marketing.label')}
+ </FieldLabel>
+ <Controller
name="accepts_email_marketing"
- checked={acceptsMarketing}
- onCheckedChange={setAcceptsMarketing}
+ control={form.control}
+ render={({ field }) => (
+ <Checkbox
+ id="new-customer-marketing"
+ checked={!!field.value}
+ onCheckedChange={field.onChange}
+ />
+ )}
/>
- Subscribed to marketing
- </label>
+ </div>
</Field>
<Field>
- <FieldLabel htmlFor="internal_note">Internal note</FieldLabel>
+ <FieldLabel htmlFor="new-customer-note">
+ {t('admin.fields.customer.internal_note.label')}
+ </FieldLabel>
<Textarea
- id="internal_note"
- name="internal_note"
+ id="new-customer-note"
rows={4}
- placeholder="Staff-only context about this customer…"
+ placeholder={t('admin.fields.customer.internal_note.placeholder')}
+ aria-invalid={!!form.formState.errors.internal_note || undefined}
+ {...form.register('internal_note')}
/>
+ <FieldError errors={[form.formState.errors.internal_note]} />
</Field>
- {createMutation.error && (
- <p className="text-sm text-destructive">
- {(createMutation.error as Error).message}
- </p>
- )}
</FieldGroup>
</div>
<SheetFooter>
diff --git a/packages/admin/src/routes/_authenticated/$storeId/orders/new.tsx b/packages/admin/src/routes/_authenticated/$storeId/orders/new.tsx
index ed995ffddf..98ff20ef65 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/orders/new.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/orders/new.tsx
@@ -1,18 +1,25 @@
+import { zodResolver } from '@hookform/resolvers/zod'
import type { Customer, Variant } from '@spree/admin-sdk'
import { useMutation, useQuery } from '@tanstack/react-query'
import { createFileRoute, useNavigate } from '@tanstack/react-router'
-import { TrashIcon, XIcon } from 'lucide-react'
-import { type FormEvent, useState } from 'react'
+import { TrashIcon } from 'lucide-react'
+import { useState } from 'react'
+import { useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
import { adminClient } from '@/client'
import { PageHeader } from '@/components/spree/page-header'
+import { ResourceCombobox } from '@/components/spree/resource-combobox'
import { ResourceLayout } from '@/components/spree/resource-layout'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
import { Textarea } from '@/components/ui/textarea'
+import { customerAutocompleteProps } from '@/hooks/use-customers'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
import { formatPrice } from '@/lib/formatters'
+import { NEW_ORDER_DEFAULTS, type NewOrderFormValues, newOrderFormSchema } from '@/schemas/order'
export const Route = createFileRoute('/_authenticated/$storeId/orders/new')({
component: NewOrderPage,
@@ -24,27 +31,23 @@ interface PendingItem {
}
function NewOrderPage() {
+ const { t } = useTranslation()
const { storeId } = Route.useParams()
const navigate = useNavigate()
+ // Customer/items/typeahead state lives outside RHF — they're domain objects
+ // (Customer record, picked Variants) and bespoke widgets (ResourceCombobox,
+ // typeahead button list, items table), not standard form fields.
const [customer, setCustomer] = useState<Customer | null>(null)
- const [customerSearch, setCustomerSearch] = useState('')
- const [email, setEmail] = useState('')
const [items, setItems] = useState<PendingItem[]>([])
const [variantSearch, setVariantSearch] = useState('')
const [useDefaultAddress, setUseDefaultAddress] = useState(true)
- const [internalNote, setInternalNote] = useState('')
- const [customerNote, setCustomerNote] = useState('')
- const [couponCode, setCouponCode] = useState('')
- // Customer typeahead
- const { data: customersData } = useQuery({
- queryKey: ['customers', 'search', customerSearch],
- queryFn: () => adminClient.customers.list({ search: customerSearch, limit: 8 }),
- enabled: !customer && customerSearch.length >= 2,
- staleTime: 30_000,
+ const form = useForm<NewOrderFormValues>({
+ resolver: zodResolver(newOrderFormSchema),
+ defaultValues: NEW_ORDER_DEFAULTS,
})
- const customerResults = customersData?.data ?? []
+ const { errors } = form.formState
// Variant typeahead
const { data: variantsData } = useQuery({
@@ -56,19 +59,19 @@ function NewOrderPage() {
const variantResults = variantsData?.data ?? []
const createMutation = useMutation({
- mutationFn: () => {
+ mutationFn: (values: NewOrderFormValues) => {
const payload: Record<string, unknown> = {
items: items.map((i) => ({ variant_id: i.variant.id, quantity: i.quantity })),
}
if (customer) {
payload.customer_id = customer.id
payload.use_customer_default_address = useDefaultAddress
- } else if (email) {
- payload.email = email
+ } else if (values.email) {
+ payload.email = values.email
}
- if (internalNote) payload.internal_note = internalNote
- if (customerNote) payload.customer_note = customerNote
- if (couponCode) payload.coupon_code = couponCode
+ if (values.internal_note) payload.internal_note = values.internal_note
+ if (values.customer_note) payload.customer_note = values.customer_note
+ if (values.coupon_code) payload.coupon_code = values.coupon_code
return adminClient.orders.create(payload)
},
onSuccess: (order) => {
@@ -76,12 +79,16 @@ function NewOrderPage() {
},
})
+ const email = form.watch('email')
const canSubmit = (Boolean(customer) || email.length > 0) && !createMutation.isPending
- function handleSubmit(e: FormEvent<HTMLFormElement>) {
- e.preventDefault()
+ async function onSubmit(values: NewOrderFormValues) {
if (!canSubmit) return
- createMutation.mutate()
+ try {
+ await createMutation.mutateAsync(values)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
function addItem(variant: Variant) {
@@ -106,82 +113,54 @@ function NewOrderPage() {
}
return (
- <form onSubmit={handleSubmit}>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
<ResourceLayout
header={<PageHeader title="New Order" backTo="orders/drafts" />}
main={
<>
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
<Card>
<CardHeader>
<CardTitle>Customer</CardTitle>
</CardHeader>
<CardContent>
- {customer ? (
- <div className="flex items-center justify-between rounded-md border p-3">
- <div>
- <div className="font-medium">{customer.email}</div>
- {(customer.first_name || customer.last_name) && (
- <div className="text-sm text-muted-foreground">
- {[customer.first_name, customer.last_name].filter(Boolean).join(' ')}
- </div>
- )}
- </div>
- <Button
- type="button"
- size="sm"
- variant="outline"
- onClick={() => {
- setCustomer(null)
- setCustomerSearch('')
- }}
- >
- <XIcon className="size-4" />
- Change
- </Button>
- </div>
- ) : (
- <FieldGroup>
- <Field>
- <FieldLabel>Search by email or name</FieldLabel>
- <Input
- placeholder="Type 2+ chars to search…"
- value={customerSearch}
- onChange={(e) => setCustomerSearch(e.target.value)}
- />
- {customerSearch.length >= 2 && customerResults.length > 0 && (
- <div className="mt-1 rounded-lg border border-border bg-popover text-popover-foreground shadow-xs max-h-[280px] overflow-y-auto">
- {customerResults.map((c) => (
- <button
- key={c.id}
- type="button"
- onClick={() => {
- setCustomer(c)
- setCustomerSearch('')
- }}
- className="block w-full px-3 py-2.5 text-left text-sm hover:bg-muted transition-colors border-b last:border-0"
- >
- <div className="font-medium">{c.email}</div>
- {(c.first_name || c.last_name) && (
- <div className="text-xs text-muted-foreground">
- {[c.first_name, c.last_name].filter(Boolean).join(' ')}
- </div>
- )}
- </button>
- ))}
+ <FieldGroup>
+ <Field>
+ <FieldLabel>Search by email or name</FieldLabel>
+ <ResourceCombobox<Customer>
+ {...customerAutocompleteProps('customer-picker')}
+ value={customer?.id}
+ onChange={(_id, record) => setCustomer(record)}
+ renderOption={(c) => (
+ <div>
+ <div className="font-medium">{c.email}</div>
+ {(c.first_name || c.last_name) && (
+ <div className="text-xs text-muted-foreground">{c.full_name}</div>
+ )}
</div>
)}
- </Field>
+ />
+ </Field>
+ {!customer && (
<Field>
- <FieldLabel>Or use a guest email</FieldLabel>
+ <FieldLabel htmlFor="order-email">
+ {t('admin.fields.order.email.label')}
+ </FieldLabel>
<Input
+ id="order-email"
type="email"
- placeholder="[email protected]"
- value={email}
- onChange={(e) => setEmail(e.target.value)}
+ placeholder={t('admin.fields.order.email.placeholder')}
+ aria-invalid={!!errors.email || undefined}
+ {...form.register('email')}
/>
+ <FieldError errors={[errors.email]} />
</Field>
- </FieldGroup>
- )}
+ )}
+ </FieldGroup>
{customer && (
<div className="mt-4 flex items-center gap-3">
@@ -284,23 +263,27 @@ function NewOrderPage() {
<FieldGroup>
<Field>
<FieldLabel htmlFor="customer-note">
- Customer note (visible to customer)
+ {t('admin.fields.order.customer_note.label')}
</FieldLabel>
<Textarea
id="customer-note"
rows={3}
- value={customerNote}
- onChange={(e) => setCustomerNote(e.target.value)}
+ aria-invalid={!!errors.customer_note || undefined}
+ {...form.register('customer_note')}
/>
+ <FieldError errors={[errors.customer_note]} />
</Field>
<Field>
- <FieldLabel htmlFor="internal-note">Internal note (staff only)</FieldLabel>
+ <FieldLabel htmlFor="internal-note">
+ {t('admin.fields.order.internal_note.label')}
+ </FieldLabel>
<Textarea
id="internal-note"
rows={3}
- value={internalNote}
- onChange={(e) => setInternalNote(e.target.value)}
+ aria-invalid={!!errors.internal_note || undefined}
+ {...form.register('internal_note')}
/>
+ <FieldError errors={[errors.internal_note]} />
</Field>
</FieldGroup>
</CardContent>
@@ -313,13 +296,16 @@ function NewOrderPage() {
<CardContent>
<FieldGroup>
<Field>
- <FieldLabel htmlFor="coupon-code">Coupon code</FieldLabel>
+ <FieldLabel htmlFor="coupon-code">
+ {t('admin.fields.order.coupon_code.label')}
+ </FieldLabel>
<Input
id="coupon-code"
- placeholder="Optional"
- value={couponCode}
- onChange={(e) => setCouponCode(e.target.value)}
+ placeholder={t('admin.fields.order.coupon_code.placeholder')}
+ aria-invalid={!!errors.coupon_code || undefined}
+ {...form.register('coupon_code')}
/>
+ <FieldError errors={[errors.coupon_code]} />
</Field>
</FieldGroup>
</CardContent>
@@ -330,7 +316,7 @@ function NewOrderPage() {
<Button type="submit" disabled={!canSubmit}>
{createMutation.isPending ? 'Creating…' : 'Create Order'}
</Button>
- {createMutation.error && (
+ {createMutation.error && !errors.root && (
<p className="text-sm text-destructive">
{(createMutation.error as Error).message}
</p>
diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx
index 706a8425cf..20925af5c4 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/products/$productId.tsx
@@ -14,11 +14,12 @@ import {
} from '@dnd-kit/sortable'
import { CSS } from '@dnd-kit/utilities'
import { zodResolver } from '@hookform/resolvers/zod'
-import type { Media, Product, Variant } from '@spree/admin-sdk'
+import { type Media, type Product, SpreeError, type Variant } from '@spree/admin-sdk'
import { createFileRoute, useRouter } from '@tanstack/react-router'
import { ImagePlusIcon, Loader2Icon, PencilIcon, TrashIcon } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Controller, type UseFormReturn, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { adminClient } from '@/client'
import { useConfirm } from '@/components/spree/confirm-dialog'
@@ -47,7 +48,7 @@ import {
ComboboxValue,
useComboboxAnchor,
} from '@/components/ui/combobox'
-import { Field, FieldLabel } from '@/components/ui/field'
+import { Field, FieldError, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { RichTextEditor } from '@/components/ui/rich-text-editor'
import {
@@ -69,6 +70,7 @@ import {
useUpdateProductMedia,
} from '@/hooks/use-product-media'
import { useTaxCategories } from '@/hooks/use-tax-categories'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
import { type ProductFormValues, productFormSchema } from '@/schemas/product'
// Purchasable attributes (sku, barcode, prices, weight, dimensions, stock,
@@ -184,7 +186,9 @@ function ProductForm({ product }: { product: Product }) {
try {
await updateProduct.mutateAsync({ id: productId, ...payload })
toast.success('Product saved')
- } catch {
+ } catch (err) {
+ if (mapSpreeErrorsToForm(err, form.setError)) return
+ if (err instanceof SpreeError) throw err
toast.error('Failed to save product')
}
}
@@ -213,6 +217,11 @@ function ProductForm({ product }: { product: Product }) {
return (
<form onSubmit={form.handleSubmit(onSubmit)}>
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {form.formState.errors.root.message}
+ </p>
+ )}
<ResourceLayout
header={
<PageHeader
@@ -271,6 +280,8 @@ type FormCardProps = {
// ---------------------------------------------------------------------------
function GeneralCard({ form }: FormCardProps) {
+ const { t } = useTranslation()
+ const { errors } = form.formState
return (
<Card>
<CardHeader>
@@ -278,15 +289,17 @@ function GeneralCard({ form }: FormCardProps) {
</CardHeader>
<CardContent className="flex flex-col gap-4">
<Field>
- <FieldLabel htmlFor="name">Name</FieldLabel>
- <Input id="name" placeholder="Product name" {...form.register('name')} />
- {form.formState.errors.name && (
- <p className="text-sm text-destructive">{form.formState.errors.name.message}</p>
- )}
+ <FieldLabel htmlFor="product-name">{t('admin.fields.name.label')}</FieldLabel>
+ <Input
+ id="product-name"
+ placeholder={t('admin.fields.product.name.placeholder')}
+ aria-invalid={!!errors.name || undefined}
+ {...form.register('name')}
+ />
+ <FieldError errors={[errors.name]} />
</Field>
-
<Field>
- <FieldLabel>Description</FieldLabel>
+ <FieldLabel>{t('admin.fields.description.label')}</FieldLabel>
<Controller
name="description"
control={form.control}
@@ -620,6 +633,7 @@ function SEOCard({ form, product }: FormCardProps & { product: Product }) {
const slug = form.watch('slug')
const metaTitle = form.watch('meta_title')
const metaDescription = form.watch('meta_description')
+ const { errors } = form.formState
return (
<Card>
@@ -639,23 +653,35 @@ function SEOCard({ form, product }: FormCardProps & { product: Product }) {
</div>
<Field>
- <FieldLabel htmlFor="slug">URL handle</FieldLabel>
- <Input id="slug" placeholder="product-url-handle" {...form.register('slug')} />
+ <FieldLabel htmlFor="product-slug">URL handle</FieldLabel>
+ <Input
+ id="product-slug"
+ placeholder="product-url-handle"
+ aria-invalid={!!errors.slug || undefined}
+ {...form.register('slug')}
+ />
+ <FieldError errors={[errors.slug]} />
</Field>
-
<Field>
- <FieldLabel htmlFor="meta_title">Meta title</FieldLabel>
- <Input id="meta_title" placeholder="SEO title" {...form.register('meta_title')} />
+ <FieldLabel htmlFor="product-meta-title">Meta title</FieldLabel>
+ <Input
+ id="product-meta-title"
+ placeholder="SEO title"
+ aria-invalid={!!errors.meta_title || undefined}
+ {...form.register('meta_title')}
+ />
+ <FieldError errors={[errors.meta_title]} />
</Field>
-
<Field>
- <FieldLabel htmlFor="meta_description">Meta description</FieldLabel>
+ <FieldLabel htmlFor="product-meta-description">Meta description</FieldLabel>
<Textarea
- id="meta_description"
- placeholder="SEO description"
+ id="product-meta-description"
rows={3}
+ placeholder="SEO description"
+ aria-invalid={!!errors.meta_description || undefined}
{...form.register('meta_description')}
/>
+ <FieldError errors={[errors.meta_description]} />
</Field>
</CardContent>
</Card>
diff --git a/packages/admin/src/routes/_authenticated/$storeId/products/options.tsx b/packages/admin/src/routes/_authenticated/$storeId/products/options.tsx
index f109da9fc5..bc8e8aef6e 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/products/options.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/products/options.tsx
@@ -32,6 +32,7 @@ import {
useFieldArray,
useForm,
} from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { z } from 'zod/v4'
import { adminClient } from '@/client'
@@ -51,7 +52,7 @@ import {
TableRow,
} from '@/components/ui/data-table'
import { Dialog, DialogContent } from '@/components/ui/dialog'
-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import {
Select,
@@ -78,6 +79,7 @@ import {
useOptionType,
useUpdateOptionType,
} from '@/hooks/use-option-types'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
import { Subject } from '@/lib/permissions'
import { cn } from '@/lib/utils'
import '@/tables/option-types'
@@ -242,12 +244,16 @@ function CreateOptionTypeSheet({
})
async function onSubmit(values: FormValues) {
- await createMutation.mutateAsync({
- ...values,
- option_values: values.option_values.map(valueToParam),
- } as OptionTypeCreateParams)
- form.reset(DEFAULT_VALUES)
- onOpenChange(false)
+ try {
+ await createMutation.mutateAsync({
+ ...values,
+ option_values: values.option_values.map(valueToParam),
+ } as OptionTypeCreateParams)
+ form.reset(DEFAULT_VALUES)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
return (
@@ -267,6 +273,11 @@ function CreateOptionTypeSheet({
</SheetHeader>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
<div className="flex flex-1 flex-col gap-6 overflow-y-auto p-4">
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {form.formState.errors.root.message}
+ </p>
+ )}
<OptionTypeFormFields form={form} />
<OptionValuesFieldArray form={form} />
</div>
@@ -325,16 +336,20 @@ function EditOptionTypeSheet({
}, [optionType, form])
async function onSubmit(values: FormValues) {
- await updateMutation.mutateAsync({
- ...values,
- option_values: values.option_values.map(valueToParam),
- })
- // The sheet closes here; the `useOptionType` cache invalidation done by
- // the mutation hook re-hydrates the form via `useEffect` the next time
- // the sheet opens. Don't reset from the update response — the v3
- // serializer omits `option_values` when not expanded, and resetting with
- // `[]` flashes empty rows during the closing animation.
- onOpenChange(false)
+ try {
+ await updateMutation.mutateAsync({
+ ...values,
+ option_values: values.option_values.map(valueToParam),
+ })
+ // The sheet closes here; the `useOptionType` cache invalidation done by
+ // the mutation hook re-hydrates the form via `useEffect` the next time
+ // the sheet opens. Don't reset from the update response — the v3
+ // serializer omits `option_values` when not expanded, and resetting with
+ // `[]` flashes empty rows during the closing animation.
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
async function onDelete() {
@@ -364,6 +379,11 @@ function EditOptionTypeSheet({
) : (
<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
<div className="flex flex-1 flex-col gap-6 overflow-y-auto p-4">
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {form.formState.errors.root.message}
+ </p>
+ )}
<OptionTypeFormFields form={form} />
<OptionValuesFieldArray form={form} />
</div>
@@ -408,92 +428,79 @@ function EditOptionTypeSheet({
// Top-level fields
// ---------------------------------------------------------------------------
-function OptionTypeFormFields({
- form,
-}: {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- form: any
-}) {
+function OptionTypeFormFields({ form }: { form: UseFormReturn<FormValues> }) {
+ const { t } = useTranslation()
+ const { errors } = form.formState
return (
<FieldGroup>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<Field>
- <FieldLabel htmlFor="label">Label</FieldLabel>
+ <FieldLabel htmlFor="ot-label">{t('admin.fields.option_type.label.label')}</FieldLabel>
<Input
- id="label"
+ id="ot-label"
autoFocus
- placeholder="e.g. Shirt size"
+ placeholder={t('admin.fields.option_type.label.placeholder')}
+ aria-invalid={!!errors.label || undefined}
{...form.register('label')}
- aria-invalid={!!form.formState.errors.label}
/>
- <p className="text-xs text-muted-foreground">Shown to customers on the storefront.</p>
- {form.formState.errors.label && (
- <p className="text-sm text-destructive">{form.formState.errors.label.message}</p>
- )}
+ <p className="text-xs text-muted-foreground">
+ {t('admin.fields.option_type.label.help')}
+ </p>
+ <FieldError errors={[errors.label]} />
</Field>
-
<Field>
- <FieldLabel htmlFor="name">Internal name</FieldLabel>
+ <FieldLabel htmlFor="ot-name">{t('admin.fields.option_type.name.label')}</FieldLabel>
<Input
- id="name"
- placeholder="e.g. shirt-size"
+ id="ot-name"
+ placeholder={t('admin.fields.option_type.name.placeholder')}
+ aria-invalid={!!errors.name || undefined}
{...form.register('name')}
- aria-invalid={!!form.formState.errors.name}
/>
- <p className="text-xs text-muted-foreground">
- Lowercase identifier. Must be unique across the store.
- </p>
- {form.formState.errors.name && (
- <p className="text-sm text-destructive">{form.formState.errors.name.message}</p>
- )}
+ <p className="text-xs text-muted-foreground">{t('admin.fields.option_type.name.help')}</p>
+ <FieldError errors={[errors.name]} />
</Field>
</div>
-
<Field>
- <FieldLabel htmlFor="kind">Kind</FieldLabel>
+ <FieldLabel htmlFor="ot-kind">{t('admin.fields.option_type.kind.label')}</FieldLabel>
<Controller
name="kind"
control={form.control}
render={({ field }) => (
- <Select value={field.value} onValueChange={field.onChange}>
- <SelectTrigger id="kind">
- <SelectValue>
- {(value) =>
- KIND_OPTIONS.find((o) => o.value === value)?.label ?? (value as string)
- }
- </SelectValue>
+ <Select
+ items={KIND_OPTIONS as never}
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger id="ot-kind">
+ <SelectValue />
</SelectTrigger>
<SelectContent>
- {KIND_OPTIONS.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label}
+ {KIND_OPTIONS.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
</SelectItem>
))}
</SelectContent>
</Select>
)}
/>
- <p className="text-xs text-muted-foreground">
- Controls how the option renders on the storefront. Color swatch shows a hex color; buttons
- show a thumbnail image.
- </p>
+ <p className="text-xs text-muted-foreground">{t('admin.fields.option_type.kind.help')}</p>
</Field>
-
<Field>
<div className="flex items-start justify-between gap-4">
<div className="flex flex-col">
- <FieldLabel htmlFor="filterable" className="cursor-pointer">
- Filterable
+ <FieldLabel htmlFor="ot-filterable" className="cursor-pointer">
+ {t('admin.fields.option_type.filterable.label')}
</FieldLabel>
<span className="text-xs text-muted-foreground">
- Show this option as a filter in storefront product listings.
+ {t('admin.fields.option_type.filterable.help')}
</span>
</div>
<Controller
name="filterable"
control={form.control}
render={({ field }) => (
- <Switch id="filterable" checked={!!field.value} onCheckedChange={field.onChange} />
+ <Switch id="ot-filterable" checked={!!field.value} onCheckedChange={field.onChange} />
)}
/>
</div>
diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/api-keys.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/api-keys.tsx
index 221f2e4221..bc0ad57cca 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/settings/api-keys.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/api-keys.tsx
@@ -1,5 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
-import type { ApiKey, ApiKeyCreateParams } from '@spree/admin-sdk'
+import { type ApiKey, type ApiKeyCreateParams, SpreeError } from '@spree/admin-sdk'
import { createFileRoute } from '@tanstack/react-router'
import {
AlertTriangleIcon,
@@ -11,6 +11,7 @@ import {
} from 'lucide-react'
import { useState } from 'react'
import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { z } from 'zod/v4'
import { useConfirm } from '@/components/spree/confirm-dialog'
@@ -49,6 +50,7 @@ import {
Field,
FieldContent,
FieldDescription,
+ FieldError,
FieldLabel,
FieldTitle,
} from '@/components/ui/field'
@@ -66,6 +68,7 @@ import {
import { Skeleton } from '@/components/ui/skeleton'
import { useApiKeys, useCreateApiKey, useDeleteApiKey, useRevokeApiKey } from '@/hooks/use-api-keys'
import { useCopyToClipboard } from '@/hooks/use-copy-to-clipboard'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
import { cn } from '@/lib/utils'
export const Route = createFileRoute('/_authenticated/$storeId/settings/api-keys')({
@@ -415,6 +418,7 @@ function CreateApiKeyDialog({
onOpenChange: (open: boolean) => void
onCreated: (key: ApiKey) => void
}) {
+ const { t } = useTranslation()
const createMutation = useCreateApiKey()
const form = useForm<CreateFormValues>({
@@ -436,6 +440,8 @@ function CreateApiKeyDialog({
form.reset({ name: '', key_type: 'secret', scopes: [] })
onCreated(key)
} catch (err) {
+ if (mapSpreeErrorsToForm(err, form.setError)) return
+ if (err instanceof SpreeError) throw err
toast.error(err instanceof Error ? err.message : 'Failed to create key')
}
}
@@ -460,22 +466,25 @@ function CreateApiKeyDialog({
{/* `flex-1 overflow-y-auto` keeps the footer pinned while the body
scrolls when the scope grid overflows. */}
<div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {form.formState.errors.root.message}
+ </p>
+ )}
<Field>
- <FieldLabel htmlFor="key-name">Name</FieldLabel>
+ <FieldLabel htmlFor="api-key-name">{t('admin.fields.api_key.name.label')}</FieldLabel>
<Input
- id="key-name"
+ id="api-key-name"
autoFocus
- placeholder="Backend integration, Storefront prod, …"
+ placeholder={t('admin.fields.api_key.name.placeholder')}
+ aria-invalid={!!form.formState.errors.name || undefined}
{...form.register('name')}
- aria-invalid={!!form.formState.errors.name}
/>
- {form.formState.errors.name && (
- <p className="text-sm text-destructive">{form.formState.errors.name.message}</p>
- )}
+ <FieldError errors={[form.formState.errors.name]} />
</Field>
<Field>
- <FieldLabel>Type</FieldLabel>
+ <FieldLabel>{t('admin.fields.api_key.key_type.label')}</FieldLabel>
<Controller
name="key_type"
control={form.control}
@@ -498,7 +507,7 @@ function CreateApiKeyDialog({
{keyType === 'secret' && (
<Field>
- <FieldLabel>Scopes</FieldLabel>
+ <FieldLabel>{t('admin.fields.api_key.scopes.label')}</FieldLabel>
<Controller
name="scopes"
control={form.control}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx
index fe8fe55611..3492a5922f 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/payment-methods.tsx
@@ -35,6 +35,7 @@ import {
usePaymentMethodTypes,
useUpdatePaymentMethod,
} from '@/hooks/use-payment-methods'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
import { Subject } from '@/lib/permissions'
import '@/tables/payment-methods'
@@ -180,10 +181,14 @@ function CreatePaymentMethodSheet({
}
async function onSubmit(values: PaymentMethodFormValues) {
- await createMutation.mutateAsync(valuesToCreateParams(values, preferences))
- form.reset(CREATE_DEFAULTS)
- setPreferences({})
- onOpenChange(false)
+ try {
+ await createMutation.mutateAsync(valuesToCreateParams(values, preferences))
+ form.reset(CREATE_DEFAULTS)
+ setPreferences({})
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
return (
@@ -204,6 +209,11 @@ function CreatePaymentMethodSheet({
</SheetHeader>
<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
<div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {form.formState.errors.root.message}
+ </p>
+ )}
<PaymentMethodForm
mode="create"
form={form}
@@ -288,10 +298,14 @@ function EditPaymentMethodSheet({
async function onSubmit(values: PaymentMethodFormValues) {
const params = valuesToUpdateParams(values)
if (preferencesDirty) params.preferences = preferences
- await updateMutation.mutateAsync(params)
- form.reset(values)
- originalPreferencesRef.current = JSON.stringify(preferences)
- onOpenChange(false)
+ try {
+ await updateMutation.mutateAsync(params)
+ form.reset(values)
+ originalPreferencesRef.current = JSON.stringify(preferences)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
async function onDelete() {
@@ -330,6 +344,11 @@ function EditPaymentMethodSheet({
) : (
<form onSubmit={form.handleSubmit(onSubmit)} className="flex min-h-0 flex-1 flex-col">
<div className="flex flex-1 flex-col gap-4 overflow-y-auto p-4">
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {form.formState.errors.root.message}
+ </p>
+ )}
<PaymentMethodForm
mode="edit"
form={form}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/staff.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/staff.tsx
index 876b43a7c1..f705abf32f 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/settings/staff.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/staff.tsx
@@ -1,5 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
-import type { AdminUser, Invitation, Role } from '@spree/admin-sdk'
+import { type AdminUser, type Invitation, type Role, SpreeError } from '@spree/admin-sdk'
import { createFileRoute } from '@tanstack/react-router'
import {
ClockIcon,
@@ -12,6 +12,7 @@ import {
} from 'lucide-react'
import { useState } from 'react'
import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { z } from 'zod/v4'
import { useConfirm } from '@/components/spree/confirm-dialog'
@@ -47,7 +48,7 @@ import {
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty'
-import { Field, FieldLabel } from '@/components/ui/field'
+import { Field, FieldError, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import {
Select,
@@ -68,6 +69,7 @@ import {
useStaff,
useUpdateStaff,
} from '@/hooks/use-staff'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
import { getInitials } from '@/lib/formatters'
export const Route = createFileRoute('/_authenticated/$storeId/settings/staff')({
@@ -393,6 +395,7 @@ function InviteDialog({
open: boolean
onOpenChange: (open: boolean) => void
}) {
+ const { t } = useTranslation()
const { data: roles, isLoading: rolesLoading } = useRoles()
const createMutation = useCreateInvitation()
@@ -408,6 +411,8 @@ function InviteDialog({
form.reset({ email: '', role_id: '' })
onOpenChange(false)
} catch (err) {
+ if (mapSpreeErrorsToForm(err, form.setError)) return
+ if (err instanceof SpreeError) throw err
toast.error(err instanceof Error ? err.message : 'Failed to send invitation')
}
}
@@ -429,22 +434,25 @@ function InviteDialog({
</DialogHeader>
<form onSubmit={form.handleSubmit(onSubmit)}>
<DialogBody className="flex flex-col gap-4">
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {form.formState.errors.root.message}
+ </p>
+ )}
<Field>
- <FieldLabel htmlFor="invite-email">Email</FieldLabel>
+ <FieldLabel htmlFor="invite-email">{t('admin.fields.email.label')}</FieldLabel>
<Input
id="invite-email"
type="email"
autoFocus
placeholder="[email protected]"
+ aria-invalid={!!form.formState.errors.email || undefined}
{...form.register('email')}
- aria-invalid={!!form.formState.errors.email}
/>
- {form.formState.errors.email && (
- <p className="text-sm text-destructive">{form.formState.errors.email.message}</p>
- )}
+ <FieldError errors={[form.formState.errors.email]} />
</Field>
<Field>
- <FieldLabel htmlFor="invite-role">Role</FieldLabel>
+ <FieldLabel htmlFor="invite-role">{t('admin.fields.role_id.label')}</FieldLabel>
<Controller
name="role_id"
control={form.control}
@@ -526,6 +534,7 @@ function EditStaffDialog({
onOpenChange: (open: boolean) => void
member: AdminUser
}) {
+ const { t } = useTranslation()
const { data: roles } = useRoles()
const updateMutation = useUpdateStaff()
@@ -551,6 +560,8 @@ function EditStaffDialog({
toast.success('Staff updated')
onOpenChange(false)
} catch (err) {
+ if (mapSpreeErrorsToForm(err, form.setError)) return
+ if (err instanceof SpreeError) throw err
toast.error(err instanceof Error ? err.message : 'Failed to update staff')
}
}
@@ -576,14 +587,33 @@ function EditStaffDialog({
</DialogHeader>
<form onSubmit={form.handleSubmit(onSubmit)}>
<DialogBody className="flex flex-col gap-4">
+ {form.formState.errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {form.formState.errors.root.message}
+ </p>
+ )}
<div className="grid grid-cols-2 gap-3">
<Field>
- <FieldLabel htmlFor="edit-first-name">First name</FieldLabel>
- <Input id="edit-first-name" {...form.register('first_name')} />
+ <FieldLabel htmlFor="staff-first-name">
+ {t('admin.fields.first_name.label')}
+ </FieldLabel>
+ <Input
+ id="staff-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="edit-last-name">Last name</FieldLabel>
- <Input id="edit-last-name" {...form.register('last_name')} />
+ <FieldLabel htmlFor="staff-last-name">
+ {t('admin.fields.last_name.label')}
+ </FieldLabel>
+ <Input
+ id="staff-last-name"
+ aria-invalid={!!form.formState.errors.last_name || undefined}
+ {...form.register('last_name')}
+ />
+ <FieldError errors={[form.formState.errors.last_name]} />
</Field>
</div>
<Field>
diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsx
index 98b9ce0493..0b59419406 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/stock-locations.tsx
@@ -8,7 +8,8 @@ import type {
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
import { ChevronDownIcon, ChevronRightIcon, PlusIcon } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
-import { Controller, useForm } from 'react-hook-form'
+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'
@@ -19,7 +20,7 @@ import { ResourceTable, resourceSearchSchema } from '@/components/spree/resource
import { useRowClickBridge } from '@/components/spree/row-click-bridge'
import { Button } from '@/components/ui/button'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'
-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import {
Select,
@@ -45,6 +46,7 @@ import {
useStockLocation,
useUpdateStockLocation,
} from '@/hooks/use-stock-locations'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
import { Subject } from '@/lib/permissions'
import '@/tables/stock-locations'
@@ -250,10 +252,14 @@ function CreateStockLocationSheet({
})
async function onSubmit(values: FormValues) {
- const params = formValuesToParams(values) as StockLocationCreateParams
- await createMutation.mutateAsync(params)
- form.reset(DEFAULT_VALUES)
- onOpenChange(false)
+ try {
+ const params = formValuesToParams(values) as StockLocationCreateParams
+ await createMutation.mutateAsync(params)
+ form.reset(DEFAULT_VALUES)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
return (
@@ -328,10 +334,14 @@ function EditStockLocationSheet({
}, [stockLocation, form])
async function onSubmit(values: FormValues) {
- const params = formValuesToParams(values) as StockLocationUpdateParams
- await updateMutation.mutateAsync(params)
- form.reset(values)
- onOpenChange(false)
+ try {
+ const params = formValuesToParams(values) as StockLocationUpdateParams
+ await updateMutation.mutateAsync(params)
+ form.reset(values)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
async function onDelete() {
@@ -635,56 +645,64 @@ function StockItemRow({ item }: { item: StockItem }) {
// Shared form fields
// ============================================================================
-function StockLocationFormFields({
- form,
-}: {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- form: any
-}) {
+function StockLocationFormFields({ form }: { form: UseFormReturn<FormValues> }) {
+ const { t } = useTranslation()
+ const { errors } = form.formState
const countryIso = form.watch('country_iso')
const { states } = useCountryStates(countryIso)
-
const pickupEnabled = form.watch('pickup_enabled')
return (
<FieldGroup>
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
+
<Field>
- <FieldLabel htmlFor="name">Name</FieldLabel>
+ <FieldLabel htmlFor="sl-name">{t('admin.fields.name.label')}</FieldLabel>
<Input
- id="name"
+ id="sl-name"
autoFocus
- placeholder="Brooklyn warehouse"
+ placeholder={t('admin.fields.stock_location.name.placeholder')}
+ aria-invalid={!!errors.name || undefined}
{...form.register('name')}
- aria-invalid={!!form.formState.errors.name}
/>
- {form.formState.errors.name && (
- <p className="text-sm text-destructive">{form.formState.errors.name.message}</p>
- )}
+ <FieldError errors={[errors.name]} />
</Field>
<Field>
- <FieldLabel htmlFor="admin_name">Internal name</FieldLabel>
+ <FieldLabel htmlFor="sl-admin-name">
+ {t('admin.fields.stock_location.admin_name.label')}
+ </FieldLabel>
<Input
- id="admin_name"
- placeholder="Optional — shown only in the admin"
+ id="sl-admin-name"
+ placeholder={t('admin.fields.stock_location.admin_name.placeholder')}
+ aria-invalid={!!errors.admin_name || undefined}
{...form.register('admin_name')}
/>
+ <FieldError errors={[errors.admin_name]} />
</Field>
<Field>
- <FieldLabel>Kind</FieldLabel>
+ <FieldLabel htmlFor="sl-kind">{t('admin.fields.stock_location.kind.label')}</FieldLabel>
<Controller
name="kind"
control={form.control}
render={({ field }) => (
- <Select items={KIND_OPTIONS} value={field.value} onValueChange={field.onChange}>
- <SelectTrigger>
+ <Select
+ items={KIND_OPTIONS as never}
+ value={field.value}
+ onValueChange={field.onChange}
+ >
+ <SelectTrigger id="sl-kind">
<SelectValue />
</SelectTrigger>
<SelectContent>
- {KIND_OPTIONS.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label}
+ {KIND_OPTIONS.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
</SelectItem>
))}
</SelectContent>
@@ -693,54 +711,78 @@ function StockLocationFormFields({
/>
</Field>
- <ToggleField
+ <BooleanRow
+ id="sl-active"
+ label={t('admin.fields.stock_location.active.label')}
+ help={t('admin.fields.stock_location.active.help')}
form={form}
name="active"
- label="Active"
- description="Inactive locations don't appear in fulfillment selection."
/>
- <ToggleField
+ <BooleanRow
+ id="sl-default"
+ label={t('admin.fields.stock_location.default.label')}
+ help={t('admin.fields.stock_location.default.help')}
form={form}
name="default"
- label="Default location"
- description="New stock items propagate here. Only one location can be default."
/>
- <ToggleField
+ <BooleanRow
+ id="sl-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"
- label="Backorderable by default"
- description="New stock items at this location allow backorders."
/>
- <ToggleField
+ <BooleanRow
+ id="sl-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}
name="propagate_all_variants"
- label="Auto-create stock items for all variants"
- description="When a new variant is added anywhere, create a zero-quantity stock item here."
/>
<div className="border-t border-border pt-4">
<h3 className="mb-3 text-sm font-medium">Address</h3>
<FieldGroup>
<Field>
- <FieldLabel htmlFor="address1">Address line 1</FieldLabel>
- <Input id="address1" {...form.register('address1')} />
+ <FieldLabel htmlFor="sl-address1">{t('admin.fields.address1.label')}</FieldLabel>
+ <Input
+ id="sl-address1"
+ aria-invalid={!!errors.address1 || undefined}
+ {...form.register('address1')}
+ />
+ <FieldError errors={[errors.address1]} />
</Field>
<Field>
- <FieldLabel htmlFor="address2">Address line 2</FieldLabel>
- <Input id="address2" {...form.register('address2')} />
+ <FieldLabel htmlFor="sl-address2">{t('admin.fields.address2.label')}</FieldLabel>
+ <Input
+ id="sl-address2"
+ aria-invalid={!!errors.address2 || undefined}
+ {...form.register('address2')}
+ />
+ <FieldError errors={[errors.address2]} />
</Field>
<div className="grid grid-cols-2 gap-3">
<Field>
- <FieldLabel htmlFor="city">City</FieldLabel>
- <Input id="city" {...form.register('city')} />
+ <FieldLabel htmlFor="sl-city">{t('admin.fields.city.label')}</FieldLabel>
+ <Input
+ id="sl-city"
+ aria-invalid={!!errors.city || undefined}
+ {...form.register('city')}
+ />
+ <FieldError errors={[errors.city]} />
</Field>
<Field>
- <FieldLabel htmlFor="zipcode">Postal code</FieldLabel>
- <Input id="zipcode" {...form.register('zipcode')} />
+ <FieldLabel htmlFor="sl-zipcode">{t('admin.fields.zipcode.label')}</FieldLabel>
+ <Input
+ id="sl-zipcode"
+ aria-invalid={!!errors.zipcode || undefined}
+ {...form.register('zipcode')}
+ />
+ <FieldError errors={[errors.zipcode]} />
</Field>
</div>
<Field>
- <FieldLabel>Country</FieldLabel>
+ <FieldLabel>{t('admin.fields.country_iso.label')}</FieldLabel>
<Controller
name="country_iso"
control={form.control}
@@ -749,8 +791,6 @@ function StockLocationFormFields({
value={field.value}
onValueChange={(iso) => {
field.onChange(iso)
- // Clear both shapes so a previously-typed free-text state
- // doesn't bleed across countries.
form.setValue('state_abbr', '', { shouldDirty: true })
form.setValue('state_name', '', { shouldDirty: true })
}}
@@ -760,7 +800,7 @@ function StockLocationFormFields({
</Field>
{states.length > 0 ? (
<Field>
- <FieldLabel>State / Province</FieldLabel>
+ <FieldLabel>{t('admin.fields.state_abbr.label')}</FieldLabel>
<Controller
name="state_abbr"
control={form.control}
@@ -776,17 +816,32 @@ function StockLocationFormFields({
</Field>
) : (
<Field>
- <FieldLabel htmlFor="state_name">State / Province</FieldLabel>
- <Input id="state_name" {...form.register('state_name')} />
+ <FieldLabel htmlFor="sl-state-name">{t('admin.fields.state_name.label')}</FieldLabel>
+ <Input
+ id="sl-state-name"
+ aria-invalid={!!errors.state_name || undefined}
+ {...form.register('state_name')}
+ />
+ <FieldError errors={[errors.state_name]} />
</Field>
)}
<Field>
- <FieldLabel htmlFor="phone">Phone</FieldLabel>
- <Input id="phone" {...form.register('phone')} />
+ <FieldLabel htmlFor="sl-phone">{t('admin.fields.phone.label')}</FieldLabel>
+ <Input
+ id="sl-phone"
+ aria-invalid={!!errors.phone || undefined}
+ {...form.register('phone')}
+ />
+ <FieldError errors={[errors.phone]} />
</Field>
<Field>
- <FieldLabel htmlFor="company">Company</FieldLabel>
- <Input id="company" {...form.register('company')} />
+ <FieldLabel htmlFor="sl-company">{t('admin.fields.company.label')}</FieldLabel>
+ <Input
+ id="sl-company"
+ aria-invalid={!!errors.company || undefined}
+ {...form.register('company')}
+ />
+ <FieldError errors={[errors.company]} />
</Field>
</FieldGroup>
</div>
@@ -794,32 +849,35 @@ function StockLocationFormFields({
<div className="border-t border-border pt-4">
<h3 className="mb-3 text-sm font-medium">Pickup</h3>
<FieldGroup>
- <ToggleField
+ <BooleanRow
+ id="sl-pickup-enabled"
+ label={t('admin.fields.stock_location.pickup_enabled.label')}
+ help={t('admin.fields.stock_location.pickup_enabled.help')}
form={form}
name="pickup_enabled"
- label="Allow customer pickup"
- description="Show this location to customers as a pickup option at checkout."
/>
{pickupEnabled && (
<>
<Field>
- <FieldLabel>Stock policy</FieldLabel>
+ <FieldLabel htmlFor="sl-pickup-stock-policy">
+ {t('admin.fields.stock_location.pickup_stock_policy.label')}
+ </FieldLabel>
<Controller
name="pickup_stock_policy"
control={form.control}
render={({ field }) => (
<Select
- items={PICKUP_POLICY_OPTIONS}
+ items={PICKUP_POLICY_OPTIONS as never}
value={field.value}
onValueChange={field.onChange}
>
- <SelectTrigger>
+ <SelectTrigger id="sl-pickup-stock-policy">
<SelectValue />
</SelectTrigger>
<SelectContent>
- {PICKUP_POLICY_OPTIONS.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label}
+ {PICKUP_POLICY_OPTIONS.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
</SelectItem>
))}
</SelectContent>
@@ -828,26 +886,32 @@ function StockLocationFormFields({
/>
</Field>
<Field>
- <FieldLabel htmlFor="pickup_ready_in_minutes">Ready in (minutes)</FieldLabel>
+ <FieldLabel htmlFor="sl-pickup-ready-in-minutes">
+ {t('admin.fields.stock_location.pickup_ready_in_minutes.label')}
+ </FieldLabel>
<Input
- id="pickup_ready_in_minutes"
+ id="sl-pickup-ready-in-minutes"
type="number"
min={0}
step={5}
- placeholder="60"
- {...form.register('pickup_ready_in_minutes', {
- setValueAs: (v: unknown) => (v === '' || v == null ? null : Number(v)),
- })}
+ 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 })}
/>
+ <FieldError errors={[errors.pickup_ready_in_minutes]} />
</Field>
<Field>
- <FieldLabel htmlFor="pickup_instructions">Pickup instructions</FieldLabel>
+ <FieldLabel htmlFor="sl-pickup-instructions">
+ {t('admin.fields.stock_location.pickup_instructions.label')}
+ </FieldLabel>
<Textarea
- id="pickup_instructions"
- placeholder="Where the customer should go to collect their order."
+ id="sl-pickup-instructions"
rows={3}
+ placeholder={t('admin.fields.stock_location.pickup_instructions.placeholder')}
+ aria-invalid={!!errors.pickup_instructions || undefined}
{...form.register('pickup_instructions')}
/>
+ <FieldError errors={[errors.pickup_instructions]} />
</Field>
</>
)}
@@ -857,32 +921,33 @@ function StockLocationFormFields({
)
}
-function ToggleField({
+function BooleanRow({
+ id,
+ label,
+ help,
form,
name,
- label,
- description,
}: {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- form: any
- name: keyof FormValues
+ id: string
label: string
- description?: string
+ help?: string
+ form: UseFormReturn<FormValues>
+ name: keyof FormValues
}) {
return (
<Field>
<div className="flex items-start justify-between gap-4">
<div className="flex flex-col">
- <FieldLabel htmlFor={String(name)} className="cursor-pointer">
+ <FieldLabel htmlFor={id} className="cursor-pointer">
{label}
</FieldLabel>
- {description && <span className="text-xs text-muted-foreground">{description}</span>}
+ {help && <span className="text-xs text-muted-foreground">{help}</span>}
</div>
<Controller
- name={name as string}
+ name={name as never}
control={form.control}
render={({ field }) => (
- <Switch id={String(name)} checked={!!field.value} onCheckedChange={field.onChange} />
+ <Switch id={id} checked={!!field.value} onCheckedChange={field.onChange} />
)}
/>
</div>
diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/store.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/store.tsx
index 284361d311..76534099a9 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/settings/store.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/store.tsx
@@ -1,15 +1,16 @@
import { zodResolver } from '@hookform/resolvers/zod'
-import type { Store } from '@spree/admin-sdk'
+import { SpreeError, type Store } from '@spree/admin-sdk'
import { createFileRoute } from '@tanstack/react-router'
-import { useEffect } from 'react'
+import { useEffect, useMemo } from 'react'
import { Controller, useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import { FormActions, useFormSubmitShortcut } from '@/components/spree/form-actions'
import { PageHeader } from '@/components/spree/page-header'
import { ResourceLayout } from '@/components/spree/resource-layout'
import { ErrorState } from '@/components/spree/route-error-boundary'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
-import { Field, FieldGroup, FieldLabel } from '@/components/ui/field'
+import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import {
Select,
@@ -20,6 +21,7 @@ import {
} from '@/components/ui/select'
import { Skeleton } from '@/components/ui/skeleton'
import { useStoreSettings, useUpdateStoreSettings } from '@/hooks/use-store-settings'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
import {
ADMIN_LOCALE_OPTIONS,
type StoreSettingsFormValues,
@@ -92,6 +94,7 @@ function StoreSettingsPage() {
}
function StoreSettingsForm({ store }: { store: Store }) {
+ const { t } = useTranslation()
const updateMutation = useUpdateStoreSettings()
const form = useForm<StoreSettingsFormValues>({
@@ -123,12 +126,21 @@ function StoreSettingsForm({ store }: { store: Store }) {
toast.success('Store settings updated')
form.reset(values)
} catch (err) {
+ if (mapSpreeErrorsToForm(err, form.setError)) return
+ if (err instanceof SpreeError) throw err
toast.error(err instanceof Error ? err.message : 'Failed to update store settings')
}
}
useFormSubmitShortcut(form, onSubmit)
+ // 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 { errors } = form.formState
+
return (
<form onSubmit={form.handleSubmit(onSubmit)}>
<ResourceLayout
@@ -141,6 +153,11 @@ function StoreSettingsForm({ store }: { store: Store }) {
}
main={
<>
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
<Card>
<CardHeader>
<CardTitle>General</CardTitle>
@@ -148,17 +165,15 @@ function StoreSettingsForm({ store }: { store: Store }) {
<CardContent>
<FieldGroup>
<Field>
- <FieldLabel htmlFor="name">Store name</FieldLabel>
+ <FieldLabel htmlFor="store-name">
+ {t('admin.fields.store.name.label')}
+ </FieldLabel>
<Input
- id="name"
+ id="store-name"
+ aria-invalid={!!errors.name || undefined}
{...form.register('name')}
- aria-invalid={!!form.formState.errors.name}
/>
- {form.formState.errors.name && (
- <p className="text-sm text-destructive">
- {form.formState.errors.name.message}
- </p>
- )}
+ <FieldError errors={[errors.name]} />
</Field>
</FieldGroup>
</CardContent>
@@ -170,114 +185,36 @@ function StoreSettingsForm({ store }: { store: Store }) {
</CardHeader>
<CardContent>
<FieldGroup>
- <Field>
- <FieldLabel htmlFor="preferred_admin_locale">Admin language</FieldLabel>
- <Controller
- name="preferred_admin_locale"
- control={form.control}
- render={({ field }) => (
- <Select
- items={ADMIN_LOCALE_OPTIONS}
- value={field.value ?? ''}
- onValueChange={(v) => field.onChange(v || null)}
- >
- <SelectTrigger id="preferred_admin_locale">
- <SelectValue placeholder="Use the default language" />
- </SelectTrigger>
- <SelectContent>
- {ADMIN_LOCALE_OPTIONS.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- />
- </Field>
-
- <Field>
- <FieldLabel htmlFor="preferred_timezone">Timezone</FieldLabel>
- <Controller
- name="preferred_timezone"
- control={form.control}
- render={({ field }) => (
- <Select value={field.value} onValueChange={field.onChange}>
- <SelectTrigger id="preferred_timezone">
- <SelectValue placeholder="Select a timezone" />
- </SelectTrigger>
- <SelectContent className="max-h-80">
- {TIMEZONES.map((tz) => (
- <SelectItem key={tz} value={tz}>
- {tz}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- />
- {form.formState.errors.preferred_timezone && (
- <p className="text-sm text-destructive">
- {form.formState.errors.preferred_timezone.message}
- </p>
- )}
- </Field>
-
- <Field>
- <FieldLabel htmlFor="preferred_unit_system">Unit system</FieldLabel>
- <Controller
- name="preferred_unit_system"
- control={form.control}
- render={({ field }) => (
- <Select
- items={UNIT_SYSTEM_OPTIONS}
- value={field.value}
- onValueChange={field.onChange}
- >
- <SelectTrigger id="preferred_unit_system">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {UNIT_SYSTEM_OPTIONS.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )}
- />
- </Field>
-
- <Field>
- <FieldLabel htmlFor="preferred_weight_unit">Weight unit</FieldLabel>
- <Controller
- name="preferred_weight_unit"
- control={form.control}
- render={({ field }) => {
- const weightOptions =
- WEIGHT_UNIT_OPTIONS[unitSystem] ?? WEIGHT_UNIT_OPTIONS.metric
- return (
- <Select
- items={weightOptions}
- value={field.value}
- onValueChange={field.onChange}
- >
- <SelectTrigger id="preferred_weight_unit">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {weightOptions.map((opt) => (
- <SelectItem key={opt.value} value={opt.value}>
- {opt.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- )
- }}
- />
- </Field>
+ <SelectField
+ id="store-admin-locale"
+ label={t('admin.fields.store.preferred_admin_locale.label')}
+ placeholder={t('admin.fields.store.preferred_admin_locale.placeholder')}
+ name="preferred_admin_locale"
+ control={form.control}
+ options={ADMIN_LOCALE_OPTIONS}
+ />
+ <SelectField
+ id="store-timezone"
+ label={t('admin.fields.store.preferred_timezone.label')}
+ placeholder={t('admin.fields.store.preferred_timezone.placeholder')}
+ name="preferred_timezone"
+ control={form.control}
+ options={timezoneOptions}
+ />
+ <SelectField
+ id="store-unit-system"
+ label={t('admin.fields.store.preferred_unit_system.label')}
+ name="preferred_unit_system"
+ control={form.control}
+ options={UNIT_SYSTEM_OPTIONS as never}
+ />
+ <SelectField
+ id="store-weight-unit"
+ label={t('admin.fields.store.preferred_weight_unit.label')}
+ name="preferred_weight_unit"
+ control={form.control}
+ options={weightOptions}
+ />
</FieldGroup>
</CardContent>
</Card>
@@ -287,3 +224,40 @@ function StoreSettingsForm({ store }: { store: Store }) {
</form>
)
}
+
+interface SelectFieldProps {
+ id: string
+ label: string
+ placeholder?: string
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ name: any
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ control: any
+ options: ReadonlyArray<{ value: string; label: string }>
+}
+
+function SelectField({ id, label, placeholder, name, control, options }: SelectFieldProps) {
+ return (
+ <Field>
+ <FieldLabel htmlFor={id}>{label}</FieldLabel>
+ <Controller
+ name={name}
+ control={control}
+ render={({ field }) => (
+ <Select items={options as never} value={field.value} onValueChange={field.onChange}>
+ <SelectTrigger id={id}>
+ <SelectValue placeholder={placeholder} />
+ </SelectTrigger>
+ <SelectContent>
+ {options.map((o) => (
+ <SelectItem key={o.value} value={o.value}>
+ {o.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ />
+ </Field>
+ )
+}
diff --git a/packages/admin/src/routes/_authenticated/$storeId/settings/tax-categories.tsx b/packages/admin/src/routes/_authenticated/$storeId/settings/tax-categories.tsx
index e25dd696c6..58839349ec 100644
--- a/packages/admin/src/routes/_authenticated/$storeId/settings/tax-categories.tsx
+++ b/packages/admin/src/routes/_authenticated/$storeId/settings/tax-categories.tsx
@@ -7,7 +7,8 @@ import type {
import { createFileRoute, useNavigate } from '@tanstack/react-router'
import { PlusIcon } from 'lucide-react'
import { useEffect } from 'react'
-import { Controller, useForm } from 'react-hook-form'
+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'
@@ -33,6 +34,7 @@ import {
useTaxCategory,
useUpdateTaxCategory,
} from '@/hooks/use-tax-categories'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
import { Subject } from '@/lib/permissions'
import '@/tables/tax-categories'
@@ -128,9 +130,13 @@ function CreateTaxCategorySheet({
})
async function onSubmit(values: FormValues) {
- await createMutation.mutateAsync(valuesToParams(values) as TaxCategoryCreateParams)
- form.reset(DEFAULT_VALUES)
- onOpenChange(false)
+ try {
+ await createMutation.mutateAsync(valuesToParams(values) as TaxCategoryCreateParams)
+ form.reset(DEFAULT_VALUES)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
return (
@@ -205,9 +211,13 @@ function EditTaxCategorySheet({
}, [taxCategory, form])
async function onSubmit(values: FormValues) {
- await updateMutation.mutateAsync(valuesToParams(values))
- form.reset(values)
- onOpenChange(false)
+ try {
+ await updateMutation.mutateAsync(valuesToParams(values))
+ form.reset(values)
+ onOpenChange(false)
+ } catch (err) {
+ if (!mapSpreeErrorsToForm(err, form.setError)) throw err
+ }
}
async function onDelete() {
@@ -273,56 +283,61 @@ function EditTaxCategorySheet({
)
}
-function TaxCategoryFormFields({
- form,
-}: {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- form: any
-}) {
+function TaxCategoryFormFields({ form }: { form: UseFormReturn<FormValues> }) {
+ const { t } = useTranslation()
+ const { errors } = form.formState
return (
<FieldGroup>
+ {errors.root?.message && (
+ <p className="text-sm text-destructive" role="alert">
+ {errors.root.message}
+ </p>
+ )}
<Field>
- <FieldLabel htmlFor="name">Name</FieldLabel>
+ <FieldLabel htmlFor="name">{t('admin.fields.name.label')}</FieldLabel>
<Input
id="name"
autoFocus
- placeholder="e.g. Reduced rate"
+ placeholder={t('admin.fields.tax_category.name.placeholder')}
+ aria-invalid={!!errors.name || undefined}
{...form.register('name')}
- aria-invalid={!!form.formState.errors.name}
/>
- {form.formState.errors.name && (
- <p className="text-sm text-destructive">{form.formState.errors.name.message}</p>
- )}
+ {errors.name && <p className="text-sm text-destructive">{errors.name.message}</p>}
</Field>
<Field>
- <FieldLabel htmlFor="tax_code">Tax code</FieldLabel>
+ <FieldLabel htmlFor="tax_code">{t('admin.fields.tax_category.tax_code.label')}</FieldLabel>
<Input
id="tax_code"
- placeholder="External tax provider code (Avalara, etc.)"
+ placeholder={t('admin.fields.tax_category.tax_code.placeholder')}
+ aria-invalid={!!errors.tax_code || undefined}
{...form.register('tax_code')}
/>
+ {errors.tax_code && <p className="text-sm text-destructive">{errors.tax_code.message}</p>}
</Field>
<Field>
- <FieldLabel htmlFor="description">Description</FieldLabel>
+ <FieldLabel htmlFor="description">{t('admin.fields.description.label')}</FieldLabel>
<Textarea
id="description"
rows={3}
- placeholder="Optional internal description"
+ placeholder={t('admin.fields.tax_category.description.placeholder')}
+ aria-invalid={!!errors.description || undefined}
{...form.register('description')}
/>
+ {errors.description && (
+ <p className="text-sm text-destructive">{errors.description.message}</p>
+ )}
</Field>
<Field>
<div className="flex items-start justify-between gap-4">
<div className="flex flex-col">
<FieldLabel htmlFor="is_default" className="cursor-pointer">
- Default
+ {t('admin.fields.tax_category.is_default.label')}
</FieldLabel>
<span className="text-xs text-muted-foreground">
- Setting this demotes the previous default. Products without an explicit category fall
- back to this one.
+ {t('admin.fields.tax_category.is_default.help')}
</span>
</div>
<Controller
diff --git a/packages/admin/src/routes/accept-invitation.$invitationId.tsx b/packages/admin/src/routes/accept-invitation.$invitationId.tsx
index 6ceda31b28..c8f4301d76 100644
--- a/packages/admin/src/routes/accept-invitation.$invitationId.tsx
+++ b/packages/admin/src/routes/accept-invitation.$invitationId.tsx
@@ -3,6 +3,7 @@ import type { InvitationLookup, SpreeError } from '@spree/admin-sdk'
import { useQuery } from '@tanstack/react-query'
import { createFileRoute, Navigate, useNavigate } from '@tanstack/react-router'
import { useForm } from 'react-hook-form'
+import { useTranslation } from 'react-i18next'
import { z } from 'zod/v4'
import { adminClient } from '@/client'
import { Button } from '@/components/ui/button'
@@ -10,6 +11,7 @@ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/com
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useAuth } from '@/hooks/use-auth'
+import { mapSpreeErrorsToForm } from '@/lib/form-errors'
const acceptSearchSchema = z.object({
token: z.string().min(1).optional(),
@@ -109,6 +111,7 @@ function SignInForm({
token: string
invitation: InvitationLookup
}) {
+ const { t } = useTranslation()
const { acceptInvitation, isLoading } = useAuth()
const navigate = useNavigate()
@@ -116,6 +119,7 @@ function SignInForm({
resolver: zodResolver(signInSchema),
defaultValues: { password: '' },
})
+ const { errors } = form.formState
const onSubmit = async (data: SignInForm) => {
try {
@@ -123,9 +127,13 @@ function SignInForm({
navigate({ to: '/', replace: true })
} catch (err) {
const e = err as SpreeError
- form.setError('root', {
- message: e.status === 401 ? 'Invalid password' : e.message || 'Could not accept invitation',
- })
+ if (e?.status === 401) {
+ form.setError('root', { message: 'Invalid password' })
+ return
+ }
+ if (!mapSpreeErrorsToForm(err, form.setError)) {
+ form.setError('root', { message: e?.message || 'Could not accept invitation' })
+ }
}
}
@@ -142,20 +150,26 @@ function SignInForm({
</CardHeader>
<CardContent>
<form onSubmit={form.handleSubmit(onSubmit)} className="grid gap-6">
- {form.formState.errors.root && (
- <p className="text-center text-sm text-destructive">
- {form.formState.errors.root.message}
- </p>
+ {errors.root && (
+ <p className="text-center text-sm text-destructive">{errors.root.message}</p>
)}
<div className="grid gap-2">
- <Label htmlFor="invitee-email">Email</Label>
+ <Label htmlFor="invitee-email">{t('admin.fields.email.label')}</Label>
<Input id="invitee-email" value={invitation.email} disabled />
</div>
<div className="grid gap-2">
- <Label htmlFor="password">Password</Label>
- <Input id="password" type="password" autoFocus {...form.register('password')} />
- {form.formState.errors.password && (
- <p className="text-sm text-destructive">{form.formState.errors.password.message}</p>
+ <Label htmlFor="password">
+ {t('admin.fields.invitation_acceptance.password.label')}
+ </Label>
+ <Input
+ id="password"
+ type="password"
+ autoFocus
+ aria-invalid={!!errors.password || undefined}
+ {...form.register('password')}
+ />
+ {errors.password && (
+ <p className="text-sm text-destructive">{errors.password.message}</p>
)}
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
@@ -189,6 +203,7 @@ function SignUpForm({
token: string
invitation: InvitationLookup
}) {
+ const { t } = useTranslation()
const { acceptInvitation, isLoading } = useAuth()
const navigate = useNavigate()
@@ -196,14 +211,17 @@ function SignUpForm({
resolver: zodResolver(signUpSchema),
defaultValues: { first_name: '', last_name: '', password: '', password_confirmation: '' },
})
+ const { errors } = form.formState
const onSubmit = async (data: SignUpForm) => {
try {
await acceptInvitation(invitationId, token, data)
navigate({ to: '/', replace: true })
} catch (err) {
- const e = err as SpreeError
- form.setError('root', { message: e.message || 'Could not accept invitation' })
+ if (!mapSpreeErrorsToForm(err, form.setError)) {
+ const e = err as SpreeError
+ form.setError('root', { message: e?.message || 'Could not accept invitation' })
+ }
}
}
@@ -221,53 +239,64 @@ function SignUpForm({
</CardHeader>
<CardContent>
<form onSubmit={form.handleSubmit(onSubmit)} className="grid gap-6">
- {form.formState.errors.root && (
- <p className="text-center text-sm text-destructive">
- {form.formState.errors.root.message}
- </p>
+ {errors.root && (
+ <p className="text-center text-sm text-destructive">{errors.root.message}</p>
)}
<div className="grid gap-2">
- <Label htmlFor="invitee-email">Email</Label>
+ <Label htmlFor="invitee-email">{t('admin.fields.email.label')}</Label>
<Input id="invitee-email" value={invitation.email} disabled />
</div>
<div className="grid grid-cols-2 gap-3">
<div className="grid gap-2">
- <Label htmlFor="first_name">First name</Label>
- <Input id="first_name" autoFocus {...form.register('first_name')} />
- {form.formState.errors.first_name && (
- <p className="text-sm text-destructive">
- {form.formState.errors.first_name.message}
- </p>
+ <Label htmlFor="first_name">{t('admin.fields.first_name.label')}</Label>
+ <Input
+ id="first_name"
+ autoFocus
+ aria-invalid={!!errors.first_name || undefined}
+ {...form.register('first_name')}
+ />
+ {errors.first_name && (
+ <p className="text-sm text-destructive">{errors.first_name.message}</p>
)}
</div>
<div className="grid gap-2">
- <Label htmlFor="last_name">Last name</Label>
- <Input id="last_name" {...form.register('last_name')} />
- {form.formState.errors.last_name && (
- <p className="text-sm text-destructive">
- {form.formState.errors.last_name.message}
- </p>
+ <Label htmlFor="last_name">{t('admin.fields.last_name.label')}</Label>
+ <Input
+ id="last_name"
+ aria-invalid={!!errors.last_name || undefined}
+ {...form.register('last_name')}
+ />
+ {errors.last_name && (
+ <p className="text-sm text-destructive">{errors.last_name.message}</p>
)}
</div>
</div>
<div className="grid gap-2">
- <Label htmlFor="password">Password</Label>
- <Input id="password" type="password" {...form.register('password')} />
- {form.formState.errors.password && (
- <p className="text-sm text-destructive">{form.formState.errors.password.message}</p>
+ <Label htmlFor="password">
+ {t('admin.fields.invitation_acceptance.password.label')}
+ </Label>
+ <Input
+ id="password"
+ type="password"
+ aria-invalid={!!errors.password || undefined}
+ {...form.register('password')}
+ />
+ {errors.password && (
+ <p className="text-sm text-destructive">{errors.password.message}</p>
)}
</div>
<div className="grid gap-2">
- <Label htmlFor="password_confirmation">Confirm password</Label>
+ <Label htmlFor="password_confirmation">
+ {t('admin.fields.invitation_acceptance.password_confirmation.label')}
+ </Label>
<Input
id="password_confirmation"
type="password"
+ aria-invalid={!!errors.password_confirmation || undefined}
{...form.register('password_confirmation')}
/>
- {form.formState.errors.password_confirmation && (
- <p className="text-sm text-destructive">
- {form.formState.errors.password_confirmation.message}
- </p>
+ {errors.password_confirmation && (
+ <p className="text-sm text-destructive">{errors.password_confirmation.message}</p>
)}
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
diff --git a/packages/admin/src/routes/login.tsx b/packages/admin/src/routes/login.tsx
index 4ea1da7e7d..d706aa002b 100644
--- a/packages/admin/src/routes/login.tsx
+++ b/packages/admin/src/routes/login.tsx
@@ -1,6 +1,7 @@
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'
@@ -64,6 +65,8 @@ function LoginFormCard({
isLoading: boolean
className?: string
}) {
+ const { t } = useTranslation()
+ const { errors } = form.formState
return (
<div className={cn('flex flex-col gap-6', className)}>
<Card>
@@ -74,33 +77,33 @@ function LoginFormCard({
<CardContent>
<form onSubmit={form.handleSubmit(onSubmit)}>
<div className="grid gap-6">
- {form.formState.errors.root && (
- <p className="text-sm text-destructive text-center">
- {form.formState.errors.root.message}
- </p>
+ {errors.root && (
+ <p className="text-sm text-destructive text-center">{errors.root.message}</p>
)}
<div className="grid gap-6">
<div className="grid gap-2">
- <Label htmlFor="email">Email</Label>
+ <Label htmlFor="email">{t('admin.fields.email.label')}</Label>
<Input
id="email"
type="email"
- placeholder="[email protected]"
+ placeholder={t('admin.fields.login.email.placeholder')}
+ aria-invalid={!!errors.email || undefined}
{...form.register('email')}
/>
- {form.formState.errors.email && (
- <p className="text-sm text-destructive">
- {form.formState.errors.email.message}
- </p>
+ {errors.email && (
+ <p className="text-sm text-destructive">{errors.email.message}</p>
)}
</div>
<div className="grid gap-2">
- <Label htmlFor="password">Password</Label>
- <Input id="password" type="password" {...form.register('password')} />
- {form.formState.errors.password && (
- <p className="text-sm text-destructive">
- {form.formState.errors.password.message}
- </p>
+ <Label htmlFor="password">{t('admin.fields.password.label')}</Label>
+ <Input
+ id="password"
+ type="password"
+ aria-invalid={!!errors.password || undefined}
+ {...form.register('password')}
+ />
+ {errors.password && (
+ <p className="text-sm text-destructive">{errors.password.message}</p>
)}
</div>
<Button type="submit" className="w-full" disabled={isLoading}>
diff --git a/packages/admin/src/schemas/order.ts b/packages/admin/src/schemas/order.ts
new file mode 100644
index 0000000000..f8bea77480
--- /dev/null
+++ b/packages/admin/src/schemas/order.ts
@@ -0,0 +1,27 @@
+import { z } from 'zod/v4'
+
+/**
+ * New-order form schema. The "customer OR email" rule is enforced at the
+ * page level rather than in this schema because `customer` lives outside
+ * the RHF state (it's a domain object held in `useState` for the resource
+ * combobox). See `routes/_authenticated/$storeId/orders/new.tsx` for the
+ * combined `canSubmit` check.
+ *
+ * Per-attribute server validation (line items, customer reachability, etc.)
+ * 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('')),
+ customer_note: z.string(),
+ internal_note: z.string(),
+ coupon_code: z.string(),
+})
+
+export type NewOrderFormValues = z.infer<typeof newOrderFormSchema>
+
+export const NEW_ORDER_DEFAULTS: NewOrderFormValues = {
+ email: '',
+ customer_note: '',
+ internal_note: '',
+ coupon_code: '',
+}
diff --git a/packages/admin/src/schemas/promotion.ts b/packages/admin/src/schemas/promotion.ts
new file mode 100644
index 0000000000..821eee5cda
--- /dev/null
+++ b/packages/admin/src/schemas/promotion.ts
@@ -0,0 +1,111 @@
+import { z } from 'zod/v4'
+import type {
+ PromotionActionFormDraft,
+ PromotionRuleFormDraft,
+} from '@/components/spree/promotion-editors/types'
+
+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 }>
+
+/**
+ * Promotion form schema.
+ *
+ * Most field-level rules (presence of name, currency, etc.) are validated
+ * server-side and surfaced via `mapSpreeErrorsToForm`. The client-side
+ * `superRefine` block here only catches **cross-field** rules where the UI
+ * can react before the server round-trip:
+ *
+ * - `code` is required for single-code coupon promotions
+ * - `number_of_codes` + `code_prefix` are required for multi-code batches
+ * - `expires_at` must be after `starts_at` when both are set
+ *
+ * The shape of `rules` and `actions` is preserved through `z.array(z.any())`
+ * because they're complex discriminated drafts owned by their own editor
+ * components (see `promotion-editors/types.ts`). Validating them here would
+ * duplicate that logic; the server is the source of truth for rule/action
+ * payload validity.
+ */
+export const promotionFormSchema = z
+ .object({
+ name: z.string().min(1, 'Name is required'),
+ description: z.string(),
+ kind: z.enum(['coupon_code', 'automatic']),
+ code: z.string(),
+ multi_codes: z.boolean(),
+ number_of_codes: z.coerce.number().int().positive().optional(),
+ code_prefix: z.string(),
+ starts_at: z.string(),
+ expires_at: z.string(),
+ usage_limit: z.coerce.number().int().positive().optional(),
+ match_policy: z.enum(['all', 'any']),
+ // Rule/action drafts are owned by the editor components; we accept whatever
+ // shape they emit and let the server's rule/action serializers validate.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ rules: z.array(z.any() as z.ZodType<PromotionRuleFormDraft>),
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ actions: z.array(z.any() as z.ZodType<PromotionActionFormDraft>),
+ })
+ .superRefine((v, ctx) => {
+ if (v.kind === 'coupon_code') {
+ if (v.multi_codes) {
+ if (!v.code_prefix?.trim()) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['code_prefix'],
+ message: 'Prefix is required for multi-code batches',
+ })
+ }
+ 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',
+ })
+ }
+ } else {
+ if (!v.code?.trim()) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['code'],
+ message: 'Code is required (or click Generate)',
+ })
+ }
+ }
+ }
+
+ if (v.starts_at && v.expires_at && v.starts_at >= v.expires_at) {
+ ctx.addIssue({
+ code: 'custom',
+ path: ['expires_at'],
+ message: 'Expiry must be after the start date',
+ })
+ }
+ })
+
+export type PromotionFormValues = z.infer<typeof promotionFormSchema>
+
+export const PROMOTION_DEFAULTS: PromotionFormValues = {
+ name: '',
+ description: '',
+ kind: 'coupon_code',
+ code: '',
+ multi_codes: false,
+ number_of_codes: undefined,
+ code_prefix: '',
+ starts_at: '',
+ expires_at: '',
+ usage_limit: undefined,
+ match_policy: 'all',
+ rules: [],
+ actions: [],
+}