Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Fix: Show state validation when saving a company address (#14811)
Damian Legawiec971816643480
diff --git a/packages/dashboard-core/src/components/address-form-dialog.tsx b/packages/dashboard-core/src/components/address-form-dialog.tsxindex d317b12862..9b60208be1 100644--- a/packages/dashboard-core/src/components/address-form-dialog.tsx+++ b/packages/dashboard-core/src/components/address-form-dialog.tsx@@ -100,6 +100,11 @@ const businessSchema = z.object({type AddressFormValues = z.infer<typeof personalSchema>+/** Address rows validate on `state`; every address form binds `state_code`. */+const ADDRESS_SERVER_FIELD_ALIASES = { state: 'state_code' } as const satisfies Partial<+ Record<string, keyof AddressFormValues>+>+/*** Just the fields this dialog reads.*@@ -202,6 +207,9 @@ export function AddressFormDialog({})const { errors } = form.formState+ const countryCode = form.watch('country_code')+ const { states, statesRequired } = useCountryStates(countryCode)+// The parent keys the dialog on the address id so a fresh instance mounts// for each open, but `address` can also stream in async (loaded after the// sheet mounts). Reset only when the *record identity* changes — otherwise a@@ -225,14 +233,20 @@ export function AddressFormDialog({form.setValue('country_code', storeDefaultCountryCode)}, [address?.country_code, storeDefaultCountryCode, form])- const countryCode = form.watch('country_code')- const { states } = useCountryStates(countryCode)// Show the dropdown whenever the country enumerates subdivisions, not only// when it strictly requires one — so a country like Pakistan still lets the// user pick a province instead of typing a name that may not match.const useStateCombobox = states.length > 0async function onSubmit(values: AddressFormValues) {+ if (statesRequired && !values.state_code.trim()) {+ form.setError('state_code', {+ type: 'manual',+ message: requiredMessage('state_code')(),+ })+ return+ }+try {await onSave({first_name: values.first_name,@@ -255,7 +269,8 @@ export function AddressFormDialog({// Surface server-side 422 validation errors on the matching fields so// the dialog reflects whatever the API rejected (e.g. "phone is too// short"). Non-validation errors bubble to the parent's toast.- if (!mapSpreeErrorsToForm(err, form.setError)) throw err+ if (!mapSpreeErrorsToForm(err, form.setError, { fieldAliases: ADDRESS_SERVER_FIELD_ALIASES }))+ throw err}}@@ -284,6 +299,11 @@ export function AddressFormDialog({className="flex flex-col flex-1 overflow-hidden"><div className="flex-1 overflow-y-auto p-4">+ {errors.root?.message && (+ <p className="mb-4 text-sm text-destructive" role="alert">+ {errors.root.message}+ </p>+ )}<FieldGroup>{showLabel && (<Field>diff --git a/packages/dashboard-core/src/lib/form-errors.ts b/packages/dashboard-core/src/lib/form-errors.tsindex 0b09a75ba7..5250051db8 100644--- a/packages/dashboard-core/src/lib/form-errors.ts+++ b/packages/dashboard-core/src/lib/form-errors.ts@@ -71,6 +71,7 @@ function hasTranslation(field: string, entry: ValidationErrorDetail): boolean {*/function translatedSummary(details: Record<string, Array<string | ValidationErrorDetail>>,+ fieldAliases?: Record<string, string>,): string | null {const sentences: string[] = []@@ -85,7 +86,8 @@ function translatedSummary(// would fall through to the server's own sentence.if (!hasTranslation(field, entry)) return null- sentences.push(`${attributeLabel(field)} ${resolveDetailMessage(field, entry)}`.trim())+ const labelField = fieldAliases?.[field] ?? field+ sentences.push(`${attributeLabel(labelField)} ${resolveDetailMessage(field, entry)}`.trim())}}@@ -163,19 +165,30 @@ function attributeLabel(field: string): string {* the bare `base` key and any `*.base` key as record-level and route them* to root.*/+export interface MapSpreeErrorsToFormOptions<TFieldValues extends FieldValues> {+ /**+ * Rails attribute names that differ from the form field the input is bound+ * to. Address validation reports on `state`; the dashboard writes+ * `state_code`.+ */+ fieldAliases?: Partial<Record<string, Path<TFieldValues>>>+}+export function mapSpreeErrorsToForm<TFieldValues extends FieldValues>(error: unknown,setError: UseFormSetError<TFieldValues>,+ options?: MapSpreeErrorsToFormOptions<TFieldValues>,): boolean {if (!(error instanceof SpreeError)) return falseconst { details, message } = error+ const fieldAliases = options?.fieldAliases as Record<string, string> | undefined// The summary banner is the line a merchant actually reads, so it follows// their interface language too. It is rebuilt from the translated entries// when every one of them translated; a single untranslated code means the// server's own sentence is still the more complete summary, and it stays.- const summary = (details && translatedSummary(details)) || message+ const summary = (details && translatedSummary(details, fieldAliases)) || messageif (summary) {setError('root' as Path<TFieldValues>, { type: 'server', message: summary })}@@ -193,9 +206,11 @@ export function mapSpreeErrorsToForm<TFieldValues extends FieldValues>(// worse failure mode than redundant root messages.for (const [field, entries] of Object.entries(details)) {if (!entries?.length) continue- if (!isRenderableFieldKey(field)) continue- setError(field as Path<TFieldValues>, {+ const formField = (fieldAliases?.[field] ?? field) as string+ if (!isRenderableFieldKey(formField)) continue++ setError(formField as Path<TFieldValues>, {type: 'server',message: entries.map((entry) => resolveDetailMessage(field, entry)).join(', '),})diff --git a/packages/dashboard-core/tests/form-errors.test.ts b/packages/dashboard-core/tests/form-errors.test.tsindex 91fd8467b9..b9c7e759da 100644--- a/packages/dashboard-core/tests/form-errors.test.ts+++ b/packages/dashboard-core/tests/form-errors.test.ts@@ -207,6 +207,22 @@ describe('the summary banner', () => {})})+describe('field aliases', () => {+ it('maps a server attribute onto the form field the input is bound to', () => {+ const setError = vi.fn()+ mapSpreeErrorsToForm(+ spreeError({ state: [{ code: 'blank', message: "can't be blank" }] }),+ setError,+ { fieldAliases: { state: 'state_code' } },+ )++ expect(setError).toHaveBeenCalledWith('state_code', {+ type: 'server',+ message: 'Required',+ })+ })+})+describe('the banner and the field agree', () => {it('uses a per-attribute key in both, even for a message the model worded', () => {// The banner used to bail on any `specific` entry while the field below itdiff --git a/packages/dashboard/e2e/companies.spec.ts b/packages/dashboard/e2e/companies.spec.tsindex 38997e6815..661a009d28 100644--- a/packages/dashboard/e2e/companies.spec.ts+++ b/packages/dashboard/e2e/companies.spec.ts@@ -118,6 +118,29 @@ test.describe('companies', () => {await expect(members.getByText(email)).toHaveCount(0, { timeout: 15_000 })})+ test('requires a state when saving a company address for the United States', async ({ page }) => {+ const creds = await login(page)+ await createCompany(page, creds.store_id, `E2E Austin ${Date.now()}`)++ const addressBook = card(page, /^address book/i)+ await addressBook.getByRole('button', { name: /add address/i }).click()+ await expect(page.getByRole('heading', { name: /^new address$/i })).toBeVisible()+ await fillAddressForm(page, {+ address1: '1 Test Street',+ city: 'Austin',+ postalCode: '78701',+ })+ await page+ .getByRole('dialog')+ .getByRole('button', { name: /^save$/i })+ .click()++ await expect(page.getByText(/state \/ province is required/i)).toBeVisible({+ timeout: 15_000,+ })+ await expect(addressBook.getByText('1 Test Street')).toHaveCount(0)+ })+test('adds an address to the address book', async ({ page }) => {const creds = await login(page)await createCompany(page, creds.store_id, `E2E Depots ${Date.now()}`)