Просмотр исходного кода

Show form errors next to the field, in the user's language (#682)

* Show form errors next to the field, in the user's language

* Read the changed field's name without a type cast
Bernt Christian Egeland 3 дней назад
Родитель
Сommit
18c7f279fd
83 измененных файлов с 1434 добавлено и 81 удалено
  1. 38 0
      e2e/specs/customers/field-errors.spec.ts
  2. 14 0
      messages/bg/common.json
  3. 2 1
      messages/bg/faultCodes.json
  4. 1 1
      messages/bg/laborPresets.json
  5. 2 1
      messages/bg/vehicles.json
  6. 14 0
      messages/de/common.json
  7. 2 1
      messages/de/faultCodes.json
  8. 1 1
      messages/de/laborPresets.json
  9. 2 1
      messages/de/vehicles.json
  10. 14 0
      messages/en/common.json
  11. 2 1
      messages/en/faultCodes.json
  12. 1 1
      messages/en/laborPresets.json
  13. 2 1
      messages/en/vehicles.json
  14. 14 0
      messages/es/common.json
  15. 2 1
      messages/es/faultCodes.json
  16. 1 1
      messages/es/laborPresets.json
  17. 2 1
      messages/es/vehicles.json
  18. 14 0
      messages/fr/common.json
  19. 2 1
      messages/fr/faultCodes.json
  20. 1 1
      messages/fr/laborPresets.json
  21. 2 1
      messages/fr/vehicles.json
  22. 14 0
      messages/it/common.json
  23. 2 1
      messages/it/faultCodes.json
  24. 1 1
      messages/it/laborPresets.json
  25. 2 1
      messages/it/vehicles.json
  26. 14 0
      messages/lt/common.json
  27. 2 1
      messages/lt/faultCodes.json
  28. 1 1
      messages/lt/laborPresets.json
  29. 2 1
      messages/lt/vehicles.json
  30. 14 0
      messages/nb/common.json
  31. 2 1
      messages/nb/faultCodes.json
  32. 1 1
      messages/nb/laborPresets.json
  33. 2 1
      messages/nb/vehicles.json
  34. 14 0
      messages/nl/common.json
  35. 2 1
      messages/nl/faultCodes.json
  36. 1 1
      messages/nl/laborPresets.json
  37. 2 1
      messages/nl/vehicles.json
  38. 14 0
      messages/pl/common.json
  39. 2 1
      messages/pl/faultCodes.json
  40. 1 1
      messages/pl/laborPresets.json
  41. 2 1
      messages/pl/vehicles.json
  42. 14 0
      messages/pt-BR/common.json
  43. 2 1
      messages/pt-BR/faultCodes.json
  44. 1 1
      messages/pt-BR/laborPresets.json
  45. 2 1
      messages/pt-BR/vehicles.json
  46. 14 0
      messages/pt-PT/common.json
  47. 2 1
      messages/pt-PT/faultCodes.json
  48. 1 1
      messages/pt-PT/laborPresets.json
  49. 2 1
      messages/pt-PT/vehicles.json
  50. 14 0
      messages/ru/common.json
  51. 2 1
      messages/ru/faultCodes.json
  52. 1 1
      messages/ru/laborPresets.json
  53. 2 1
      messages/ru/vehicles.json
  54. 14 0
      messages/tr/common.json
  55. 2 1
      messages/tr/faultCodes.json
  56. 1 1
      messages/tr/laborPresets.json
  57. 2 1
      messages/tr/vehicles.json
  58. 112 0
      src/__tests__/features/customers/customer-form-field-errors.test.tsx
  59. 19 0
      src/__tests__/features/fault-codes/codes.test.ts
  60. 16 0
      src/__tests__/features/fault-codes/components.test.tsx
  61. 93 0
      src/__tests__/features/labor-presets/preset-item-name.test.tsx
  62. 20 0
      src/__tests__/features/meters/meter-value.test.ts
  63. 64 0
      src/__tests__/features/meters/reading-refused-next-to-field.test.tsx
  64. 131 0
      src/__tests__/features/vehicles/vehicle-form-field-errors.test.tsx
  65. 60 0
      src/__tests__/lib/field-errors.test.ts
  66. 2 0
      src/__tests__/lib/with-auth.test.ts
  67. 123 0
      src/components/field-errors.tsx
  68. 39 0
      src/features/customers/Components/CustomerForm.tsx
  69. 20 1
      src/features/fault-codes/Components/FaultCodeEntryDialog.tsx
  70. 22 0
      src/features/fault-codes/Lib/codes.ts
  71. 58 9
      src/features/labor-presets/Components/LaborPresetForm.tsx
  72. 27 0
      src/features/labor-presets/Lib/namelessItems.ts
  73. 3 1
      src/features/meters/Actions/jobMeterActions.ts
  74. 25 5
      src/features/meters/Components/JobMeters.tsx
  75. 81 16
      src/features/meters/Components/VehicleMeters.tsx
  76. 23 0
      src/features/meters/Lib/meterValue.ts
  77. 8 2
      src/features/meters/Lib/readingInput.server.ts
  78. 55 2
      src/features/vehicles/Components/VehicleForm.tsx
  79. 35 0
      src/features/vehicles/Components/service-page/useServiceActions.ts
  80. 7 0
      src/features/vehicles/Lib/vehicleYear.ts
  81. 3 2
      src/features/vehicles/Schema/vehicleSchema.ts
  82. 75 0
      src/lib/field-errors.ts
  83. 9 1
      src/lib/with-auth.ts

+ 38 - 0
e2e/specs/customers/field-errors.spec.ts

@@ -0,0 +1,38 @@
+import { expect, test } from '@playwright/test'
+
+/**
+ * What the server refuses on a form is said under the field it is about, in
+ * the person's words: the server's schema, its error shape and the form all
+ * have to be put together for this to work, so it is checked here end to end.
+ *
+ * It used to be a box over the form reading "email: Invalid email". An
+ * address the browser takes as one ("kari@nordvik") is still refused by the
+ * server, which is how this reaches the server at all. Nothing is saved.
+ */
+test('an email the server refuses is said under the email, and nothing typed is lost', async ({
+  page,
+}) => {
+  await page.goto('/customers')
+  await page.getByRole('button', { name: 'Add Customer' }).first().click()
+  const dialog = page.getByRole('dialog', { name: 'Add New Customer' })
+  await expect(dialog).toBeVisible()
+
+  const name = `E2E field errors ${Date.now()}`
+  await dialog.locator('#name').fill(name)
+  await dialog.locator('#email').fill('kari@nordvik')
+  await dialog.locator('button[type="submit"]').click()
+
+  const email = dialog.locator('#email')
+  await expect(dialog.getByText('Enter an email address like name@example.com.')).toBeVisible()
+  await expect(email).toHaveAttribute('aria-invalid', 'true')
+  await expect(email).toBeFocused()
+  await expect(page.getByText(/Invalid email/)).toHaveCount(0)
+  // The dialog stays on what was typed.
+  await expect(dialog.locator('#name')).toHaveValue(name)
+  await expect(email).toHaveValue('kari@nordvik')
+
+  // Fixing it takes the mark away.
+  await email.fill('kari@example.com')
+  await expect(dialog.getByText('Enter an email address like name@example.com.')).toHaveCount(0)
+  await expect(email).not.toHaveAttribute('aria-invalid', 'true')
+})

+ 14 - 0
messages/bg/common.json

@@ -328,5 +328,19 @@
     "ok": "Паролата отговаря на изискванията.",
     "mismatch": "Не съвпада с паролата по-горе.",
     "match": "Паролите съвпадат."
+  },
+  "fieldErrors": {
+    "required": "Попълнете това поле.",
+    "email": "Въведете имейл адрес, например name@example.com.",
+    "tooShort": "Използвайте поне {limit} знака.",
+    "tooLong": "Използвайте най-много {limit} знака.",
+    "negative": "Не може да е отрицателно.",
+    "tooSmall": "Трябва да е поне {limit}.",
+    "tooLarge": "Трябва да е {limit} или по-малко.",
+    "notNumber": "Въведете число.",
+    "wholeNumber": "Въведете цяло число.",
+    "invalid": "Тази стойност е невалидна.",
+    "notSaved": "Не е запазено. Проверете отбелязаните полета.",
+    "withLabel": "{label}: {problem}"
   }
 }

+ 2 - 1
messages/bg/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# код вече е добавен към тази работна поръчка} other {# кода вече са добавени към тази работна поръчка}}",
     "failed": "Кодовете не можаха да бъдат добавени",
     "descriptionOem": "Въведете или поставете кодовете от диагностичния уред: OBD кодове като P0420 или кодове на BMW като 2A82. Всеки код се превръща в наблюдение към тази работна поръчка, като значението му се запазва.",
-    "placeholderOem": "P0420, 2A82 stored"
+    "placeholderOem": "P0420, 2A82 stored",
+    "unrecognised": "{count, plural, one {Не е код за грешка, пропуснат: {codes}} other {Не са кодове за грешки, пропуснати: {codes}}}"
   },
   "finding": {
     "seenBefore": "Засечен на {date}",

+ 1 - 1
messages/bg/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "Пакетът за труд не можа да бъде запазен",
     "deleteFailed": "Пакетът за труд не можа да бъде изтрит",
     "loadFailed": "Пакетът за труд не можа да бъде зареден",
-    "noItems": "Необходима е поне една позиция"
+    "itemNameMissing": "Дайте име на тази позиция."
   }
 }

+ 2 - 1
messages/bg/vehicles.json

@@ -749,6 +749,7 @@
     "added": "{name} е добавен",
     "itemTitle": "Броячи",
     "noItemMeters": "Няма броячи на това оборудване.",
-    "addItemMeterHint": "Броячът следва това оборудване, където и да е монтирано."
+    "addItemMeterHint": "Броячът следва това оборудване, където и да е монтирано.",
+    "negativeReading": "Показанието не може да е отрицателно."
   }
 }

+ 14 - 0
messages/de/common.json

@@ -328,5 +328,19 @@
     "irreversible": "Dies kann nicht rückgängig gemacht werden.",
     "andMore": "und {count} weitere",
     "typeToConfirm": "Geben Sie <b>{text}</b> zur Bestätigung ein"
+  },
+  "fieldErrors": {
+    "required": "Bitte ausfüllen.",
+    "email": "Geben Sie eine E-Mail-Adresse wie name@beispiel.de ein.",
+    "tooShort": "Mindestens {limit} Zeichen.",
+    "tooLong": "Höchstens {limit} Zeichen.",
+    "negative": "Darf nicht negativ sein.",
+    "tooSmall": "Muss mindestens {limit} sein.",
+    "tooLarge": "Darf höchstens {limit} sein.",
+    "notNumber": "Geben Sie eine Zahl ein.",
+    "wholeNumber": "Geben Sie eine ganze Zahl ein.",
+    "invalid": "Dieser Wert ist ungültig.",
+    "notSaved": "Nicht gespeichert. Prüfen Sie die markierten Felder.",
+    "withLabel": "{label}: {problem}"
   }
 }

+ 2 - 1
messages/de/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# Code war schon an diesem Auftrag} other {# Codes waren schon an diesem Auftrag}}",
     "failed": "Die Codes konnten nicht hinzugefügt werden",
     "descriptionOem": "Tippen oder fügen Sie Codes vom Diagnosegerät ein, OBD-Codes wie P0420 oder BMW-Codes wie 2A82. Jeder wird eine Beobachtung an diesem Auftrag, mit gespeicherter Bedeutung.",
-    "placeholderOem": "P0420, 2A82 gespeichert"
+    "placeholderOem": "P0420, 2A82 gespeichert",
+    "unrecognised": "{count, plural, one {Kein Fehlercode, ausgelassen: {codes}} other {Keine Fehlercodes, ausgelassen: {codes}}}"
   },
   "finding": {
     "seenBefore": "Gesehen {date}",

+ 1 - 1
messages/de/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "Arbeitsvorlage konnte nicht gespeichert werden",
     "deleteFailed": "Arbeitsvorlage konnte nicht gelöscht werden",
     "loadFailed": "Arbeitsvorlage konnte nicht geladen werden",
-    "noItems": "Mindestens eine Position ist erforderlich"
+    "itemNameMissing": "Geben Sie diesem Eintrag einen Namen."
   }
 }

+ 2 - 1
messages/de/vehicles.json

@@ -749,6 +749,7 @@
     "added": "{name} hinzugefügt",
     "itemTitle": "Zähler",
     "noItemMeters": "Keine Zähler an diesem Eintrag.",
-    "addItemMeterHint": "Der Zähler bleibt bei diesem Eintrag, egal wo er montiert ist."
+    "addItemMeterHint": "Der Zähler bleibt bei diesem Eintrag, egal wo er montiert ist.",
+    "negativeReading": "Ein Zählerstand kann nicht negativ sein."
   }
 }

+ 14 - 0
messages/en/common.json

@@ -328,5 +328,19 @@
     "irreversible": "This cannot be undone.",
     "andMore": "and {count} more",
     "typeToConfirm": "Type <b>{text}</b> to confirm"
+  },
+  "fieldErrors": {
+    "required": "Fill this in.",
+    "email": "Enter an email address like name@example.com.",
+    "tooShort": "Use at least {limit} characters.",
+    "tooLong": "Use at most {limit} characters.",
+    "negative": "Can't be negative.",
+    "tooSmall": "Must be at least {limit}.",
+    "tooLarge": "Must be {limit} or less.",
+    "notNumber": "Enter a number.",
+    "wholeNumber": "Enter a whole number.",
+    "invalid": "This value isn't valid.",
+    "notSaved": "Not saved. Check the marked fields.",
+    "withLabel": "{label}: {problem}"
   }
 }

+ 2 - 1
messages/en/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# code was already on this job} other {# codes were already on this job}}",
     "failed": "Could not add the codes",
     "descriptionOem": "Type or paste codes from the scan tool, OBD codes like P0420 or BMW codes like 2A82. Each one becomes an observation on this job, with its meaning saved.",
-    "placeholderOem": "P0420, 2A82 stored"
+    "placeholderOem": "P0420, 2A82 stored",
+    "unrecognised": "{count, plural, one {Not a fault code, left out: {codes}} other {Not fault codes, left out: {codes}}}"
   },
   "finding": {
     "seenBefore": "Seen {date}",

+ 1 - 1
messages/en/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "Failed to save labor package",
     "deleteFailed": "Failed to delete labor package",
     "loadFailed": "Failed to load labor package",
-    "noItems": "At least one item is required"
+    "itemNameMissing": "Give this item a name."
   }
 }

+ 2 - 1
messages/en/vehicles.json

@@ -749,6 +749,7 @@
     "added": "{name} added",
     "itemTitle": "Meters",
     "noItemMeters": "No meters on this item.",
-    "addItemMeterHint": "The meter goes with this item wherever it is fitted."
+    "addItemMeterHint": "The meter goes with this item wherever it is fitted.",
+    "negativeReading": "A reading can't be negative."
   }
 }

+ 14 - 0
messages/es/common.json

@@ -328,5 +328,19 @@
     "irreversible": "Esta acción no se puede deshacer.",
     "andMore": "y {count} más",
     "typeToConfirm": "Escriba <b>{text}</b> para confirmar"
+  },
+  "fieldErrors": {
+    "required": "Rellena este campo.",
+    "email": "Introduce un correo electrónico como nombre@ejemplo.com.",
+    "tooShort": "Usa al menos {limit} caracteres.",
+    "tooLong": "Usa como máximo {limit} caracteres.",
+    "negative": "No puede ser negativo.",
+    "tooSmall": "Debe ser al menos {limit}.",
+    "tooLarge": "Debe ser {limit} o menos.",
+    "notNumber": "Introduce un número.",
+    "wholeNumber": "Introduce un número entero.",
+    "invalid": "Este valor no es válido.",
+    "notSaved": "No se ha guardado. Revisa los campos marcados.",
+    "withLabel": "{label}: {problem}"
   }
 }

+ 2 - 1
messages/es/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# código ya estaba en este trabajo} other {# códigos ya estaban en este trabajo}}",
     "failed": "No se pudieron añadir los códigos",
     "descriptionOem": "Escribe o pega los códigos del equipo de diagnosis, códigos OBD como P0420 o códigos BMW como 2A82. Cada uno se convierte en una observación de este trabajo, con su significado guardado.",
-    "placeholderOem": "P0420, 2A82 almacenado"
+    "placeholderOem": "P0420, 2A82 almacenado",
+    "unrecognised": "{count, plural, one {No es un código de avería, omitido: {codes}} other {No son códigos de avería, omitidos: {codes}}}"
   },
   "finding": {
     "seenBefore": "Visto {date}",

+ 1 - 1
messages/es/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "Error al guardar la plantilla de mano de obra",
     "deleteFailed": "Error al eliminar la plantilla de mano de obra",
     "loadFailed": "Error al cargar la plantilla de mano de obra",
-    "noItems": "Se requiere al menos un elemento"
+    "itemNameMissing": "Ponle un nombre a este elemento."
   }
 }

+ 2 - 1
messages/es/vehicles.json

@@ -749,6 +749,7 @@
     "added": "{name} añadido",
     "itemTitle": "Contadores",
     "noItemMeters": "Este elemento no tiene contadores.",
-    "addItemMeterHint": "El contador va con este elemento dondequiera que esté instalado."
+    "addItemMeterHint": "El contador va con este elemento dondequiera que esté instalado.",
+    "negativeReading": "Una lectura no puede ser negativa."
   }
 }

+ 14 - 0
messages/fr/common.json

@@ -328,5 +328,19 @@
     "irreversible": "Cette action est irréversible.",
     "andMore": "et {count} de plus",
     "typeToConfirm": "Saisissez <b>{text}</b> pour confirmer"
+  },
+  "fieldErrors": {
+    "required": "Remplissez ce champ.",
+    "email": "Saisissez une adresse e-mail comme nom@exemple.fr.",
+    "tooShort": "Utilisez au moins {limit} caractères.",
+    "tooLong": "Utilisez au plus {limit} caractères.",
+    "negative": "Ne peut pas être négatif.",
+    "tooSmall": "Doit être au moins {limit}.",
+    "tooLarge": "Doit être {limit} ou moins.",
+    "notNumber": "Saisissez un nombre.",
+    "wholeNumber": "Saisissez un nombre entier.",
+    "invalid": "Cette valeur n'est pas valide.",
+    "notSaved": "Non enregistré. Vérifiez les champs signalés.",
+    "withLabel": "{label} : {problem}"
   }
 }

+ 2 - 1
messages/fr/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# code figurait déjà sur ce travail} other {# codes figuraient déjà sur ce travail}}",
     "failed": "Impossible d'ajouter les codes",
     "descriptionOem": "Saisissez ou collez les codes de l'outil de diagnostic, des codes OBD comme P0420 ou des codes BMW comme 2A82. Chacun devient une observation sur ce travail, avec sa signification enregistrée.",
-    "placeholderOem": "P0420, 2A82 mémorisé"
+    "placeholderOem": "P0420, 2A82 mémorisé",
+    "unrecognised": "{count, plural, one {Pas un code défaut, ignoré : {codes}} other {Pas des codes défaut, ignorés : {codes}}}"
   },
   "finding": {
     "seenBefore": "Vu {date}",

+ 1 - 1
messages/fr/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "Échec de l'enregistrement du modèle de main-d'œuvre",
     "deleteFailed": "Échec de la suppression du modèle de main-d'œuvre",
     "loadFailed": "Échec du chargement du modèle de main-d'œuvre",
-    "noItems": "Au moins un élément est requis"
+    "itemNameMissing": "Donnez un nom à cet élément."
   }
 }

+ 2 - 1
messages/fr/vehicles.json

@@ -749,6 +749,7 @@
     "added": "{name} ajouté",
     "itemTitle": "Compteurs",
     "noItemMeters": "Aucun compteur sur cet élément.",
-    "addItemMeterHint": "Le compteur suit cet élément, quel que soit l'endroit où il est monté."
+    "addItemMeterHint": "Le compteur suit cet élément, quel que soit l'endroit où il est monté.",
+    "negativeReading": "Un relevé ne peut pas être négatif."
   }
 }

+ 14 - 0
messages/it/common.json

@@ -328,5 +328,19 @@
     "irreversible": "Questa azione non può essere annullata.",
     "andMore": "e altri {count}",
     "typeToConfirm": "Digita <b>{text}</b> per confermare"
+  },
+  "fieldErrors": {
+    "required": "Compila questo campo.",
+    "email": "Inserisci un indirizzo email come nome@esempio.it.",
+    "tooShort": "Usa almeno {limit} caratteri.",
+    "tooLong": "Usa al massimo {limit} caratteri.",
+    "negative": "Non può essere negativo.",
+    "tooSmall": "Deve essere almeno {limit}.",
+    "tooLarge": "Deve essere {limit} o meno.",
+    "notNumber": "Inserisci un numero.",
+    "wholeNumber": "Inserisci un numero intero.",
+    "invalid": "Questo valore non è valido.",
+    "notSaved": "Non salvato. Controlla i campi evidenziati.",
+    "withLabel": "{label}: {problem}"
   }
 }

+ 2 - 1
messages/it/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# codice era già su questo lavoro} other {# codici erano già su questo lavoro}}",
     "failed": "Impossibile aggiungere i codici",
     "descriptionOem": "Digita o incolla i codici dallo strumento di diagnosi, codici OBD come P0420 o codici BMW come 2A82. Ognuno diventa un’osservazione su questo lavoro, con il significato salvato.",
-    "placeholderOem": "P0420, 2A82 memorizzato"
+    "placeholderOem": "P0420, 2A82 memorizzato",
+    "unrecognised": "{count, plural, one {Non è un codice guasto, escluso: {codes}} other {Non sono codici guasto, esclusi: {codes}}}"
   },
   "finding": {
     "seenBefore": "Visto {date}",

+ 1 - 1
messages/it/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "Impossibile salvare il modello di manodopera",
     "deleteFailed": "Impossibile eliminare il modello di manodopera",
     "loadFailed": "Impossibile caricare il modello di manodopera",
-    "noItems": "È richiesta almeno una voce"
+    "itemNameMissing": "Dai un nome a questa voce."
   }
 }

+ 2 - 1
messages/it/vehicles.json

@@ -749,6 +749,7 @@
     "added": "{name} aggiunto",
     "itemTitle": "Contatori",
     "noItemMeters": "Nessun contatore su questo elemento.",
-    "addItemMeterHint": "Il contatore segue questo elemento ovunque sia montato."
+    "addItemMeterHint": "Il contatore segue questo elemento ovunque sia montato.",
+    "negativeReading": "Una lettura non può essere negativa."
   }
 }

+ 14 - 0
messages/lt/common.json

@@ -328,5 +328,19 @@
     "irreversible": "Šio veiksmo negalima atšaukti.",
     "andMore": "ir dar {count}",
     "typeToConfirm": "Įveskite <b>{text}</b>, kad patvirtintumėte"
+  },
+  "fieldErrors": {
+    "required": "Užpildykite šį lauką.",
+    "email": "Įveskite el. pašto adresą, pvz., vardas@pavyzdys.lt.",
+    "tooShort": "Naudokite bent {limit} simbolių.",
+    "tooLong": "Naudokite ne daugiau kaip {limit} simbolių.",
+    "negative": "Negali būti neigiamas.",
+    "tooSmall": "Turi būti ne mažiau kaip {limit}.",
+    "tooLarge": "Turi būti {limit} arba mažiau.",
+    "notNumber": "Įveskite skaičių.",
+    "wholeNumber": "Įveskite sveikąjį skaičių.",
+    "invalid": "Ši reikšmė netinkama.",
+    "notSaved": "Neišsaugota. Patikrinkite pažymėtus laukus.",
+    "withLabel": "{label}: {problem}"
   }
 }

+ 2 - 1
messages/lt/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# kodas jau buvo šiame darbe} few {# kodai jau buvo šiame darbe} many {# kodo jau buvo šiame darbe} other {# kodų jau buvo šiame darbe}}",
     "failed": "Nepavyko pridėti kodų",
     "descriptionOem": "Įveskite arba įklijuokite kodus iš diagnostikos įrangos: OBD kodus, pvz., P0420, arba BMW kodus, pvz., 2A82. Kiekvienas tampa šio darbo pastaba su išsaugota reikšme.",
-    "placeholderOem": "P0420, 2A82 išsaugotas"
+    "placeholderOem": "P0420, 2A82 išsaugotas",
+    "unrecognised": "{count, plural, one {Ne gedimo kodas, praleista: {codes}} few {Ne gedimo kodai, praleista: {codes}} other {Ne gedimo kodai, praleista: {codes}}}"
   },
   "finding": {
     "seenBefore": "Matytas {date}",

+ 1 - 1
messages/lt/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "Nepavyko išsaugoti darbų šablono",
     "deleteFailed": "Nepavyko ištrinti darbų šablono",
     "loadFailed": "Nepavyko įkelti darbų šablono",
-    "noItems": "Reikalingas bent vienas elementas"
+    "itemNameMissing": "Suteikite šiai eilutei pavadinimą."
   }
 }

+ 2 - 1
messages/lt/vehicles.json

@@ -749,6 +749,7 @@
     "added": "{name} pridėtas",
     "itemTitle": "Skaitikliai",
     "noItemMeters": "Šis vienetas neturi skaitiklių.",
-    "addItemMeterHint": "Skaitiklis keliauja su šiuo vienetu, kad ir kur jis būtų sumontuotas."
+    "addItemMeterHint": "Skaitiklis keliauja su šiuo vienetu, kad ir kur jis būtų sumontuotas.",
+    "negativeReading": "Rodmuo negali būti neigiamas."
   }
 }

+ 14 - 0
messages/nb/common.json

@@ -328,5 +328,19 @@
     "irreversible": "Dette kan ikke angres.",
     "andMore": "og {count} til",
     "typeToConfirm": "Skriv <b>{text}</b> for å bekrefte"
+  },
+  "fieldErrors": {
+    "required": "Fyll ut dette feltet.",
+    "email": "Skriv inn en e-postadresse, for eksempel navn@eksempel.no.",
+    "tooShort": "Bruk minst {limit} tegn.",
+    "tooLong": "Bruk høyst {limit} tegn.",
+    "negative": "Kan ikke være negativ.",
+    "tooSmall": "Må være minst {limit}.",
+    "tooLarge": "Må være {limit} eller mindre.",
+    "notNumber": "Skriv inn et tall.",
+    "wholeNumber": "Skriv inn et heltall.",
+    "invalid": "Denne verdien er ikke gyldig.",
+    "notSaved": "Ikke lagret. Sjekk de merkede feltene.",
+    "withLabel": "{label}: {problem}"
   }
 }

+ 2 - 1
messages/nb/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# kode var allerede på denne jobben} other {# koder var allerede på denne jobben}}",
     "failed": "Kunne ikke legge til kodene",
     "descriptionOem": "Skriv eller lim inn koder fra skanneren, OBD-koder som P0420 eller BMW-koder som 2A82. Hver kode blir en observasjon på denne jobben, med betydningen lagret.",
-    "placeholderOem": "P0420, 2A82 lagret"
+    "placeholderOem": "P0420, 2A82 lagret",
+    "unrecognised": "{count, plural, one {Ikke en feilkode, utelatt: {codes}} other {Ikke feilkoder, utelatt: {codes}}}"
   },
   "finding": {
     "seenBefore": "Sett {date}",

+ 1 - 1
messages/nb/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "Kunne ikke lagre arbeidsmalen",
     "deleteFailed": "Kunne ikke slette arbeidsmalen",
     "loadFailed": "Kunne ikke laste arbeidsmalen",
-    "noItems": "Minst ett element er påkrevd"
+    "itemNameMissing": "Gi denne posten et navn."
   }
 }

+ 2 - 1
messages/nb/vehicles.json

@@ -749,6 +749,7 @@
     "added": "{name} lagt til",
     "itemTitle": "Målere",
     "noItemMeters": "Ingen målere på denne enheten.",
-    "addItemMeterHint": "Måleren følger denne enheten uansett hvor den er montert."
+    "addItemMeterHint": "Måleren følger denne enheten uansett hvor den er montert.",
+    "negativeReading": "En avlesning kan ikke være negativ."
   }
 }

+ 14 - 0
messages/nl/common.json

@@ -328,5 +328,19 @@
     "irreversible": "Dit kan niet ongedaan worden gemaakt.",
     "andMore": "en {count} meer",
     "typeToConfirm": "Typ <b>{text}</b> om te bevestigen"
+  },
+  "fieldErrors": {
+    "required": "Vul dit in.",
+    "email": "Vul een e-mailadres in, zoals naam@voorbeeld.nl.",
+    "tooShort": "Gebruik minstens {limit} tekens.",
+    "tooLong": "Gebruik hoogstens {limit} tekens.",
+    "negative": "Mag niet negatief zijn.",
+    "tooSmall": "Moet minstens {limit} zijn.",
+    "tooLarge": "Moet {limit} of minder zijn.",
+    "notNumber": "Vul een getal in.",
+    "wholeNumber": "Vul een heel getal in.",
+    "invalid": "Deze waarde is niet geldig.",
+    "notSaved": "Niet opgeslagen. Controleer de gemarkeerde velden.",
+    "withLabel": "{label}: {problem}"
   }
 }

+ 2 - 1
messages/nl/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# code stond al bij deze klus} other {# codes stonden al bij deze klus}}",
     "failed": "De codes konden niet worden toegevoegd",
     "descriptionOem": "Typ of plak codes uit het diagnoseapparaat, OBD-codes zoals P0420 of BMW-codes zoals 2A82. Elke code wordt een observatie op deze opdracht, met de betekenis opgeslagen.",
-    "placeholderOem": "P0420, 2A82 opgeslagen"
+    "placeholderOem": "P0420, 2A82 opgeslagen",
+    "unrecognised": "{count, plural, one {Geen foutcode, weggelaten: {codes}} other {Geen foutcodes, weggelaten: {codes}}}"
   },
   "finding": {
     "seenBefore": "Gezien {date}",

+ 1 - 1
messages/nl/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "Kan arbeidssjabloon niet opslaan",
     "deleteFailed": "Kan arbeidssjabloon niet verwijderen",
     "loadFailed": "Kan arbeidssjabloon niet laden",
-    "noItems": "Minimaal één item is vereist"
+    "itemNameMissing": "Geef dit item een naam."
   }
 }

+ 2 - 1
messages/nl/vehicles.json

@@ -749,6 +749,7 @@
     "added": "{name} toegevoegd",
     "itemTitle": "Tellers",
     "noItemMeters": "Geen tellers op dit onderdeel.",
-    "addItemMeterHint": "De teller gaat mee met dit onderdeel, waar het ook gemonteerd is."
+    "addItemMeterHint": "De teller gaat mee met dit onderdeel, waar het ook gemonteerd is.",
+    "negativeReading": "Een stand kan niet negatief zijn."
   }
 }

+ 14 - 0
messages/pl/common.json

@@ -328,5 +328,19 @@
     "irreversible": "Tej operacji nie można cofnąć.",
     "andMore": "i jeszcze {count}",
     "typeToConfirm": "Wpisz <b>{text}</b>, aby potwierdzić"
+  },
+  "fieldErrors": {
+    "required": "Wypełnij to pole.",
+    "email": "Wpisz adres e-mail, np. imie@przyklad.pl.",
+    "tooShort": "Użyj co najmniej {limit} znaków.",
+    "tooLong": "Użyj najwyżej {limit} znaków.",
+    "negative": "Nie może być ujemne.",
+    "tooSmall": "Musi wynosić co najmniej {limit}.",
+    "tooLarge": "Musi wynosić {limit} lub mniej.",
+    "notNumber": "Wpisz liczbę.",
+    "wholeNumber": "Wpisz liczbę całkowitą.",
+    "invalid": "Ta wartość jest nieprawidłowa.",
+    "notSaved": "Nie zapisano. Sprawdź zaznaczone pola.",
+    "withLabel": "{label}: {problem}"
   }
 }

+ 2 - 1
messages/pl/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# kod był już w tym zleceniu} few {# kody były już w tym zleceniu} many {# kodów było już w tym zleceniu} other {# kodu było już w tym zleceniu}}",
     "failed": "Nie udało się dodać kodów",
     "descriptionOem": "Wpisz lub wklej kody z testera diagnostycznego: kody OBD, np. P0420, lub kody BMW, np. 2A82. Każdy staje się obserwacją w tym zleceniu z zapisanym znaczeniem.",
-    "placeholderOem": "P0420, 2A82 zapisany"
+    "placeholderOem": "P0420, 2A82 zapisany",
+    "unrecognised": "{count, plural, one {To nie kod usterki, pominięto: {codes}} few {To nie kody usterek, pominięto: {codes}} many {To nie kody usterek, pominięto: {codes}} other {To nie kody usterek, pominięto: {codes}}}"
   },
   "finding": {
     "seenBefore": "Widziany {date}",

+ 1 - 1
messages/pl/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "Nie udało się zapisać szablonu robocizny",
     "deleteFailed": "Nie udało się usunąć szablonu robocizny",
     "loadFailed": "Nie udało się załadować szablonu robocizny",
-    "noItems": "Wymagana jest co najmniej jedna pozycja"
+    "itemNameMissing": "Nadaj tej pozycji nazwę."
   }
 }

+ 2 - 1
messages/pl/vehicles.json

@@ -749,6 +749,7 @@
     "added": "Dodano {name}",
     "itemTitle": "Liczniki",
     "noItemMeters": "Brak liczników na tym elemencie.",
-    "addItemMeterHint": "Licznik pozostaje z tym elementem, gdziekolwiek jest zamontowany."
+    "addItemMeterHint": "Licznik pozostaje z tym elementem, gdziekolwiek jest zamontowany.",
+    "negativeReading": "Odczyt nie może być ujemny."
   }
 }

+ 14 - 0
messages/pt-BR/common.json

@@ -328,5 +328,19 @@
     "irreversible": "Esta ação não pode ser desfeita.",
     "andMore": "e mais {count}",
     "typeToConfirm": "Digite <b>{text}</b> para confirmar"
+  },
+  "fieldErrors": {
+    "required": "Preencha este campo.",
+    "email": "Digite um e-mail como nome@exemplo.com.",
+    "tooShort": "Use pelo menos {limit} caracteres.",
+    "tooLong": "Use no máximo {limit} caracteres.",
+    "negative": "Não pode ser negativo.",
+    "tooSmall": "Deve ser pelo menos {limit}.",
+    "tooLarge": "Deve ser {limit} ou menos.",
+    "notNumber": "Digite um número.",
+    "wholeNumber": "Digite um número inteiro.",
+    "invalid": "Este valor não é válido.",
+    "notSaved": "Não salvo. Verifique os campos marcados.",
+    "withLabel": "{label}: {problem}"
   }
 }

+ 2 - 1
messages/pt-BR/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# código já estava neste serviço} other {# códigos já estavam neste serviço}}",
     "failed": "Não foi possível adicionar os códigos",
     "descriptionOem": "Digite ou cole os códigos do scanner, códigos OBD como P0420 ou códigos BMW como 2A82. Cada um vira uma observação neste serviço, com o significado salvo.",
-    "placeholderOem": "P0420, 2A82 armazenado"
+    "placeholderOem": "P0420, 2A82 armazenado",
+    "unrecognised": "{count, plural, one {Não é um código de falha, ignorado: {codes}} other {Não são códigos de falha, ignorados: {codes}}}"
   },
   "finding": {
     "seenBefore": "Visto {date}",

+ 1 - 1
messages/pt-BR/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "Falha ao salvar o modelo de mão de obra",
     "deleteFailed": "Falha ao excluir o modelo de mão de obra",
     "loadFailed": "Falha ao carregar o modelo de mão de obra",
-    "noItems": "Pelo menos um item é obrigatório"
+    "itemNameMissing": "Dê um nome a este item."
   }
 }

+ 2 - 1
messages/pt-BR/vehicles.json

@@ -749,6 +749,7 @@
     "added": "{name} adicionado",
     "itemTitle": "Medidores",
     "noItemMeters": "Nenhum medidor neste item.",
-    "addItemMeterHint": "O medidor acompanha este item onde quer que esteja instalado."
+    "addItemMeterHint": "O medidor acompanha este item onde quer que esteja instalado.",
+    "negativeReading": "Uma leitura não pode ser negativa."
   }
 }

+ 14 - 0
messages/pt-PT/common.json

@@ -328,5 +328,19 @@
     "irreversible": "Esta ação não pode ser anulada.",
     "andMore": "e mais {count}",
     "typeToConfirm": "Escreva <b>{text}</b> para confirmar"
+  },
+  "fieldErrors": {
+    "required": "Preencha este campo.",
+    "email": "Introduza um email como nome@exemplo.pt.",
+    "tooShort": "Use pelo menos {limit} caracteres.",
+    "tooLong": "Use no máximo {limit} caracteres.",
+    "negative": "Não pode ser negativo.",
+    "tooSmall": "Tem de ser pelo menos {limit}.",
+    "tooLarge": "Tem de ser {limit} ou menos.",
+    "notNumber": "Introduza um número.",
+    "wholeNumber": "Introduza um número inteiro.",
+    "invalid": "Este valor não é válido.",
+    "notSaved": "Não guardado. Verifique os campos assinalados.",
+    "withLabel": "{label}: {problem}"
   }
 }

+ 2 - 1
messages/pt-PT/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# código já estava neste trabalho} other {# códigos já estavam neste trabalho}}",
     "failed": "Não foi possível adicionar os códigos",
     "descriptionOem": "Escreva ou cole os códigos do equipamento de diagnóstico, códigos OBD como P0420 ou códigos BMW como 2A82. Cada um torna-se uma observação neste trabalho, com o significado guardado.",
-    "placeholderOem": "P0420, 2A82 memorizado"
+    "placeholderOem": "P0420, 2A82 memorizado",
+    "unrecognised": "{count, plural, one {Não é um código de avaria, ignorado: {codes}} other {Não são códigos de avaria, ignorados: {codes}}}"
   },
   "finding": {
     "seenBefore": "Visto {date}",

+ 1 - 1
messages/pt-PT/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "Não foi possível guardar o modelo de mão de obra",
     "deleteFailed": "Não foi possível eliminar o modelo de mão de obra",
     "loadFailed": "Não foi possível carregar o modelo de mão de obra",
-    "noItems": "É necessário pelo menos um item"
+    "itemNameMissing": "Dê um nome a este item."
   }
 }

+ 2 - 1
messages/pt-PT/vehicles.json

@@ -749,6 +749,7 @@
     "added": "{name} adicionado",
     "itemTitle": "Contadores",
     "noItemMeters": "Nenhum contador neste item.",
-    "addItemMeterHint": "O contador acompanha este item onde quer que esteja instalado."
+    "addItemMeterHint": "O contador acompanha este item onde quer que esteja instalado.",
+    "negativeReading": "Uma leitura não pode ser negativa."
   }
 }

+ 14 - 0
messages/ru/common.json

@@ -328,5 +328,19 @@
     "irreversible": "Это действие необратимо.",
     "andMore": "и ещё {count}",
     "typeToConfirm": "Введите <b>{text}</b> для подтверждения"
+  },
+  "fieldErrors": {
+    "required": "Заполните это поле.",
+    "email": "Введите адрес эл. почты, например name@example.com.",
+    "tooShort": "Не менее {limit} символов.",
+    "tooLong": "Не более {limit} символов.",
+    "negative": "Не может быть отрицательным.",
+    "tooSmall": "Должно быть не меньше {limit}.",
+    "tooLarge": "Должно быть не больше {limit}.",
+    "notNumber": "Введите число.",
+    "wholeNumber": "Введите целое число.",
+    "invalid": "Недопустимое значение.",
+    "notSaved": "Не сохранено. Проверьте отмеченные поля.",
+    "withLabel": "{label}: {problem}"
   }
 }

+ 2 - 1
messages/ru/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# код уже был в этой работе} few {# кода уже были в этой работе} many {# кодов уже были в этой работе} other {# кода уже были в этой работе}}",
     "failed": "Не удалось добавить коды",
     "descriptionOem": "Введите или вставьте коды из диагностического сканера: коды OBD, например P0420, или коды BMW, например 2A82. Каждый станет наблюдением в этом заказе с сохранённым значением.",
-    "placeholderOem": "P0420, 2A82 сохранён"
+    "placeholderOem": "P0420, 2A82 сохранён",
+    "unrecognised": "{count, plural, one {Не код неисправности, пропущен: {codes}} few {Не коды неисправностей, пропущены: {codes}} many {Не коды неисправностей, пропущены: {codes}} other {Не коды неисправностей, пропущены: {codes}}}"
   },
   "finding": {
     "seenBefore": "Был {date}",

+ 1 - 1
messages/ru/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "Не удалось сохранить шаблон",
     "deleteFailed": "Не удалось удалить шаблон",
     "loadFailed": "Не удалось загрузить шаблон",
-    "noItems": "Необходима хотя бы одна позиция"
+    "itemNameMissing": "Укажите название этой позиции."
   }
 }

+ 2 - 1
messages/ru/vehicles.json

@@ -749,6 +749,7 @@
     "added": "{name}: добавлен",
     "itemTitle": "Счётчики",
     "noItemMeters": "На этой единице нет счётчиков.",
-    "addItemMeterHint": "Счётчик остаётся с этой единицей, где бы она ни была установлена."
+    "addItemMeterHint": "Счётчик остаётся с этой единицей, где бы она ни была установлена.",
+    "negativeReading": "Показание не может быть отрицательным."
   }
 }

+ 14 - 0
messages/tr/common.json

@@ -328,5 +328,19 @@
     "irreversible": "Bu işlem geri alınamaz.",
     "andMore": "ve {count} tane daha",
     "typeToConfirm": "Onaylamak için <b>{text}</b> yazın"
+  },
+  "fieldErrors": {
+    "required": "Bu alanı doldurun.",
+    "email": "ad@ornek.com gibi bir e-posta adresi girin.",
+    "tooShort": "En az {limit} karakter kullanın.",
+    "tooLong": "En fazla {limit} karakter kullanın.",
+    "negative": "Negatif olamaz.",
+    "tooSmall": "En az {limit} olmalı.",
+    "tooLarge": "{limit} veya daha az olmalı.",
+    "notNumber": "Bir sayı girin.",
+    "wholeNumber": "Tam sayı girin.",
+    "invalid": "Bu değer geçerli değil.",
+    "notSaved": "Kaydedilmedi. İşaretli alanları kontrol edin.",
+    "withLabel": "{label}: {problem}"
   }
 }

+ 2 - 1
messages/tr/faultCodes.json

@@ -185,7 +185,8 @@
     "skipped": "{count, plural, one {# kod bu işte zaten vardı} other {# kod bu işte zaten vardı}}",
     "failed": "Kodlar eklenemedi",
     "descriptionOem": "Arıza tespit cihazındaki kodları yazın veya yapıştırın: P0420 gibi OBD kodları ya da 2A82 gibi BMW kodları. Her biri bu işte, anlamı kaydedilmiş bir gözlem olur.",
-    "placeholderOem": "P0420, 2A82 kayıtlı"
+    "placeholderOem": "P0420, 2A82 kayıtlı",
+    "unrecognised": "{count, plural, other {Arıza kodu değil, atlandı: {codes}}}"
   },
   "finding": {
     "seenBefore": "Görüldü: {date}",

+ 1 - 1
messages/tr/laborPresets.json

@@ -71,6 +71,6 @@
     "saveFailed": "İşçilik şablonu kaydedilemedi",
     "deleteFailed": "İşçilik şablonu silinemedi",
     "loadFailed": "İşçilik şablonu yüklenemedi",
-    "noItems": "En az bir kalem gereklidir"
+    "itemNameMissing": "Bu kaleme bir ad verin."
   }
 }

+ 2 - 1
messages/tr/vehicles.json

@@ -749,6 +749,7 @@
     "added": "{name} eklendi",
     "itemTitle": "Sayaçlar",
     "noItemMeters": "Bu öğede sayaç yok.",
-    "addItemMeterHint": "Sayaç, nereye takılırsa takılsın bu öğeyle birlikte gider."
+    "addItemMeterHint": "Sayaç, nereye takılırsa takılsın bu öğeyle birlikte gider.",
+    "negativeReading": "Okuma değeri negatif olamaz."
   }
 }

+ 112 - 0
src/__tests__/features/customers/customer-form-field-errors.test.tsx

@@ -0,0 +1,112 @@
+/**
+ * A customer the server refused: what is wrong is said under the field it is
+ * about, in the person's words rather than the schema's ("email: Invalid
+ * email"), the field is focused, and what was typed stays.
+ */
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const modalOpen = vi.hoisted(() => vi.fn())
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ refresh: vi.fn(), push: vi.fn(), replace: vi.fn() }),
+  usePathname: () => '/customers',
+  useSearchParams: () => new URLSearchParams(),
+}))
+vi.mock('@/components/glass-modal', () => ({ useGlassModal: () => ({ open: modalOpen }) }))
+vi.mock('@/lib/analytics', () => ({ track: vi.fn() }))
+vi.mock('sonner', () => ({
+  toast: { error: vi.fn(), success: vi.fn(), loading: vi.fn(), warning: vi.fn() },
+}))
+vi.mock('@/features/invoice-designer/Actions/documentDesignActions', () => ({
+  listDesignOptions: vi.fn(async () => ({ success: true, data: [] })),
+}))
+vi.mock('@/features/customers/Actions/customerActions', () => ({
+  createCustomer: vi.fn(),
+  updateCustomer: vi.fn(),
+}))
+vi.mock('@/features/vehicles/Actions/vehicleActions', () => ({ createVehicle: vi.fn() }))
+vi.mock('@/features/vehicles/Components/ScanDocumentButton', () => ({
+  ScanDocumentButton: () => null,
+}))
+
+import { toast } from 'sonner'
+import { TooltipProvider } from '@/components/ui/tooltip'
+import { CustomerForm } from '@/features/customers/Components/CustomerForm'
+import { createCustomer } from '@/features/customers/Actions/customerActions'
+
+function renderForm() {
+  const onOpenChange = vi.fn()
+  render(
+    <TooltipProvider>
+      <CustomerForm open onOpenChange={onOpenChange} />
+    </TooltipProvider>
+  )
+  return { onOpenChange }
+}
+
+const submit = async () => {
+  const form = screen.getByRole('dialog').querySelector('form') as HTMLFormElement
+  await act(async () => {
+    fireEvent.submit(form)
+  })
+}
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  // The switches measure themselves; jsdom has nothing to measure with.
+  const nothing = () => undefined
+  globalThis.ResizeObserver = class {
+    observe = nothing
+    unobserve = nothing
+    disconnect = nothing
+  }
+})
+
+describe('a customer the server refused', () => {
+  it('says what is wrong under the email, focuses it and keeps what was typed', async () => {
+    vi.mocked(createCustomer).mockResolvedValue({
+      success: false,
+      error: 'email: Invalid email',
+      fieldErrors: [{ field: 'email', issue: 'email' }],
+    })
+    const { onOpenChange } = renderForm()
+    const name = screen.getByLabelText('Name *') as HTMLInputElement
+    const email = screen.getByLabelText('Email') as HTMLInputElement
+    fireEvent.change(name, { target: { value: 'ZZ Test Fleet' } })
+    fireEvent.change(email, { target: { value: 'kari@nordvik' } })
+
+    await submit()
+
+    const message = await screen.findByText('Enter an email address like name@example.com.')
+    expect(email).toHaveAttribute('aria-invalid', 'true')
+    expect(email.getAttribute('aria-describedby')).toBe(message.id)
+    expect(email).toHaveFocus()
+    // Not the schema's English, and not in a box that hides the form.
+    expect(screen.queryByText(/Invalid email/)).not.toBeInTheDocument()
+    expect(modalOpen).not.toHaveBeenCalled()
+    expect(toast.error).toHaveBeenCalledWith('Not saved. Check the marked fields.')
+    // Still open, on what was typed.
+    expect(onOpenChange).not.toHaveBeenCalledWith(false)
+    expect(name.value).toBe('ZZ Test Fleet')
+    expect(email.value).toBe('kari@nordvik')
+  })
+
+  it('takes the mark away once the field is changed', async () => {
+    vi.mocked(createCustomer).mockResolvedValue({
+      success: false,
+      error: 'address: Too big',
+      fieldErrors: [{ field: 'address', issue: 'tooLong', limit: 500 }],
+    })
+    renderForm()
+    fireEvent.change(screen.getByLabelText('Name *'), { target: { value: 'ZZ Test Fleet' } })
+    await submit()
+
+    const address = screen.getByLabelText('Address')
+    expect(await screen.findByText('Use at most 500 characters.')).toBeInTheDocument()
+    expect(address).toHaveAttribute('aria-invalid', 'true')
+
+    fireEvent.change(address, { target: { value: 'Storgata 1' } })
+    expect(screen.queryByText('Use at most 500 characters.')).not.toBeInTheDocument()
+    expect(address).not.toHaveAttribute('aria-invalid')
+  })
+})

+ 19 - 0
src/__tests__/features/fault-codes/codes.test.ts

@@ -13,6 +13,7 @@ import {
   normalizeMakeCode,
   normalizeOemCode,
   oemSourceFor,
+  unrecognisedCodeWords,
   vehicleCarriesMake,
 } from '@/features/fault-codes/Lib/codes'
 import { visiblePageCommands } from '@/features/search/Lib/commands'
@@ -245,3 +246,21 @@ describe("which cars carry a make's codes", () => {
     expect(vehicleCarriesMake('ford', null)).toBe(false)
   })
 })
+
+describe('words that look like a code and are not one', () => {
+  it('names them, so a pasted code is not left out without a word', () => {
+    expect(unrecognisedCodeWords('P0401 p0300, XYZ123')).toEqual(['XYZ123'])
+    expect(unrecognisedCodeWords('P04011 and P041, P0420')).toEqual(['P04011', 'P041'])
+  })
+
+  it('leaves out words, years, mileages and codes with their failure byte', () => {
+    expect(
+      unrecognisedCodeWords('P0420-1F stored since 2015, 120000 km. Customer says (P0171)')
+    ).toEqual([])
+  })
+
+  it('reads a manufacturer code as one when the car has its own codes', () => {
+    expect(unrecognisedCodeWords('CD87 2A82', { oem: true })).toEqual([])
+    expect(unrecognisedCodeWords('CD87')).toEqual(['CD87'])
+  })
+})

+ 16 - 0
src/__tests__/features/fault-codes/components.test.tsx

@@ -127,6 +127,22 @@ describe('typing codes into a work order', () => {
     await waitFor(() => expect(h.refresh).toHaveBeenCalled())
   })
 
+  it('says which pasted words were not codes instead of leaving them out silently', async () => {
+    h.lookup.mockResolvedValue({ success: true, data: { available: true, results: [] } })
+    open()
+
+    fireEvent.change(screen.getByRole('textbox'), {
+      target: { value: 'P0401 p0300, XYZ123' },
+    })
+    expect(screen.getByText('P0401')).toBeInTheDocument()
+    expect(screen.getByText('P0300')).toBeInTheDocument()
+    expect(screen.getByText('Not a fault code, left out: XYZ123')).toBeInTheDocument()
+    expect(screen.getByRole('button', { name: 'Add 2 codes' })).toBeEnabled()
+
+    fireEvent.change(screen.getByRole('textbox'), { target: { value: 'P0401 p0300' } })
+    expect(screen.queryByText(/left out/)).not.toBeInTheDocument()
+  })
+
   it('says a meaning is not available while the service is down, and still lets the codes be added', async () => {
     h.lookup.mockResolvedValueOnce({
       success: true,

+ 93 - 0
src/__tests__/features/labor-presets/preset-item-name.test.tsx

@@ -0,0 +1,93 @@
+/**
+ * A labour preset row with hours but no name is marked under its own name
+ * field ("Give this item a name."), not refused with "At least one item is
+ * required" while the item sits right there. The blank spare row is dropped
+ * without a word, as before.
+ */
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const createLaborPreset = vi.hoisted(() => vi.fn())
+const modalOpen = vi.hoisted(() => vi.fn())
+vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) }))
+vi.mock('@/components/glass-modal', () => ({ useGlassModal: () => ({ open: modalOpen }) }))
+vi.mock('@/features/labor-presets/Actions/laborPresetActions', () => ({
+  createLaborPreset,
+  updateLaborPreset: vi.fn(),
+}))
+
+import { LaborPresetForm } from '@/features/labor-presets/Components/LaborPresetForm'
+import { namelessItemRows } from '@/features/labor-presets/Lib/namelessItems'
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  createLaborPreset.mockResolvedValue({ success: true, data: { id: 'p1' } })
+})
+
+function renderForm() {
+  render(
+    <LaborPresetForm
+      open
+      onOpenChange={vi.fn()}
+      defaultLaborRate={900}
+      inventoryParts={[]}
+      currencyCode="NOK"
+    />
+  )
+}
+
+const save = async () => {
+  await act(async () => {
+    fireEvent.click(screen.getByRole('button', { name: 'Create Package' }))
+  })
+}
+
+describe('a preset item without a name', () => {
+  it('is marked under its name, and nothing is saved', async () => {
+    renderForm()
+    const hours = screen.getAllByRole('spinbutton')[0]
+    fireEvent.change(hours, { target: { value: '1.5' } })
+    await save()
+
+    const name = screen.getByRole('textbox', { name: 'Name' })
+    const message = screen.getByText('Give this item a name.')
+    expect(name).toHaveAttribute('aria-invalid', 'true')
+    expect(name.getAttribute('aria-describedby')).toBe(message.id)
+    expect(name).toHaveFocus()
+    expect(screen.queryByText(/At least one item is required/)).not.toBeInTheDocument()
+    expect(modalOpen).not.toHaveBeenCalled()
+    expect(createLaborPreset).not.toHaveBeenCalled()
+
+    // Named, the mark goes and the item saves.
+    fireEvent.change(name, { target: { value: 'Oil change' } })
+    expect(screen.queryByText('Give this item a name.')).not.toBeInTheDocument()
+    await save()
+    expect(createLaborPreset).toHaveBeenCalledTimes(1)
+  })
+})
+
+describe('which rows need a name', () => {
+  it('marks rows with hours or a description and no name', () => {
+    expect(
+      namelessItemRows([
+        { name: 'Brakes', hours: 1 },
+        { name: '', hours: 2 },
+        { name: '', description: 'Front axle', hours: 0 },
+        { name: '', hours: 0 },
+      ])
+    ).toEqual([1, 2])
+  })
+
+  it('drops an untouched spare row once another has a name', () => {
+    expect(
+      namelessItemRows([
+        { name: 'Brakes', hours: 1 },
+        { name: '', hours: 0 },
+      ])
+    ).toEqual([])
+  })
+
+  it('marks the first row when none has a name at all', () => {
+    expect(namelessItemRows([{ name: '', hours: 0 }])).toEqual([0])
+  })
+})

+ 20 - 0
src/__tests__/features/meters/meter-value.test.ts

@@ -11,6 +11,7 @@ import {
   lastMeterValueBefore,
   meterLine,
   meterState,
+  meterValueProblem,
   parseMeterValue,
 } from '@/features/meters/Lib/meterValue'
 import { documentNumbers } from '@/lib/document-numbers'
@@ -156,3 +157,22 @@ describe('a lower reading', () => {
     expect(isLowerMeterValue('1', null)).toBe(false)
   })
 })
+
+describe('why a reading was refused', () => {
+  it('says a minus in front of a good reading is a negative one', () => {
+    expect(meterValueProblem('-5')).toBe('negative')
+    expect(meterValueProblem('- 4,256.7')).toBe('negative')
+    expect(meterValueProblem(-5)).toBe('negative')
+  })
+
+  it('says anything else that does not read is not a reading', () => {
+    expect(meterValueProblem('12.345')).toBe('invalid')
+    expect(meterValueProblem('abc')).toBe('invalid')
+    expect(meterValueProblem('-abc')).toBe('invalid')
+  })
+
+  it('has nothing to say about a good one', () => {
+    expect(meterValueProblem('4256.7')).toBeNull()
+    expect(meterValueProblem(0)).toBeNull()
+  })
+})

+ 64 - 0
src/__tests__/features/meters/reading-refused-next-to-field.test.tsx

@@ -0,0 +1,64 @@
+/**
+ * A reading typed with a minus is refused for what it is, under the box it
+ * was typed in ("A reading can't be negative."), not with the advice to type
+ * a number with two decimals, and nothing is sent.
+ */
+import { act, fireEvent, render, screen, within } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const addVehicleMeter = vi.hoisted(() => vi.fn())
+vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh: vi.fn() }) }))
+vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn(), warning: vi.fn() } }))
+vi.mock('@/features/equipment/Actions/equipmentItemActions', () => ({
+  addEquipmentMeter: vi.fn(),
+}))
+vi.mock('@/features/meters/Actions/vehicleMeterActions', () => ({
+  addMeterReading: vi.fn(),
+  addVehicleMeter,
+  markMeterReadingWrong: vi.fn(),
+  removeVehicleMeter: vi.fn(),
+  replaceVehicleMeter: vi.fn(),
+}))
+
+import { toast } from 'sonner'
+import { VehicleMeters } from '@/features/meters/Components/VehicleMeters'
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  addVehicleMeter.mockResolvedValue({ success: true })
+})
+
+describe('a negative reading', () => {
+  it('is said under the box and not sent', async () => {
+    render(
+      <VehicleMeters
+        vehicleId="veh-1"
+        types={[{ id: 'hours', name: 'Engine hours', unit: 'h' }]}
+        meters={[]}
+      />
+    )
+    fireEvent.click(screen.getByRole('button', { name: 'Add meter' }))
+    const dialog = await screen.findByRole('dialog')
+    const reading = within(dialog).getByLabelText('First reading (optional)')
+    fireEvent.change(reading, { target: { value: '-5' } })
+    await act(async () => {
+      fireEvent.click(within(dialog).getByRole('button', { name: 'Add meter' }))
+    })
+
+    const message = within(dialog).getByText("A reading can't be negative.")
+    expect(reading).toHaveAttribute('aria-invalid', 'true')
+    expect(reading.getAttribute('aria-describedby')).toContain(message.id)
+    expect(reading).toHaveFocus()
+    expect(within(dialog).queryByText(/up to two decimals/)).not.toBeInTheDocument()
+    expect(toast.error).not.toHaveBeenCalled()
+    expect(addVehicleMeter).not.toHaveBeenCalled()
+
+    // Fixed, the mark goes and the meter is added.
+    fireEvent.change(reading, { target: { value: '5' } })
+    expect(within(dialog).queryByText("A reading can't be negative.")).not.toBeInTheDocument()
+    await act(async () => {
+      fireEvent.click(within(dialog).getByRole('button', { name: 'Add meter' }))
+    })
+    expect(addVehicleMeter).toHaveBeenCalledWith(expect.objectContaining({ value: '5' }))
+  })
+})

+ 131 - 0
src/__tests__/features/vehicles/vehicle-form-field-errors.test.tsx

@@ -0,0 +1,131 @@
+/**
+ * A vehicle the server refused: each problem said under its own field in the
+ * person's words, not "year: Year is too far in the future" in a box, the
+ * first field focused and everything typed kept. The year and the reading
+ * carry the limits a browser can check before anything is sent.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, fireEvent, render, screen } from '@testing-library/react'
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ refresh: vi.fn(), push: vi.fn(), replace: vi.fn() }),
+  usePathname: () => '/vehicles/veh-1',
+  useSearchParams: () => new URLSearchParams(),
+}))
+const modalOpen = vi.hoisted(() => vi.fn())
+vi.mock('@/components/glass-modal', () => ({ useGlassModal: () => ({ open: modalOpen }) }))
+vi.mock('@/features/vehicles/Actions/vehicleActions', () => ({
+  createVehicle: vi.fn(),
+  updateVehicle: vi.fn(async () => ({ success: true })),
+}))
+vi.mock('sonner', () => ({
+  toast: { error: vi.fn(), success: vi.fn(), loading: vi.fn(), warning: vi.fn() },
+}))
+vi.mock('@/features/customers/Actions/customerActions', () => ({
+  createCustomer: vi.fn(),
+  findOwnerCandidates: vi.fn(async () => ({ success: true, data: [] })),
+  getCustomerOption: vi.fn(async () => ({ success: true, data: null })),
+  searchCustomers: vi.fn(async () => ({ success: true, data: [] })),
+}))
+vi.mock('@/features/vehicles/Actions/aiAnalyzeVehicleDocument', () => ({
+  aiAnalyzeVehicleDocument: vi.fn(),
+  getVehicleScanAvailability: vi.fn(async () => ({ success: true, data: false })),
+}))
+const getVehicleLookupAvailability = vi.hoisted(() => vi.fn())
+const lookupVehicle = vi.hoisted(() => vi.fn())
+vi.mock('@/features/integrations/Actions/vehicleLookupActions', () => ({
+  getVehicleLookupAvailability,
+  lookupVehicle,
+}))
+vi.mock('@/features/vehicles/Actions/photoHandoffActions', () => ({
+  countPhotosSince: vi.fn(),
+  createPhotoHandoffLink: vi.fn(),
+  createVehiclePhotoHandoffLink: vi.fn(),
+  getVehiclePhotoUrl: vi.fn(),
+}))
+vi.mock('@/features/inspections/Actions/attachmentActions', () => ({
+  countInspectionMedia: vi.fn(),
+  createInspectionHandoffLink: vi.fn(),
+}))
+
+import { toast } from 'sonner'
+import { TooltipProvider } from '@/components/ui/tooltip'
+import { VehicleForm } from '@/features/vehicles/Components/VehicleForm'
+import { updateVehicle } from '@/features/vehicles/Actions/vehicleActions'
+
+const VEHICLE = {
+  id: 'veh-1',
+  make: 'BMW',
+  model: '5-Serie F11',
+  year: 2011,
+  vin: null,
+  licensePlate: 'ZZ10001',
+  color: null,
+  mileage: 225040,
+  fuelType: 'diesel',
+  transmission: 'automatic',
+  engineSize: null,
+  engineCode: null,
+  imageUrl: null,
+  customerId: null,
+  customer: null,
+  inspectionStatus: null,
+}
+
+function renderForm() {
+  const onOpenChange = vi.fn()
+  render(
+    <TooltipProvider>
+      <VehicleForm open onOpenChange={onOpenChange} vehicle={VEHICLE} distanceUnit="km" />
+    </TooltipProvider>
+  )
+  return { onOpenChange }
+}
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  getVehicleLookupAvailability.mockResolvedValue({ success: true, data: {} })
+})
+
+describe('a vehicle the server refused', () => {
+  it('says each problem under its field and focuses the first', async () => {
+    vi.mocked(updateVehicle).mockResolvedValue({
+      success: false,
+      error: 'year: Year is too far in the future. mileage: Too small: expected number to be >=0',
+      fieldErrors: [
+        { field: 'mileage', issue: 'negative' },
+        { field: 'year', issue: 'tooLarge', limit: 2028 },
+      ],
+    })
+    const { onOpenChange } = renderForm()
+    const year = (await screen.findByLabelText('Year *')) as HTMLInputElement
+    fireEvent.change(year, { target: { value: '2099' } })
+
+    const form = screen.getByRole('dialog').querySelector('form') as HTMLFormElement
+    await act(async () => {
+      fireEvent.submit(form)
+    })
+
+    expect(await screen.findByText('Must be 2028 or less.')).toBeInTheDocument()
+    expect(screen.getByText("Can't be negative.")).toBeInTheDocument()
+    expect(year).toHaveAttribute('aria-invalid', 'true')
+    const mileage = document.querySelector('input[name="mileage"]') as HTMLInputElement
+    expect(mileage).toHaveAttribute('aria-invalid', 'true')
+    // The year comes first on the form, whatever order the schema found them in.
+    expect(year).toHaveFocus()
+    expect(screen.queryByText(/too far in the future/)).not.toBeInTheDocument()
+    expect(modalOpen).not.toHaveBeenCalled()
+    expect(toast.error).toHaveBeenCalledWith('Not saved. Check the marked fields.')
+    expect(onOpenChange).not.toHaveBeenCalledWith(false)
+    expect(year.value).toBe('2099')
+  })
+
+  it('lets the browser check the year and the reading before anything is sent', async () => {
+    renderForm()
+    const year = await screen.findByLabelText('Year *')
+    expect(year).toHaveAttribute('min', '1900')
+    expect(year).toHaveAttribute('max', String(new Date().getFullYear() + 2))
+    expect(document.querySelector('input[name="mileage"]')).toHaveAttribute('min', '0')
+  })
+})

+ 60 - 0
src/__tests__/lib/field-errors.test.ts

@@ -0,0 +1,60 @@
+/**
+ * What a schema refused, turned into something a form can say under the
+ * field in the person's language: the field, the kind of problem, the limit.
+ */
+import { describe, expect, it } from 'vitest'
+import { z } from 'zod'
+import { fieldErrorsFromZod } from '@/lib/field-errors'
+
+function refused(schema: z.ZodType, input: unknown) {
+  const result = schema.safeParse(input)
+  if (result.success) throw new Error('expected the schema to refuse')
+  return fieldErrorsFromZod(result.error)
+}
+
+describe('field errors from a schema', () => {
+  it('names the field and the problem, not the library English', () => {
+    const schema = z.object({
+      name: z.string().min(1, 'Name is required'),
+      email: z.string().email('Invalid email'),
+      year: z.coerce.number().min(1900).max(2028, 'Year is too far in the future'),
+      mileage: z.coerce.number().min(0),
+    })
+    expect(refused(schema, { name: '', email: 'a@b', year: 2099, mileage: -5 })).toEqual([
+      { field: 'name', issue: 'required' },
+      { field: 'email', issue: 'email' },
+      { field: 'year', issue: 'tooLarge', limit: 2028 },
+      { field: 'mileage', issue: 'negative' },
+    ])
+  })
+
+  it('keeps the limit of a length or a lower bound', () => {
+    const schema = z.object({
+      address: z.string().max(500),
+      code: z.string().min(3),
+      year: z.coerce.number().min(1900),
+    })
+    expect(refused(schema, { address: 'x'.repeat(501), code: 'ab', year: 1800 })).toEqual([
+      { field: 'address', issue: 'tooLong', limit: 500 },
+      { field: 'code', issue: 'tooShort', limit: 3 },
+      { field: 'year', issue: 'tooSmall', limit: 1900 },
+    ])
+  })
+
+  it('says a number is wanted, or a whole one', () => {
+    const schema = z.object({ hours: z.coerce.number(), months: z.number().int() })
+    expect(refused(schema, { hours: 'abc', months: 1.5 })).toEqual([
+      { field: 'hours', issue: 'notNumber' },
+      { field: 'months', issue: 'wholeNumber' },
+    ])
+  })
+
+  it('gives a line in a list its full path, once per field', () => {
+    const schema = z.object({
+      partItems: z.array(z.object({ quantity: z.number().min(0).max(10) })),
+    })
+    expect(refused(schema, { partItems: [{ quantity: 1 }, { quantity: -1 }] })).toEqual([
+      { field: 'partItems.1.quantity', issue: 'negative' },
+    ])
+  })
+})

+ 2 - 0
src/__tests__/lib/with-auth.test.ts

@@ -204,6 +204,8 @@ describe('withAuth', () => {
     expect(result.success).toBe(false)
     expect(result.error).toContain('email')
     expect(result.error).toContain('Required')
+    // And for the form, the field and what is wrong with it, to say in words.
+    expect(result.fieldErrors).toEqual([{ field: 'email', issue: 'required' }])
   })
 
   it('action throwing a generic Error returns the error message', async () => {

+ 123 - 0
src/components/field-errors.tsx

@@ -0,0 +1,123 @@
+'use client'
+
+import { useCallback, useState } from 'react'
+import { useFormatter, useTranslations } from 'next-intl'
+import type { FieldError } from '@/lib/field-errors'
+
+/** The id of the line under a field that says what is wrong with it. */
+export const fieldErrorId = (field: string) => `field-error-${field.replace(/[^\w-]/g, '-')}`
+
+/**
+ * A field error in words, in the language of whoever is signed in: "Can't be
+ * negative.", "Use at most 200 characters.". A limit that is a year stays as
+ * it is written; a large amount or count is grouped the way the person reads
+ * numbers.
+ */
+export function useFieldErrorText() {
+  const t = useTranslations('common.fieldErrors')
+  const format = useFormatter()
+  return useCallback(
+    (error: Pick<FieldError, 'issue' | 'limit'>) => {
+      const limit =
+        error.limit == null
+          ? ''
+          : Math.abs(error.limit) >= 10_000
+            ? format.number(error.limit)
+            : String(error.limit)
+      return t(error.issue, { limit })
+    },
+    [t, format]
+  )
+}
+
+/** The form's control for a field, by name and then by id. */
+function controlFor(form: HTMLFormElement, field: string): HTMLElement | null {
+  const named = form.elements.namedItem(field)
+  if (named instanceof HTMLElement) return named
+  if (named && 'length' in named && named.length > 0) return named[0] as HTMLElement
+  const byId = form.querySelector<HTMLElement>(`#${CSS.escape(field)}`)
+  return byId
+}
+
+/**
+ * The fields a server action refused, kept for the form that sent them, so
+ * each can be marked where it is and said under it.
+ *
+ * `report` takes the action's `fieldErrors`, marks those the form has a
+ * control for, focuses the first of them and hands back the rest, which the
+ * form says some other way. Nothing typed is touched: the form stays open on
+ * what was written. A field's mark goes when the field is changed (`clear`,
+ * usually from the form's own onChange).
+ */
+export function useFieldErrors() {
+  const [errors, setErrors] = useState<Record<string, FieldError>>({})
+  const text = useFieldErrorText()
+
+  const report = useCallback(
+    (form: HTMLFormElement | null, list: FieldError[] | undefined): FieldError[] => {
+      if (!list?.length) return []
+      if (!form) return list
+      const marked: Record<string, FieldError> = {}
+      const rest: FieldError[] = []
+      const controls: HTMLElement[] = []
+      for (const error of list) {
+        const control = controlFor(form, error.field)
+        if (control) {
+          marked[error.field] = error
+          controls.push(control)
+        } else {
+          rest.push(error)
+        }
+      }
+      setErrors(marked)
+      // The first in the order the form is read, not the order the schema checked.
+      controls.sort((a, b) =>
+        a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1
+      )
+      controls[0]?.focus()
+      return rest
+    },
+    []
+  )
+
+  const clear = useCallback((field: string | null | undefined) => {
+    if (!field) return
+    setErrors((prev) => {
+      if (!(field in prev)) return prev
+      const next = { ...prev }
+      delete next[field]
+      return next
+    })
+  }, [])
+
+  const reset = useCallback(() => setErrors({}), [])
+
+  /** aria-invalid and aria-describedby for a field's control, merged with what it already says. */
+  const invalidProps = useCallback(
+    (field: string, describedBy?: string) => {
+      const error = errors[field]
+      const ids = [describedBy, error ? fieldErrorId(field) : undefined].filter(Boolean).join(' ')
+      return {
+        'aria-invalid': error ? true : undefined,
+        'aria-describedby': ids || undefined,
+      }
+    },
+    [errors]
+  )
+
+  /** The line under a field, or nothing when the field is fine. */
+  const message = useCallback(
+    (field: string) => {
+      const error = errors[field]
+      if (!error) return null
+      return (
+        <p id={fieldErrorId(field)} role="alert" className="text-xs text-destructive">
+          {text(error)}
+        </p>
+      )
+    },
+    [errors, text]
+  )
+
+  return { errors, report, clear, reset, invalidProps, message, text }
+}

+ 39 - 0
src/features/customers/Components/CustomerForm.tsx

@@ -40,6 +40,7 @@ import {
 } from '@/features/custom-fields/Components/CustomFieldsForm'
 import { customFieldsRefusal } from '@/features/custom-fields/Lib/customFieldsRefusal'
 import type { CustomFieldError } from '@/features/custom-fields/Lib/customFieldValueRules'
+import { useFieldErrors } from '@/components/field-errors'
 
 interface CustomerFormProps {
   open: boolean
@@ -81,6 +82,12 @@ export function CustomerForm({
   const modal = useGlassModal()
   const tv = useTranslations('vehicles.form')
   const [loading, setLoading] = useState(false)
+  // What the server refused, said under each field it was about.
+  const fieldErrors = useFieldErrors()
+  const { reset: resetFieldErrors } = fieldErrors
+  useEffect(() => {
+    if (!open) resetFieldErrors()
+  }, [open, resetFieldErrors])
   // The workshop's own fields for a customer, when it has defined any. They
   // save through their own action: checked before the customer is written,
   // saved under its id once it has one.
@@ -204,6 +211,20 @@ export function CustomerForm({
       return
     }
 
+    // Refused by the customer's own rules (an email that is not one, a
+    // field too long): each is said under its field, the first is focused,
+    // and everything typed stays where it is.
+    if (!result.success && result.fieldErrors?.length) {
+      const unplaced = fieldErrors.report(formRef.current, result.fieldErrors)
+      toast.error(
+        unplaced.length > 0
+          ? unplaced.map((error) => fieldErrors.text(error)).join(' ')
+          : tc('fieldErrors.notSaved')
+      )
+      setLoading(false)
+      return
+    }
+
     if (result.success) {
       if (!customer) track('customer:create')
       const created = result.data as
@@ -279,6 +300,8 @@ export function CustomerForm({
           key={customer?.id ?? `${defaults?.name ?? ''}|${defaults?.address ?? ''}`}
           ref={formRef}
           onSubmit={handleSubmit}
+          // A refused field's mark goes as soon as it is changed.
+          onChange={(e) => fieldErrors.clear((e.target as Element).getAttribute('name') ?? '')}
           className="flex min-h-0 flex-1 flex-col"
         >
           <DialogBody className="grid content-start gap-x-8 gap-y-4 md:grid-cols-2">
@@ -311,20 +334,24 @@ export function CustomerForm({
                   <Input
                     id="name"
                     name="name"
+                    {...fieldErrors.invalidProps('name')}
                     placeholder={t('namePlaceholder')}
                     defaultValue={customer?.name ?? defaults?.name ?? ''}
                     required
                   />
+                  {fieldErrors.message('name')}
                 </div>
                 <div className="space-y-2">
                   <Label htmlFor="customerNumber">{t('customerNumber')}</Label>
                   <Input
                     id="customerNumber"
                     name="customerNumber"
+                    {...fieldErrors.invalidProps('customerNumber')}
                     placeholder={t('customerNumberAuto')}
                     defaultValue={customer?.customerNumber ?? ''}
                     maxLength={20}
                   />
+                  {fieldErrors.message('customerNumber')}
                 </div>
               </div>
 
@@ -334,19 +361,23 @@ export function CustomerForm({
                   <Input
                     id="email"
                     name="email"
+                    {...fieldErrors.invalidProps('email')}
                     type="email"
                     placeholder={t('emailPlaceholder')}
                     defaultValue={customer?.email ?? ''}
                   />
+                  {fieldErrors.message('email')}
                 </div>
                 <div className="space-y-2">
                   <Label htmlFor="phone">{tc('form.phone')}</Label>
                   <Input
                     id="phone"
                     name="phone"
+                    {...fieldErrors.invalidProps('phone')}
                     placeholder={t('phonePlaceholder')}
                     defaultValue={customer?.phone ?? ''}
                   />
+                  {fieldErrors.message('phone')}
                 </div>
               </div>
 
@@ -358,11 +389,13 @@ export function CustomerForm({
                 <Textarea
                   id="address"
                   name="address"
+                  {...fieldErrors.invalidProps('address')}
                   placeholder={t('addressPlaceholder')}
                   rows={2}
                   className="min-h-9 resize-none"
                   defaultValue={customer?.address ?? defaults?.address ?? ''}
                 />
+                {fieldErrors.message('address')}
               </div>
             </div>
 
@@ -377,9 +410,11 @@ export function CustomerForm({
                 <Input
                   id="company"
                   name="company"
+                  {...fieldErrors.invalidProps('company')}
                   placeholder={t('companyPlaceholder')}
                   defaultValue={customer?.company ?? ''}
                 />
+                {fieldErrors.message('company')}
               </div>
 
               <div className="space-y-2">
@@ -387,9 +422,11 @@ export function CustomerForm({
                 <Input
                   id="taxId"
                   name="taxId"
+                  {...fieldErrors.invalidProps('taxId')}
                   placeholder={t('taxIdPlaceholder')}
                   defaultValue={customer?.taxId ?? ''}
                 />
+                {fieldErrors.message('taxId')}
                 <p className="text-xs text-muted-foreground">{t('taxIdHint')}</p>
               </div>
 
@@ -440,10 +477,12 @@ export function CustomerForm({
               <Textarea
                 id="notes"
                 name="notes"
+                {...fieldErrors.invalidProps('notes')}
                 placeholder={t('notesPlaceholder')}
                 rows={3}
                 defaultValue={customer?.notes ?? ''}
               />
+              {fieldErrors.message('notes')}
             </div>
 
             {hasCustomFields && open && (

+ 20 - 1
src/features/fault-codes/Components/FaultCodeEntryDialog.tsx

@@ -26,7 +26,7 @@ import {
 import { Textarea } from '@/components/ui/textarea'
 import { addFaultCodeFindings } from '../Actions/addFaultCodeFindings'
 import { lookupFaultCodes } from '../Actions/lookupFaultCodes'
-import { extractFaultCodes, isManufacturerCode } from '../Lib/codes'
+import { extractFaultCodes, isManufacturerCode, unrecognisedCodeWords } from '../Lib/codes'
 import type { FaultCodeView } from '../Lib/types'
 import { FaultCodeChip, FaultStatusBadge, MeaningSourceLabel, MeaningText } from './FaultCodeChip'
 
@@ -95,6 +95,12 @@ export function FaultCodeEntryDialog({
     [text, oemSource]
   )
   const codes = found.filter((c) => !removed.has(c.code))
+  // Words that look like a code and are not one: said, so a code mistyped off
+  // the scan tool is not left out without a word.
+  const unrecognised = useMemo(
+    () => unrecognisedCodeWords(text, { oem: oemSource !== null }),
+    [text, oemSource]
+  )
 
   // Ask once per code, for the codes not asked about yet.
   useEffect(() => {
@@ -178,7 +184,20 @@ export function FaultCodeEntryDialog({
               className="font-mono"
               spellCheck={false}
               autoCapitalize="characters"
+              aria-describedby={unrecognised.length > 0 ? 'fault-code-unrecognised' : undefined}
             />
+            {unrecognised.length > 0 && (
+              <p
+                id="fault-code-unrecognised"
+                role="status"
+                className="text-xs text-amber-600 dark:text-amber-500"
+              >
+                {t('unrecognised', {
+                  count: unrecognised.length,
+                  codes: unrecognised.join(', '),
+                })}
+              </p>
+            )}
           </div>
 
           {codes.length === 0 ? (

+ 22 - 0
src/features/fault-codes/Lib/codes.ts

@@ -297,3 +297,25 @@ export function findingLine(finding: {
     ? description
     : `${finding.faultCode} ${description}`
 }
+
+/**
+ * Words in pasted text that look like a code but are not one this reads:
+ * "XYZ123" in "P0401 p0300, XYZ123", a code with a digit too many (P04011)
+ * or one short (P041). A letter first, a digit somewhere, four to eight
+ * characters. Said back to the person rather than dropped without a word,
+ * so a code mistyped off the scan tool is noticed before the job is saved.
+ * Upper case, once each, in the order they appear.
+ */
+export function unrecognisedCodeWords(text: string, options?: { oem?: boolean }): string[] {
+  const out: string[] = []
+  for (const raw of text.split(/[\s,;|]+/)) {
+    // Brackets and sentence marks around a word are not part of it.
+    const word = raw.replace(/^[("'[]+|[)"'\].:!?]+$/g, '').toUpperCase()
+    if (word.length < 4 || word.length > 8) continue
+    if (!/^[A-Z][A-Z0-9:-]*$/.test(word) || !/\d/.test(word)) continue
+    if (out.includes(word)) continue
+    if (extractFaultCodes(word, options).length > 0) continue
+    out.push(word)
+  }
+  return out
+}

+ 58 - 9
src/features/labor-presets/Components/LaborPresetForm.tsx

@@ -22,6 +22,9 @@ import { Loader2, Plus, Trash2 } from 'lucide-react'
 import { PresetPartsEditor } from './PresetPartsEditor'
 import type { PresetPartItem } from './PresetPartsEditor'
 import { clearableInput } from '@/lib/clearable'
+import { namelessItemRows } from '../Lib/namelessItems'
+import { useFieldErrorText } from '@/components/field-errors'
+import type { FieldError } from '@/lib/field-errors'
 
 type PricingType = 'hourly' | 'service'
 
@@ -128,6 +131,12 @@ export function LaborPresetForm({
   const router = useRouter()
   const modal = useGlassModal()
   const t = useTranslations('laborPresets')
+  const fieldErrorText = useFieldErrorText()
+  /** Why a save failed: what the schema refused in the person's words, else the server's. */
+  const failure = (result: { error?: string; fieldErrors?: FieldError[] }) =>
+    result.fieldErrors?.length
+      ? result.fieldErrors.map((error) => fieldErrorText(error)).join(' ')
+      : result.error || t('errors.saveFailed')
   const [loading, setLoading] = useState(false)
   const [mode, setMode] = useState<PresetMode>(() => detectMode(preset))
 
@@ -215,8 +224,32 @@ export function LaborPresetForm({
     onOpenChange(isOpen)
   }
 
+  /**
+   * Rows that were refused for want of a name, by index in the mode on
+   * screen. Said under the row's own name field rather than in a box about
+   * the whole form; a row's mark goes when it is named or removed.
+   */
+  const [namelessRows, setNamelessRows] = useState<number[]>([])
+  const nameFieldId = (index: number) => `preset-item-name-${index}`
+  const nameErrorId = (index: number) => `preset-item-name-error-${index}`
+  const markNameless = (rows: number[]) => {
+    setNamelessRows(rows)
+    document.getElementById(nameFieldId(rows[0]))?.focus()
+  }
+  const nameInvalidProps = (index: number) =>
+    namelessRows.includes(index)
+      ? { 'aria-invalid': true, 'aria-describedby': nameErrorId(index) }
+      : {}
+  const nameError = (index: number) =>
+    namelessRows.includes(index) ? (
+      <p id={nameErrorId(index)} role="alert" className="col-span-full text-xs text-destructive">
+        {t('errors.itemNameMissing')}
+      </p>
+    ) : null
+
   const handleModeChange = (newMode: PresetMode) => {
     setMode(newMode)
+    setNamelessRows([])
   }
 
   // Package mode helpers
@@ -226,6 +259,7 @@ export function LaborPresetForm({
       updated[index] = { ...updated[index], [field]: value }
       return updated
     })
+    if (field === 'description') setNamelessRows((rows) => rows.filter((row) => row !== index))
   }
 
   const addItem = () => {
@@ -237,6 +271,7 @@ export function LaborPresetForm({
 
   const removeItem = (index: number) => {
     setItems((prev) => prev.filter((_, i) => i !== index))
+    setNamelessRows([])
   }
 
   // Single item mode helpers
@@ -246,6 +281,7 @@ export function LaborPresetForm({
       updated[index] = { ...updated[index], [field]: value }
       return updated
     })
+    if (field === 'name') setNamelessRows((rows) => rows.filter((row) => row !== index))
   }
 
   const addSingleItem = () => {
@@ -257,6 +293,7 @@ export function LaborPresetForm({
 
   const removeSingleItem = (index: number) => {
     setSingleItems((prev) => prev.filter((_, i) => i !== index))
+    setNamelessRows([])
   }
 
   const buildPartsPayload = () =>
@@ -279,12 +316,13 @@ export function LaborPresetForm({
     const partsPayload = buildPartsPayload()
 
     if (mode === 'single') {
-      const validItems = singleItems.filter((i) => i.name.trim())
-      if (validItems.length === 0) {
-        modal.open('error', t('errors.error'), t('errors.noItems'))
+      const nameless = namelessItemRows(singleItems)
+      if (nameless.length > 0) {
+        markNameless(nameless)
         setLoading(false)
         return
       }
+      const validItems = singleItems.filter((i) => i.name.trim())
 
       if (preset) {
         const item = validItems[0]
@@ -308,7 +346,7 @@ export function LaborPresetForm({
           onOpenChange(false)
           router.refresh()
         } else {
-          modal.open('error', t('errors.error'), result.error || t('errors.saveFailed'))
+          modal.open('error', t('errors.error'), failure(result))
         }
       } else {
         let allSuccess = true
@@ -328,7 +366,7 @@ export function LaborPresetForm({
             parts: partsPayload,
           })
           if (!result.success) {
-            modal.open('error', t('errors.error'), result.error || t('errors.saveFailed'))
+            modal.open('error', t('errors.error'), failure(result))
             allSuccess = false
             break
           }
@@ -339,12 +377,15 @@ export function LaborPresetForm({
         }
       }
     } else {
-      const validItems = items.filter((i) => i.description.trim())
-      if (validItems.length === 0) {
-        modal.open('error', t('errors.error'), t('errors.noItems'))
+      const nameless = namelessItemRows(
+        items.map((item) => ({ name: item.description, hours: item.hours }))
+      )
+      if (nameless.length > 0) {
+        markNameless(nameless)
         setLoading(false)
         return
       }
+      const validItems = items.filter((i) => i.description.trim())
 
       const data = {
         name,
@@ -366,7 +407,7 @@ export function LaborPresetForm({
         onOpenChange(false)
         router.refresh()
       } else {
-        modal.open('error', t('errors.error'), result.error || t('errors.saveFailed'))
+        modal.open('error', t('errors.error'), failure(result))
       }
     }
 
@@ -427,6 +468,9 @@ export function LaborPresetForm({
                     <div className="grid grid-cols-2 gap-2 sm:grid-cols-[2fr_1fr_1fr_auto]">
                       <div className="col-span-2 flex gap-2 sm:col-span-1">
                         <Input
+                          id={nameFieldId(i)}
+                          aria-label={t('form.singleNameLabel')}
+                          {...nameInvalidProps(i)}
                           placeholder={t('form.singleNamePlaceholder')}
                           value={item.name}
                           onChange={(e) => updateSingleItem(i, 'name', e.target.value)}
@@ -467,6 +511,7 @@ export function LaborPresetForm({
                       >
                         <Trash2 className="h-4 w-4" />
                       </Button>
+                      {nameError(i)}
                     </div>
                     <Textarea
                       placeholder={t('form.descriptionPlaceholder')}
@@ -536,6 +581,9 @@ export function LaborPresetForm({
                     <div key={i} className="grid grid-cols-2 gap-2 sm:grid-cols-[2fr_1fr_1fr_auto]">
                       <div className="col-span-2 flex gap-2 sm:col-span-1">
                         <Input
+                          id={nameFieldId(i)}
+                          aria-label={t('form.itemDescription')}
+                          {...nameInvalidProps(i)}
                           placeholder={t('form.itemDescriptionPlaceholder')}
                           value={item.description}
                           onChange={(e) => updateItem(i, 'description', e.target.value)}
@@ -576,6 +624,7 @@ export function LaborPresetForm({
                       >
                         <Trash2 className="h-4 w-4" />
                       </Button>
+                      {nameError(i)}
                     </div>
                   ))}
 

+ 27 - 0
src/features/labor-presets/Lib/namelessItems.ts

@@ -0,0 +1,27 @@
+/**
+ * The rows of a labour preset that stop it being saved for want of a name.
+ *
+ * A row with nothing in it is the spare line the form keeps ready, and is
+ * dropped on save without a word. A row with hours or a description and no
+ * name was meant, and saying "at least one item is required" about it, with
+ * the item right there, told the person nothing: it is marked instead, under
+ * its own name field. When no row has a name at all, the first one is
+ * marked, since a preset needs one.
+ *
+ * Pure, so the rule is tested without the dialog.
+ */
+export interface PresetRow {
+  /** What the row is called: the name of a single item, the description of a package line. */
+  name: string
+  /** A single item's longer description, when it has one. */
+  description?: string
+  hours: number | string
+}
+
+export function namelessItemRows(rows: PresetRow[]): number[] {
+  const hasContent = (row: PresetRow) => Boolean(row.description?.trim()) || Number(row.hours) > 0
+  const nameless = rows.flatMap((row, i) => (!row.name.trim() && hasContent(row) ? [i] : []))
+  if (nameless.length > 0) return nameless
+  if (rows.length > 0 && !rows.some((row) => row.name.trim())) return [0]
+  return []
+}

+ 3 - 1
src/features/meters/Actions/jobMeterActions.ts

@@ -7,6 +7,7 @@ import { requireFeature } from '@/lib/features'
 import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { withAuth } from '@/lib/with-auth'
 import { writeJobMeterReading } from '../Lib/jobMeterReading.server'
+import { METER_PROBLEM_KEY, meterValueProblem } from '../Lib/meterValue'
 import { setJobMeterReadingSchema } from '../Schema/meterSchema'
 
 /**
@@ -36,7 +37,8 @@ export async function setJobMeterReading(input: unknown) {
         return { ...result, jobId: data.jobId, jobRef: job?.invoiceNumber || data.jobId }
       } catch (error) {
         if (error instanceof Error && error.name === 'InvalidMeterReadingError') {
-          throw new Error((await getTranslations('vehicles.meters'))('invalidReading'))
+          const problem = meterValueProblem(data.value) ?? 'invalid'
+          throw new Error((await getTranslations('vehicles.meters'))(METER_PROBLEM_KEY[problem]))
         }
         throw error
       }

+ 25 - 5
src/features/meters/Components/JobMeters.tsx

@@ -9,7 +9,12 @@ import { Input } from '@/components/ui/input'
 import { Label } from '@/components/ui/label'
 import { cn } from '@/lib/utils'
 import { setJobMeterReading } from '../Actions/jobMeterActions'
-import { isLowerMeterValue, parseMeterValue } from '../Lib/meterValue'
+import {
+  isLowerMeterValue,
+  METER_PROBLEM_KEY,
+  meterValueProblem,
+  parseMeterValue,
+} from '../Lib/meterValue'
 import { ReadingQuestion } from '@/features/vehicles/Components/ReadingQuestion'
 import { readingNeedsAnswer } from '@/features/vehicles/Lib/vehicleReading'
 import { meterReadingKind } from '../Lib/meterAsk'
@@ -162,8 +167,14 @@ function JobMeterField({
       confirmed,
     })
 
+  // A reading that does not read is said under the box, not sent.
+  const [refused, setRefused] = useState<'negative' | 'invalid' | null>(null)
+
   const save = async (answered = false) => {
     if (typed.trim() === saved.current.trim()) return
+    const problem = typed.trim() === '' ? null : meterValueProblem(typed)
+    setRefused(problem)
+    if (problem) return
     if (asking && !answered) return
     const result = await setJobMeterReading({
       jobId,
@@ -219,9 +230,12 @@ function JobMeterField({
             )}
             value={typed}
             aria-required={meter.required || undefined}
-            aria-invalid={missing || undefined}
+            aria-invalid={missing || refused ? true : undefined}
             disabled={locked}
-            onChange={(e) => setTyped(e.target.value)}
+            onChange={(e) => {
+              setTyped(e.target.value)
+              setRefused(null)
+            }}
             // Saved here, on its own: not an unsaved change of the page's form.
             onInput={(e) => e.stopPropagation()}
             onBlur={() => void save()}
@@ -232,8 +246,9 @@ function JobMeterField({
               }
             }}
             aria-describedby={
-              [missing && `${id}-required`, lower && `${id}-lower`].filter(Boolean).join(' ') ||
-              undefined
+              [missing && `${id}-required`, refused && `${id}-invalid`, lower && `${id}-lower`]
+                .filter(Boolean)
+                .join(' ') || undefined
             }
           />
           {meter.unit && <span className="text-xs text-muted-foreground">{meter.unit}</span>}
@@ -258,6 +273,11 @@ function JobMeterField({
           {t('requiredMissing')}
         </p>
       )}
+      {refused && (
+        <p id={`${id}-invalid`} role="alert" className="text-xs text-destructive">
+          {t(METER_PROBLEM_KEY[refused])}
+        </p>
+      )}
       {asking && last != null && typedValue !== null && (
         <ReadingQuestion
           id={`${id}-question`}

+ 81 - 16
src/features/meters/Components/VehicleMeters.tsx

@@ -40,7 +40,12 @@ import {
   removeVehicleMeter,
   replaceVehicleMeter,
 } from '../Actions/vehicleMeterActions'
-import { isLowerMeterValue, parseMeterValue } from '../Lib/meterValue'
+import {
+  isLowerMeterValue,
+  METER_PROBLEM_KEY,
+  meterValueProblem,
+  parseMeterValue,
+} from '../Lib/meterValue'
 import { ReadingQuestion } from '@/features/vehicles/Components/ReadingQuestion'
 import { readingNeedsAnswer } from '@/features/vehicles/Lib/vehicleReading'
 import { meterReadingKind } from '../Lib/meterAsk'
@@ -254,6 +259,7 @@ function ReadingField({
   onChange,
   describedBy,
   autoFocus,
+  error,
 }: {
   id: string
   label: string
@@ -262,7 +268,10 @@ function ReadingField({
   onChange: (value: string) => void
   describedBy?: string
   autoFocus?: boolean
+  /** Why the reading was refused, said under it. */
+  error?: string | null
 }) {
+  const errorId = `${id}-error`
   return (
     <div className="space-y-1.5">
       <Label htmlFor={id}>{label}</Label>
@@ -274,15 +283,52 @@ function ReadingField({
           className="w-40"
           value={value}
           onChange={(e) => onChange(e.target.value)}
-          aria-describedby={describedBy}
+          aria-invalid={error ? true : undefined}
+          aria-describedby={[describedBy, error && errorId].filter(Boolean).join(' ') || undefined}
           autoFocus={autoFocus}
         />
         {unit && <span className="text-sm text-muted-foreground">{unit}</span>}
       </div>
+      {error && (
+        <p id={errorId} role="alert" className="text-xs text-destructive">
+          {error}
+        </p>
+      )}
     </div>
   )
 }
 
+/**
+ * The reading fields of one dialog that were refused, by field id, with the
+ * words for each. A field's mark goes as soon as it is typed in again; the
+ * first refused one takes the focus.
+ */
+function useReadingErrors() {
+  const t = useTranslations('vehicles.meters')
+  const [errors, setErrors] = useState<Record<string, string>>({})
+  /** Checks each field; true when all read. `optional` fields may be left empty. */
+  const check = (fields: { id: string; value: string; optional?: boolean }[]) => {
+    const next: Record<string, string> = {}
+    for (const field of fields) {
+      if (field.optional && !field.value.trim()) continue
+      const problem = meterValueProblem(field.value)
+      if (problem) next[field.id] = t(METER_PROBLEM_KEY[problem])
+    }
+    setErrors(next)
+    const first = fields.find((field) => next[field.id])
+    if (first) document.getElementById(first.id)?.focus()
+    return !first
+  }
+  const clear = (id: string) =>
+    setErrors((prev) => {
+      if (!(id in prev)) return prev
+      const next = { ...prev }
+      delete next[id]
+      return next
+    })
+  return { errors, check, clear }
+}
+
 function AddMeterDialog({
   open,
   onClose,
@@ -314,12 +360,11 @@ function AddMeterDialog({
     onClose()
   }
 
+  const readingErrors = useReadingErrors()
+
   const save = async () => {
     if (!chosen) return
-    if (value.trim() && parseMeterValue(value) === null) {
-      toast.error(t('invalidReading'))
-      return
-    }
+    if (!readingErrors.check([{ id: 'meter-first-reading', value, optional: true }])) return
     setSaving(true)
     const fields = {
       meterTypeId: chosen.id,
@@ -378,7 +423,11 @@ function AddMeterDialog({
             label={t('firstReading')}
             unit={chosen?.unit ?? ''}
             value={value}
-            onChange={setValue}
+            onChange={(next) => {
+              setValue(next)
+              readingErrors.clear('meter-first-reading')
+            }}
+            error={readingErrors.errors['meter-first-reading']}
           />
           <div className="space-y-1.5">
             <Label htmlFor="meter-reading-date-0">{t('readingDate')}</Label>
@@ -413,6 +462,7 @@ function ReadingDialog({ meter, onClose }: { meter: VehicleMeterView; onClose: (
   // A reading far above the last one waits for a yes, the odometer's question,
   // with the limit for the meter's unit (meterAsk.ts).
   const [confirmed, setConfirmed] = useState<number | null>(null)
+  const readingErrors = useReadingErrors()
   const typedValue = parseMeterValue(value)
   const askKind = meterReadingKind(meter.unit)
   const asking =
@@ -427,10 +477,7 @@ function ReadingDialog({ meter, onClose }: { meter: VehicleMeterView; onClose: (
     })
 
   const save = async (answered = false) => {
-    if (parseMeterValue(value) === null) {
-      toast.error(t('invalidReading'))
-      return
-    }
+    if (!readingErrors.check([{ id: 'meter-reading', value }])) return
     if (asking && !answered) return
     setSaving(true)
     const result = await addMeterReading({
@@ -469,7 +516,11 @@ function ReadingDialog({ meter, onClose }: { meter: VehicleMeterView; onClose: (
             label={t('reading')}
             unit={meter.unit}
             value={value}
-            onChange={setValue}
+            onChange={(next) => {
+              setValue(next)
+              readingErrors.clear('meter-reading')
+            }}
+            error={readingErrors.errors['meter-reading']}
             describedBy={lower ? 'meter-reading-lower' : undefined}
             autoFocus
           />
@@ -528,9 +579,15 @@ function ReplaceDialog({ meter, onClose }: { meter: VehicleMeterView; onClose: (
   const [day, setDay] = useState('')
   const [saving, setSaving] = useState(false)
 
+  const readingErrors = useReadingErrors()
+
   const save = async () => {
-    if (parseMeterValue(oldEnd) === null || parseMeterValue(newStart) === null) {
-      toast.error(t('invalidReading'))
+    if (
+      !readingErrors.check([
+        { id: 'meter-old-end', value: oldEnd },
+        { id: 'meter-new-start', value: newStart },
+      ])
+    ) {
       return
     }
     setSaving(true)
@@ -563,14 +620,22 @@ function ReplaceDialog({ meter, onClose }: { meter: VehicleMeterView; onClose: (
             label={t('oldEnd')}
             unit={meter.unit}
             value={oldEnd}
-            onChange={setOldEnd}
+            onChange={(next) => {
+              setOldEnd(next)
+              readingErrors.clear('meter-old-end')
+            }}
+            error={readingErrors.errors['meter-old-end']}
           />
           <ReadingField
             id="meter-new-start"
             label={t('newStart')}
             unit={meter.unit}
             value={newStart}
-            onChange={setNewStart}
+            onChange={(next) => {
+              setNewStart(next)
+              readingErrors.clear('meter-new-start')
+            }}
+            error={readingErrors.errors['meter-new-start']}
           />
           <div className="space-y-1.5">
             <Label htmlFor="meter-replaced-date-2">{t('replacedOn')}</Label>

+ 23 - 0
src/features/meters/Lib/meterValue.ts

@@ -45,6 +45,29 @@ export function parseMeterValue(text: string | number | null | undefined): numbe
   return finish(`${head}${groups.map((g) => g.trim()).join('')}${decimal ? `.${decimals}` : ''}`)
 }
 
+/**
+ * Why a typed reading was refused, so the person is told the thing they can
+ * fix: a minus in front of an otherwise good reading is `negative` ("can't be
+ * negative", not "type it as a number"), anything else that does not read is
+ * `invalid`. Null when it reads.
+ */
+export function meterValueProblem(
+  text: string | number | null | undefined
+): 'negative' | 'invalid' | null {
+  if (parseMeterValue(text) !== null) return null
+  if (typeof text === 'number') return text < 0 ? 'negative' : 'invalid'
+  const raw = (text ?? '').trim()
+  const unsigned = raw.replace(/^[-−]\s*/, '')
+  if (unsigned !== raw && parseMeterValue(unsigned) !== null) return 'negative'
+  return 'invalid'
+}
+
+/** The words for a refused reading, as a key under vehicles.meters. */
+export const METER_PROBLEM_KEY = {
+  negative: 'negativeReading',
+  invalid: 'invalidReading',
+} as const
+
 function finish(normalized: string): number | null {
   const value = Number(normalized)
   return validMeterValue(value) ? value : null

+ 8 - 2
src/features/meters/Lib/readingInput.server.ts

@@ -3,7 +3,12 @@ import 'server-only'
 import { getTranslations } from 'next-intl/server'
 import { workshopTimeZone } from '@/lib/workshop-timezone'
 import { zonedDate, zonedDayKey } from '@/lib/timezone'
-import { parseMeterValue, roundMeterValue } from './meterValue'
+import {
+  METER_PROBLEM_KEY,
+  meterValueProblem,
+  parseMeterValue,
+  roundMeterValue,
+} from './meterValue'
 
 /**
  * When a reading typed on the vehicle was taken. Today's is now, so it comes
@@ -26,7 +31,8 @@ export async function readingTime(
 export async function readingValue(typed: string | number): Promise<number> {
   const value = parseMeterValue(typed)
   if (value === null) {
-    throw new Error((await getTranslations('vehicles.meters'))('invalidReading'))
+    const problem = meterValueProblem(typed) ?? 'invalid'
+    throw new Error((await getTranslations('vehicles.meters'))(METER_PROBLEM_KEY[problem]))
   }
   return roundMeterValue(value)
 }

+ 55 - 2
src/features/vehicles/Components/VehicleForm.tsx

@@ -20,9 +20,11 @@ import {
 } from '@/components/ui/dialog'
 import { DocsLink } from '@/components/docs-link'
 import { toast } from 'sonner'
+import { useFieldErrors } from '@/components/field-errors'
 import { useGlassModal } from '@/components/glass-modal'
 import { useDateSettings } from '@/components/date-settings-context'
 import { inspectionDueInput } from '../Lib/inspectionDueInput'
+import { VEHICLE_YEAR_MIN, vehicleYearMax } from '../Lib/vehicleYear'
 import type { RegistryLookup } from '../Lib/registryLookup'
 import { createVehicle, updateVehicle } from '../Actions/vehicleActions'
 import type { VehicleDocumentScan } from '../Actions/aiAnalyzeVehicleDocument'
@@ -185,8 +187,15 @@ export function VehicleForm({
   const tDetail = useTranslations('vehicles.detail')
   const { timezone } = useDateSettings()
   const tc = useTranslations('common.buttons')
+  const tCommon = useTranslations('common')
   const format = useFormatter()
   const [loading, setLoading] = useState(false)
+  // What the server refused, said under each field it was about.
+  const fieldErrors = useFieldErrors()
+  const { reset: resetFieldErrors } = fieldErrors
+  useEffect(() => {
+    if (!open) resetFieldErrors()
+  }, [open, resetFieldErrors])
   const [preview, setPreview] = useState<string | null>(vehicle?.imageUrl ?? null)
   const [imageFile, setImageFile] = useState<File | null>(null)
   const [selectedCustomerId, setSelectedCustomerId] = useState<string>(
@@ -693,6 +702,19 @@ export function VehicleForm({
         return
       }
 
+      // Refused by the vehicle's own rules (a year out of range, a reading
+      // below zero): each is said under its field, the first is focused,
+      // and everything typed stays where it is.
+      if (!result.success && result.fieldErrors?.length) {
+        const unplaced = fieldErrors.report(formRef.current, result.fieldErrors)
+        toast.error(
+          unplaced.length > 0
+            ? unplaced.map((error) => fieldErrors.text(error)).join(' ')
+            : tCommon('fieldErrors.notSaved')
+        )
+        return
+      }
+
       if (result.success) {
         // The vehicle as a picker shows it, with the owner it was saved under:
         // the one chosen, or the keeper off the papers just made a customer.
@@ -733,7 +755,7 @@ export function VehicleForm({
         if (created && onCreated) onCreated(created)
         else router.refresh()
       } else {
-        modal.open('error', 'Error', result.error || t('saveError'))
+        modal.open('error', tCommon('errors.error'), result.error || t('saveError'))
       }
     } finally {
       setLoading(false)
@@ -857,6 +879,8 @@ export function VehicleForm({
             ref={formRef}
             onSubmit={handleSubmit}
             onInput={readDrafts}
+            // A refused field's mark goes as soon as it is changed.
+            onChange={(e) => fieldErrors.clear((e.target as Element).getAttribute('name') ?? '')}
             className="flex min-h-0 flex-1 flex-col"
           >
             <DialogBody className="space-y-4">
@@ -1133,6 +1157,7 @@ export function VehicleForm({
                       <Input
                         id="licensePlate"
                         name="licensePlate"
+                        {...fieldErrors.invalidProps('licensePlate')}
                         placeholder="ABC-1234"
                         defaultValue={vehicle?.licensePlate ?? ''}
                         className="flex-1"
@@ -1164,6 +1189,7 @@ export function VehicleForm({
                         />
                       )}
                     </div>
+                    {fieldErrors.message('licensePlate')}
                   </div>
 
                   <div className="space-y-2">
@@ -1195,6 +1221,7 @@ export function VehicleForm({
                       <Input
                         id="vin"
                         name="vin"
+                        {...fieldErrors.invalidProps('vin')}
                         placeholder="1HGCM82633A004352"
                         defaultValue={vehicle?.vin ?? ''}
                         autoComplete="off"
@@ -1211,6 +1238,7 @@ export function VehicleForm({
                         />
                       )}
                     </div>
+                    {fieldErrors.message('vin')}
                   </div>
 
                   {/* Under both fields, since either button may have answered */}
@@ -1235,6 +1263,7 @@ export function VehicleForm({
                           <Input
                             id="hsn"
                             name="hsn"
+                            {...fieldErrors.invalidProps('hsn')}
                             placeholder="0603"
                             inputMode="numeric"
                             maxLength={6}
@@ -1242,18 +1271,21 @@ export function VehicleForm({
                             className="font-mono"
                             defaultValue={vehicle?.hsn ?? ''}
                           />
+                          {fieldErrors.message('hsn')}
                         </div>
                         <div className="space-y-2">
                           <Label htmlFor="tsn">{t('tsn')}</Label>
                           <Input
                             id="tsn"
                             name="tsn"
+                            {...fieldErrors.invalidProps('tsn')}
                             placeholder="BFQ"
                             maxLength={12}
                             autoComplete="off"
                             className="font-mono uppercase"
                             defaultValue={vehicle?.tsn ?? ''}
                           />
+                          {fieldErrors.message('tsn')}
                         </div>
                       </div>
                       <p className="text-xs text-muted-foreground">{t('typeKeyHint')}</p>
@@ -1266,11 +1298,13 @@ export function VehicleForm({
                       <Input
                         id="fleetNumber"
                         name="fleetNumber"
+                        {...fieldErrors.invalidProps('fleetNumber')}
                         placeholder={t('fleetNumberPlaceholder')}
                         autoComplete="off"
                         className="w-full sm:w-48"
                         defaultValue={vehicle?.fleetNumber ?? ''}
                       />
+                      {fieldErrors.message('fleetNumber')}
                     </div>
                   )}
 
@@ -1280,10 +1314,12 @@ export function VehicleForm({
                       <Input
                         id="inspectionDueAt"
                         name="inspectionDueAt"
+                        {...fieldErrors.invalidProps('inspectionDueAt')}
                         type="date"
                         defaultValue={openedInspectionDue}
                         className="w-full sm:w-48"
                       />
+                      {fieldErrors.message('inspectionDueAt')}
                       <p className="text-xs text-muted-foreground">
                         {vehicle?.inspectionStatus?.source &&
                         vehicle.inspectionStatus.source !== 'manual'
@@ -1301,31 +1337,39 @@ export function VehicleForm({
                       <Input
                         id="make"
                         name="make"
+                        {...fieldErrors.invalidProps('make')}
                         placeholder={isMarine ? 'Boston Whaler' : 'Toyota'}
                         defaultValue={vehicle?.make}
                         required
                       />
+                      {fieldErrors.message('make')}
                     </div>
                     <div className="space-y-2">
                       <Label htmlFor="model">{t('model')}</Label>
                       <Input
                         id="model"
                         name="model"
+                        {...fieldErrors.invalidProps('model')}
                         placeholder={isMarine ? 'Montauk 170' : 'Camry'}
                         defaultValue={vehicle?.model}
                         required
                       />
+                      {fieldErrors.message('model')}
                     </div>
                     <div className="col-span-2 space-y-2 sm:col-span-1">
                       <Label htmlFor="year">{t('year')}</Label>
                       <Input
                         id="year"
                         name="year"
+                        {...fieldErrors.invalidProps('year')}
                         type="number"
+                        min={VEHICLE_YEAR_MIN}
+                        max={vehicleYearMax()}
                         placeholder="2024"
                         defaultValue={vehicle?.year}
                         required
                       />
+                      {fieldErrors.message('year')}
                     </div>
                   </div>
 
@@ -1371,9 +1415,11 @@ export function VehicleForm({
                       <Input
                         id="engineCode"
                         name="engineCode"
+                        {...fieldErrors.invalidProps('engineCode')}
                         placeholder="2AR-FE"
                         defaultValue={vehicle?.engineCode ?? ''}
                       />
+                      {fieldErrors.message('engineCode')}
                     </div>
                   </div>
 
@@ -1396,11 +1442,13 @@ export function VehicleForm({
                         <Input
                           id="color"
                           name="color"
+                          {...fieldErrors.invalidProps('color')}
                           placeholder="Silver"
                           defaultValue={vehicle?.color ?? ''}
                           className="pl-8"
                         />
                       </div>
+                      {fieldErrors.message('color')}
                     </div>
                     <div className="space-y-2">
                       <Label htmlFor="mileage">{mileageLabel}</Label>
@@ -1410,10 +1458,14 @@ export function VehicleForm({
                           id="mileage"
                           name="mileage"
                           type="number"
+                          min={0}
                           placeholder="0"
                           value={mileageDraft}
                           onChange={(e) => setMileageDraft(e.target.value)}
-                          aria-describedby={readingNotice ? 'mileage-notice' : undefined}
+                          {...fieldErrors.invalidProps(
+                            'mileage',
+                            readingNotice ? 'mileage-notice' : undefined
+                          )}
                           // No spinner: it would sit on top of the unit, and
                           // nobody steps an odometer reading one at a time.
                           className={cn(
@@ -1430,6 +1482,7 @@ export function VehicleForm({
                           </span>
                         )}
                       </div>
+                      {fieldErrors.message('mileage')}
                       <ReadingNotice
                         id="mileage-notice"
                         entered={mileageDraft}

+ 35 - 0
src/features/vehicles/Components/service-page/useServiceActions.ts

@@ -19,6 +19,8 @@ import { formatCurrency } from '@/lib/format'
 import { findServiceFormProblem } from '@/features/vehicles/Lib/validateServiceForm'
 import { WARRANTY_NONE } from '@/lib/warranty'
 import { useServiceType } from '@/components/service-type-context'
+import { useFieldErrorText } from '@/components/field-errors'
+import type { FieldError } from '@/lib/field-errors'
 import { readingNeedsAnswer } from '@/features/vehicles/Lib/vehicleReading'
 import { revealRequiredMeters } from '@/features/meters/Lib/requiredMetersReveal'
 import type { ServiceDetail } from '../service-detail/types'
@@ -44,6 +46,36 @@ export function useServiceActions({
   const tc = useTranslations('common')
   const tv = useTranslations('vehicles.form')
   const readingKind = useServiceType() === 'marine' ? 'hours' : 'distance'
+  const fieldErrorText = useFieldErrorText()
+
+  /**
+   * What the server's schema refused, in the person's language and under the
+   * name the page gives the field: "Mileage: Can't be negative." A part or
+   * labour line is named by its section. The field itself is focused when the
+   * page draws it.
+   */
+  const describeFieldErrors = (form: HTMLFormElement, errors: FieldError[]): string => {
+    const labelOf = (field: string): string | null => {
+      const [head] = field.split('.')
+      if (head === 'mileage') {
+        return t(readingKind === 'hours' ? 'basicInfo.mileageMarine' : 'basicInfo.mileage')
+      }
+      if (head === 'partItems') return t('parts.title')
+      if (head === 'laborItems') return t('labor.title')
+      return null
+    }
+    const control = errors
+      .map((error) => form.elements.namedItem(error.field))
+      .find((el): el is HTMLInputElement => el instanceof HTMLInputElement)
+    control?.focus()
+    return errors
+      .map((error) => {
+        const problem = fieldErrorText(error)
+        const label = labelOf(error.field)
+        return label ? tc('fieldErrors.withLabel', { label, problem }) : problem
+      })
+      .join(' ')
+  }
 
   const [carouselIndex, setCarouselIndex] = useState<number | null>(null)
   const [downloading, setDownloading] = useState(false)
@@ -336,6 +368,9 @@ export function useServiceActions({
       revealRequiredMeters(initialData.id, result.requiredMeters, {
         focus: !autosave && !leavingRef.current,
       })
+    } else if (result.fieldErrors?.length) {
+      // Refused by the work order's own rules: said in words, nothing typed lost.
+      refuse(describeFieldErrors(form, result.fieldErrors))
     } else {
       const message = result.error || t('page.failedUpdate')
       refuse(message, () => modal.open('error', tc('errors.error'), message))

+ 7 - 0
src/features/vehicles/Lib/vehicleYear.ts

@@ -0,0 +1,7 @@
+/** The oldest model year a vehicle can be saved with. */
+export const VEHICLE_YEAR_MIN = 1900
+
+/** The newest: next year's models are sold this year, and the one after is announced. */
+export function vehicleYearMax(): number {
+  return new Date().getFullYear() + 2
+}

+ 3 - 2
src/features/vehicles/Schema/vehicleSchema.ts

@@ -3,6 +3,7 @@ import { FLEET_NUMBER_MAX_LENGTH } from '../Lib/fleetNumber'
 import { optionalUploadUrlSchema } from '@/lib/upload-url'
 import { registryLookupSchema } from '../Lib/registryLookup'
 import { HSN_PATTERN, normalizeHsn, normalizeTsn, TSN_PATTERN } from '../Lib/typeKey'
+import { VEHICLE_YEAR_MIN, vehicleYearMax } from '../Lib/vehicleYear'
 
 // An empty string passes: on an update it is how a cleared field says so.
 const hsnSchema = z
@@ -19,8 +20,8 @@ export const createVehicleSchema = z.object({
   model: z.string().min(1, 'Model is required'),
   year: z.coerce
     .number()
-    .min(1900, 'Year must be after 1900')
-    .max(new Date().getFullYear() + 2, 'Year is too far in the future'),
+    .min(VEHICLE_YEAR_MIN, 'Year must be after 1900')
+    .max(vehicleYearMax(), 'Year is too far in the future'),
   vin: z.string().optional(),
   licensePlate: z.string().optional(),
   color: z.string().optional(),

+ 75 - 0
src/lib/field-errors.ts

@@ -0,0 +1,75 @@
+import type { ZodError } from 'zod'
+
+/**
+ * What was wrong with one field a server action refused, in a form any
+ * screen can put into words in the person's own language.
+ *
+ * The action's zod schema says what is wrong in library English ("Too small:
+ * expected number to be >=0") under the field's code name ("mileage"). That
+ * is what the error string carries, for the log. The form gets this instead:
+ * the field, a kind of problem it has words for, and the number the rule
+ * stopped at, so the message can sit under the field it is about.
+ */
+export type FieldIssue =
+  | 'required'
+  | 'email'
+  | 'tooShort'
+  | 'tooLong'
+  | 'negative'
+  | 'tooSmall'
+  | 'tooLarge'
+  | 'notNumber'
+  | 'wholeNumber'
+  | 'invalid'
+
+export interface FieldError {
+  /** The field's path in the action's input, dotted: "email", "partItems.2.quantity". */
+  field: string
+  issue: FieldIssue
+  /** The limit the rule stopped at: the length, the smallest or the largest value. */
+  limit?: number
+}
+
+type Issue = ZodError['issues'][number]
+
+function issueOf(issue: Issue): Pick<FieldError, 'issue' | 'limit'> {
+  switch (issue.code) {
+    case 'too_small': {
+      const minimum = Number(issue.minimum)
+      if (issue.origin === 'string') {
+        return minimum <= 1 ? { issue: 'required' } : { issue: 'tooShort', limit: minimum }
+      }
+      if (issue.origin === 'array' || issue.origin === 'set') return { issue: 'required' }
+      if (minimum === 0 && issue.inclusive !== false) return { issue: 'negative' }
+      return { issue: 'tooSmall', limit: minimum }
+    }
+    case 'too_big': {
+      const maximum = Number(issue.maximum)
+      if (issue.origin === 'string') return { issue: 'tooLong', limit: maximum }
+      return { issue: 'tooLarge', limit: maximum }
+    }
+    case 'invalid_format':
+      return issue.format === 'email' ? { issue: 'email' } : { issue: 'invalid' }
+    case 'invalid_type':
+      // An integer rule fails this way on a number with decimals.
+      if (issue.expected === 'int') return { issue: 'wholeNumber' }
+      // A number box sent empty or with letters arrives as undefined or NaN.
+      if (issue.expected === 'number') return { issue: 'notNumber' }
+      return { issue: 'invalid' }
+    default:
+      return { issue: 'invalid' }
+  }
+}
+
+/** One problem per field, the first the schema found, in the order it found them. */
+export function fieldErrorsFromZod(error: ZodError): FieldError[] {
+  const out: FieldError[] = []
+  const seen = new Set<string>()
+  for (const issue of error.issues) {
+    const field = issue.path.map(String).join('.')
+    if (!field || seen.has(field)) continue
+    seen.add(field)
+    out.push({ field, ...issueOf(issue) })
+  }
+  return out
+}

+ 9 - 1
src/lib/with-auth.ts

@@ -7,6 +7,7 @@ import { hasAllPermissions, PermissionAction } from './permissions'
 import { logAudit } from '@/lib/audit'
 import type { AuditEvent } from '@/lib/audit'
 import type { FeatureGatedError } from '@/lib/features'
+import { type FieldError, fieldErrorsFromZod } from '@/lib/field-errors'
 import { publicErrorMessage } from '@/lib/public-error-message'
 import { runAsActor } from '@/lib/realtime/actor.server'
 import { SCOPED_SESSION_MESSAGE, sessionOrganizationScope } from './session-scope'
@@ -33,6 +34,13 @@ export type ActionResult<T = unknown> = {
    * Nothing was written. `error` already names them.
    */
   customFieldErrors?: { fieldId: string; label: string; issue: string }[]
+  /**
+   * Set when the action's input failed its schema: each field, what was
+   * wrong with it and the limit, so the form can say it under the field in
+   * the person's language. Nothing was written. `error` is the schema's own
+   * English, for the log.
+   */
+  fieldErrors?: FieldError[]
   /**
    * Set when a job was not completed, or its invoice not sent or shared,
    * because a meter the workshop requires has no reading on it: which
@@ -231,7 +239,7 @@ export async function withAuth<T>(
       })
       const message = messages.join('. ')
       console.error('[withAuth] Validation error:', message)
-      return { success: false, error: message }
+      return { success: false, error: message, fieldErrors: fieldErrorsFromZod(error) }
     }
     // Matched by name rather than `instanceof`: tests replace '@/lib/features'
     // with partial mocks, and a plan refusal must still come through as one.