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

Check custom field values on the server and remove them with their record (#640)

* Check custom field values on the server and remove them with their record

Saving a work order's or quote's custom fields now goes through
saveValidatedCustomFieldValues, which checks every value against its field
(required, number, date, checkbox, select option, length), refuses a locked
document like every other edit to it, and writes all values or none. The
form shows what was refused next to the field. The old action name is gone,
so a tab opened before the change is asked to reload.

Deleting a work order, a quote, a vehicle, imported or sample data, or all
content now removes the custom field values of the records that go, and a
migration removes the ones left behind by earlier deletes.

* Remove values only for the records a delete took, and ask for required fields a request leaves out

A cancelled booking's placeholder job loses its values only when the delete
removed it, and Delete content removes values by the ids it found instead of
every value in the workshop, so a record made meanwhile keeps its own. A
required field left out of a save is judged by what the record shows for
it, and the form draws a field that was made required while it was open.

* Name the required custom fields that are missing when a save is stopped

A save stopped by an empty required custom field now says which, by the
workshop's own label: the message under the field, the field marked invalid
and tied to that message, focus and scroll to the first one on a save the
person asked for, and a toast (or the leave dialog) reading "Not saved.
Fill in: Fleet contact, Cost centre". The server returns each refused
field's id and label, so a stale or hand-made request is told the same.
An autosave says it without moving the focus.

* Take the block next dev writes back out of AGENTS.md

* Refuse a locked record only when a custom field value changes

The page saves its custom fields along with everything else, so a save
that changes none of them must not fail on the lock. The server now
refuses a locked work order or quote only when a submitted value differs
from what the record shows (the stored value, else the field's default),
and asks a locked record for nothing: a required field left empty before
the lock cannot be filled in. The form skips its step on a locked page.
Bernt Christian Egeland 2 дней назад
Родитель
Сommit
ae3a3b8f8f
72 измененных файлов с 2743 добавлено и 210 удалено
  1. 2 1
      messages/de/quotes.json
  2. 2 1
      messages/de/service.json
  3. 6 1
      messages/de/settings.json
  4. 2 1
      messages/en/quotes.json
  5. 2 1
      messages/en/service.json
  6. 6 1
      messages/en/settings.json
  7. 2 1
      messages/es/quotes.json
  8. 2 1
      messages/es/service.json
  9. 6 1
      messages/es/settings.json
  10. 2 1
      messages/fr/quotes.json
  11. 2 1
      messages/fr/service.json
  12. 6 1
      messages/fr/settings.json
  13. 2 1
      messages/it/quotes.json
  14. 2 1
      messages/it/service.json
  15. 6 1
      messages/it/settings.json
  16. 2 1
      messages/lt/quotes.json
  17. 2 1
      messages/lt/service.json
  18. 6 1
      messages/lt/settings.json
  19. 2 1
      messages/nb/quotes.json
  20. 2 1
      messages/nb/service.json
  21. 6 1
      messages/nb/settings.json
  22. 2 1
      messages/nl/quotes.json
  23. 2 1
      messages/nl/service.json
  24. 6 1
      messages/nl/settings.json
  25. 2 1
      messages/pl/quotes.json
  26. 2 1
      messages/pl/service.json
  27. 6 1
      messages/pl/settings.json
  28. 2 1
      messages/pt-BR/quotes.json
  29. 2 1
      messages/pt-BR/service.json
  30. 6 1
      messages/pt-BR/settings.json
  31. 2 1
      messages/pt-PT/quotes.json
  32. 2 1
      messages/pt-PT/service.json
  33. 6 1
      messages/pt-PT/settings.json
  34. 2 1
      messages/ru/quotes.json
  35. 2 1
      messages/ru/service.json
  36. 6 1
      messages/ru/settings.json
  37. 2 1
      messages/tr/quotes.json
  38. 2 1
      messages/tr/service.json
  39. 6 1
      messages/tr/settings.json
  40. 19 0
      prisma/migrations/20261119193000_remove_orphaned_custom_field_values/migration.sql
  41. 289 0
      src/__tests__/features/custom-fields/delete-removes-values.test.ts
  42. 207 0
      src/__tests__/features/custom-fields/form-server-errors.test.tsx
  43. 3 3
      src/__tests__/features/custom-fields/form-strings.test.tsx
  44. 291 0
      src/__tests__/features/custom-fields/missing-required-field.test.tsx
  45. 290 0
      src/__tests__/features/custom-fields/missing-required-page-save.test.tsx
  46. 18 6
      src/__tests__/features/custom-fields/record-permissions.test.ts
  47. 527 0
      src/__tests__/features/custom-fields/save-validated-values.test.ts
  48. 119 0
      src/__tests__/features/custom-fields/value-rules.test.ts
  49. 37 1
      src/__tests__/features/inspection-reminders/booking-actions.test.ts
  50. 20 1
      src/__tests__/features/onboarding/sample-data.test.ts
  51. 6 0
      src/__tests__/multitenancy/quote-inspection-isolation.test.ts
  52. 4 0
      src/__tests__/multitenancy/vehicle-service-isolation.test.ts
  53. 7 0
      src/components/ui/date-input.tsx
  54. 4 0
      src/components/ui/searchable-select.tsx
  55. 136 48
      src/features/custom-fields/Actions/customFieldActions.ts
  56. 238 97
      src/features/custom-fields/Components/CustomFieldsForm.tsx
  57. 86 0
      src/features/custom-fields/Lib/customFieldRecords.server.ts
  58. 89 0
      src/features/custom-fields/Lib/customFieldValueRules.ts
  59. 66 0
      src/features/custom-fields/Lib/deleteCustomFieldValues.ts
  60. 17 0
      src/features/import/Actions/importActions.ts
  61. 9 1
      src/features/inspection-reminders/Actions/bookingActions.ts
  62. 25 0
      src/features/onboarding/Actions/checklistActions.ts
  63. 6 1
      src/features/quotes/Actions/quoteActions.ts
  64. 1 0
      src/features/quotes/Components/QuoteRightColumn.tsx
  65. 29 5
      src/features/quotes/Components/useQuoteFormState.ts
  66. 10 0
      src/features/settings/Actions/deleteContent.ts
  67. 13 2
      src/features/vehicles/Actions/deleteVehicle.ts
  68. 3 0
      src/features/vehicles/Actions/serviceActions.ts
  69. 11 1
      src/features/vehicles/Actions/vehicleActions.ts
  70. 1 0
      src/features/vehicles/Components/service-page/modern/ModernDetails.tsx
  71. 21 3
      src/features/vehicles/Components/service-page/useServiceActions.ts
  72. 11 2
      src/features/vehicles/Components/service-page/useServiceFormState.ts

+ 2 - 1
messages/de/quotes.json

@@ -89,7 +89,8 @@
       "images": "Bilder",
       "documents": "Dokumente"
     },
-    "customFieldsInvalid": "Bitte alle erforderlichen benutzerdefinierten Felder ausfüllen",
+    "customFieldsMissing": "Nicht gespeichert. Bitte ausfüllen: {fields}",
+    "customFieldsNotValid": "Nicht gespeichert. Bitte prüfen: {fields}",
     "customFieldsSaveFailed": "Benutzerdefinierte Felder konnten nicht gespeichert werden"
   },
   "form": {

+ 2 - 1
messages/de/service.json

@@ -15,7 +15,8 @@
     "datesExpiredCustomize": "Daten manuell auswählen",
     "datesExpiredBack": "Zurück",
     "datesExpiredSetToday": "Auf heute setzen",
-    "customFieldsInvalid": "Bitte füllen Sie alle erforderlichen benutzerdefinierten Felder aus",
+    "customFieldsMissing": "Nicht gespeichert. Bitte ausfüllen: {fields}",
+    "customFieldsNotValid": "Nicht gespeichert. Bitte prüfen: {fields}",
     "customFieldsSaveFailed": "Benutzerdefinierte Felder konnten nicht gespeichert werden",
     "problems": {
       "title": "Der Auftrag braucht einen Titel, bevor er gespeichert werden kann.",

+ 6 - 1
messages/de/settings.json

@@ -1197,7 +1197,12 @@
     "placementHint": "In welchem Abschnitt der Rechnung oder des Angebots dieses Feld gedruckt wird. Im Designer kann es zusätzlich in weiteren Abschnitten aktiviert werden.",
     "failedSavePlacement": "Feldposition konnte nicht gespeichert werden",
     "formTitle": "Benutzerdefinierte Felder",
-    "requiredError": "{label} ist erforderlich"
+    "requiredError": "{label} ist erforderlich",
+    "numberError": "{label} muss eine Zahl sein",
+    "dateError": "{label} muss ein gültiges Datum sein",
+    "optionError": "{label} muss eine der vorgegebenen Optionen sein",
+    "checkboxError": "{label} muss entweder angehakt oder nicht angehakt sein",
+    "tooLongError": "{label} darf höchstens {max} Zeichen lang sein"
   },
   "workshop": {
     "title": "Werkstatt-Standards",

+ 2 - 1
messages/en/quotes.json

@@ -89,7 +89,8 @@
       "images": "Images",
       "documents": "Documents"
     },
-    "customFieldsInvalid": "Please fill in all required custom fields",
+    "customFieldsMissing": "Not saved. Fill in: {fields}",
+    "customFieldsNotValid": "Not saved. Check: {fields}",
     "customFieldsSaveFailed": "Failed to save custom fields"
   },
   "form": {

+ 2 - 1
messages/en/service.json

@@ -15,7 +15,8 @@
     "datesExpiredCustomize": "Choose dates manually",
     "datesExpiredBack": "Back",
     "datesExpiredSetToday": "Set to today",
-    "customFieldsInvalid": "Please fill in all required custom fields",
+    "customFieldsMissing": "Not saved. Fill in: {fields}",
+    "customFieldsNotValid": "Not saved. Check: {fields}",
     "customFieldsSaveFailed": "Failed to save custom fields",
     "problems": {
       "title": "The job needs a title before it can be saved.",

+ 6 - 1
messages/en/settings.json

@@ -1197,7 +1197,12 @@
     "placementHint": "Which section of the invoice or quote this field prints in. In the designer you can also switch it on in more sections.",
     "failedSavePlacement": "Failed to save field placement",
     "formTitle": "Custom Fields",
-    "requiredError": "{label} is required"
+    "requiredError": "{label} is required",
+    "numberError": "{label} must be a number",
+    "dateError": "{label} must be a valid date",
+    "optionError": "{label} must be one of its options",
+    "checkboxError": "{label} must be either ticked or unticked",
+    "tooLongError": "{label} can be at most {max} characters"
   },
   "workshop": {
     "title": "Workshop Defaults",

+ 2 - 1
messages/es/quotes.json

@@ -89,7 +89,8 @@
       "images": "Imágenes",
       "documents": "Documentos"
     },
-    "customFieldsInvalid": "Completa todos los campos personalizados obligatorios",
+    "customFieldsMissing": "No se ha guardado. Rellene: {fields}",
+    "customFieldsNotValid": "No se ha guardado. Revise: {fields}",
     "customFieldsSaveFailed": "No se pudieron guardar los campos personalizados"
   },
   "form": {

+ 2 - 1
messages/es/service.json

@@ -15,7 +15,8 @@
     "datesExpiredCustomize": "Elegir fechas manualmente",
     "datesExpiredBack": "Atrás",
     "datesExpiredSetToday": "Establecer a hoy",
-    "customFieldsInvalid": "Por favor complete todos los campos personalizados obligatorios",
+    "customFieldsMissing": "No se ha guardado. Rellena: {fields}",
+    "customFieldsNotValid": "No se ha guardado. Revisa: {fields}",
     "customFieldsSaveFailed": "Error al guardar los campos personalizados",
     "problems": {
       "title": "El trabajo necesita un título antes de poder guardarse.",

+ 6 - 1
messages/es/settings.json

@@ -1197,7 +1197,12 @@
     "placementHint": "En qué sección de la factura o del presupuesto se imprime este campo. En el diseñador también puedes activarlo en más secciones.",
     "failedSavePlacement": "No se pudo guardar la ubicación del campo",
     "formTitle": "Campos personalizados",
-    "requiredError": "El campo {label} es obligatorio"
+    "requiredError": "El campo {label} es obligatorio",
+    "numberError": "El campo {label} debe ser un número",
+    "dateError": "El campo {label} debe ser una fecha válida",
+    "optionError": "El campo {label} debe ser una de sus opciones",
+    "checkboxError": "El campo {label} debe estar marcado o desmarcado",
+    "tooLongError": "El campo {label} admite como máximo {max} caracteres"
   },
   "workshop": {
     "title": "Valores predeterminados del taller",

+ 2 - 1
messages/fr/quotes.json

@@ -89,7 +89,8 @@
       "images": "Images",
       "documents": "Documents"
     },
-    "customFieldsInvalid": "Veuillez remplir tous les champs personnalisés obligatoires",
+    "customFieldsMissing": "Non enregistré. Renseignez : {fields}",
+    "customFieldsNotValid": "Non enregistré. Vérifiez : {fields}",
     "customFieldsSaveFailed": "Impossible d'enregistrer les champs personnalisés"
   },
   "form": {

+ 2 - 1
messages/fr/service.json

@@ -15,7 +15,8 @@
     "datesExpiredCustomize": "Choisir les dates manuellement",
     "datesExpiredBack": "Retour",
     "datesExpiredSetToday": "Définir à aujourd'hui",
-    "customFieldsInvalid": "Veuillez remplir tous les champs personnalisés obligatoires",
+    "customFieldsMissing": "Non enregistré. Renseignez : {fields}",
+    "customFieldsNotValid": "Non enregistré. Vérifiez : {fields}",
     "customFieldsSaveFailed": "Échec de l'enregistrement des champs personnalisés",
     "problems": {
       "title": "Le travail doit avoir un titre avant d'être enregistré.",

+ 6 - 1
messages/fr/settings.json

@@ -1197,7 +1197,12 @@
     "placementHint": "Dans quelle section de la facture ou du devis ce champ est imprimé. Dans le designer, vous pouvez aussi l'activer dans d'autres sections.",
     "failedSavePlacement": "Impossible d'enregistrer l'emplacement du champ",
     "formTitle": "Champs personnalisés",
-    "requiredError": "Le champ {label} est obligatoire"
+    "requiredError": "Le champ {label} est obligatoire",
+    "numberError": "Le champ {label} doit être un nombre",
+    "dateError": "Le champ {label} doit être une date valide",
+    "optionError": "Le champ {label} doit correspondre à l'une de ses options",
+    "checkboxError": "Le champ {label} doit être coché ou décoché",
+    "tooLongError": "Le champ {label} ne peut pas dépasser {max} caractères"
   },
   "workshop": {
     "title": "Valeurs par défaut de l'atelier",

+ 2 - 1
messages/it/quotes.json

@@ -89,7 +89,8 @@
       "images": "Immagini",
       "documents": "Documenti"
     },
-    "customFieldsInvalid": "Compila tutti i campi personalizzati obbligatori",
+    "customFieldsMissing": "Non salvato. Compila: {fields}",
+    "customFieldsNotValid": "Non salvato. Controlla: {fields}",
     "customFieldsSaveFailed": "Impossibile salvare i campi personalizzati"
   },
   "form": {

+ 2 - 1
messages/it/service.json

@@ -15,7 +15,8 @@
     "datesExpiredCustomize": "Scegli le date manualmente",
     "datesExpiredBack": "Indietro",
     "datesExpiredSetToday": "Imposta a oggi",
-    "customFieldsInvalid": "Compila tutti i campi personalizzati obbligatori",
+    "customFieldsMissing": "Non salvato. Compila: {fields}",
+    "customFieldsNotValid": "Non salvato. Controlla: {fields}",
     "customFieldsSaveFailed": "Impossibile salvare i campi personalizzati",
     "problems": {
       "title": "Il lavoro deve avere un titolo prima di poter essere salvato.",

+ 6 - 1
messages/it/settings.json

@@ -1197,7 +1197,12 @@
     "placementHint": "In quale sezione della fattura o del preventivo viene stampato questo campo. Nel designer puoi attivarlo anche in altre sezioni.",
     "failedSavePlacement": "Impossibile salvare la posizione del campo",
     "formTitle": "Campi personalizzati",
-    "requiredError": "Il campo {label} è obbligatorio"
+    "requiredError": "Il campo {label} è obbligatorio",
+    "numberError": "Il campo {label} deve essere un numero",
+    "dateError": "Il campo {label} deve essere una data valida",
+    "optionError": "Il campo {label} deve essere una delle opzioni disponibili",
+    "checkboxError": "Il campo {label} deve essere selezionato o deselezionato",
+    "tooLongError": "Il campo {label} può contenere al massimo {max} caratteri"
   },
   "workshop": {
     "title": "Predefiniti officina",

+ 2 - 1
messages/lt/quotes.json

@@ -89,7 +89,8 @@
       "images": "Vaizdai",
       "documents": "Dokumentai"
     },
-    "customFieldsInvalid": "Užpildykite visus privalomus pasirinktinius laukus",
+    "customFieldsMissing": "Neišsaugota. Užpildykite: {fields}",
+    "customFieldsNotValid": "Neišsaugota. Patikrinkite: {fields}",
     "customFieldsSaveFailed": "Nepavyko išsaugoti pasirinktinių laukų"
   },
   "form": {

+ 2 - 1
messages/lt/service.json

@@ -15,7 +15,8 @@
     "datesExpiredCustomize": "Pasirinkti datas rankiniu būdu",
     "datesExpiredBack": "Atgal",
     "datesExpiredSetToday": "Nustatyti šiandienos datą",
-    "customFieldsInvalid": "Užpildykite visus privalomus pasirinktinius laukus",
+    "customFieldsMissing": "Neišsaugota. Užpildykite: {fields}",
+    "customFieldsNotValid": "Neišsaugota. Patikrinkite: {fields}",
     "customFieldsSaveFailed": "Nepavyko išsaugoti pasirinktinių laukų",
     "problems": {
       "title": "Užsakymui reikia pavadinimo, kad jį būtų galima išsaugoti.",

+ 6 - 1
messages/lt/settings.json

@@ -1197,7 +1197,12 @@
     "placementHint": "Kurioje sąskaitos arba pasiūlymo dalyje spausdinamas šis laukas. Dizaineryje jį galima įjungti ir kitose dalyse.",
     "failedSavePlacement": "Nepavyko išsaugoti lauko vietos",
     "formTitle": "Pasirinktiniai laukai",
-    "requiredError": "{label}: būtina užpildyti"
+    "requiredError": "{label}: būtina užpildyti",
+    "numberError": "{label}: turi būti skaičius",
+    "dateError": "{label}: turi būti tinkama data",
+    "optionError": "{label}: turi būti viena iš parinkčių",
+    "checkboxError": "{label}: langelis turi būti pažymėtas arba nepažymėtas",
+    "tooLongError": "{label}: ne daugiau kaip {max} simbolių"
   },
   "workshop": {
     "title": "Dirbtuvių numatytosios reikšmės",

+ 2 - 1
messages/nb/quotes.json

@@ -89,7 +89,8 @@
       "images": "Bilder",
       "documents": "Dokumenter"
     },
-    "customFieldsInvalid": "Fyll ut alle obligatoriske egendefinerte felt",
+    "customFieldsMissing": "Ikke lagret. Fyll ut: {fields}",
+    "customFieldsNotValid": "Ikke lagret. Sjekk: {fields}",
     "customFieldsSaveFailed": "Kunne ikke lagre egendefinerte felt"
   },
   "form": {

+ 2 - 1
messages/nb/service.json

@@ -15,7 +15,8 @@
     "datesExpiredCustomize": "Velg datoer manuelt",
     "datesExpiredBack": "Tilbake",
     "datesExpiredSetToday": "Sett til i dag",
-    "customFieldsInvalid": "Vennligst fyll ut alle obligatoriske egendefinerte felt",
+    "customFieldsMissing": "Ikke lagret. Fyll ut: {fields}",
+    "customFieldsNotValid": "Ikke lagret. Sjekk: {fields}",
     "customFieldsSaveFailed": "Kunne ikke lagre egendefinerte felt",
     "problems": {
       "title": "Jobben må ha en tittel før den kan lagres.",

+ 6 - 1
messages/nb/settings.json

@@ -1197,7 +1197,12 @@
     "placementHint": "Hvilken del av fakturaen eller tilbudet dette feltet skrives ut i. I designeren kan du også slå det på i flere seksjoner.",
     "failedSavePlacement": "Kunne ikke lagre feltplasseringen",
     "formTitle": "Egendefinerte felter",
-    "requiredError": "{label} er påkrevd"
+    "requiredError": "{label} er påkrevd",
+    "numberError": "{label} må være et tall",
+    "dateError": "{label} må være en gyldig dato",
+    "optionError": "{label} må være ett av valgene",
+    "checkboxError": "{label} må enten være avkrysset eller ikke avkrysset",
+    "tooLongError": "{label} kan ha maks {max} tegn"
   },
   "workshop": {
     "title": "Verkstedstandarder",

+ 2 - 1
messages/nl/quotes.json

@@ -89,7 +89,8 @@
       "images": "Afbeeldingen",
       "documents": "Documenten"
     },
-    "customFieldsInvalid": "Vul alle verplichte aangepaste velden in",
+    "customFieldsMissing": "Niet opgeslagen. Vul in: {fields}",
+    "customFieldsNotValid": "Niet opgeslagen. Controleer: {fields}",
     "customFieldsSaveFailed": "Kan aangepaste velden niet opslaan"
   },
   "form": {

+ 2 - 1
messages/nl/service.json

@@ -15,7 +15,8 @@
     "datesExpiredCustomize": "Datums handmatig kiezen",
     "datesExpiredBack": "Terug",
     "datesExpiredSetToday": "Instellen op vandaag",
-    "customFieldsInvalid": "Vul alle verplichte aangepaste velden in",
+    "customFieldsMissing": "Niet opgeslagen. Vul in: {fields}",
+    "customFieldsNotValid": "Niet opgeslagen. Controleer: {fields}",
     "customFieldsSaveFailed": "Kan aangepaste velden niet opslaan",
     "problems": {
       "title": "De opdracht heeft een titel nodig voordat deze kan worden opgeslagen.",

+ 6 - 1
messages/nl/settings.json

@@ -1197,7 +1197,12 @@
     "placementHint": "In welke sectie van de factuur of offerte dit veld wordt afgedrukt. In de designer kun je het ook in meer secties inschakelen.",
     "failedSavePlacement": "Kan de veldplaatsing niet opslaan",
     "formTitle": "Aangepaste velden",
-    "requiredError": "{label} is verplicht"
+    "requiredError": "{label} is verplicht",
+    "numberError": "{label} moet een getal zijn",
+    "dateError": "{label} moet een geldige datum zijn",
+    "optionError": "{label} moet een van de opties zijn",
+    "checkboxError": "{label} moet aangevinkt of niet aangevinkt zijn",
+    "tooLongError": "{label} mag maximaal {max} tekens bevatten"
   },
   "workshop": {
     "title": "Werkplaatsstandaarden",

+ 2 - 1
messages/pl/quotes.json

@@ -89,7 +89,8 @@
       "images": "Zdjęcia",
       "documents": "Dokumenty"
     },
-    "customFieldsInvalid": "Wypełnij wszystkie wymagane pola niestandardowe",
+    "customFieldsMissing": "Nie zapisano. Uzupełnij: {fields}",
+    "customFieldsNotValid": "Nie zapisano. Sprawdź: {fields}",
     "customFieldsSaveFailed": "Nie udało się zapisać pól niestandardowych"
   },
   "form": {

+ 2 - 1
messages/pl/service.json

@@ -15,7 +15,8 @@
     "datesExpiredCustomize": "Wybierz daty ręcznie",
     "datesExpiredBack": "Wstecz",
     "datesExpiredSetToday": "Ustaw na dziś",
-    "customFieldsInvalid": "Proszę wypełnić wszystkie wymagane pola niestandardowe",
+    "customFieldsMissing": "Nie zapisano. Uzupełnij: {fields}",
+    "customFieldsNotValid": "Nie zapisano. Sprawdź: {fields}",
     "customFieldsSaveFailed": "Nie udało się zapisać pól niestandardowych",
     "problems": {
       "title": "Zlecenie musi mieć tytuł, zanim będzie można je zapisać.",

+ 6 - 1
messages/pl/settings.json

@@ -1197,7 +1197,12 @@
     "placementHint": "W której sekcji faktury lub wyceny drukowane jest to pole. W projektancie można je włączyć także w innych sekcjach.",
     "failedSavePlacement": "Nie udało się zapisać miejsca pola",
     "formTitle": "Pola niestandardowe",
-    "requiredError": "Pole {label} jest wymagane"
+    "requiredError": "Pole {label} jest wymagane",
+    "numberError": "Pole {label} musi zawierać liczbę",
+    "dateError": "Pole {label} musi zawierać prawidłową datę",
+    "optionError": "Pole {label} musi zawierać jedną z dostępnych opcji",
+    "checkboxError": "Pole {label} musi być zaznaczone lub odznaczone",
+    "tooLongError": "Pole {label} może zawierać maksymalnie {max} znaków"
   },
   "workshop": {
     "title": "Domyślne warsztatu",

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

@@ -89,7 +89,8 @@
       "images": "Imagens",
       "documents": "Documentos"
     },
-    "customFieldsInvalid": "Preencha todos os campos personalizados obrigatórios",
+    "customFieldsMissing": "Não salvo. Preencha: {fields}",
+    "customFieldsNotValid": "Não salvo. Verifique: {fields}",
     "customFieldsSaveFailed": "Não foi possível salvar os campos personalizados"
   },
   "form": {

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

@@ -15,7 +15,8 @@
     "datesExpiredCustomize": "Escolher datas manualmente",
     "datesExpiredBack": "Voltar",
     "datesExpiredSetToday": "Definir para hoje",
-    "customFieldsInvalid": "Preencha todos os campos personalizados obrigatórios",
+    "customFieldsMissing": "Não salvo. Preencha: {fields}",
+    "customFieldsNotValid": "Não salvo. Verifique: {fields}",
     "customFieldsSaveFailed": "Falha ao salvar campos personalizados",
     "problems": {
       "title": "A ordem precisa de um título antes de ser salva.",

+ 6 - 1
messages/pt-BR/settings.json

@@ -1197,7 +1197,12 @@
     "placementHint": "Em qual seção da fatura ou do orçamento este campo é impresso. No designer você também pode ativá-lo em mais seções.",
     "failedSavePlacement": "Não foi possível salvar a posição do campo",
     "formTitle": "Campos personalizados",
-    "requiredError": "O campo {label} é obrigatório"
+    "requiredError": "O campo {label} é obrigatório",
+    "numberError": "O campo {label} deve ser um número",
+    "dateError": "O campo {label} deve ser uma data válida",
+    "optionError": "O campo {label} deve ser uma das opções disponíveis",
+    "checkboxError": "O campo {label} deve estar marcado ou desmarcado",
+    "tooLongError": "O campo {label} pode ter no máximo {max} caracteres"
   },
   "workshop": {
     "title": "Padrões da oficina",

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

@@ -89,7 +89,8 @@
       "images": "Imagens",
       "documents": "Documentos"
     },
-    "customFieldsInvalid": "Preencha todos os campos personalizados obrigatórios",
+    "customFieldsMissing": "Não guardado. Preencha: {fields}",
+    "customFieldsNotValid": "Não guardado. Verifique: {fields}",
     "customFieldsSaveFailed": "Não foi possível guardar os campos personalizados"
   },
   "form": {

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

@@ -15,7 +15,8 @@
     "datesExpiredCustomize": "Escolher datas manualmente",
     "datesExpiredBack": "Voltar",
     "datesExpiredSetToday": "Definir para hoje",
-    "customFieldsInvalid": "Preencha todos os campos personalizados obrigatórios",
+    "customFieldsMissing": "Não guardado. Preencha: {fields}",
+    "customFieldsNotValid": "Não guardado. Verifique: {fields}",
     "customFieldsSaveFailed": "Não foi possível guardar os campos personalizados",
     "problems": {
       "title": "A ordem de serviço precisa de um título antes de ser guardada.",

+ 6 - 1
messages/pt-PT/settings.json

@@ -1197,7 +1197,12 @@
     "placementHint": "Em que secção da fatura ou do orçamento este campo é impresso. No editor também pode ativá-lo em mais secções.",
     "failedSavePlacement": "Não foi possível guardar a posição do campo",
     "formTitle": "Campos personalizados",
-    "requiredError": "O campo {label} é obrigatório"
+    "requiredError": "O campo {label} é obrigatório",
+    "numberError": "O campo {label} tem de ser um número",
+    "dateError": "O campo {label} tem de ser uma data válida",
+    "optionError": "O campo {label} tem de ser uma das opções disponíveis",
+    "checkboxError": "O campo {label} tem de estar assinalado ou não assinalado",
+    "tooLongError": "O campo {label} pode ter, no máximo, {max} caracteres"
   },
   "workshop": {
     "title": "Predefinições da oficina",

+ 2 - 1
messages/ru/quotes.json

@@ -89,7 +89,8 @@
       "images": "Изображения",
       "documents": "Документы"
     },
-    "customFieldsInvalid": "Заполните все обязательные пользовательские поля",
+    "customFieldsMissing": "Не сохранено. Заполните: {fields}",
+    "customFieldsNotValid": "Не сохранено. Проверьте: {fields}",
     "customFieldsSaveFailed": "Не удалось сохранить пользовательские поля"
   },
   "form": {

+ 2 - 1
messages/ru/service.json

@@ -15,7 +15,8 @@
     "datesExpiredCustomize": "Выбрать даты вручную",
     "datesExpiredBack": "Назад",
     "datesExpiredSetToday": "Установить на сегодня",
-    "customFieldsInvalid": "Заполните все обязательные пользовательские поля",
+    "customFieldsMissing": "Не сохранено. Заполните: {fields}",
+    "customFieldsNotValid": "Не сохранено. Проверьте: {fields}",
     "customFieldsSaveFailed": "Не удалось сохранить пользовательские поля",
     "problems": {
       "title": "Заказу нужно название, прежде чем его можно сохранить.",

+ 6 - 1
messages/ru/settings.json

@@ -1197,7 +1197,12 @@
     "placementHint": "В каком разделе счёта или сметы печатается это поле. В дизайнере его можно включить и в других разделах.",
     "failedSavePlacement": "Не удалось сохранить расположение поля",
     "formTitle": "Пользовательские поля",
-    "requiredError": "Поле {label} обязательно для заполнения"
+    "requiredError": "Поле {label} обязательно для заполнения",
+    "numberError": "Поле {label} должно содержать число",
+    "dateError": "Поле {label} должно содержать корректную дату",
+    "optionError": "Поле {label} должно содержать один из вариантов списка",
+    "checkboxError": "Поле {label}: флажок должен быть установлен или снят",
+    "tooLongError": "Поле {label} может содержать не более {max} символов"
   },
   "workshop": {
     "title": "Настройки мастерской",

+ 2 - 1
messages/tr/quotes.json

@@ -89,7 +89,8 @@
       "images": "Görseller",
       "documents": "Belgeler"
     },
-    "customFieldsInvalid": "Lütfen tüm zorunlu özel alanları doldurun",
+    "customFieldsMissing": "Kaydedilmedi. Doldurun: {fields}",
+    "customFieldsNotValid": "Kaydedilmedi. Kontrol edin: {fields}",
     "customFieldsSaveFailed": "Özel alanlar kaydedilemedi"
   },
   "form": {

+ 2 - 1
messages/tr/service.json

@@ -15,7 +15,8 @@
     "datesExpiredCustomize": "Tarihleri manuel olarak seç",
     "datesExpiredBack": "Geri",
     "datesExpiredSetToday": "Bugüne ayarla",
-    "customFieldsInvalid": "Lütfen tüm zorunlu özel alanları doldurun",
+    "customFieldsMissing": "Kaydedilmedi. Doldurun: {fields}",
+    "customFieldsNotValid": "Kaydedilmedi. Kontrol edin: {fields}",
     "customFieldsSaveFailed": "Özel alanlar kaydedilemedi",
     "problems": {
       "title": "İş kaydedilmeden önce bir başlık gerekiyor.",

+ 6 - 1
messages/tr/settings.json

@@ -1197,7 +1197,12 @@
     "placementHint": "Bu alanın faturanın veya teklifin hangi bölümünde yazdırılacağı. Tasarımcıda başka bölümlerde de açabilirsiniz.",
     "failedSavePlacement": "Alan konumu kaydedilemedi",
     "formTitle": "Özel alanlar",
-    "requiredError": "{label} zorunludur"
+    "requiredError": "{label} zorunludur",
+    "numberError": "{label} bir sayı olmalıdır",
+    "dateError": "{label} geçerli bir tarih olmalıdır",
+    "optionError": "{label} seçeneklerinden biri olmalıdır",
+    "checkboxError": "{label} işaretli ya da işaretsiz olmalıdır",
+    "tooLongError": "{label} en fazla {max} karakter olabilir"
   },
   "workshop": {
     "title": "Atölye Varsayılanları",

+ 19 - 0
prisma/migrations/20261119193000_remove_orphaned_custom_field_values/migration.sql

@@ -0,0 +1,19 @@
+-- Custom field values are keyed by the id of the work order or quote they
+-- belong to, with no foreign key, so deleting the record left its values
+-- behind. The app now removes them with the record; this removes the ones
+-- left from before.
+--
+-- A row is removed only when its kind names a table and no row of that table
+-- has its id. Ids are never reused, so nothing can show such a value again.
+-- Values of any other kind are not touched.
+BEGIN;
+
+DELETE FROM "custom_field_values" v
+WHERE v."entityType" = 'service_record'
+  AND NOT EXISTS (SELECT 1 FROM "service_records" r WHERE r."id" = v."entityId");
+
+DELETE FROM "custom_field_values" v
+WHERE v."entityType" = 'quote'
+  AND NOT EXISTS (SELECT 1 FROM "quotes" q WHERE q."id" = v."entityId");
+
+COMMIT;

+ 289 - 0
src/__tests__/features/custom-fields/delete-removes-values.test.ts

@@ -0,0 +1,289 @@
+/**
+ * @vitest-environment node
+ *
+ * A custom field value is keyed by the id of its work order or quote, with no
+ * foreign key, so the database removes nothing when that record is deleted.
+ * The values used to stay behind for good. Every delete now takes them along,
+ * for the records it deleted and for this workshop only.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const calls = vi.hoisted(() => ({ list: [] as { key: string; args: unknown }[] }))
+const rows = vi.hoisted(() => ({
+  findFirst: {} as Record<string, unknown>,
+  findMany: {} as Record<string, unknown[]>,
+}))
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(async () => ({ user: { id: 'user-a', email: 'a@x.test' } })),
+  getCachedMembership: vi.fn(async () => ({
+    organizationId: 'org-a',
+    role: 'owner',
+    roleId: null,
+    customRole: null,
+  })),
+}))
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
+vi.mock('@/lib/audit', () => ({ logAudit: vi.fn(), auditDetails: vi.fn(() => undefined) }))
+vi.mock('@/lib/notification-bus', () => ({ notificationBus: { emit: vi.fn() } }))
+vi.mock('@/lib/demo', () => ({
+  demoGuard: vi.fn(),
+  demoGuardSettingKey: vi.fn(),
+  isDemoMode: vi.fn(() => false),
+}))
+vi.mock('@/lib/features', () => ({
+  requireFeature: vi.fn(),
+  getFeatures: vi.fn(async () => ({})),
+}))
+vi.mock('@/lib/document-lock.server', () => ({
+  assertInvoiceEditable: vi.fn(),
+  assertQuoteEditable: vi.fn(),
+  getDocumentLockSettings: vi.fn(async () => ({})),
+}))
+vi.mock('@/features/inventory/Lib/onInventoryChanged', () => ({ onInventoryChanged: vi.fn() }))
+vi.mock('@/features/inventory/Lib/reconcileStock', () => ({
+  reconcileInventoryForParts: vi.fn(),
+}))
+vi.mock('@/features/settings/Lib/armFeatureHints', () => ({ armFeatureHints: vi.fn() }))
+vi.mock('@/lib/torqvoice-com', () => ({
+  billingRequest: vi.fn(),
+  isTorqvoiceComBillingConfigured: vi.fn(() => false),
+}))
+vi.mock('@/lib/files/collect', () => ({
+  serviceRecordFileUrls: vi.fn(async () => []),
+  inspectionFileUrls: vi.fn(async () => []),
+  vehicleFileUrls: vi.fn(async () => []),
+  quoteFileUrls: vi.fn(async () => []),
+  tireSetFileUrls: vi.fn(async () => []),
+  inventoryPartFileUrls: vi.fn(async () => []),
+}))
+vi.mock('@/lib/files/manager', () => ({
+  releaseFiles: vi.fn(async () => ({ removed: [], kept: [], skipped: [] })),
+  removeOrganizationFiles: vi.fn(),
+  parseStoredFileUrl: () => null,
+}))
+
+/**
+ * A database stand-in that records every call with what it was given.
+ * `findFirst` answers from `rows.findFirst[model]`, `findMany` from
+ * `rows.findMany[model]`; writes answer with one row changed.
+ */
+vi.mock('@/lib/db', () => {
+  const method = (model: string, name: string) => async (args: unknown) => {
+    calls.list.push({ key: `${model}.${name}`, args })
+    if (name === 'findFirst' || name === 'findUnique') return rows.findFirst[model] ?? null
+    if (name === 'findMany') return rows.findMany[model] ?? []
+    if (name === 'count') return 0
+    if (name.endsWith('Many')) return { count: 1 }
+    return {}
+  }
+  const client: Record<string, unknown> = new Proxy(
+    {},
+    {
+      get: (_, model: string) => {
+        if (model === '$transaction') {
+          return async (arg: unknown) =>
+            typeof arg === 'function' ? arg(client) : Promise.all(arg as Promise<unknown>[])
+        }
+        if (model === 'then') return undefined
+        return new Proxy({}, { get: (__, name: string) => method(model, name) })
+      },
+    }
+  )
+  return { db: client }
+})
+
+import { deleteCustomFieldValuesOf } from '@/features/custom-fields/Lib/deleteCustomFieldValues'
+import { deleteQuote } from '@/features/quotes/Actions/quoteActions'
+import { deleteContent } from '@/features/settings/Actions/deleteContent'
+import { deleteVehicle as deleteVehicleFromPage } from '@/features/vehicles/Actions/deleteVehicle'
+import { deleteServiceRecord } from '@/features/vehicles/Actions/serviceActions'
+import { deleteVehicle } from '@/features/vehicles/Actions/vehicleActions'
+
+const index = (key: string) => calls.list.findIndex((call) => call.key === key)
+const valueDeletes = () =>
+  calls.list.filter((call) => call.key === 'customFieldValue.deleteMany').map((call) => call.args)
+
+beforeEach(() => {
+  calls.list = []
+  rows.findFirst = { user: { isSuperAdmin: false } }
+  rows.findMany = {}
+  vi.spyOn(console, 'error').mockImplementation(() => undefined)
+})
+
+describe('deleting a work order', () => {
+  it('removes its custom field values in the same transaction, after the record', async () => {
+    rows.findFirst.serviceRecord = { id: 'sr-1', vehicleId: 'v-1', invoiceNumber: 'WO-1' }
+
+    expect((await deleteServiceRecord('sr-1')).success).toBe(true)
+
+    expect(valueDeletes()).toEqual([
+      {
+        where: {
+          entityType: 'service_record',
+          entityId: { in: ['sr-1'] },
+          field: { organizationId: 'org-a' },
+        },
+      },
+    ])
+    expect(index('customFieldValue.deleteMany')).toBeGreaterThan(index('serviceRecord.delete'))
+  })
+
+  it('removes nothing when the work order is not this workshop’s', async () => {
+    expect((await deleteServiceRecord('theirs')).success).toBe(false)
+
+    expect(valueDeletes()).toEqual([])
+  })
+})
+
+describe('deleting a quote', () => {
+  it('removes its custom field values with it', async () => {
+    rows.findFirst.quote = { id: 'q-1', organizationId: 'org-a' }
+
+    expect((await deleteQuote('q-1')).success).toBe(true)
+
+    expect(valueDeletes()).toEqual([
+      {
+        where: {
+          entityType: 'quote',
+          entityId: { in: ['q-1'] },
+          field: { organizationId: 'org-a' },
+        },
+      },
+    ])
+    expect(index('customFieldValue.deleteMany')).toBeGreaterThan(index('quote.deleteMany'))
+  })
+
+  it('removes nothing when the quote is not this workshop’s', async () => {
+    expect((await deleteQuote('theirs')).success).toBe(false)
+
+    expect(valueDeletes()).toEqual([])
+  })
+})
+
+describe('deleting a vehicle, which takes its work orders with it', () => {
+  const expected = [
+    {
+      where: {
+        entityType: 'service_record',
+        entityId: { in: ['sr-1', 'sr-2'] },
+        field: { organizationId: 'org-a' },
+      },
+    },
+  ]
+
+  it('removes the values of those work orders, from the vehicles list', async () => {
+    rows.findFirst.vehicle = { year: 2020, make: 'Ford', model: 'F-150', licensePlate: null }
+    rows.findMany.serviceRecord = [{ id: 'sr-1' }, { id: 'sr-2' }]
+
+    expect((await deleteVehicle('v-1')).success).toBe(true)
+
+    expect(valueDeletes()).toEqual(expected)
+    // Read while the work orders could still be found.
+    expect(index('serviceRecord.findMany')).toBeLessThan(index('vehicle.deleteMany'))
+    expect(calls.list[index('serviceRecord.findMany')].args).toEqual({
+      where: { organizationId: 'org-a', vehicleId: { in: ['v-1'] } },
+      select: { id: true },
+    })
+  })
+
+  it('removes them from the vehicle’s own page too', async () => {
+    rows.findMany.serviceRecord = [{ id: 'sr-1' }, { id: 'sr-2' }]
+
+    expect((await deleteVehicleFromPage('v-1')).success).toBe(true)
+
+    expect(valueDeletes()).toEqual(expected)
+  })
+
+  it('asks for nothing when the vehicle had no work orders', async () => {
+    expect((await deleteVehicleFromPage('v-1')).success).toBe(true)
+
+    expect(valueDeletes()).toEqual([])
+  })
+})
+
+describe('delete content', () => {
+  it('removes the values of the work orders and quotes it found, by id', async () => {
+    rows.findMany.serviceRecord = [{ id: 'sr-1' }, { id: 'sr-2' }]
+    rows.findMany.quote = [{ id: 'q-1' }]
+
+    const result = await deleteContent({ vehicles: true, quotes: true } as never)
+
+    expect(result.success).toBe(true)
+    // By id, never "every value in the workshop": a job or quote made while
+    // this runs is not in the list and keeps its values.
+    expect(valueDeletes()).toEqual([
+      {
+        where: {
+          entityType: 'service_record',
+          entityId: { in: ['sr-1', 'sr-2'] },
+          field: { organizationId: 'org-a' },
+        },
+      },
+      {
+        where: {
+          entityType: 'quote',
+          entityId: { in: ['q-1'] },
+          field: { organizationId: 'org-a' },
+        },
+      },
+    ])
+    // The field definitions were not ticked, so they stay.
+    expect(index('customFieldDefinition.deleteMany')).toBe(-1)
+  })
+
+  it('leaves quote values alone when only vehicles are deleted', async () => {
+    rows.findMany.serviceRecord = [{ id: 'sr-1' }]
+    rows.findMany.quote = [{ id: 'q-1' }]
+
+    await deleteContent({ vehicles: true } as never)
+
+    expect(valueDeletes()).toEqual([
+      {
+        where: {
+          entityType: 'service_record',
+          entityId: { in: ['sr-1'] },
+          field: { organizationId: 'org-a' },
+        },
+      },
+    ])
+  })
+})
+
+describe('the helper every delete goes through', () => {
+  const store = () => {
+    const deleteMany = vi.fn(async (_args: { where: { entityId: { in: string[] } } }) => ({
+      count: 0,
+    }))
+    return { store: { customFieldValue: { deleteMany } }, deleteMany }
+  }
+
+  it('asks the database nothing for an empty list', async () => {
+    const { store: s, deleteMany } = store()
+    await deleteCustomFieldValuesOf(s, 'org-a', 'quote', [])
+    expect(deleteMany).not.toHaveBeenCalled()
+  })
+
+  it('splits a very long list so no single query is too large', async () => {
+    const { store: s, deleteMany } = store()
+    const ids = Array.from({ length: 12000 }, (_, i) => `sr-${i}`)
+
+    await deleteCustomFieldValuesOf(s, 'org-a', 'service_record', ids)
+
+    const asked = deleteMany.mock.calls.flatMap(([args]) => args.where.entityId.in)
+    expect(deleteMany).toHaveBeenCalledTimes(3)
+    expect(asked).toEqual(ids)
+  })
+
+  it('never reaches past the workshop, whatever ids it is given', async () => {
+    const { store: s, deleteMany } = store()
+    await deleteCustomFieldValuesOf(s, 'org-a', 'quote', ['q-of-another-workshop'])
+    expect(deleteMany).toHaveBeenCalledWith({
+      where: {
+        entityType: 'quote',
+        entityId: { in: ['q-of-another-workshop'] },
+        field: { organizationId: 'org-a' },
+      },
+    })
+  })
+})

+ 207 - 0
src/__tests__/features/custom-fields/form-server-errors.test.tsx

@@ -0,0 +1,207 @@
+/**
+ * The custom fields card shows what the server refused next to the field it
+ * refused, and tells the page why the save stopped.
+ */
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const save = vi.hoisted(() => vi.fn())
+const load = vi.hoisted(() => vi.fn())
+vi.mock('@/features/custom-fields/Actions/customFieldActions', () => ({
+  getCustomFieldValues: load,
+  getFieldDefinitions: vi.fn(async () => ({ success: true, data: [] })),
+  saveValidatedCustomFieldValues: save,
+}))
+
+import {
+  CustomFieldsForm,
+  type CustomFieldsSaveOutcome,
+} from '@/features/custom-fields/Components/CustomFieldsForm'
+
+async function mount() {
+  let run: (() => Promise<CustomFieldsSaveOutcome>) | undefined
+  render(
+    <CustomFieldsForm
+      entityId="job-1"
+      entityType="service_record"
+      onValuesReady={(fn) => {
+        run = fn
+      }}
+    />
+  )
+  await screen.findByText('Custom Fields')
+  return async () => {
+    let outcome: CustomFieldsSaveOutcome | undefined
+    await act(async () => {
+      outcome = await run?.()
+    })
+    return outcome
+  }
+}
+
+const field = (id: string) => screen.getByTestId(`custom-field-${id}`)
+
+const FIELDS = [
+  {
+    id: 'po',
+    name: 'po',
+    label: 'PO number',
+    fieldType: 'text',
+    options: null,
+    required: true,
+    value: 'PO 1',
+  },
+  {
+    id: 'axles',
+    name: 'axles',
+    label: 'Axles',
+    fieldType: 'number',
+    options: null,
+    required: false,
+    value: '2',
+  },
+  {
+    id: 'bay',
+    name: 'bay',
+    label: 'Bay',
+    fieldType: 'select',
+    options: 'Bay 1, Bay 2',
+    required: false,
+    value: 'Bay 3',
+  },
+]
+
+beforeEach(() => {
+  save.mockReset().mockResolvedValue({ success: true, data: { saved: true } })
+  load.mockReset().mockResolvedValue({ success: true, data: FIELDS })
+})
+
+describe('saving the custom fields', () => {
+  it('sends the values to the checked action and reports a clean save', async () => {
+    const run = await mount()
+
+    expect(await run()).toEqual({ valid: true })
+    expect(save).toHaveBeenCalledWith('job-1', 'service_record', {
+      po: 'PO 1',
+      axles: '2',
+      bay: 'Bay 3',
+    })
+    expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+  })
+
+  it('does not hold an old value against the record: "Bay 3" was an option once', async () => {
+    const run = await mount()
+
+    expect(await run()).toEqual({ valid: true })
+    expect(save).toHaveBeenCalledTimes(1)
+  })
+
+  it('shows what the server refused next to the field it refused', async () => {
+    save.mockResolvedValue({
+      success: true,
+      data: {
+        saved: false,
+        fieldErrors: [
+          { fieldId: 'axles', label: 'Axles', issue: 'number' },
+          { fieldId: 'bay', label: 'Bay', issue: 'option' },
+        ],
+      },
+    })
+    const run = await mount()
+
+    expect(await run()).toEqual({ valid: false, problem: 'invalid', fields: ['Axles', 'Bay'] })
+    expect(field('axles')).toHaveTextContent('Axles must be a number')
+    expect(field('bay')).toHaveTextContent('Bay must be one of its options')
+    expect(field('po')).not.toHaveTextContent('PO number is required')
+    expect(field('axles').querySelector('input')).toHaveAttribute('aria-invalid', 'true')
+  })
+
+  it('says "required" when that is all the server found', async () => {
+    save.mockResolvedValue({
+      success: true,
+      data: {
+        saved: false,
+        fieldErrors: [{ fieldId: 'po', label: 'PO number', issue: 'required' }],
+      },
+    })
+    const run = await mount()
+
+    expect(await run()).toEqual({ valid: false, problem: 'required', fields: ['PO number'] })
+    expect(field('po')).toHaveTextContent('PO number is required')
+  })
+
+  it('clears a field’s message as soon as it is edited', async () => {
+    save.mockResolvedValue({
+      success: true,
+      data: { saved: false, fieldErrors: [{ fieldId: 'axles', label: 'Axles', issue: 'number' }] },
+    })
+    const run = await mount()
+    await run()
+    expect(field('axles')).toHaveTextContent('Axles must be a number')
+
+    fireEvent.change(field('axles').querySelector('input') as HTMLInputElement, {
+      target: { value: '3' },
+    })
+
+    expect(field('axles')).not.toHaveTextContent('Axles must be a number')
+  })
+
+  it('hands the page the server’s own words when the document is locked', async () => {
+    save.mockResolvedValue({
+      success: false,
+      error: 'This document is locked because it has been sent.',
+    })
+    const run = await mount()
+
+    expect(await run()).toEqual({
+      valid: false,
+      error: 'This document is locked because it has been sent.',
+    })
+  })
+
+  it('draws a field made required while the form was open, and marks it', async () => {
+    const run = await mount()
+    fireEvent.change(field('axles').querySelector('input') as HTMLInputElement, {
+      target: { value: '4' },
+    })
+    // The workshop added "Order ref" and made it required since the page loaded.
+    load.mockResolvedValue({
+      success: true,
+      data: [
+        ...FIELDS,
+        {
+          id: 'ref',
+          name: 'ref',
+          label: 'Order ref',
+          fieldType: 'text',
+          options: null,
+          required: true,
+          value: '',
+        },
+      ],
+    })
+    save.mockResolvedValue({
+      success: true,
+      data: {
+        saved: false,
+        fieldErrors: [{ fieldId: 'ref', label: 'Order ref', issue: 'required' }],
+      },
+    })
+
+    expect(await run()).toEqual({ valid: false, problem: 'required', fields: ['Order ref'] })
+    expect(field('ref')).toHaveTextContent('Order ref is required')
+    // What was typed is kept.
+    expect(field('axles').querySelector('input')).toHaveValue(4)
+  })
+
+  it('stops an empty required field before anything is sent', async () => {
+    const run = await mount()
+    fireEvent.change(field('po').querySelector('input') as HTMLInputElement, {
+      target: { value: '  ' },
+    })
+
+    expect(await run()).toEqual({ valid: false, problem: 'required', fields: ['PO number'] })
+    expect(save).not.toHaveBeenCalled()
+    expect(field('po')).toHaveTextContent('PO number is required')
+  })
+})

+ 3 - 3
src/__tests__/features/custom-fields/form-strings.test.tsx

@@ -30,7 +30,7 @@ vi.mock('@/features/custom-fields/Actions/customFieldActions', () => ({
     ],
   })),
   getFieldDefinitions: vi.fn(async () => ({ success: true, data: [] })),
-  saveCustomFieldValues: vi.fn(async () => ({ success: true })),
+  saveValidatedCustomFieldValues: vi.fn(async () => ({ success: true, data: { saved: true } })),
 }))
 
 import { CustomFieldsForm } from '@/features/custom-fields/Components/CustomFieldsForm'
@@ -55,11 +55,11 @@ describe('the custom fields card', () => {
     )
     expect(await screen.findByText('Custom Fields')).toBeInTheDocument()
 
-    let result: { valid: boolean } | undefined
+    let result: unknown
     await act(async () => {
       result = await save?.()
     })
-    expect(result).toEqual({ valid: false })
+    expect(result).toEqual({ valid: false, problem: 'required', fields: ['Key number'] })
     expect(screen.getByText('Key number is required')).toBeInTheDocument()
     // A checkbox left unticked is an answer, never a missing one.
     expect(screen.queryByText('Courtesy car is required')).not.toBeInTheDocument()

+ 291 - 0
src/__tests__/features/custom-fields/missing-required-field.test.tsx

@@ -0,0 +1,291 @@
+/**
+ * A required custom field left empty: the person is shown which one, by the
+ * name the workshop gave it.
+ *
+ * Under the field, its own message. On the field, the invalid mark, tied to
+ * that message for a screen reader. On a save they asked for, the focus goes
+ * to the first field that is missing and it is scrolled into view. And the
+ * page is handed the names, so its toast can say "Fill in: Fleet contact,
+ * Cost centre" rather than that something, somewhere, is wrong.
+ */
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const save = vi.hoisted(() => vi.fn())
+const load = vi.hoisted(() => vi.fn())
+vi.mock('@/features/custom-fields/Actions/customFieldActions', () => ({
+  getCustomFieldValues: load,
+  getFieldDefinitions: vi.fn(async () => ({ success: true, data: [] })),
+  saveValidatedCustomFieldValues: save,
+}))
+
+import {
+  CustomFieldsForm,
+  type CustomFieldsSave,
+  type CustomFieldsSaveOutcome,
+} from '@/features/custom-fields/Components/CustomFieldsForm'
+
+const base = { options: null as string | null, required: false, value: '' }
+const FIELDS = [
+  { ...base, id: 'colour', name: 'colour', label: 'Colour', fieldType: 'text' },
+  {
+    ...base,
+    id: 'contact',
+    name: 'contact',
+    label: 'Fleet contact',
+    fieldType: 'text',
+    required: true,
+  },
+  { ...base, id: 'due', name: 'due', label: 'Next test due', fieldType: 'date', required: true },
+  {
+    ...base,
+    id: 'centre',
+    name: 'centre',
+    label: 'Cost centre',
+    fieldType: 'select',
+    options: 'North, South',
+    required: true,
+  },
+  {
+    ...base,
+    id: 'loan',
+    name: 'loan',
+    label: 'Courtesy car',
+    fieldType: 'checkbox',
+    required: true,
+  },
+]
+
+async function mount(entityType: 'service_record' | 'quote' = 'service_record', locked = false) {
+  let run: CustomFieldsSave | undefined
+  render(
+    <CustomFieldsForm
+      entityId="rec-1"
+      entityType={entityType}
+      locked={locked}
+      onValuesReady={(fn) => {
+        run = fn
+      }}
+    />
+  )
+  await screen.findByText('Custom Fields')
+  return async (options?: { reveal?: boolean }) => {
+    let outcome: CustomFieldsSaveOutcome | undefined
+    await act(async () => {
+      outcome = await run?.(options)
+    })
+    return outcome
+  }
+}
+
+const wrapper = (id: string) => screen.getByTestId(`custom-field-${id}`)
+const control = (id: string) =>
+  wrapper(id).querySelector(
+    'input:not([type="hidden"]), textarea, button[role="combobox"]'
+  ) as HTMLElement
+const type = (id: string, value: string) => fireEvent.change(control(id), { target: { value } })
+
+const scrolled = vi.fn()
+
+beforeEach(() => {
+  save.mockReset().mockResolvedValue({ success: true, data: { saved: true } })
+  load.mockReset().mockResolvedValue({ success: true, data: FIELDS })
+  scrolled.mockReset()
+  // The dropdown measures itself; jsdom has nothing to measure with.
+  const nothing = () => undefined
+  globalThis.ResizeObserver = class {
+    observe = nothing
+    unobserve = nothing
+    disconnect = nothing
+  }
+  // jsdom draws nothing, so it has no scrolling of its own to watch.
+  Element.prototype.scrollIntoView = function scrollIntoView(this: Element) {
+    scrolled(this.textContent)
+  }
+})
+
+describe.each(['service_record', 'quote'] as const)('saving a %s', (entityType) => {
+  it('with one required field empty: names it under the field and takes the person there', async () => {
+    const run = await mount(entityType)
+    type('due', '25/03/2027')
+    fireEvent.blur(control('due'))
+    fireEvent.click(control('centre'))
+    fireEvent.click(await screen.findByRole('option', { name: 'North' }))
+
+    const outcome = await run()
+
+    expect(outcome).toEqual({ valid: false, problem: 'required', fields: ['Fleet contact'] })
+    expect(save).not.toHaveBeenCalled()
+    // Its own message, under its own field, and nowhere else.
+    expect(screen.getAllByRole('alert')).toHaveLength(1)
+    expect(wrapper('contact')).toHaveTextContent('Fleet contact is required')
+    // Marked invalid, and the mark points at the message.
+    const input = control('contact')
+    const message = screen.getByText('Fleet contact is required')
+    expect(input).toHaveAttribute('aria-invalid', 'true')
+    expect(input).toHaveAttribute('aria-describedby', message.id)
+    // Focus on the field, and the message brought into view.
+    expect(input).toHaveFocus()
+    expect(scrolled).toHaveBeenLastCalledWith('Fleet contact is required')
+  })
+
+  it('with two required fields empty: names both, and goes to the first', async () => {
+    const run = await mount(entityType)
+    type('due', '25/03/2027')
+    fireEvent.blur(control('due'))
+
+    const outcome = await run()
+
+    expect(outcome).toEqual({
+      valid: false,
+      problem: 'required',
+      fields: ['Fleet contact', 'Cost centre'],
+    })
+    expect(wrapper('contact')).toHaveTextContent('Fleet contact is required')
+    expect(wrapper('centre')).toHaveTextContent('Cost centre is required')
+    expect(screen.getAllByRole('alert')).toHaveLength(2)
+    // A dropdown is marked and tied to its message like any other field.
+    const dropdown = control('centre')
+    expect(dropdown).toHaveAttribute('aria-invalid', 'true')
+    expect(dropdown).toHaveAttribute(
+      'aria-describedby',
+      screen.getByText('Cost centre is required').id
+    )
+    expect(control('contact')).toHaveFocus()
+  })
+
+  it('with every required field filled: saves, with nothing marked', async () => {
+    const run = await mount(entityType)
+    type('contact', 'Dana')
+    type('due', '25/03/2027')
+    fireEvent.blur(control('due'))
+    fireEvent.click(control('centre'))
+    fireEvent.click(await screen.findByRole('option', { name: 'South' }))
+
+    expect(await run()).toEqual({ valid: true })
+
+    expect(save).toHaveBeenCalledWith('rec-1', entityType, {
+      colour: '',
+      contact: 'Dana',
+      due: '2027-03-25',
+      centre: 'South',
+      loan: '',
+    })
+    expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+    expect(control('contact')).not.toHaveAttribute('aria-invalid')
+  })
+})
+
+describe('the details', () => {
+  it('a date field is marked and tied to its message too', async () => {
+    const run = await mount()
+    type('contact', 'Dana')
+
+    await run()
+
+    const date = control('due')
+    expect(date).toHaveAttribute('aria-invalid', 'true')
+    expect(date).toHaveAttribute(
+      'aria-describedby',
+      screen.getByText('Next test due is required').id
+    )
+    expect(date).toHaveFocus()
+  })
+
+  it('each label belongs to its field, so a screen reader names what it lands on', async () => {
+    await mount()
+    expect(screen.getByLabelText(/Fleet contact/)).toBe(control('contact'))
+    expect(screen.getByLabelText(/Next test due/)).toBe(control('due'))
+  })
+
+  it('an autosave marks the field but leaves the person where they are typing', async () => {
+    const run = await mount()
+    const elsewhere = document.createElement('input')
+    document.body.appendChild(elsewhere)
+    elsewhere.focus()
+
+    const outcome = await run({ reveal: false })
+
+    expect(outcome).toMatchObject({
+      valid: false,
+      fields: ['Fleet contact', 'Next test due', 'Cost centre'],
+    })
+    expect(wrapper('contact')).toHaveTextContent('Fleet contact is required')
+    expect(elsewhere).toHaveFocus()
+    expect(scrolled).not.toHaveBeenCalled()
+    elsewhere.remove()
+  })
+
+  it('pressing Save again with nothing fixed takes them to the field again', async () => {
+    const run = await mount()
+    await run()
+    expect(control('contact')).toHaveFocus()
+    act(() => control('colour').focus())
+    scrolled.mockReset()
+
+    await run()
+
+    expect(control('contact')).toHaveFocus()
+    expect(scrolled).toHaveBeenCalledTimes(1)
+  })
+
+  it('the message goes as soon as the field is filled in, and the next one is next', async () => {
+    const run = await mount()
+    await run()
+    type('contact', 'Dana')
+    expect(wrapper('contact')).not.toHaveTextContent('is required')
+    expect(control('contact')).not.toHaveAttribute('aria-invalid')
+
+    const outcome = await run()
+
+    expect(outcome).toMatchObject({ fields: ['Next test due', 'Cost centre'] })
+    expect(control('due')).toHaveFocus()
+  })
+
+  it('a field the server says is missing is named the same way', async () => {
+    load.mockResolvedValue({
+      success: true,
+      data: FIELDS.map((f) => ({ ...f, required: false })),
+    })
+    save.mockResolvedValue({
+      success: true,
+      data: {
+        saved: false,
+        fieldErrors: [
+          { fieldId: 'contact', label: 'Fleet contact', issue: 'required' },
+          { fieldId: 'centre', label: 'Cost centre', issue: 'required' },
+        ],
+      },
+    })
+    const run = await mount()
+
+    const outcome = await run()
+
+    expect(outcome).toEqual({
+      valid: false,
+      problem: 'required',
+      fields: ['Fleet contact', 'Cost centre'],
+    })
+    expect(wrapper('contact')).toHaveTextContent('Fleet contact is required')
+    expect(wrapper('centre')).toHaveTextContent('Cost centre is required')
+    expect(control('contact')).toHaveFocus()
+  })
+
+  it('on a locked document the fields are no step of the save: nothing is asked for or sent', async () => {
+    // Read-only on the page, so an empty required field cannot be filled in
+    // and must not stop the page saving what it still can.
+    const run = await mount('service_record', true)
+
+    expect(await run()).toEqual({ valid: true })
+
+    expect(save).not.toHaveBeenCalled()
+    expect(screen.queryByRole('alert')).not.toBeInTheDocument()
+    expect(scrolled).not.toHaveBeenCalled()
+  })
+
+  it('a required checkbox left unticked is never called missing', async () => {
+    const run = await mount()
+    const outcome = await run()
+    expect(outcome).toMatchObject({ fields: expect.not.arrayContaining(['Courtesy car']) })
+  })
+})

+ 290 - 0
src/__tests__/features/custom-fields/missing-required-page-save.test.tsx

@@ -0,0 +1,290 @@
+/**
+ * What the page does when its save is stopped by a required custom field.
+ *
+ * The custom fields are saved first, as part of the page's own save: the Save
+ * button, the autosave five seconds after an edit, and the save a link waits
+ * for all go through it. When a required field is empty, nothing of the work
+ * order or quote is saved, and the person is told so with the fields named:
+ * in a toast for a save or an autosave, in the leave dialog when a link was
+ * waiting. Nothing is dropped quietly: the page stays marked unsaved.
+ */
+import { act, cleanup, fireEvent, render, renderHook, screen } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const toastError = vi.fn()
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }),
+  usePathname: () => '/quotes/quote-1',
+}))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: (m: string) => toastError(m) } }))
+vi.mock('@/components/confirm-dialog', async (importOriginal) => ({
+  ...(await importOriginal<typeof import('@/components/confirm-dialog')>()),
+  useConfirm: () => vi.fn(async () => true),
+}))
+const updateQuote = vi.fn()
+vi.mock('@/features/quotes/Actions/quoteActions', () => ({
+  updateQuote: (input: unknown) => updateQuote(input),
+  deleteQuote: vi.fn(),
+  convertQuoteToServiceRecord: vi.fn(),
+}))
+vi.mock('@/features/quotes/Actions/quoteResponseActions', () => ({
+  acknowledgeQuoteResponse: vi.fn(),
+}))
+const updateServiceRecord = vi.fn()
+vi.mock('@/features/vehicles/Actions/serviceActions', () => ({
+  updateServiceRecord: (input: unknown) => updateServiceRecord(input),
+  deleteServiceRecord: vi.fn(),
+  deleteServiceAttachment: vi.fn(),
+  toggleManuallyPaid: vi.fn(),
+}))
+vi.mock('@/features/payments/Actions/paymentActions', () => ({
+  createPayment: vi.fn(),
+  deletePayment: vi.fn(),
+}))
+vi.mock('@/features/sms/Actions/smsActions', () => ({ getSmsTemplates: vi.fn() }))
+
+import type { CustomFieldsSave } from '@/features/custom-fields/Components/CustomFieldsForm'
+import { useQuoteFormState } from '@/features/quotes/Components/useQuoteFormState'
+import { LeaveUnsavedDialog } from '@/features/vehicles/Components/service-page/LeaveUnsavedDialog'
+import { useServiceActions } from '@/features/vehicles/Components/service-page/useServiceActions'
+import quotesEn from '../../../../messages/en/quotes.json'
+import serviceEn from '../../../../messages/en/service.json'
+
+const ONE = { valid: false as const, problem: 'required' as const, fields: ['Fleet contact'] }
+const TWO = {
+  valid: false as const,
+  problem: 'required' as const,
+  fields: ['Fleet contact', 'Cost centre'],
+}
+
+afterEach(() => {
+  vi.useRealTimers()
+  cleanup()
+  document.body.innerHTML = ''
+})
+
+beforeEach(() => {
+  toastError.mockClear()
+  updateQuote.mockReset().mockResolvedValue({ success: true })
+  updateServiceRecord.mockReset().mockResolvedValue({ success: true })
+})
+
+describe('the words', () => {
+  it('say nothing was saved and leave room for the field names', () => {
+    for (const page of [serviceEn.page, quotesEn.page]) {
+      expect(page.customFieldsMissing).toBe('Not saved. Fill in: {fields}')
+      expect(page.customFieldsNotValid).toBe('Not saved. Check: {fields}')
+    }
+  })
+})
+
+describe('a work order', () => {
+  type Options = Parameters<typeof useServiceActions>[0]
+
+  function page(customFieldsSave: CustomFieldsSave) {
+    // What a save reads before it gets to the work order itself.
+    const form = {
+      isSavingRef: { current: false },
+      autosaveTimer: { current: null },
+      autosaveRunRef: { current: false },
+      leavingRef: { current: false },
+      lastSaveErrorRef: { current: null as string | null },
+      editRevisionRef: { current: 0 },
+      customFieldsSaveRef: { current: customFieldsSave },
+      setHasUnsavedChanges: vi.fn(),
+    }
+    const hook = renderHook(() =>
+      useServiceActions({
+        record: { id: 'job1' } as unknown as Options['record'],
+        vehicleId: 'v1',
+        currencyCode: 'GBP',
+        formState: form as unknown as Options['formState'],
+      })
+    )
+    const save = () =>
+      act(() =>
+        hook.result.current.handleSubmit({
+          preventDefault: () => undefined,
+          currentTarget: document.createElement('form'),
+        } as unknown as React.FormEvent<HTMLFormElement>)
+      )
+    return { form, save }
+  }
+
+  it('one required field empty: the toast names it, and nothing of the work order is saved', async () => {
+    const customFields = vi.fn(async () => ONE)
+    const { form, save } = page(customFields)
+
+    await save()
+
+    expect(toastError).toHaveBeenCalledWith('Not saved. Fill in: Fleet contact')
+    expect(updateServiceRecord).not.toHaveBeenCalled()
+    // Saving is free again, and the page was not marked saved.
+    expect(form.isSavingRef.current).toBe(false)
+    expect(form.setHasUnsavedChanges).not.toHaveBeenCalled()
+    // The person asked for this save, so they are taken to the field.
+    expect(customFields).toHaveBeenCalledWith({ reveal: true })
+  })
+
+  it('two required fields empty: the toast names both', async () => {
+    const { save } = page(vi.fn(async () => TWO))
+
+    await save()
+
+    expect(toastError).toHaveBeenCalledWith('Not saved. Fill in: Fleet contact, Cost centre')
+    expect(updateServiceRecord).not.toHaveBeenCalled()
+  })
+
+  it('a value that does not fit is named too, in its own words', async () => {
+    const { save } = page(
+      vi.fn(async () => ({ valid: false as const, problem: 'invalid' as const, fields: ['Axles'] }))
+    )
+
+    await save()
+
+    expect(toastError).toHaveBeenCalledWith('Not saved. Check: Axles')
+  })
+
+  it('an autosave says the same, without taking the person away from what they are typing', async () => {
+    const customFields = vi.fn(async () => TWO)
+    const { form, save } = page(customFields)
+    form.autosaveRunRef.current = true
+
+    await save()
+
+    expect(customFields).toHaveBeenCalledWith({ reveal: false })
+    expect(toastError).toHaveBeenCalledWith('Not saved. Fill in: Fleet contact, Cost centre')
+    // Spent: the next save, one they ask for, takes them to the field.
+    expect(form.autosaveRunRef.current).toBe(false)
+  })
+
+  it('a link waiting on the save gets the names for its dialog, not a toast on top of it', async () => {
+    const { form, save } = page(vi.fn(async () => TWO))
+    form.leavingRef.current = true
+
+    await save()
+
+    expect(form.lastSaveErrorRef.current).toBe('Not saved. Fill in: Fleet contact, Cost centre')
+    expect(toastError).not.toHaveBeenCalled()
+    expect(updateServiceRecord).not.toHaveBeenCalled()
+  })
+})
+
+describe('a quote', () => {
+  const quote = {
+    id: 'quote-1',
+    status: 'draft',
+    customer: null,
+    vehicle: null,
+    partItems: [],
+    laborItems: [],
+    taxRate: 0,
+    taxInclusive: false,
+    discountType: 'none',
+    discountValue: 0,
+    description: '',
+    notes: '',
+    validUntil: null,
+  } as never
+
+  /** The quote page as far as saving goes, with the real English for its messages. */
+  function QuotePage({ customFieldsSave }: { customFieldsSave: CustomFieldsSave }) {
+    const state = useQuoteFormState({
+      quote,
+      currencyCode: 'GBP',
+      defaultTaxRate: 0,
+      taxEnabled: true,
+      defaultLaborRate: 0,
+      locked: false,
+      t: ((key: string, values?: Record<string, string>) => {
+        const text =
+          (quotesEn.page as unknown as Record<string, string>)[key.replace('page.', '')] ?? key
+        return text.replace('{fields}', values?.fields ?? '')
+      }) as never,
+    })
+    state.onCustomFieldsReady(customFieldsSave)
+    return (
+      <>
+        <a href="/customers">Customers</a>
+        <form ref={state.formRef} onSubmit={state.handleSubmit} aria-label="Quote">
+          <input name="title" aria-label="Title" defaultValue="Brakes" onChange={state.markDirty} />
+          <button type="submit">Save</button>
+        </form>
+        <LeaveUnsavedDialog
+          open={state.blockedLeave !== null}
+          reason={state.blockedLeave?.reason ?? null}
+          onStay={state.stayOnPage}
+          onLeave={state.leaveWithoutSaving}
+        />
+      </>
+    )
+  }
+
+  const pressSave = () =>
+    act(async () => fireEvent.submit(screen.getByRole('form', { name: 'Quote' })))
+
+  it('one required field empty: the toast names it, and nothing of the quote is saved', async () => {
+    const customFields = vi.fn(async () => ONE)
+    render(<QuotePage customFieldsSave={customFields} />)
+
+    await pressSave()
+
+    expect(toastError).toHaveBeenCalledWith('Not saved. Fill in: Fleet contact')
+    expect(updateQuote).not.toHaveBeenCalled()
+    expect(customFields).toHaveBeenCalledWith({ reveal: true })
+  })
+
+  it('two required fields empty: the toast names both', async () => {
+    render(<QuotePage customFieldsSave={vi.fn(async () => TWO)} />)
+
+    await pressSave()
+
+    expect(toastError).toHaveBeenCalledWith('Not saved. Fill in: Fleet contact, Cost centre')
+    expect(updateQuote).not.toHaveBeenCalled()
+  })
+
+  it('all filled in: the quote is saved and nothing is said', async () => {
+    render(<QuotePage customFieldsSave={vi.fn(async () => ({ valid: true as const }))} />)
+
+    await pressSave()
+
+    expect(updateQuote).toHaveBeenCalledTimes(1)
+    expect(toastError).not.toHaveBeenCalled()
+  })
+
+  it('the autosave says it too, and leaves the focus where the person is typing', async () => {
+    vi.useFakeTimers()
+    const customFields = vi.fn(async () => TWO)
+    render(<QuotePage customFieldsSave={customFields} />)
+
+    fireEvent.change(screen.getByLabelText('Title'), { target: { value: 'Brakes, rear' } })
+    await act(async () => {
+      await vi.advanceTimersByTimeAsync(5100)
+    })
+
+    expect(customFields).toHaveBeenCalledWith({ reveal: false })
+    expect(toastError).toHaveBeenCalledWith('Not saved. Fill in: Fleet contact, Cost centre')
+    expect(updateQuote).not.toHaveBeenCalled()
+  })
+
+  it('leaving by a link is held, and the dialog names the fields', async () => {
+    vi.useFakeTimers()
+    render(<QuotePage customFieldsSave={vi.fn(async () => TWO)} />)
+    const link = screen.getByRole('link', { name: 'Customers' })
+    const followed = vi.fn((event: Event) => event.preventDefault())
+    link.addEventListener('click', followed)
+
+    fireEvent.change(screen.getByLabelText('Title'), { target: { value: 'Brakes, rear' } })
+    fireEvent.click(link)
+    await act(async () => {
+      await vi.advanceTimersByTimeAsync(400)
+    })
+
+    expect(followed).not.toHaveBeenCalled()
+    expect(screen.getByRole('alertdialog')).toHaveTextContent(
+      'Not saved. Fill in: Fleet contact, Cost centre'
+    )
+    expect(toastError).not.toHaveBeenCalled()
+    expect(updateQuote).not.toHaveBeenCalled()
+  })
+})

+ 18 - 6
src/__tests__/features/custom-fields/record-permissions.test.ts

@@ -34,12 +34,16 @@ vi.mock('@/lib/with-auth', () => ({
   },
 }))
 vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
+vi.mock('@/lib/document-lock.server', () => ({
+  assertInvoiceEditable: vi.fn(),
+  assertQuoteEditable: vi.fn(),
+}))
 vi.mock('@/lib/features', () => ({ requireFeature: vi.fn() }))
 
 import {
   getCustomFieldValues,
   getFieldDefinitions,
-  saveCustomFieldValues,
+  saveValidatedCustomFieldValues,
 } from '@/features/custom-fields/Actions/customFieldActions'
 import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 
@@ -47,7 +51,11 @@ const needed = () => seenOptions.at(-1)?.requiredPermissions
 
 beforeEach(() => {
   seenOptions.length = 0
-  db.customFieldDefinition.findMany.mockReset().mockResolvedValue([{ id: 'f-1', defaultValue: '' }])
+  db.customFieldDefinition.findMany
+    .mockReset()
+    .mockResolvedValue([
+      { id: 'f-1', fieldType: 'text', options: null, required: false, defaultValue: '' },
+    ])
   db.customFieldValue.findMany.mockReset().mockResolvedValue([])
   db.customFieldValue.upsert.mockReset().mockReturnValue('upsert')
   db.serviceRecord.count.mockReset().mockResolvedValue(1)
@@ -86,7 +94,9 @@ describe("reading a record's custom fields", () => {
 
 describe('filling them in', () => {
   it('needs what saving the work order needs', async () => {
-    const result = await saveCustomFieldValues('job-1', 'service_record', { 'f-1': 'Blue' })
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {
+      'f-1': 'Blue',
+    })
     expect(result.success).toBe(true)
     expect(needed()).toEqual([
       { action: PermissionAction.UPDATE, subject: PermissionSubject.SERVICES },
@@ -95,7 +105,7 @@ describe('filling them in', () => {
   })
 
   it('needs what saving the quote needs', async () => {
-    await saveCustomFieldValues('q-1', 'quote', { 'f-1': 'Blue' })
+    await saveValidatedCustomFieldValues('q-1', 'quote', { 'f-1': 'Blue' })
     expect(needed()).toEqual([
       { action: PermissionAction.UPDATE, subject: PermissionSubject.QUOTES },
     ])
@@ -118,7 +128,9 @@ describe("a record that is not this workshop's", () => {
   it('cannot have values attached to it', async () => {
     db.quote.count.mockResolvedValue(0)
 
-    const result = await saveCustomFieldValues('somebody-elses-quote', 'quote', { 'f-1': 'x' })
+    const result = await saveValidatedCustomFieldValues('somebody-elses-quote', 'quote', {
+      'f-1': 'x',
+    })
 
     expect(result).toEqual({ success: false, error: 'Record not found' })
     expect(db.customFieldValue.upsert).not.toHaveBeenCalled()
@@ -134,7 +146,7 @@ describe('a kind of record nobody defined', () => {
     ])
     expect(read).toEqual({ success: false, error: 'Unknown record type' })
 
-    const saved = await saveCustomFieldValues('x', 'customer', { 'f-1': 'x' })
+    const saved = await saveValidatedCustomFieldValues('x', 'customer', { 'f-1': 'x' })
     expect(needed()).toEqual([
       { action: PermissionAction.UPDATE, subject: PermissionSubject.SETTINGS },
     ])

+ 527 - 0
src/__tests__/features/custom-fields/save-validated-values.test.ts

@@ -0,0 +1,527 @@
+/**
+ * @vitest-environment node
+ *
+ * The server checks a record's custom field values itself. It used to write
+ * whatever the browser sent: text in a number field, a choice that is not an
+ * option, nothing in a required field, and all of it on a locked invoice.
+ */
+import { readdirSync, readFileSync, statSync } from 'node:fs'
+import { join } from 'node:path'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const db = vi.hoisted(() => ({
+  customFieldDefinition: { findMany: vi.fn() },
+  customFieldValue: { findMany: vi.fn(), upsert: vi.fn() },
+  serviceRecord: { count: vi.fn() },
+  quote: { count: vi.fn() },
+  $transaction: vi.fn(),
+}))
+vi.mock('@/lib/db', () => ({ db }))
+
+vi.mock('@/lib/with-auth', () => ({
+  withAuth: async (action: (ctx: { userId: string; organizationId: string }) => unknown) => {
+    try {
+      return { success: true, data: await action({ userId: 'u-1', organizationId: 'org-1' }) }
+    } catch (error) {
+      return { success: false, error: (error as Error).message }
+    }
+  },
+}))
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
+vi.mock('@/lib/features', () => ({ requireFeature: vi.fn() }))
+
+const lock = vi.hoisted(() => ({
+  assertInvoiceEditable: vi.fn(),
+  assertQuoteEditable: vi.fn(),
+}))
+vi.mock('@/lib/document-lock.server', () => lock)
+
+import * as actions from '@/features/custom-fields/Actions/customFieldActions'
+import { DocumentLockedError } from '@/lib/document-lock'
+
+const { saveValidatedCustomFieldValues } = actions
+
+const FIELDS = [
+  { id: 'po', label: 'PO number', fieldType: 'text', options: null, required: true },
+  { id: 'axles', label: 'Axles', fieldType: 'number', options: null, required: false },
+  { id: 'due', label: 'Next test due', fieldType: 'date', options: null, required: false },
+  { id: 'bay', label: 'Bay', fieldType: 'select', options: 'Bay 1, Bay 2', required: false },
+  { id: 'loan', label: 'Courtesy car', fieldType: 'checkbox', options: null, required: true },
+  { id: 'note', label: 'Handover notes', fieldType: 'textarea', options: null, required: false },
+]
+
+/**
+ * What the server answers for these faults: each refused field with the
+ * workshop's label for it, in the order the form shows the fields.
+ */
+const refusals = (faults: Record<string, string>) =>
+  FIELDS.filter((field) => field.id in faults).map((field) => ({
+    fieldId: field.id,
+    label: field.label,
+    issue: faults[field.id],
+  }))
+
+const VALID = {
+  po: 'PO 4471',
+  axles: '3',
+  due: '2026-03-10',
+  bay: 'Bay 2',
+  loan: 'true',
+  note: 'Call before\ncollection',
+}
+
+/** What was written, as field id to value. */
+const written = () =>
+  Object.fromEntries(
+    db.customFieldValue.upsert.mock.calls.map(([args]) => [args.create.fieldId, args.create.value])
+  )
+
+beforeEach(() => {
+  db.customFieldDefinition.findMany.mockReset().mockResolvedValue(FIELDS)
+  db.customFieldValue.findMany.mockReset().mockResolvedValue([])
+  db.customFieldValue.upsert.mockReset().mockReturnValue('upsert')
+  db.serviceRecord.count.mockReset().mockResolvedValue(1)
+  db.quote.count.mockReset().mockResolvedValue(1)
+  db.$transaction.mockReset().mockResolvedValue([])
+  lock.assertInvoiceEditable.mockReset().mockResolvedValue(undefined)
+  lock.assertQuoteEditable.mockReset().mockResolvedValue(undefined)
+})
+
+describe('values that suit their fields', () => {
+  it('are saved exactly as sent, one row per field, in one transaction', async () => {
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', VALID)
+
+    expect(result).toEqual({ success: true, data: { saved: true } })
+    expect(written()).toEqual(VALID)
+    expect(db.$transaction).toHaveBeenCalledTimes(1)
+    expect(db.customFieldValue.upsert).toHaveBeenCalledWith({
+      where: { fieldId_entityId: { fieldId: 'bay', entityId: 'job-1' } },
+      create: { fieldId: 'bay', entityId: 'job-1', entityType: 'service_record', value: 'Bay 2' },
+      update: { value: 'Bay 2' },
+    })
+  })
+
+  it('may be empty where the field is not required', async () => {
+    const result = await saveValidatedCustomFieldValues('q-1', 'quote', {
+      ...VALID,
+      axles: '',
+      due: '',
+      bay: '',
+      note: '',
+    })
+
+    expect(result).toEqual({ success: true, data: { saved: true } })
+    expect(written()).toMatchObject({ axles: '', due: '', bay: '', note: '' })
+  })
+
+  it('reads only this workshop’s active fields for that kind of record', async () => {
+    await saveValidatedCustomFieldValues('q-1', 'quote', VALID)
+
+    expect(db.customFieldDefinition.findMany).toHaveBeenCalledWith({
+      where: { organizationId: 'org-1', entityType: 'quote', isActive: true },
+      orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }],
+    })
+  })
+
+  it('skips a field that is unknown or switched off, and saves the rest', async () => {
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {
+      ...VALID,
+      'switched-off': 'anything',
+    })
+
+    expect(result).toEqual({ success: true, data: { saved: true } })
+    expect(written()).toEqual(VALID)
+  })
+})
+
+describe('a value that does not suit its field', () => {
+  it.each([
+    ['text in a number field', { axles: 'three' }, { axles: 'number' }],
+    ['a date that is not a calendar day', { due: '31/02/2026' }, { due: 'date' }],
+    ['a choice that is not one of the options', { bay: 'Bay 9' }, { bay: 'option' }],
+    ['a checkbox that is neither ticked nor unticked', { loan: 'maybe' }, { loan: 'checkbox' }],
+    ['a text the length of a book', { note: 'x'.repeat(10001) }, { note: 'tooLong' }],
+  ])('refuses %s and names the field', async (_what, bad, fieldErrors) => {
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {
+      ...VALID,
+      ...bad,
+    })
+
+    expect(result).toEqual({
+      success: true,
+      data: { saved: false, fieldErrors: refusals(fieldErrors) },
+    })
+  })
+
+  it('writes none of the values, the good ones included', async () => {
+    await saveValidatedCustomFieldValues('job-1', 'service_record', { ...VALID, axles: 'three' })
+
+    expect(db.customFieldValue.upsert).not.toHaveBeenCalled()
+    expect(db.$transaction).not.toHaveBeenCalled()
+  })
+
+  it('names every field at fault at once', async () => {
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {
+      ...VALID,
+      po: '',
+      axles: 'three',
+      bay: 'Bay 9',
+    })
+
+    expect(result.data).toEqual({
+      saved: false,
+      fieldErrors: refusals({ po: 'required', axles: 'number', bay: 'option' }),
+    })
+  })
+
+  it('refuses a value that is not text at all', async () => {
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {
+      ...VALID,
+      axles: 3 as unknown as string,
+    })
+
+    expect(result.success).toBe(false)
+    expect(db.customFieldValue.upsert).not.toHaveBeenCalled()
+  })
+})
+
+describe('a required field', () => {
+  it('refuses an empty value, and one of only spaces', async () => {
+    for (const po of ['', '   ']) {
+      const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {
+        ...VALID,
+        po,
+      })
+      expect(result.data).toEqual({ saved: false, fieldErrors: refusals({ po: 'required' }) })
+    }
+    expect(db.customFieldValue.upsert).not.toHaveBeenCalled()
+  })
+
+  it('refuses it on a record that already holds it empty, as the form always has', async () => {
+    db.customFieldValue.findMany.mockResolvedValue([{ fieldId: 'po', value: '' }])
+
+    const result = await saveValidatedCustomFieldValues('old-job', 'service_record', {
+      ...VALID,
+      po: '',
+    })
+
+    expect(result.data).toEqual({ saved: false, fieldErrors: refusals({ po: 'required' }) })
+  })
+
+  it('takes an unticked checkbox: that is an answer', async () => {
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {
+      ...VALID,
+      loan: 'false',
+    })
+
+    expect(result.data).toEqual({ saved: true })
+  })
+
+  it('cannot be got around by leaving it out of the request', async () => {
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', { axles: '2' })
+
+    expect(result.data).toEqual({ saved: false, fieldErrors: refusals({ po: 'required' }) })
+    expect(db.customFieldValue.upsert).not.toHaveBeenCalled()
+  })
+
+  it('may be left out when the record already holds a value for it', async () => {
+    db.customFieldValue.findMany.mockResolvedValue([{ fieldId: 'po', value: 'PO 1' }])
+
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', { axles: '2' })
+
+    expect(result.data).toEqual({ saved: true })
+    expect(written()).toEqual({ axles: '2' })
+  })
+
+  it('may be left out when the field has a default the record shows', async () => {
+    db.customFieldDefinition.findMany.mockResolvedValue(
+      FIELDS.map((field) => (field.id === 'po' ? { ...field, defaultValue: 'On account' } : field))
+    )
+
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', { axles: '2' })
+
+    expect(result.data).toEqual({ saved: true })
+    expect(written()).toEqual({ axles: '2' })
+  })
+
+  it('is still asked for when the record holds it empty and the request leaves it out', async () => {
+    db.customFieldValue.findMany.mockResolvedValue([{ fieldId: 'po', value: '' }])
+
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', { axles: '2' })
+
+    expect(result.data).toEqual({ saved: false, fieldErrors: refusals({ po: 'required' }) })
+  })
+
+  it('leaves alone a field that is not required and not sent', async () => {
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {
+      po: 'PO 7',
+      loan: 'true',
+    })
+
+    expect(result.data).toEqual({ saved: true })
+    expect(written()).toEqual({ po: 'PO 7', loan: 'true' })
+  })
+})
+
+describe('what the person is told is missing', () => {
+  const TWO_REQUIRED = [
+    { id: 'contact', label: 'Fleet contact', fieldType: 'text', options: null, required: true },
+    { id: 'colour', label: 'Colour', fieldType: 'text', options: null, required: false },
+    { id: 'centre', label: 'Cost centre', fieldType: 'select', options: 'A, B', required: true },
+  ]
+
+  beforeEach(() => {
+    db.customFieldDefinition.findMany.mockResolvedValue(TWO_REQUIRED)
+  })
+
+  it('names the one empty required field by the workshop\u2019s own label', async () => {
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {
+      contact: '',
+      colour: 'Blue',
+      centre: 'A',
+    })
+
+    expect(result.data).toEqual({
+      saved: false,
+      fieldErrors: [{ fieldId: 'contact', label: 'Fleet contact', issue: 'required' }],
+    })
+    expect(db.customFieldValue.upsert).not.toHaveBeenCalled()
+  })
+
+  it('names both when two are empty, in the order the form shows them', async () => {
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {
+      centre: '',
+      colour: 'Blue',
+      contact: ' ',
+    })
+
+    expect(result.data).toEqual({
+      saved: false,
+      fieldErrors: [
+        { fieldId: 'contact', label: 'Fleet contact', issue: 'required' },
+        { fieldId: 'centre', label: 'Cost centre', issue: 'required' },
+      ],
+    })
+  })
+
+  it('names them to a client that sent neither, so a stale or hand-made request is told too', async () => {
+    const result = await saveValidatedCustomFieldValues('q-1', 'quote', { colour: 'Blue' })
+
+    expect(result.data).toEqual({
+      saved: false,
+      fieldErrors: [
+        { fieldId: 'contact', label: 'Fleet contact', issue: 'required' },
+        { fieldId: 'centre', label: 'Cost centre', issue: 'required' },
+      ],
+    })
+  })
+
+  it('saves once all of them are filled in', async () => {
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {
+      contact: 'Dana',
+      colour: '',
+      centre: 'B',
+    })
+
+    expect(result.data).toEqual({ saved: true })
+    expect(written()).toEqual({ contact: 'Dana', colour: '', centre: 'B' })
+  })
+})
+
+describe('a value the record already holds', () => {
+  it('is left alone even when it would not pass today, so the rest can be saved', async () => {
+    // "Bay 3" was an option when it was chosen; the date came from an import.
+    db.customFieldValue.findMany.mockResolvedValue([
+      { fieldId: 'bay', value: 'Bay 3' },
+      { fieldId: 'due', value: 'March 10, 2026' },
+      { fieldId: 'po', value: 'PO 1' },
+    ])
+
+    const result = await saveValidatedCustomFieldValues('old-job', 'service_record', {
+      ...VALID,
+      bay: 'Bay 3',
+      due: 'March 10, 2026',
+      po: 'PO 2',
+    })
+
+    expect(result.data).toEqual({ saved: true })
+    // Only what changed is written; the old values stay as they are.
+    expect(written()).toEqual({ po: 'PO 2', axles: '3', loan: 'true', note: VALID.note })
+  })
+
+  it('has to pass once it is changed', async () => {
+    db.customFieldValue.findMany.mockResolvedValue([{ fieldId: 'bay', value: 'Bay 3' }])
+
+    const result = await saveValidatedCustomFieldValues('old-job', 'service_record', {
+      ...VALID,
+      bay: 'Bay 4',
+    })
+
+    expect(result.data).toEqual({ saved: false, fieldErrors: refusals({ bay: 'option' }) })
+  })
+
+  it('writes nothing when nothing changed', async () => {
+    db.customFieldValue.findMany.mockResolvedValue(
+      Object.entries(VALID).map(([fieldId, value]) => ({ fieldId, value }))
+    )
+
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', VALID)
+
+    expect(result.data).toEqual({ saved: true })
+    expect(db.customFieldValue.upsert).not.toHaveBeenCalled()
+  })
+})
+
+describe('a locked document', () => {
+  it('refuses values on a locked work order, in the words every other edit gets', async () => {
+    lock.assertInvoiceEditable.mockRejectedValue(new DocumentLockedError('sent'))
+
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', VALID)
+
+    expect(result).toEqual({
+      success: false,
+      error: 'This document is locked because it has been sent.',
+    })
+    expect(lock.assertInvoiceEditable).toHaveBeenCalledWith('job-1', 'org-1')
+    expect(db.customFieldValue.upsert).not.toHaveBeenCalled()
+  })
+
+  it('refuses values on a locked quote', async () => {
+    lock.assertQuoteEditable.mockRejectedValue(new DocumentLockedError('accepted'))
+
+    const result = await saveValidatedCustomFieldValues('q-1', 'quote', VALID)
+
+    expect(result).toEqual({
+      success: false,
+      error: 'This document is locked because it has been accepted.',
+    })
+    expect(lock.assertQuoteEditable).toHaveBeenCalledWith('q-1', 'org-1')
+    expect(lock.assertInvoiceEditable).not.toHaveBeenCalled()
+    expect(db.customFieldValue.upsert).not.toHaveBeenCalled()
+  })
+
+  it('lets a save through that changes no value, so what stays open on the page still saves', async () => {
+    lock.assertInvoiceEditable.mockRejectedValue(new DocumentLockedError('sent'))
+    db.customFieldValue.findMany.mockResolvedValue(
+      Object.entries(VALID).map(([fieldId, value]) => ({ fieldId, value }))
+    )
+
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', VALID)
+
+    expect(result).toEqual({ success: true, data: { saved: true } })
+    expect(db.customFieldValue.upsert).not.toHaveBeenCalled()
+    expect(db.$transaction).not.toHaveBeenCalled()
+  })
+
+  it('does not count a field nobody filled in, sent back as its default, as a change', async () => {
+    lock.assertQuoteEditable.mockRejectedValue(new DocumentLockedError('accepted'))
+    db.customFieldDefinition.findMany.mockResolvedValue(
+      FIELDS.map((field) => (field.id === 'bay' ? { ...field, defaultValue: 'Bay 1' } : field))
+    )
+    db.customFieldValue.findMany.mockResolvedValue([{ fieldId: 'po', value: 'PO 1' }])
+
+    // What the form sends for a record with one stored value: that value,
+    // the default where there is one, and nothing for the rest.
+    const result = await saveValidatedCustomFieldValues('q-1', 'quote', {
+      po: 'PO 1',
+      axles: '',
+      due: '',
+      bay: 'Bay 1',
+      loan: '',
+      note: '',
+    })
+
+    expect(result).toEqual({ success: true, data: { saved: true } })
+    expect(db.customFieldValue.upsert).not.toHaveBeenCalled()
+  })
+
+  it('does not ask a locked record for a required field it was locked without', async () => {
+    lock.assertInvoiceEditable.mockRejectedValue(new DocumentLockedError('paid'))
+
+    // "PO number" became required after this invoice was paid; nothing is stored.
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {
+      po: '',
+      axles: '',
+    })
+
+    expect(result).toEqual({ success: true, data: { saved: true } })
+    expect(db.customFieldValue.upsert).not.toHaveBeenCalled()
+  })
+
+  it('refuses the whole save when one value among unchanged ones is changed', async () => {
+    lock.assertInvoiceEditable.mockRejectedValue(new DocumentLockedError('sent'))
+    db.customFieldValue.findMany.mockResolvedValue(
+      Object.entries(VALID).map(([fieldId, value]) => ({ fieldId, value }))
+    )
+
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {
+      ...VALID,
+      axles: '4',
+    })
+
+    expect(result).toEqual({
+      success: false,
+      error: 'This document is locked because it has been sent.',
+    })
+    expect(db.customFieldValue.upsert).not.toHaveBeenCalled()
+  })
+
+  it('refuses clearing a value on a locked record too', async () => {
+    lock.assertQuoteEditable.mockRejectedValue(new DocumentLockedError('sent'))
+    db.customFieldValue.findMany.mockResolvedValue([{ fieldId: 'note', value: 'Keys in office' }])
+
+    const result = await saveValidatedCustomFieldValues('q-1', 'quote', { note: '' })
+
+    expect(result.success).toBe(false)
+    expect(result.error).toBe('This document is locked because it has been sent.')
+  })
+
+  it('still fails on anything that is not the lock', async () => {
+    lock.assertInvoiceEditable.mockRejectedValue(new Error('Something else'))
+
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', {})
+
+    expect(result).toEqual({ success: false, error: 'Something else' })
+  })
+
+  it('takes them again once an owner has unlocked it', async () => {
+    // assertInvoiceEditable passes for an unlocked invoice; nothing else stands in the way.
+    const result = await saveValidatedCustomFieldValues('job-1', 'service_record', VALID)
+
+    expect(result.data).toEqual({ saved: true })
+  })
+
+  it('does not ask about the lock of a record that is not this workshop’s', async () => {
+    db.serviceRecord.count.mockResolvedValue(0)
+
+    const result = await saveValidatedCustomFieldValues('theirs', 'service_record', VALID)
+
+    expect(result).toEqual({ success: false, error: 'Record not found' })
+    expect(lock.assertInvoiceEditable).not.toHaveBeenCalled()
+  })
+})
+
+describe('a tab opened before this change', () => {
+  /** Every source file under a folder. */
+  function sources(dir: string): string[] {
+    return readdirSync(dir).flatMap((name) => {
+      const path = join(dir, name)
+      if (statSync(path).isDirectory()) {
+        return name === 'generated' || name === '__tests__' ? [] : sources(path)
+      }
+      return /\.tsx?$/.test(name) ? [path] : []
+    })
+  }
+
+  it('finds no action under the old name, so it is asked to reload instead of saving unchecked', () => {
+    expect(Object.keys(actions)).not.toContain('saveCustomFieldValues')
+    expect(Object.keys(actions)).toContain('saveValidatedCustomFieldValues')
+  })
+
+  it('has no caller left in the app', () => {
+    const callers = sources(join(process.cwd(), 'src')).filter((path) =>
+      /\bsaveCustomFieldValues\b/.test(readFileSync(path, 'utf8'))
+    )
+    expect(callers).toEqual([])
+  })
+})

+ 119 - 0
src/__tests__/features/custom-fields/value-rules.test.ts

@@ -0,0 +1,119 @@
+/**
+ * What a custom field's value may be for its type. The form and the server
+ * share these rules, so the browser and a hand-made request get one answer.
+ */
+import { describe, expect, it } from 'vitest'
+import {
+  CUSTOM_FIELD_VALUE_MAX_LENGTH,
+  customFieldOptions,
+  customFieldValueIssue,
+} from '@/features/custom-fields/Lib/customFieldValueRules'
+
+const field = (fieldType: string, extra: { options?: string; required?: boolean } = {}) => ({
+  fieldType,
+  options: extra.options ?? null,
+  required: extra.required ?? false,
+})
+
+describe('an empty value', () => {
+  it.each([
+    'text',
+    'textarea',
+    'number',
+    'date',
+    'select',
+    'checkbox',
+  ])('is fine on a %s field that is not required', (type) => {
+    expect(customFieldValueIssue(field(type, { options: 'A, B' }), '')).toBeNull()
+  })
+
+  it.each([
+    'text',
+    'textarea',
+    'number',
+    'date',
+    'select',
+  ])('is refused on a required %s field, spaces included', (type) => {
+    const required = field(type, { options: 'A, B', required: true })
+    expect(customFieldValueIssue(required, '')).toBe('required')
+    expect(customFieldValueIssue(required, '   ')).toBe('required')
+  })
+
+  it('is an answer on a required checkbox: left unticked', () => {
+    expect(customFieldValueIssue(field('checkbox', { required: true }), '')).toBeNull()
+    expect(customFieldValueIssue(field('checkbox', { required: true }), 'false')).toBeNull()
+  })
+})
+
+describe('a number field', () => {
+  it.each(['12', '-3', '12.5', '0', '1e3'])('takes %s', (value) => {
+    expect(customFieldValueIssue(field('number'), value)).toBeNull()
+  })
+
+  it.each(['twelve', '12 km', '1,5', 'NaN', 'Infinity', '   '])('refuses "%s"', (value) => {
+    expect(customFieldValueIssue(field('number'), value)).toBe('number')
+  })
+})
+
+describe('a date field', () => {
+  it('takes a calendar day', () => {
+    expect(customFieldValueIssue(field('date'), '2026-03-10')).toBeNull()
+    expect(customFieldValueIssue(field('date'), '2028-02-29')).toBeNull()
+  })
+
+  it.each([
+    '10/03/2026',
+    '2026-3-10',
+    '2026-02-30',
+    '2027-02-29',
+    '2026-13-01',
+    'tomorrow',
+  ])('refuses "%s"', (value) => {
+    expect(customFieldValueIssue(field('date'), value)).toBe('date')
+  })
+})
+
+describe('a checkbox', () => {
+  it('holds true or false and nothing else', () => {
+    expect(customFieldValueIssue(field('checkbox'), 'true')).toBeNull()
+    expect(customFieldValueIssue(field('checkbox'), 'false')).toBeNull()
+    expect(customFieldValueIssue(field('checkbox'), 'yes')).toBe('checkbox')
+    expect(customFieldValueIssue(field('checkbox'), 'on')).toBe('checkbox')
+  })
+})
+
+describe('a select field', () => {
+  const colour = field('select', { options: 'Red, Dark blue ,Green,' })
+
+  it('reads its options from the comma-separated list, trimmed', () => {
+    expect(customFieldOptions('Red, Dark blue ,Green,')).toEqual(['Red', 'Dark blue', 'Green'])
+    expect(customFieldOptions(null)).toEqual([])
+  })
+
+  it('takes one of its options', () => {
+    expect(customFieldValueIssue(colour, 'Dark blue')).toBeNull()
+  })
+
+  it('refuses anything else, however close', () => {
+    expect(customFieldValueIssue(colour, 'Yellow')).toBe('option')
+    expect(customFieldValueIssue(colour, 'red')).toBe('option')
+    expect(customFieldValueIssue(colour, 'Red, Green')).toBe('option')
+  })
+})
+
+describe('text', () => {
+  it('takes whatever is typed, on one line or several', () => {
+    expect(customFieldValueIssue(field('text'), 'PO 4471 / "urgent"')).toBeNull()
+    expect(customFieldValueIssue(field('textarea'), 'line one\nline two')).toBeNull()
+  })
+
+  it('stops at a length no field is for', () => {
+    const atLimit = 'x'.repeat(CUSTOM_FIELD_VALUE_MAX_LENGTH)
+    expect(customFieldValueIssue(field('textarea'), atLimit)).toBeNull()
+    expect(customFieldValueIssue(field('textarea'), `${atLimit}x`)).toBe('tooLong')
+  })
+
+  it('treats a type it does not know as text', () => {
+    expect(customFieldValueIssue(field('colour_picker'), '#ff0000')).toBeNull()
+  })
+})

+ 37 - 1
src/__tests__/features/inspection-reminders/booking-actions.test.ts

@@ -10,6 +10,8 @@ const serviceRecord = {
 const serviceRequest = { create: vi.fn(), findUnique: vi.fn(), updateMany: vi.fn() }
 const scheduledMessage = { create: vi.fn() }
 const appSetting = { findUnique: vi.fn() }
+// A deleted placeholder job takes its custom field values with it.
+const customFieldValue = { deleteMany: vi.fn() }
 // These tests are about workshop scoping, not files: the file manager and the
 // files a delete collects have tests of their own (src/__tests__/lib/files).
 vi.mock('@/lib/files/collect', () => ({
@@ -26,7 +28,14 @@ vi.mock('@/lib/files/manager', () => ({
 }))
 
 vi.mock('@/lib/db', () => ({
-  db: { inspectionReminderSend, serviceRecord, serviceRequest, scheduledMessage, appSetting },
+  db: {
+    inspectionReminderSend,
+    serviceRecord,
+    serviceRequest,
+    scheduledMessage,
+    appSetting,
+    customFieldValue,
+  },
 }))
 const notify = vi.fn(async () => undefined)
 vi.mock('@/lib/notify', () => ({ notify }))
@@ -110,6 +119,7 @@ beforeEach(() => {
   inspectionReminderSend.update.mockResolvedValue({})
   scheduledMessage.create.mockResolvedValue({ id: 'msg-1' })
   claimableResource.mockResolvedValue({ workBayId: 'bay-1' })
+  serviceRecord.deleteMany.mockResolvedValue({ count: 1 })
 })
 
 describe('booking link', () => {
@@ -235,6 +245,32 @@ describe('booking link', () => {
     expect(notify).toHaveBeenCalledWith(
       expect.objectContaining({ type: 'online_booking_cancelled' })
     )
+    // The placeholder is gone, and so are the custom field values on it.
+    expect(customFieldValue.deleteMany).toHaveBeenCalledWith({
+      where: {
+        entityType: 'service_record',
+        entityId: { in: ['rec-1'] },
+        field: { organizationId: 'org-a' },
+      },
+    })
+  })
+
+  it('keeps the custom field values of a job somebody started before the cancel landed', async () => {
+    inspectionReminderSend.findUnique.mockResolvedValue(
+      send({ bookedAt: new Date(), bookedServiceRecordId: 'rec-1' })
+    )
+    serviceRecord.findUnique.mockResolvedValue({
+      startDateTime: future,
+      endDateTime: new Date(future.getTime() + 3_600_000),
+      status: 'scheduled',
+    })
+    // Still a placeholder when looked up, in progress by the time of the delete.
+    serviceRecord.findFirst.mockResolvedValue({ id: 'rec-1' })
+    serviceRecord.deleteMany.mockResolvedValue({ count: 0 })
+
+    await cancelBooking(TOKEN)
+
+    expect(customFieldValue.deleteMany).not.toHaveBeenCalled()
   })
 
   it('books and cancels nothing while the workshop is being restored', async () => {

+ 20 - 1
src/__tests__/features/onboarding/sample-data.test.ts

@@ -42,7 +42,8 @@ vi.mock('@/lib/db', () => ({
     },
     customer: { count: vi.fn(), deleteMany: vi.fn() },
     vehicle: { count: vi.fn(), deleteMany: vi.fn() },
-    serviceRecord: { count: vi.fn(), findFirst: vi.fn(), deleteMany: vi.fn() },
+    serviceRecord: { count: vi.fn(), findFirst: vi.fn(), findMany: vi.fn(), deleteMany: vi.fn() },
+    customFieldValue: { deleteMany: vi.fn() },
     organization: { findUnique: vi.fn() },
     quote: { deleteMany: vi.fn() },
     inspection: { deleteMany: vi.fn() },
@@ -118,11 +119,29 @@ describe('removeSampleData', () => {
       value: JSON.stringify(SAMPLE_IDS),
     } as never)
     vi.mocked(db.$transaction).mockResolvedValue([] as never)
+    // A job someone added to a sample vehicle goes with the vehicle.
+    vi.mocked(db.serviceRecord.findMany).mockResolvedValue([{ id: 'added-later' }] as never)
 
     const result = await removeSampleData()
     expect(result.success).toBe(true)
     expect(result.data).toEqual({ removed: true })
 
+    // Custom field values filled in on a sample job or quote go with it.
+    expect(db.customFieldValue.deleteMany).toHaveBeenCalledWith({
+      where: {
+        entityType: 'service_record',
+        entityId: { in: [...SAMPLE_IDS.serviceRecords, 'added-later'] },
+        field: { organizationId: ORG },
+      },
+    })
+    expect(db.customFieldValue.deleteMany).toHaveBeenCalledWith({
+      where: {
+        entityType: 'quote',
+        entityId: { in: SAMPLE_IDS.quotes },
+        field: { organizationId: ORG },
+      },
+    })
+
     expect(db.serviceRecord.deleteMany).toHaveBeenCalledWith({
       where: { organizationId: ORG, id: { in: SAMPLE_IDS.serviceRecords } },
     })

+ 6 - 0
src/__tests__/multitenancy/quote-inspection-isolation.test.ts

@@ -69,6 +69,8 @@ vi.mock('@/lib/db', () => ({
       findFirst: vi.fn(),
       update: vi.fn(),
     },
+    // A deleted work order or quote takes its custom field values with it.
+    customFieldValue: { deleteMany: vi.fn() },
     $transaction: vi.fn(),
   },
 }))
@@ -135,6 +137,10 @@ const ORG_A_INSPECTION = {
 
 beforeEach(() => {
   vi.resetAllMocks()
+  // Deleting a quote removes it and its custom field values in one
+  // transaction; run the callback against the mock db.
+  // eslint-disable-next-line @typescript-eslint/no-explicit-any
+  vi.mocked(db.$transaction).mockImplementation(async (cb: any) => cb(db))
   vi.mocked(db.documentDesignSnapshot.findUnique).mockResolvedValue({ id: 'snap-1' } as any)
   // Locking is read before any edit to an invoice or quote; no settings
   // rows means locking is off, which is how these tests expect to run.

+ 4 - 0
src/__tests__/multitenancy/vehicle-service-isolation.test.ts

@@ -57,6 +57,8 @@ vi.mock('@/lib/db', () => ({
       delete: vi.fn(),
     },
     servicePart: { findMany: vi.fn() },
+    // A deleted work order or quote takes its custom field values with it.
+    customFieldValue: { deleteMany: vi.fn() },
     inventoryPart: { updateMany: vi.fn() },
     $transaction: vi.fn(),
   },
@@ -120,6 +122,8 @@ beforeEach(() => {
   // eslint-disable-next-line @typescript-eslint/no-explicit-any
   vi.mocked(db.$transaction).mockImplementation(async (cb: any) => cb(db))
   vi.mocked(db.servicePart.findMany).mockResolvedValue([] as any)
+  // Deleting a vehicle first reads which work orders go with it.
+  vi.mocked(db.serviceRecord.findMany).mockResolvedValue([] as any)
 })
 
 // ---------------------------------------------------------------------------

+ 7 - 0
src/components/ui/date-input.tsx

@@ -94,6 +94,8 @@ export function DateInput({
   onChange,
   className,
   placeholder,
+  'aria-invalid': ariaInvalid,
+  'aria-describedby': ariaDescribedBy,
 }: {
   id?: string
   name?: string
@@ -101,6 +103,9 @@ export function DateInput({
   onChange: (value: string) => void
   className?: string
   placeholder?: string
+  'aria-invalid'?: boolean
+  /** The id of the message that explains why the value is refused. */
+  'aria-describedby'?: string
 }) {
   const { dateFormat } = useDateSettings()
   const ta = useTranslations('common.a11y')
@@ -166,6 +171,8 @@ export function DateInput({
           }
         }}
         className={cn('pr-9', className)}
+        aria-invalid={ariaInvalid}
+        aria-describedby={ariaDescribedBy}
       />
       <Popover open={open} onOpenChange={setOpen}>
         <PopoverTrigger asChild>

+ 4 - 0
src/components/ui/searchable-select.tsx

@@ -71,6 +71,7 @@ export function SearchableSelect({
   searchable,
   'aria-label': ariaLabel,
   'aria-invalid': ariaInvalid,
+  'aria-describedby': ariaDescribedBy,
 }: {
   value: string | null | undefined
   onValueChange: (value: string) => void
@@ -88,6 +89,8 @@ export function SearchableSelect({
   searchable?: boolean
   'aria-label'?: string
   'aria-invalid'?: boolean
+  /** The id of the message that explains why the value is refused. */
+  'aria-describedby'?: string
 }) {
   const t = useTranslations('common.searchableSelect')
   const [open, setOpen] = useState(false)
@@ -125,6 +128,7 @@ export function SearchableSelect({
           aria-haspopup="listbox"
           aria-label={ariaLabel}
           aria-invalid={ariaInvalid}
+          aria-describedby={ariaDescribedBy}
           disabled={disabled}
           data-size={size}
           // The button can be narrower than the name in it; hovering shows all of it.

+ 136 - 48
src/features/custom-fields/Actions/customFieldActions.ts

@@ -2,16 +2,26 @@
 
 import { db } from '@/lib/db'
 import { withAuth } from '@/lib/with-auth'
+import { z } from 'zod'
 import {
   createFieldDefinitionSchema,
-  entityTypes,
-  type EntityType,
   updateFieldDefinitionSchema,
 } from '../Schema/customFieldSchema'
 import { revalidatePath } from 'next/cache'
 import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { requireFeature } from '@/lib/features'
 import { clearedToNull } from '@/lib/clearable'
+import {
+  assertOwnRecord,
+  recordLockError,
+  isEntityType,
+  recordSubject,
+} from '../Lib/customFieldRecords.server'
+import {
+  customFieldTypeIssue,
+  isMissingRequiredValue,
+  type CustomFieldIssue,
+} from '../Lib/customFieldValueRules'
 
 /**
  * Whose permission a record's custom fields fall under: the record's own.
@@ -21,38 +31,11 @@ import { clearedToNull } from '@/lib/clearable'
  * or the quote, the same as its title. A Member who may edit a work order saw
  * none of the workshop's custom fields on it and could not have saved one,
  * and was refused on every page load besides. Defining fields stays behind
- * Settings; reading and filling them follows the record.
+ * Settings; reading and filling them follows the record. An unknown kind of
+ * record needs Settings.
  */
-const RECORD_SUBJECT: Record<EntityType, PermissionSubject> = {
-  service_record: PermissionSubject.SERVICES,
-  quote: PermissionSubject.QUOTES,
-}
-
-function isEntityType(value: unknown): value is EntityType {
-  return typeof value === 'string' && (entityTypes as readonly string[]).includes(value)
-}
-
-/** The permission a call about one record's fields needs. An unknown kind needs Settings. */
 function recordPermission(entityType: unknown, action: PermissionAction) {
-  return [
-    {
-      action,
-      subject: isEntityType(entityType) ? RECORD_SUBJECT[entityType] : PermissionSubject.SETTINGS,
-    },
-  ]
-}
-
-/**
- * The record has to be this workshop's. These actions are handed a bare id,
- * and a value row is keyed by it, so without this a caller could attach
- * values to a record that is not theirs.
- */
-async function assertOwnRecord(entityId: string, entityType: EntityType, organizationId: string) {
-  const found =
-    entityType === 'quote'
-      ? await db.quote.count({ where: { id: entityId, organizationId } })
-      : await db.serviceRecord.count({ where: { id: entityId, organizationId } })
-  if (found === 0) throw new Error('Record not found')
+  return [{ action, subject: recordSubject(entityType) }]
 }
 
 export async function getFieldDefinitions(entityType?: string) {
@@ -221,34 +204,139 @@ export async function getCustomFieldValues(entityId: string, entityType: string)
   )
 }
 
-export async function saveCustomFieldValues(
+const saveValuesSchema = z.object({
+  entityId: z.string().min(1),
+  values: z.record(z.string(), z.string()),
+})
+
+/**
+ * One refused field: which, what the workshop calls it, and what is wrong.
+ * The label comes from the server so a form that has never heard of the
+ * field (it was added while the form was open) can still name it.
+ */
+export interface CustomFieldError {
+  fieldId: string
+  label: string
+  issue: CustomFieldIssue
+}
+
+/** What a save of a record's values comes back with. */
+export type SaveCustomFieldValuesResult =
+  | { saved: true }
+  /** Nothing was written. The refused fields, in the order the form shows them. */
+  | { saved: false; fieldErrors: CustomFieldError[] }
+
+/**
+ * Saves a record's custom field values, checked against the fields'
+ * definitions. All of them are written or none is.
+ *
+ * This replaces the action that wrote whatever it was sent, under a new
+ * name on purpose: a tab opened before the change still calls the old one,
+ * finds nothing there and is asked to reload, instead of saving values
+ * nobody checked.
+ *
+ * - A locked work order or quote refuses a change to a value, with the
+ *   error every other edit to what it prints gets. A save that changes
+ *   nothing is not an edit and goes through untouched: the page saves its
+ *   custom fields along with everything else, and what stays open on a
+ *   locked document must not be held up by fields nobody touched.
+ * - A required field refuses an empty value. One the request leaves out is
+ *   judged by what the record shows for it (the stored value, else the
+ *   field's default), so leaving a field out is no way around the rule, and
+ *   a form opened before the field became required is told about it. Only
+ *   here: nothing else that writes to the record (its status, a payment, a
+ *   line added from a phone) looks at custom fields, so a record made before
+ *   a field became required keeps working and is asked for the value when
+ *   its form is next saved, which is what the form has always done.
+ * - A value has to suit its type, unless it is the value already stored for
+ *   that field. That one is left alone and not written again: a choice whose
+ *   option was since removed, or a date an import wrote in another shape,
+ *   must not stop the rest of the record from being saved.
+ * - A field that is unknown or switched off is skipped, as before. It may
+ *   have been switched off while the form was open.
+ */
+export async function saveValidatedCustomFieldValues(
   entityId: string,
   entityType: string,
   values: Record<string, string>
 ) {
   return withAuth(
-    async ({ organizationId }) => {
+    async ({ organizationId }): Promise<SaveCustomFieldValuesResult> => {
       if (!isEntityType(entityType)) throw new Error('Unknown record type')
-      await assertOwnRecord(entityId, entityType, organizationId)
+      const input = saveValuesSchema.parse({ entityId, values })
+      await assertOwnRecord(input.entityId, entityType, organizationId)
+
       const definitions = await db.customFieldDefinition.findMany({
         where: { organizationId, entityType, isActive: true },
+        // The order the form draws them in, so the first error is the first field.
+        orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }],
       })
+      const stored = await db.customFieldValue.findMany({
+        where: {
+          entityId: input.entityId,
+          entityType,
+          fieldId: { in: definitions.map((d) => d.id) },
+        },
+        select: { fieldId: true, value: true },
+      })
+      const storedValue = new Map(stored.map((row) => [row.fieldId, row.value]))
 
-      const validFieldIds = new Set(definitions.map((d) => d.id))
+      const lockError = await recordLockError(input.entityId, entityType, organizationId)
+      if (lockError) {
+        // Changed against what the record shows: the stored value, else the
+        // field's default. A form sends that back for a field nobody has
+        // filled in, and that is not a change either.
+        const changesSomething = definitions.some((definition) => {
+          const value: string | undefined = input.values[definition.id]
+          const shown = storedValue.get(definition.id) ?? definition.defaultValue ?? ''
+          return value !== undefined && value !== shown
+        })
+        if (changesSomething) throw lockError
+        // Nothing is written and nothing is asked for: a required field left
+        // empty before the lock cannot be filled in now.
+        return { saved: true }
+      }
 
-      const ops = Object.entries(values)
-        .filter(([fieldId]) => validFieldIds.has(fieldId))
-        .map(([fieldId, value]) =>
-          db.customFieldValue.upsert({
-            where: {
-              fieldId_entityId: { fieldId, entityId },
-            },
-            create: { fieldId, entityId, entityType, value },
-            update: { value },
-          })
-        )
+      const fieldErrors: CustomFieldError[] = []
+      const refuse = (definition: { id: string; label: string }, issue: CustomFieldIssue) =>
+        fieldErrors.push({ fieldId: definition.id, label: definition.label, issue })
+      const changed: { fieldId: string; value: string }[] = []
+      for (const definition of definitions) {
+        // Only own keys: the object came through JSON and zod, so it has no
+        // inherited ones a field id could collide with.
+        const value: string | undefined = input.values[definition.id]
+        if (value === undefined) {
+          // Not sent, so nothing is written. What the record shows for it
+          // still has to satisfy "required".
+          const shown = storedValue.get(definition.id) ?? definition.defaultValue ?? ''
+          if (isMissingRequiredValue(definition, shown)) refuse(definition, 'required')
+          continue
+        }
 
-      await db.$transaction(ops)
+        if (isMissingRequiredValue(definition, value)) {
+          refuse(definition, 'required')
+          continue
+        }
+        if (storedValue.get(definition.id) === value) continue
+
+        const issue = customFieldTypeIssue(definition, value)
+        if (issue) refuse(definition, issue)
+        else changed.push({ fieldId: definition.id, value })
+      }
+
+      if (fieldErrors.length > 0) return { saved: false, fieldErrors }
+
+      if (changed.length > 0) {
+        await db.$transaction(
+          changed.map(({ fieldId, value }) =>
+            db.customFieldValue.upsert({
+              where: { fieldId_entityId: { fieldId, entityId: input.entityId } },
+              create: { fieldId, entityId: input.entityId, entityType, value },
+              update: { value },
+            })
+          )
+        )
+      }
       return { saved: true }
     },
     { requiredPermissions: recordPermission(entityType, PermissionAction.UPDATE) }

+ 238 - 97
src/features/custom-fields/Components/CustomFieldsForm.tsx

@@ -1,6 +1,6 @@
 'use client'
 
-import { useEffect, useState, useCallback } from 'react'
+import { useEffect, useRef, useState, useCallback } from 'react'
 import { useTranslations } from 'next-intl'
 import { Input } from '@/components/ui/input'
 import { DateInput } from '@/components/ui/date-input'
@@ -12,9 +12,17 @@ import { AppCard } from '@/components/app-card'
 import { Card, CardContent } from '@/components/ui/card'
 import {
   getCustomFieldValues,
-  saveCustomFieldValues,
+  saveValidatedCustomFieldValues,
   getFieldDefinitions,
+  type CustomFieldError,
 } from '@/features/custom-fields/Actions/customFieldActions'
+import {
+  CUSTOM_FIELD_VALUE_MAX_LENGTH,
+  customFieldOptions,
+  customFieldTypeIssue,
+  isMissingRequiredValue,
+  type CustomFieldIssue,
+} from '@/features/custom-fields/Lib/customFieldValueRules'
 import { Loader2 } from 'lucide-react'
 import { cn } from '@/lib/utils'
 
@@ -28,22 +36,91 @@ interface FieldWithValue {
   value: string
 }
 
+/**
+ * What saving the custom fields came to. When it is not valid the fields at
+ * fault are marked on the form, each with its own message, and the page is
+ * handed what it needs to say why its save stopped: `fields` names them by
+ * the workshop's own labels, `problem` tells a value left out from one that
+ * does not fit its field, and `error` carries the server's own words when it
+ * refused the whole save (a locked document, a missing permission).
+ */
+export type CustomFieldsSaveOutcome =
+  | { valid: true }
+  | { valid: false; problem?: 'required' | 'invalid'; fields?: string[]; error?: string }
+
+/**
+ * How a save was asked for. An autosave runs while the person is typing
+ * somewhere else on the page, so it marks the fields but leaves the focus
+ * and the scroll position alone; a save they asked for takes them to the
+ * first field at fault.
+ */
+export type CustomFieldsSave = (options?: { reveal?: boolean }) => Promise<CustomFieldsSaveOutcome>
+
+/**
+ * A field at fault: the red border, and room kept under it when the browser
+ * scrolls it into view (a phone does that as its keyboard opens), so the
+ * message beneath the field comes into view with it.
+ */
+const INVALID_CLASS = 'border-destructive focus-visible:ring-destructive scroll-mb-10'
+
+const ISSUE_MESSAGE = {
+  required: 'requiredError',
+  number: 'numberError',
+  date: 'dateError',
+  option: 'optionError',
+  checkbox: 'checkboxError',
+  tooLong: 'tooLongError',
+} as const satisfies Record<CustomFieldIssue, string>
+
 export function CustomFieldsForm({
   entityId,
   entityType,
   onValuesReady,
   onChange,
+  locked = false,
 }: {
   entityId?: string
   entityType: 'service_record' | 'quote'
-  onValuesReady?: (save: () => Promise<{ valid: boolean }>) => void
+  onValuesReady?: (save: CustomFieldsSave) => void
   onChange?: () => void
+  /**
+   * The document is locked and the fields are drawn read-only. Saving them is
+   * then no step of the page's save at all: nothing can have changed, and a
+   * required field left empty before the lock cannot be filled in now, so it
+   * must not stand in the way of what the page still saves.
+   */
+  locked?: boolean
 }) {
   const tSettings = useTranslations('settings.customFields')
   const [fields, setFields] = useState<FieldWithValue[]>([])
   const [values, setValues] = useState<Record<string, string>>({})
   const [loading, setLoading] = useState(true)
-  const [errors, setErrors] = useState<Record<string, string>>({})
+  const [errors, setErrors] = useState<Record<string, CustomFieldIssue>>({})
+  // What the server holds for each field, as last loaded or saved. A value
+  // left as it was is never re-checked for its type: see the save action.
+  const savedValues = useRef<Record<string, string>>({})
+  const card = useRef<HTMLDivElement>(null)
+  // The field to take the person to, and a count so asking twice for the same
+  // field (Save pressed again with nothing fixed) takes them there again.
+  const [reveal, setReveal] = useState<{ fieldId: string; ask: number } | null>(null)
+
+  useEffect(() => {
+    if (!reveal) return
+    const wrapper = Array.from(card.current?.children ?? []).find(
+      (child): child is HTMLElement =>
+        child instanceof HTMLElement && child.dataset.testid === `custom-field-${reveal.fieldId}`
+    )
+    if (!wrapper) return
+    const control = wrapper.querySelector<HTMLElement>(
+      'input:not([type="hidden"]), textarea, button[role="combobox"]'
+    )
+    // Focus without the browser's own jump, then bring the message to the
+    // middle of the screen: the field sits just above it, clear of a sticky
+    // header above and of a phone's keyboard below.
+    control?.focus({ preventScroll: true })
+    const target = wrapper.querySelector<HTMLElement>('[role="alert"]') ?? wrapper
+    target.scrollIntoView?.({ block: 'center', behavior: 'smooth' })
+  }, [reveal])
 
   useEffect(() => {
     async function load() {
@@ -55,6 +132,7 @@ export function CustomFieldsForm({
           const v: Record<string, string> = {}
           for (const f of result.data) v[f.id] = f.value
           setValues(v)
+          savedValues.current = v
         }
       } else {
         const result = await getFieldDefinitions(entityType)
@@ -71,35 +149,76 @@ export function CustomFieldsForm({
     load()
   }, [entityId, entityType])
 
-  const validate = useCallback((): Record<string, string> => {
-    const newErrors: Record<string, string> = {}
+  const validate = useCallback((): CustomFieldError[] => {
+    const found: CustomFieldError[] = []
     for (const field of fields) {
-      if (field.required && field.fieldType !== 'checkbox') {
-        const val = values[field.id] ?? field.value ?? ''
-        if (!val.trim()) {
-          newErrors[field.id] = tSettings('requiredError', { label: field.label })
-        }
+      const val = values[field.id] ?? field.value ?? ''
+      if (isMissingRequiredValue(field, val)) {
+        found.push({ fieldId: field.id, label: field.label, issue: 'required' })
+        continue
       }
+      if (savedValues.current[field.id] === val) continue
+      const issue = customFieldTypeIssue(field, val)
+      if (issue) found.push({ fieldId: field.id, label: field.label, issue })
     }
-    return newErrors
-  }, [fields, values, tSettings])
+    return found
+  }, [fields, values])
 
   useEffect(() => {
     if (onValuesReady) {
-      onValuesReady(async () => {
-        const validationErrors = validate()
-        if (Object.keys(validationErrors).length > 0) {
-          setErrors(validationErrors)
-          return { valid: false }
+      onValuesReady(async (options) => {
+        if (locked) {
+          setErrors({})
+          return { valid: true }
+        }
+        const refused = (found: CustomFieldError[]): CustomFieldsSaveOutcome => {
+          setErrors(Object.fromEntries(found.map((error) => [error.fieldId, error.issue])))
+          if (options?.reveal !== false && found[0]) {
+            const first = found[0].fieldId
+            setReveal((last) => ({ fieldId: first, ask: (last?.ask ?? 0) + 1 }))
+          }
+          return {
+            valid: false,
+            problem: found.every((error) => error.issue === 'required') ? 'required' : 'invalid',
+            fields: found.map((error) => error.label),
+          }
         }
+
+        const found = validate()
+        if (found.length > 0) return refused(found)
         setErrors({})
         if (entityId && Object.keys(values).length > 0) {
-          await saveCustomFieldValues(entityId, entityType, values)
+          // The server checks the same rules again: it is the one that decides.
+          const result = await saveValidatedCustomFieldValues(entityId, entityType, values)
+          if (!result.success || !result.data) return { valid: false, error: result.error }
+          if (!result.data.saved) {
+            const { fieldErrors } = result.data
+            // A field this form does not show: it was added, or made required,
+            // while the form was open. Draw the fields as they are now, keeping
+            // what was typed, so the message has a field to sit under.
+            if (fieldErrors.some((error) => !fields.some((f) => f.id === error.fieldId))) {
+              const fresh = await getCustomFieldValues(entityId, entityType)
+              if (fresh.success && fresh.data) {
+                const current = fresh.data
+                setFields(current)
+                setValues((typed) => {
+                  const next = { ...typed }
+                  for (const f of current) if (!(f.id in next)) next[f.id] = f.value
+                  return next
+                })
+                for (const f of current) {
+                  if (!(f.id in savedValues.current)) savedValues.current[f.id] = f.value
+                }
+              }
+            }
+            return refused(fieldErrors)
+          }
+          savedValues.current = { ...savedValues.current, ...values }
         }
         return { valid: true }
       })
     }
-  }, [onValuesReady, entityId, entityType, values, validate])
+  }, [onValuesReady, entityId, entityType, fields, values, validate, locked])
 
   const updateValue = (fieldId: string, value: string) => {
     setValues((prev) => ({ ...prev, [fieldId]: value }))
@@ -128,84 +247,106 @@ export function CustomFieldsForm({
 
   return (
     <AppCard title={tSettings('formTitle')} contentClassName="space-y-4">
-      {fields.map((field) => {
-        const val = values[field.id] ?? field.value ?? ''
-        const hasError = !!errors[field.id]
-        return (
-          <div key={field.id} data-testid={`custom-field-${field.id}`} className="space-y-1.5">
-            {field.fieldType !== 'checkbox' && (
-              <Label className={cn(hasError && 'text-destructive')}>
-                {field.label}
-                {field.required && <span className="text-destructive ml-1">*</span>}
-              </Label>
-            )}
-
-            {field.fieldType === 'text' && (
-              <Input
-                value={val}
-                onChange={(e) => updateValue(field.id, e.target.value)}
-                className={cn(hasError && 'border-destructive focus-visible:ring-destructive')}
-              />
-            )}
-
-            {field.fieldType === 'number' && (
-              <Input
-                type="number"
-                value={val}
-                onChange={(e) => updateValue(field.id, e.target.value)}
-                className={cn(hasError && 'border-destructive focus-visible:ring-destructive')}
-              />
-            )}
-
-            {field.fieldType === 'date' && (
-              <DateInput
-                value={val}
-                onChange={(v) => updateValue(field.id, v)}
-                className={cn(hasError && 'border-destructive focus-visible:ring-destructive')}
-              />
-            )}
-
-            {field.fieldType === 'textarea' && (
-              <Textarea
-                value={val}
-                onChange={(e) => updateValue(field.id, e.target.value)}
-                rows={3}
-                className={cn(hasError && 'border-destructive focus-visible:ring-destructive')}
-              />
-            )}
-
-            {field.fieldType === 'checkbox' && (
-              <div className="flex items-center gap-2">
-                <Checkbox
-                  checked={val === 'true'}
-                  onCheckedChange={(checked) => updateValue(field.id, String(checked))}
+      <div ref={card} className="space-y-4">
+        {fields.map((field) => {
+          const val = values[field.id] ?? field.value ?? ''
+          const issue = errors[field.id]
+          const hasError = !!issue
+          const errorId = `custom-field-error-${field.id}`
+          const inputId = `custom-field-input-${field.id}`
+          const invalid = {
+            id: inputId,
+            'aria-invalid': hasError || undefined,
+            'aria-describedby': hasError ? errorId : undefined,
+          }
+          return (
+            <div key={field.id} data-testid={`custom-field-${field.id}`} className="space-y-1.5">
+              {field.fieldType !== 'checkbox' && (
+                <Label htmlFor={inputId} className={cn(hasError && 'text-destructive')}>
+                  {field.label}
+                  {field.required && <span className="text-destructive ml-1">*</span>}
+                </Label>
+              )}
+
+              {field.fieldType === 'text' && (
+                <Input
+                  value={val}
+                  onChange={(e) => updateValue(field.id, e.target.value)}
+                  className={cn(hasError && INVALID_CLASS)}
+                  {...invalid}
+                />
+              )}
+
+              {field.fieldType === 'number' && (
+                <Input
+                  type="number"
+                  value={val}
+                  onChange={(e) => updateValue(field.id, e.target.value)}
+                  className={cn(hasError && INVALID_CLASS)}
+                  {...invalid}
+                />
+              )}
+
+              {field.fieldType === 'date' && (
+                <DateInput
+                  value={val}
+                  onChange={(v) => updateValue(field.id, v)}
+                  className={cn(hasError && INVALID_CLASS)}
+                  {...invalid}
                 />
-                <Label>{field.label}</Label>
-              </div>
-            )}
-
-            {field.fieldType === 'select' && (
-              <SearchableSelect
-                value={val || (field.required ? null : 'none')}
-                onValueChange={(v) => updateValue(field.id, v === 'none' ? '' : v)}
-                aria-invalid={hasError || undefined}
-                options={[
-                  ...(field.required
-                    ? []
-                    : [{ value: 'none', label: tSettings('defaultValueNone') }]),
-                  ...(field.options || '')
-                    .split(',')
-                    .map((o) => o.trim())
-                    .filter(Boolean)
-                    .map((option) => ({ value: option, label: option })),
-                ]}
-              />
-            )}
-
-            {hasError && <p className="text-xs text-destructive">{errors[field.id]}</p>}
-          </div>
-        )
-      })}
+              )}
+
+              {field.fieldType === 'textarea' && (
+                <Textarea
+                  value={val}
+                  onChange={(e) => updateValue(field.id, e.target.value)}
+                  rows={3}
+                  className={cn(hasError && INVALID_CLASS)}
+                  {...invalid}
+                />
+              )}
+
+              {field.fieldType === 'checkbox' && (
+                <div className="flex items-center gap-2">
+                  <Checkbox
+                    id={inputId}
+                    checked={val === 'true'}
+                    onCheckedChange={(checked) => updateValue(field.id, String(checked))}
+                  />
+                  <Label htmlFor={inputId}>{field.label}</Label>
+                </div>
+              )}
+
+              {field.fieldType === 'select' && (
+                <SearchableSelect
+                  value={val || (field.required ? null : 'none')}
+                  onValueChange={(v) => updateValue(field.id, v === 'none' ? '' : v)}
+                  className={cn(hasError && 'scroll-mb-10')}
+                  {...invalid}
+                  options={[
+                    ...(field.required
+                      ? []
+                      : [{ value: 'none', label: tSettings('defaultValueNone') }]),
+                    ...customFieldOptions(field.options).map((option) => ({
+                      value: option,
+                      label: option,
+                    })),
+                  ]}
+                />
+              )}
+
+              {issue && (
+                <p id={errorId} role="alert" className="text-xs text-destructive">
+                  {tSettings(ISSUE_MESSAGE[issue], {
+                    label: field.label,
+                    max: CUSTOM_FIELD_VALUE_MAX_LENGTH,
+                  })}
+                </p>
+              )}
+            </div>
+          )
+        })}
+      </div>
     </AppCard>
   )
 }

+ 86 - 0
src/features/custom-fields/Lib/customFieldRecords.server.ts

@@ -0,0 +1,86 @@
+import 'server-only'
+
+import { db } from '@/lib/db'
+import { DocumentLockedError } from '@/lib/document-lock'
+import { assertInvoiceEditable, assertQuoteEditable } from '@/lib/document-lock.server'
+import { PermissionSubject } from '@/lib/permissions'
+import { entityTypes, type EntityType } from '../Schema/customFieldSchema'
+
+/**
+ * What the custom field actions need to know about each kind of record that
+ * can carry custom fields. A new kind is one more entry here.
+ */
+interface CustomFieldRecordKind {
+  /**
+   * Whose permission the record's values fall under: the record's own.
+   * Defining a field is a setting; filling one in is part of the record.
+   */
+  subject: PermissionSubject
+  /** Whether the workshop has a record of this kind with this id. */
+  exists: (entityId: string, organizationId: string) => Promise<boolean>
+  /**
+   * Throws when the record may not be edited right now, with the same error
+   * every other edit to it gets. A kind that is never locked does nothing.
+   */
+  assertEditable: (entityId: string, organizationId: string) => Promise<void>
+}
+
+const RECORD_KINDS: Record<EntityType, CustomFieldRecordKind> = {
+  service_record: {
+    subject: PermissionSubject.SERVICES,
+    exists: async (id, organizationId) =>
+      (await db.serviceRecord.count({ where: { id, organizationId } })) > 0,
+    assertEditable: assertInvoiceEditable,
+  },
+  quote: {
+    subject: PermissionSubject.QUOTES,
+    exists: async (id, organizationId) =>
+      (await db.quote.count({ where: { id, organizationId } })) > 0,
+    assertEditable: assertQuoteEditable,
+  },
+}
+
+export function isEntityType(value: unknown): value is EntityType {
+  return typeof value === 'string' && (entityTypes as readonly string[]).includes(value)
+}
+
+/** The permission subject for one kind of record. An unknown kind needs Settings. */
+export function recordSubject(entityType: unknown): PermissionSubject {
+  return isEntityType(entityType) ? RECORD_KINDS[entityType].subject : PermissionSubject.SETTINGS
+}
+
+/**
+ * The record has to be this workshop's. The actions are handed a bare id, and
+ * a value row is keyed by it, so without this a caller could attach values to
+ * a record that is not theirs.
+ */
+export async function assertOwnRecord(
+  entityId: string,
+  entityType: EntityType,
+  organizationId: string
+) {
+  if (!(await RECORD_KINDS[entityType].exists(entityId, organizationId))) {
+    throw new Error('Record not found')
+  }
+}
+
+/**
+ * The refusal a locked work order or quote gives, or null when the record
+ * may be edited. Its custom fields are on the document the customer holds,
+ * so a change to one is refused with this same error, the one every other
+ * edit to the document gets. It is handed back rather than thrown because a
+ * save that changes nothing is not an edit, and must not fail on the lock.
+ */
+export async function recordLockError(
+  entityId: string,
+  entityType: EntityType,
+  organizationId: string
+): Promise<DocumentLockedError | null> {
+  try {
+    await RECORD_KINDS[entityType].assertEditable(entityId, organizationId)
+    return null
+  } catch (error) {
+    if (error instanceof DocumentLockedError) return error
+    throw error
+  }
+}

+ 89 - 0
src/features/custom-fields/Lib/customFieldValueRules.ts

@@ -0,0 +1,89 @@
+/**
+ * What a custom field's value may be, for its type.
+ *
+ * One set of rules for the form and the server. The form uses them to say
+ * what is wrong before the save leaves the browser; the server uses them
+ * because a request does not have to come from the form.
+ *
+ * Values are stored as text, whatever the type: a number as typed, a date as
+ * a calendar day (YYYY-MM-DD), a checkbox as 'true' or 'false', a choice as
+ * the option's own text. An empty string is "no value", and is fine for every
+ * type unless the field is required.
+ */
+
+/** Why a value was refused. The form turns each into a sentence. */
+export type CustomFieldIssue = 'required' | 'number' | 'date' | 'option' | 'checkbox' | 'tooLong'
+
+/** Longer than any text a field is for, and short enough to keep a row small. */
+export const CUSTOM_FIELD_VALUE_MAX_LENGTH = 10000
+
+export interface CustomFieldRuleInput {
+  fieldType: string
+  options: string | null
+  required: boolean
+}
+
+/** A select field's choices. They are kept as one comma-separated string. */
+export function customFieldOptions(options: string | null | undefined): string[] {
+  return (options || '')
+    .split(',')
+    .map((option) => option.trim())
+    .filter(Boolean)
+}
+
+const DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})$/
+
+/** A real calendar day written YYYY-MM-DD: 2026-02-30 is not one. */
+function isCalendarDay(value: string): boolean {
+  const match = DATE_ONLY.exec(value)
+  if (!match) return false
+  const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])]
+  const date = new Date(Date.UTC(year, month - 1, day))
+  return (
+    date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day
+  )
+}
+
+/**
+ * Whether a required field has been left empty. A checkbox never is: left
+ * unticked is an answer.
+ */
+export function isMissingRequiredValue(field: CustomFieldRuleInput, value: string): boolean {
+  return field.required && field.fieldType !== 'checkbox' && value.trim() === ''
+}
+
+/**
+ * Whether the value suits the field's type. Says nothing about "required".
+ * A type this file does not know is treated as text, so a field type added
+ * later is never refused by an older rule.
+ */
+export function customFieldTypeIssue(
+  field: CustomFieldRuleInput,
+  value: string
+): CustomFieldIssue | null {
+  if (value.length > CUSTOM_FIELD_VALUE_MAX_LENGTH) return 'tooLong'
+  if (value === '') return null
+
+  switch (field.fieldType) {
+    case 'number':
+      // The same test a number field's default value has to pass.
+      return value.trim() !== '' && Number.isFinite(Number(value)) ? null : 'number'
+    case 'date':
+      return isCalendarDay(value) ? null : 'date'
+    case 'checkbox':
+      return value === 'true' || value === 'false' ? null : 'checkbox'
+    case 'select':
+      return customFieldOptions(field.options).includes(value) ? null : 'option'
+    default:
+      return null
+  }
+}
+
+/** The first thing wrong with a value, or null when it may be saved. */
+export function customFieldValueIssue(
+  field: CustomFieldRuleInput,
+  value: string
+): CustomFieldIssue | null {
+  if (isMissingRequiredValue(field, value)) return 'required'
+  return customFieldTypeIssue(field, value)
+}

+ 66 - 0
src/features/custom-fields/Lib/deleteCustomFieldValues.ts

@@ -0,0 +1,66 @@
+import { db } from '@/lib/db'
+import type { EntityType } from '../Schema/customFieldSchema'
+
+/**
+ * Custom field values are keyed by the id of the record they belong to, with
+ * no foreign key to it: one table serves every kind of record. So nothing in
+ * the database removes them when the record goes, and every path that deletes
+ * a record has to say so here, in the same transaction where it has one.
+ *
+ * Values are not files and are not kept for a trash: once the record is gone
+ * nothing can show them again.
+ */
+
+/** Either the database client or a transaction on it. */
+interface ValueStore {
+  customFieldValue: {
+    deleteMany: (args: {
+      where: {
+        entityType: EntityType
+        entityId: { in: string[] }
+        field: { organizationId: string }
+      }
+    }) => PromiseLike<unknown>
+  }
+}
+
+/** Under the database's limit on values bound to one query. */
+const CHUNK = 5000
+
+/**
+ * Removes the values of the given records. Always by id: the caller names
+ * the records it deleted, so a record made in the meantime keeps its values.
+ * Scoped to the workshop's own fields, like every other query.
+ */
+export async function deleteCustomFieldValuesOf(
+  store: ValueStore,
+  organizationId: string,
+  entityType: EntityType,
+  entityIds: string[]
+): Promise<void> {
+  for (let start = 0; start < entityIds.length; start += CHUNK) {
+    await store.customFieldValue.deleteMany({
+      where: {
+        entityType,
+        entityId: { in: entityIds.slice(start, start + CHUNK) },
+        field: { organizationId },
+      },
+    })
+  }
+}
+
+/**
+ * The work orders that go when these vehicles are deleted (the database
+ * cascades them). Read before the delete, while they can still be found.
+ */
+export async function workOrderIdsOfVehicles(
+  organizationId: string,
+  vehicleIds: string[]
+): Promise<string[]> {
+  if (vehicleIds.length === 0) return []
+  const records = await db.serviceRecord.findMany({
+    where: { organizationId, vehicleId: { in: vehicleIds } },
+    select: { id: true },
+  })
+  return records.map((record) => record.id)
+}

+ 17 - 0
src/features/import/Actions/importActions.ts

@@ -1,5 +1,9 @@
 'use server'
 
+import {
+  deleteCustomFieldValuesOf,
+  workOrderIdsOfVehicles,
+} from '@/features/custom-fields/Lib/deleteCustomFieldValues'
 import { revalidatePath } from 'next/cache'
 import { z } from 'zod'
 import { db } from '@/lib/db'
@@ -855,6 +859,18 @@ export async function undoImportBatch(batchId: string) {
         )),
       ]
 
+      // Custom field values on those jobs, and on any job since added to an
+      // imported vehicle (it cascades with the vehicle), go with them.
+      const goneWorkOrderIds = [
+        ...new Set([
+          ...batchRecords.map((r) => r.id),
+          ...(await workOrderIdsOfVehicles(
+            organizationId,
+            batchVehicles.map((v) => v.id)
+          )),
+        ]),
+      ]
+
       const result = await db.$transaction(async (tx) => {
         const serviceRecords = await tx.serviceRecord.deleteMany({
           where: { importBatchId: batchId, organizationId },
@@ -862,6 +878,7 @@ export async function undoImportBatch(batchId: string) {
         const vehicles = await tx.vehicle.deleteMany({
           where: { importBatchId: batchId, organizationId },
         })
+        await deleteCustomFieldValuesOf(tx, organizationId, 'service_record', goneWorkOrderIds)
         const customers = await tx.customer.deleteMany({
           where: { importBatchId: batchId, organizationId },
         })

+ 9 - 1
src/features/inspection-reminders/Actions/bookingActions.ts

@@ -1,5 +1,6 @@
 'use server'
 
+import { deleteCustomFieldValuesOf } from '@/features/custom-fields/Lib/deleteCustomFieldValues'
 import { getTranslations } from 'next-intl/server'
 import { z } from 'zod'
 import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
@@ -332,7 +333,14 @@ export async function cancelBooking(rawToken: string) {
     const files = stillPlaceholder
       ? await serviceRecordFileUrls(send.organizationId, [stillPlaceholder.id])
       : []
-    await db.serviceRecord.deleteMany({ where: placeholder })
+    const removed = await db.serviceRecord.deleteMany({ where: placeholder })
+    // Only when the delete really took the job: one a technician started
+    // since the lookup above is kept, and keeps its custom field values.
+    if (removed.count > 0) {
+      await deleteCustomFieldValuesOf(db, send.organizationId, 'service_record', [
+        send.bookedServiceRecordId,
+      ])
+    }
     await releaseFiles(files, {
       organizationId: send.organizationId,
       reason: 'online booking cancelled',

+ 25 - 0
src/features/onboarding/Actions/checklistActions.ts

@@ -1,6 +1,7 @@
 'use server'
 
 import { db } from '@/lib/db'
+import { workOrderIdsOfVehicles } from '@/features/custom-fields/Lib/deleteCustomFieldValues'
 import { withAuth } from '@/lib/with-auth'
 import { revalidatePath } from 'next/cache'
 import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
@@ -157,7 +158,31 @@ export async function removeSampleData() {
         ...(await vehicleFileUrls(organizationId, ids.vehicles)),
       ]
 
+      // Custom field values someone filled in on a sample job or quote. They
+      // hang on the record's id alone, so nothing cascades to them; a job
+      // added to a sample vehicle since goes with the vehicle too.
+      const goneWorkOrderIds = [
+        ...new Set([
+          ...ids.serviceRecords,
+          ...(await workOrderIdsOfVehicles(organizationId, ids.vehicles)),
+        ]),
+      ]
+
       await db.$transaction([
+        db.customFieldValue.deleteMany({
+          where: {
+            entityType: 'service_record',
+            entityId: { in: goneWorkOrderIds },
+            field: { organizationId },
+          },
+        }),
+        db.customFieldValue.deleteMany({
+          where: {
+            entityType: 'quote',
+            entityId: { in: ids.quotes },
+            field: { organizationId },
+          },
+        }),
         db.serviceRecord.deleteMany({
           where: { organizationId, id: { in: ids.serviceRecords } },
         }),

+ 6 - 1
src/features/quotes/Actions/quoteActions.ts

@@ -7,6 +7,7 @@ import {
   getDocumentLockSettings,
 } from '@/lib/document-lock.server'
 import { DocumentLockedError, invoiceLockState, quoteLockState } from '@/lib/document-lock'
+import { deleteCustomFieldValuesOf } from '@/features/custom-fields/Lib/deleteCustomFieldValues'
 import { OPEN_SERVICE_STATUSES } from '@/lib/service-record'
 import { discountAmountFor } from '@/lib/tax'
 import { db } from '@/lib/db'
@@ -459,7 +460,11 @@ export async function deleteQuote(quoteId: string) {
 
       // Its attachments cascade with it; their files are let go afterwards.
       const files = await quoteFileUrls(organizationId, [quoteId])
-      await db.quote.deleteMany({ where: { id: quoteId, organizationId } })
+      // Its custom field values hang on its id alone, so nothing cascades.
+      await db.$transaction(async (tx) => {
+        await tx.quote.deleteMany({ where: { id: quoteId, organizationId } })
+        await deleteCustomFieldValuesOf(tx, organizationId, 'quote', [quoteId])
+      })
       await releaseFiles(files, { organizationId, reason: 'quote deleted' })
       revalidatePath('/quotes')
       return { quoteId }

+ 1 - 0
src/features/quotes/Components/QuoteRightColumn.tsx

@@ -296,6 +296,7 @@ export const QuoteRightColumn = memo(function QuoteRightColumn({
         <CustomFieldsForm
           entityId={quote.id}
           entityType="quote"
+          locked={locked}
           onValuesReady={state.onCustomFieldsReady}
           onChange={state.markDirty}
         />

+ 29 - 5
src/features/quotes/Components/useQuoteFormState.ts

@@ -43,6 +43,7 @@ import {
 import { isPriceOverridden, lineTotal, repricePartRow } from '@/features/inventory/Lib/partPricing'
 import type { QuoteRecord, QuotePartInput, QuoteLaborInput } from './quote-page-types'
 import { emptyPart, makeEmptyLabor, makeEmptyService } from './quote-page-types'
+import type { CustomFieldsSave } from '@/features/custom-fields/Components/CustomFieldsForm'
 
 interface SelectedVehicle {
   id: string
@@ -221,6 +222,12 @@ export function useQuoteFormState({
    * save did not carry must still be saved before the page is left.
    */
   const editRevisionRef = useRef(0)
+  /**
+   * True for the one save the autosave timer starts. The person is typing
+   * somewhere on the page then, so a refusal is said without taking the
+   * focus away from them; a save they asked for takes them to the field.
+   */
+  const autosaveRunRef = useRef(false)
   /** Why the last save failed, for the dialog that holds a link back. */
   const lastSaveErrorRef = useRef<string | null>(null)
   /** True while a link waits on its save: a failure goes into that dialog. */
@@ -232,9 +239,9 @@ export function useQuoteFormState({
   const isSavingRef = useRef(false)
 
   // Custom fields save callback ref
-  const customFieldsSaveRef = useRef<(() => Promise<{ valid: boolean }>) | null>(null)
+  const customFieldsSaveRef = useRef<CustomFieldsSave | null>(null)
 
-  const onCustomFieldsReady = useCallback((save: () => Promise<{ valid: boolean }>) => {
+  const onCustomFieldsReady = useCallback((save: CustomFieldsSave) => {
     customFieldsSaveRef.current = save
   }, [])
 
@@ -248,6 +255,7 @@ export function useQuoteFormState({
     if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
     autosaveTimer.current = setTimeout(() => {
       if (!isSavingRef.current && formRef.current) {
+        autosaveRunRef.current = true
         formRef.current.requestSubmit()
       }
     }, 5000)
@@ -505,6 +513,9 @@ export function useQuoteFormState({
     // currentTarget is nulled once the event has finished dispatching, which
     // happens during the custom-fields await below. Read the form now.
     const form = e.currentTarget
+    // Whether the autosave timer started this save, read once and spent.
+    const autosave = autosaveRunRef.current
+    autosaveRunRef.current = false
     if (isSavingRef.current) return
     if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
     // Saving from here on, the custom fields included: whoever waits for this
@@ -520,10 +531,23 @@ export function useQuoteFormState({
     // Validate and save custom fields before saving; a locked quote saves nothing.
     if (!locked && customFieldsSaveRef.current) {
       try {
-        const { valid } = await customFieldsSaveRef.current()
-        if (!valid) {
+        // A save the person asked for takes them to the first field at
+        // fault; an autosave marks it and leaves them where they are typing.
+        const outcome = await customFieldsSaveRef.current({ reveal: !autosave })
+        if (!outcome.valid) {
           isSavingRef.current = false
-          const message = t('page.customFieldsInvalid')
+          // Nothing of the quote was saved, and the message says so and names
+          // the fields by the workshop's own labels. The server's own words
+          // instead when it refused the whole save (the quote locked since
+          // the page was opened).
+          const message =
+            outcome.error ??
+            t(
+              outcome.problem === 'invalid'
+                ? 'page.customFieldsNotValid'
+                : 'page.customFieldsMissing',
+              { fields: (outcome.fields ?? []).join(', ') }
+            )
           failed(message, () => toast.error(message))
           return
         }

+ 10 - 0
src/features/settings/Actions/deleteContent.ts

@@ -1,5 +1,6 @@
 'use server'
 
+import { deleteCustomFieldValuesOf } from '@/features/custom-fields/Lib/deleteCustomFieldValues'
 import { db } from '@/lib/db'
 import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { withAuth } from '@/lib/with-auth'
@@ -73,12 +74,20 @@ export async function deleteContent(input: unknown) {
           ...(await vehicleFileUrls(organizationId, vehicleIds)),
           ...(await serviceRecordFileUrls(organizationId, counterSaleIds))
         )
+        // Every work order there is now. Their custom field values hang on
+        // the id alone, so they are removed by these ids afterwards: a job
+        // made while this runs is not in the list and keeps its values.
+        const workOrderIds = await idsOf(
+          db.serviceRecord.findMany({ where: { organizationId }, select: { id: true } })
+        )
 
         await db.vehicle.deleteMany({ where: { organizationId } })
         // Counter sales have no vehicle so the cascade above misses them, but
         // their attachment files were already collected for cleanup — delete the
         // records too so no orphaned work orders survive.
         await db.serviceRecord.deleteMany({ where: { organizationId } })
+        // The fields themselves stay unless they were ticked too.
+        await deleteCustomFieldValuesOf(db, organizationId, 'service_record', workOrderIds)
         deleted.push('vehicles')
       }
 
@@ -92,6 +101,7 @@ export async function deleteContent(input: unknown) {
         )
         filesToRelease.push(...(await quoteFileUrls(organizationId, quoteIds)))
         await db.quote.deleteMany({ where: { organizationId } })
+        await deleteCustomFieldValuesOf(db, organizationId, 'quote', quoteIds)
         deleted.push('quotes')
       }
 

+ 13 - 2
src/features/vehicles/Actions/deleteVehicle.ts

@@ -6,6 +6,10 @@ import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { revalidatePath } from 'next/cache'
 import { vehicleFileUrls } from '@/lib/files/collect'
 import { releaseFiles } from '@/lib/files/manager'
+import {
+  deleteCustomFieldValuesOf,
+  workOrderIdsOfVehicles,
+} from '@/features/custom-fields/Lib/deleteCustomFieldValues'
 
 export async function deleteVehicle(vehicleId: string) {
   return withAuth(
@@ -13,8 +17,15 @@ export async function deleteVehicle(vehicleId: string) {
       // Its files are read while the rows exist and let go once they are gone:
       // this path used to leave every photo of every job on disk.
       const files = await vehicleFileUrls(organizationId, [vehicleId])
-      const result = await db.vehicle.deleteMany({
-        where: { id: vehicleId, organizationId },
+      // Its work orders go with it by cascade; their custom field values hang
+      // on the work order's id alone and have to be removed by name.
+      const workOrderIds = await workOrderIdsOfVehicles(organizationId, [vehicleId])
+      const result = await db.$transaction(async (tx) => {
+        const deleted = await tx.vehicle.deleteMany({
+          where: { id: vehicleId, organizationId },
+        })
+        await deleteCustomFieldValuesOf(tx, organizationId, 'service_record', workOrderIds)
+        return deleted
       })
       if (result.count === 0) throw new Error('Vehicle not found')
       await releaseFiles(files, { organizationId, reason: 'vehicle deleted' })

+ 3 - 0
src/features/vehicles/Actions/serviceActions.ts

@@ -38,6 +38,7 @@ import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { reconcileInventoryForParts } from '@/features/inventory/Lib/reconcileStock'
 import { assertInvoiceEditable, getDocumentLockSettings } from '@/lib/document-lock.server'
 import { DocumentLockedError, invoiceLockState } from '@/lib/document-lock'
+import { deleteCustomFieldValuesOf } from '@/features/custom-fields/Lib/deleteCustomFieldValues'
 import { typeKeySearch } from '@/features/vehicles/Lib/typeKeySetting'
 import { applyJobReading, jobReadingDate } from '@/features/vehicles/Lib/vehicleReading'
 import { ACTIVE_HELPERS } from '@/features/workboard/Lib/jobTeam'
@@ -1431,6 +1432,8 @@ export async function deleteServiceRecord(recordId: string) {
           serviceRecordLabel: record.invoiceNumber || record.title,
         })
         await tx.serviceRecord.delete({ where: { id: recordId } })
+        // Its custom field values hang on its id alone, so nothing cascades.
+        await deleteCustomFieldValuesOf(tx, organizationId, 'service_record', [recordId])
       })
       await releaseFiles(files, { organizationId, reason: 'work order deleted' })
 

+ 11 - 1
src/features/vehicles/Actions/vehicleActions.ts

@@ -1,5 +1,9 @@
 'use server'
 
+import {
+  deleteCustomFieldValuesOf,
+  workOrderIdsOfVehicles,
+} from '@/features/custom-fields/Lib/deleteCustomFieldValues'
 import {
   INSPECTION_CAPABILITY,
   recordRegistryAnswer,
@@ -437,7 +441,13 @@ export async function deleteVehicle(vehicleId: string) {
       // Everything the delete cascades to, read while it still exists, and
       // let go once the rows are gone.
       const files = await vehicleFileUrls(organizationId, [vehicleId])
-      await db.vehicle.deleteMany({ where: { id: vehicleId, organizationId } })
+      // Its work orders go with it by cascade; their custom field values hang
+      // on the work order's id alone and have to be removed by name.
+      const workOrderIds = await workOrderIdsOfVehicles(organizationId, [vehicleId])
+      await db.$transaction(async (tx) => {
+        await tx.vehicle.deleteMany({ where: { id: vehicleId, organizationId } })
+        await deleteCustomFieldValuesOf(tx, organizationId, 'service_record', workOrderIds)
+      })
       await releaseFiles(files, { organizationId, reason: 'vehicle deleted' })
 
       const vehicleDisplay = `${vehicleName(vehicle)}${vehicle.licensePlate ? ` (${vehicle.licensePlate})` : ''}`

+ 1 - 0
src/features/vehicles/Components/service-page/modern/ModernDetails.tsx

@@ -581,6 +581,7 @@ export function ModernDetails(props: ModernDetailsProps) {
                   <CustomFieldsForm
                     entityId={record.id}
                     entityType="service_record"
+                    locked={locked}
                     onValuesReady={formState.onCustomFieldsReady}
                     onChange={formState.markDirty}
                   />

+ 21 - 3
src/features/vehicles/Components/service-page/useServiceActions.ts

@@ -80,6 +80,7 @@ export function useServiceActions({
     customFieldsSaveRef,
     lastSaveErrorRef,
     leavingRef,
+    autosaveRunRef,
     editRevisionRef,
     markSaved,
   } = formState
@@ -96,6 +97,9 @@ export function useServiceActions({
   const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
     e.preventDefault()
     const form = e.currentTarget
+    // Whether the autosave timer started this save, read once and spent.
+    const autosave = autosaveRunRef.current
+    autosaveRunRef.current = false
     if (isSavingRef.current) return
     if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
     // Running from here: the custom fields go to the server before the rest,
@@ -108,10 +112,24 @@ export function useServiceActions({
     // Validate and save custom fields before saving
     if (customFieldsSaveRef.current) {
       try {
-        const { valid } = await customFieldsSaveRef.current()
-        if (!valid) {
+        // A save the person asked for takes them to the first field at
+        // fault; an autosave marks it and leaves them where they are typing.
+        const outcome = await customFieldsSaveRef.current({ reveal: !autosave })
+        if (!outcome.valid) {
           isSavingRef.current = false
-          refuse(t('page.customFieldsInvalid'))
+          // Nothing of the work order was saved, and the message says so and
+          // names the fields by the workshop's own labels. The server's own
+          // words instead when it refused the whole save (the invoice locked
+          // since the page was opened).
+          refuse(
+            outcome.error ??
+              t(
+                outcome.problem === 'invalid'
+                  ? 'page.customFieldsNotValid'
+                  : 'page.customFieldsMissing',
+                { fields: (outcome.fields ?? []).join(', ') }
+              )
+          )
           return
         }
       } catch (err) {

+ 11 - 2
src/features/vehicles/Components/service-page/useServiceFormState.ts

@@ -23,6 +23,7 @@ import type { ConcernRow } from '../service-edit/form-types'
 import type { ServicePartInput, ServiceLaborInput, InitialData } from './service-page-types'
 import type { ServiceDetail } from '../service-detail/types'
 import { vehicleName as vehicleNameOf } from '@/lib/vehicle-name'
+import type { CustomFieldsSave } from '@/features/custom-fields/Components/CustomFieldsForm'
 
 export function useServiceFormState({
   vehicleId,
@@ -101,6 +102,12 @@ export function useServiceFormState({
    * autosave left without it.
    */
   const editRevisionRef = useRef(0)
+  /**
+   * True for the one save the autosave timer starts. The person is typing
+   * somewhere on the page then, so a refusal is said without taking the
+   * focus away from them; a save they asked for takes them to the field.
+   */
+  const autosaveRunRef = useRef(false)
 
   const markDirty = useCallback(() => {
     // A locked invoice cannot be saved, so nothing may queue an autosave that
@@ -112,6 +119,7 @@ export function useServiceFormState({
     if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
     autosaveTimer.current = setTimeout(() => {
       if (!isSavingRef.current && formRef.current) {
+        autosaveRunRef.current = true
         formRef.current.requestSubmit()
       }
     }, 5000)
@@ -282,9 +290,9 @@ export function useServiceFormState({
   })
 
   // Custom fields save callback ref
-  const customFieldsSaveRef = useRef<(() => Promise<{ valid: boolean }>) | null>(null)
+  const customFieldsSaveRef = useRef<CustomFieldsSave | null>(null)
 
-  const onCustomFieldsReady = useCallback((save: () => Promise<{ valid: boolean }>) => {
+  const onCustomFieldsReady = useCallback((save: CustomFieldsSave) => {
     customFieldsSaveRef.current = save
   }, [])
 
@@ -560,6 +568,7 @@ export function useServiceFormState({
     leaveWithoutSaving,
     lastSaveErrorRef,
     leavingRef,
+    autosaveRunRef,
     // State
     loading,
     setLoading,