diff --git a/web/src/api/queries.ts b/web/src/api/queries.ts index d53d672..5741123 100644 --- a/web/src/api/queries.ts +++ b/web/src/api/queries.ts @@ -10,6 +10,13 @@ export class HttpError extends Error { } } +export class FieldRejection extends Error { + constructor(public readonly field: string, public readonly code: string) { + super(`field rejected: ${field}`); + this.name = "FieldRejection"; + } +} + type UserView = components["schemas"]["UserView"]; type LoginRequest = components["schemas"]["LoginRequest"]; @@ -179,12 +186,19 @@ export function useSetFields() { return useMutation({ mutationFn: async ({ id, fields }: { id: string; fields: Record }) => { - const { response } = await api.PUT("/api/admin/objects/{id}/fields", { + const { response, error } = await api.PUT("/api/admin/objects/{id}/fields", { params: { path: { id } }, body: fields as Record, }); - if (response.status !== 204) throw new Error("set fields failed"); + if (response.status === 204) return; + + if (response.status === 422 && error && typeof error === "object" && "field" in error) { + const detail = error as { field: string; code: string }; + throw new FieldRejection(detail.field, detail.code); + } + + throw new Error("set fields failed"); }, onSuccess: (_d, { id }) => { void qc.invalidateQueries({ queryKey: ["object", id] }); diff --git a/web/src/i18n/en.json b/web/src/i18n/en.json index b07cfce..8f798b5 100644 --- a/web/src/i18n/en.json +++ b/web/src/i18n/en.json @@ -5,7 +5,7 @@ "objects": { "title": "Objects", "empty": "No objects yet", "loadError": "Could not load objects", "selectPrompt": "Select an object to view its details", "notFound": "Object not found", "prev": "Previous", "next": "Next", "of": "of", "new": "New object" }, "fieldsLabels": { "objectNumber": "Object number", "objectName": "Name", "count": "Number of objects", "briefDescription": "Brief description", "currentLocation": "Current location", "currentOwner": "Current owner", "recorder": "Recorder", "recordingDate": "Recording date", "visibility": "Visibility", "flexible": "Catalogue fields" }, "visibility": { "draft": "Draft", "internal": "Internal", "public": "Public" }, - "form": { "selectPlaceholder": "— select —", "create": "Create object", "save": "Save", "cancel": "Cancel", "visibility": "Visibility", "draft": "Draft", "internal": "Internal", "required": "This field is required", "rejected": "The server rejected the changes — check required and referenced fields", "flexibleHeading": "Catalogue fields" }, + "form": { "selectPlaceholder": "— select —", "create": "Create object", "save": "Save", "cancel": "Cancel", "visibility": "Visibility", "draft": "Draft", "internal": "Internal", "required": "This field is required", "rejected": "The server rejected the changes — check required and referenced fields", "fieldRejected": "The field \"{{field}}\" was rejected — check its value", "flexibleHeading": "Catalogue fields" }, "actions": { "edit": "Edit", "delete": "Delete", "confirmDelete": "Delete this object? This cannot be undone." }, "labels": { "label": "Label", "externalUri": "External URI (optional)" }, "vocab": { diff --git a/web/src/i18n/sv.json b/web/src/i18n/sv.json index b6c7567..725ab38 100644 --- a/web/src/i18n/sv.json +++ b/web/src/i18n/sv.json @@ -5,7 +5,7 @@ "objects": { "title": "Föremål", "empty": "Inga föremål ännu", "loadError": "Kunde inte ladda föremål", "selectPrompt": "Välj ett föremål för att se detaljer", "notFound": "Föremålet hittades inte", "prev": "Föregående", "next": "Nästa", "of": "av", "new": "Nytt föremål" }, "fieldsLabels": { "objectNumber": "Föremålsnummer", "objectName": "Namn", "count": "Antal föremål", "briefDescription": "Kort beskrivning", "currentLocation": "Nuvarande plats", "currentOwner": "Nuvarande ägare", "recorder": "Registrerad av", "recordingDate": "Registreringsdatum", "visibility": "Synlighet", "flexible": "Katalogfält" }, "visibility": { "draft": "Utkast", "internal": "Intern", "public": "Publik" }, - "form": { "selectPlaceholder": "— välj —", "create": "Skapa föremål", "save": "Spara", "cancel": "Avbryt", "visibility": "Synlighet", "draft": "Utkast", "internal": "Intern", "required": "Fältet är obligatoriskt", "rejected": "Servern avvisade ändringarna — kontrollera obligatoriska och refererade fält", "flexibleHeading": "Katalogfält" }, + "form": { "selectPlaceholder": "— välj —", "create": "Skapa föremål", "save": "Spara", "cancel": "Avbryt", "visibility": "Synlighet", "draft": "Utkast", "internal": "Intern", "required": "Fältet är obligatoriskt", "rejected": "Servern avvisade ändringarna — kontrollera obligatoriska och refererade fält", "fieldRejected": "Fältet \"{{field}}\" avvisades — kontrollera värdet", "flexibleHeading": "Katalogfält" }, "actions": { "edit": "Redigera", "delete": "Ta bort", "confirmDelete": "Ta bort detta föremål? Detta kan inte ångras." }, "labels": { "label": "Etikett", "externalUri": "Extern URI (valfritt)" }, "vocab": { diff --git a/web/src/objects/object-edit-form.test.tsx b/web/src/objects/object-edit-form.test.tsx index 590597d..f5cee74 100644 --- a/web/src/objects/object-edit-form.test.tsx +++ b/web/src/objects/object-edit-form.test.tsx @@ -17,6 +17,26 @@ function tree() { ); } +test("edit: fields PUT 422 with field body -> field error message shown and field marked invalid", async () => { + server.use( + http.get("/api/admin/objects/:id", () => + HttpResponse.json({ ...amphora, fields: { inscription: "old" } }), + ), + http.put("/api/admin/objects/:id", () => new HttpResponse(null, { status: 204 })), + http.put("/api/admin/objects/:id/fields", () => + HttpResponse.json({ field: "inscription", code: "type_mismatch" }, { status: 422 }), + ), + ); + + renderApp(tree(), { route: `/objects/${amphora.id}/edit` }); + + await screen.findByDisplayValue("Amphora"); + await userEvent.click(screen.getByRole("button", { name: /save/i })); + + const alerts = await screen.findAllByText(/inscription.*rejected/i); + expect(alerts.length).toBeGreaterThanOrEqual(2); +}); + test("edit: prefilled, save -> PUT core + PUT fields -> back to detail", async () => { let putCore: unknown; let putFields: unknown; diff --git a/web/src/objects/object-edit-form.tsx b/web/src/objects/object-edit-form.tsx index 63bb105..901eebe 100644 --- a/web/src/objects/object-edit-form.tsx +++ b/web/src/objects/object-edit-form.tsx @@ -2,7 +2,7 @@ import { useState } from "react"; import { useLocation, useNavigate, useParams } from "react-router-dom"; import { useTranslation } from "react-i18next"; -import { useObject, useUpdateObject, useSetFields } from "../api/queries"; +import { useObject, useUpdateObject, useSetFields, FieldRejection } from "../api/queries"; import { ObjectForm, type ObjectCore, type ObjectFormValues } from "./object-form"; export function ObjectEditForm() { @@ -15,8 +15,14 @@ export function ObjectEditForm() { const update = useUpdateObject(); const setFields = useSetFields(); + const locationState = location.state as { fieldsError?: boolean; fieldErrorKey?: string } | null; + const [error, setError] = useState( - (location.state as { fieldsError?: boolean } | null)?.fieldsError ? t("form.rejected") : null, + locationState?.fieldsError ? t("form.rejected") : null, + ); + + const [fieldErrorKey, setFieldErrorKey] = useState( + locationState?.fieldErrorKey ?? null, ); if (isLoading) return
; @@ -38,12 +44,19 @@ export function ObjectEditForm() { const onSubmit = async (values: ObjectFormValues) => { setError(null); + setFieldErrorKey(null); try { await update.mutateAsync({ id: id!, body: values.core }); await setFields.mutateAsync({ id: id!, fields: values.fields }); - } catch { - setError(t("form.rejected")); + } catch (e) { + if (e instanceof FieldRejection) { + setFieldErrorKey(e.field); + setError(t("form.fieldRejected", { field: e.field })); + } else { + setError(t("form.rejected")); + } + return; } @@ -55,6 +68,7 @@ export function ObjectEditForm() { mode="edit" defaults={defaults} formError={error} + fieldErrorKey={fieldErrorKey} onSubmit={onSubmit} onCancel={() => navigate(`/objects/${id}`)} /> diff --git a/web/src/objects/object-form.tsx b/web/src/objects/object-form.tsx index b450502..de84807 100644 --- a/web/src/objects/object-form.tsx +++ b/web/src/objects/object-form.tsx @@ -1,3 +1,4 @@ +import { useEffect } from "react"; import { useForm } from "react-hook-form"; import { useTranslation } from "react-i18next"; @@ -47,12 +48,14 @@ export function ObjectForm({ onSubmit, onCancel, formError, + fieldErrorKey, }: { mode: "create" | "edit"; defaults?: { core: ObjectCore; fields: Record }; onSubmit: (values: ObjectFormValues) => void; onCancel: () => void; formError?: string | null; + fieldErrorKey?: string | null; }) { const { t } = useTranslation(); @@ -68,6 +71,15 @@ export function ObjectForm({ const { register, handleSubmit, formState: { errors } } = form; + useEffect(() => { + if (fieldErrorKey) { + form.setError(`fields.${fieldErrorKey}` as never, { + type: "server", + message: t("form.fieldRejected", { field: fieldErrorKey }), + }); + } + }, [fieldErrorKey, form, t]); + const submit = handleSubmit((data) => { const fields = pruneFields(data.fields); @@ -149,7 +161,7 @@ export function ObjectForm({ {errors.fields?.[def.key] && (

- {t("form.required")} + {errors.fields[def.key]?.message ?? t("form.required")}

)}
diff --git a/web/src/objects/object-new-page.tsx b/web/src/objects/object-new-page.tsx index d6010bc..6f69c3a 100644 --- a/web/src/objects/object-new-page.tsx +++ b/web/src/objects/object-new-page.tsx @@ -3,7 +3,7 @@ import { useNavigate } from "react-router-dom"; import { useTranslation } from "react-i18next"; import { ObjectForm, type ObjectFormValues } from "./object-form"; -import { useCreateObject, useSetFields } from "../api/queries"; +import { useCreateObject, useSetFields, FieldRejection } from "../api/queries"; export function ObjectNewPage() { const { t } = useTranslation(); @@ -32,8 +32,9 @@ export function ObjectNewPage() { if (Object.keys(values.fields).length > 0) { try { await setFields.mutateAsync({ id, fields: values.fields }); - } catch { - navigate(`/objects/${id}/edit`, { state: { fieldsError: true } }); + } catch (e) { + const fieldErrorKey = e instanceof FieldRejection ? e.field : undefined; + navigate(`/objects/${id}/edit`, { state: { fieldsError: true, fieldErrorKey } }); return; } }