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

Warn about duplicate customers and plates, check phone numbers and VINs, and use neutral placeholders (#689)

* Warn about duplicate customers and plates, check phone numbers and VINs, and use neutral placeholders

* Drop a duplicate check's late answer once the field has changed
Bernt Christian Egeland 2 дней назад
Родитель
Сommit
8685e4949c
59 измененных файлов с 1396 добавлено и 56 удалено
  1. 4 2
      e2e/specs/settings/marine.spec.ts
  2. 1 0
      messages/bg/common.json
  3. 7 3
      messages/bg/customers.json
  4. 6 0
      messages/bg/vehicles.json
  5. 1 0
      messages/de/common.json
  6. 7 3
      messages/de/customers.json
  7. 6 0
      messages/de/vehicles.json
  8. 1 0
      messages/en/common.json
  9. 7 3
      messages/en/customers.json
  10. 6 0
      messages/en/vehicles.json
  11. 1 0
      messages/es/common.json
  12. 7 3
      messages/es/customers.json
  13. 6 0
      messages/es/vehicles.json
  14. 1 0
      messages/fr/common.json
  15. 7 3
      messages/fr/customers.json
  16. 6 0
      messages/fr/vehicles.json
  17. 1 0
      messages/it/common.json
  18. 7 3
      messages/it/customers.json
  19. 6 0
      messages/it/vehicles.json
  20. 1 0
      messages/lt/common.json
  21. 7 3
      messages/lt/customers.json
  22. 6 0
      messages/lt/vehicles.json
  23. 1 0
      messages/nb/common.json
  24. 7 3
      messages/nb/customers.json
  25. 6 0
      messages/nb/vehicles.json
  26. 1 0
      messages/nl/common.json
  27. 7 3
      messages/nl/customers.json
  28. 6 0
      messages/nl/vehicles.json
  29. 1 0
      messages/pl/common.json
  30. 7 3
      messages/pl/customers.json
  31. 6 0
      messages/pl/vehicles.json
  32. 1 0
      messages/pt-BR/common.json
  33. 7 3
      messages/pt-BR/customers.json
  34. 6 0
      messages/pt-BR/vehicles.json
  35. 1 0
      messages/pt-PT/common.json
  36. 7 3
      messages/pt-PT/customers.json
  37. 6 0
      messages/pt-PT/vehicles.json
  38. 1 0
      messages/ru/common.json
  39. 7 3
      messages/ru/customers.json
  40. 6 0
      messages/ru/vehicles.json
  41. 1 0
      messages/tr/common.json
  42. 7 3
      messages/tr/customers.json
  43. 6 0
      messages/tr/vehicles.json
  44. 217 0
      src/__tests__/features/customers/customer-duplicates.test.tsx
  45. 152 0
      src/__tests__/features/customers/find-customer-duplicates.test.ts
  46. 250 0
      src/__tests__/features/vehicles/vehicle-duplicates.test.tsx
  47. 10 0
      src/__tests__/features/vehicles/work-order-reading-notices.test.tsx
  48. 64 0
      src/components/duplicate-warning.tsx
  49. 7 1
      src/components/vehicle-picker-dialog.tsx
  50. 82 0
      src/features/customers/Actions/findCustomerDuplicates.ts
  51. 153 4
      src/features/customers/Components/CustomerForm.tsx
  52. 22 0
      src/features/customers/Lib/phoneNumber.ts
  53. 12 1
      src/features/customers/Schema/customerSchema.ts
  54. 72 0
      src/features/vehicles/Actions/findVehiclesWithPlate.ts
  55. 1 1
      src/features/vehicles/Components/ServiceForm.tsx
  56. 113 4
      src/features/vehicles/Components/VehicleForm.tsx
  57. 7 1
      src/features/vehicles/Components/service-page/modern/JobFactsCard.tsx
  58. 22 0
      src/features/vehicles/Lib/vehicleIdentifiers.ts
  59. 12 0
      src/lib/field-errors.ts

+ 4 - 2
e2e/specs/settings/marine.spec.ts

@@ -31,6 +31,8 @@ import { newWorkOrder, saveWorkOrder, seededVehicleUrl } from '../../support/wor
 test.describe.configure({ mode: 'serial', timeout: 180_000 })
 
 const stamp = Date.now()
+// Its own each run: a plate another vessel has is asked about before saving.
+const VESSEL_PLATE = `NB-${String(stamp).slice(-4)}-E`
 const EMAIL = `e2e-marine-${stamp}@example.com`
 const STATE = `e2e/.auth/marine-${stamp}.json`
 const SERVICE_TYPE = 'workshop.serviceType'
@@ -190,7 +192,7 @@ test.describe('a workshop that picks Marine', () => {
     await dialog.locator('#year').fill(VESSEL.year)
     await dialog.locator('#mileage').fill(VESSEL.hours)
     await dialog.locator('#vin').fill(`BWC${stamp}`.slice(0, 12))
-    await dialog.locator('#licensePlate').fill('NB-4521-E')
+    await dialog.locator('#licensePlate').fill(VESSEL_PLATE)
     await dialog.getByRole('button', { name: 'Add New Vessel' }).click()
     await expect(page.getByText('Vehicle added')).toBeVisible({ timeout: 30_000 })
   })
@@ -215,7 +217,7 @@ test.describe('a workshop that picks Marine', () => {
     expect(pdf.flat).not.toContain('Mileage')
     // The vessel's own numbers under a vessel's names.
     expect(pdf.flat).toContain(`HIN: ${`BWC${stamp}`.slice(0, 12)}`)
-    expect(pdf.flat).toContain('Registration: NB-4521-E')
+    expect(pdf.flat).toContain(`Registration: ${VESSEL_PLATE}`)
     expect(pdf.flat).not.toMatch(/\bVIN:|\bPlate:/)
   })
 

+ 1 - 0
messages/bg/common.json

@@ -339,6 +339,7 @@
     "tooLarge": "Трябва да е {limit} или по-малко.",
     "notNumber": "Въведете число.",
     "wholeNumber": "Въведете цяло число.",
+    "phone": "Въведете телефонен номер: само цифри, интервали и + - ( ) .",
     "invalid": "Тази стойност е невалидна.",
     "notSaved": "Не е запазено. Проверете отбелязаните полета.",
     "withLabel": "{label}: {problem}",

+ 7 - 3
messages/bg/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Име *",
     "namePlaceholder": "Иван Иванов",
     "emailPlaceholder": "john@example.com",
-    "phonePlaceholder": "(555) 123-4567",
+    "phonePlaceholder": "Телефонен номер",
     "companyPlaceholder": "Име на фирмата",
-    "addressPlaceholder": "ул. „Главна“ 123, град, област",
+    "addressPlaceholder": "Улица, пощенски код, град",
     "taxId": "Данъчен номер / ДДС номер",
-    "taxIdPlaceholder": "напр. NO123456789MVA, DE123456789",
+    "taxIdPlaceholder": "ДДС или данъчен номер",
+    "duplicateEmail": "Друг клиент има този имейл:",
+    "duplicatePhone": "Друг клиент има този телефонен номер:",
+    "duplicateName": "Вече има клиент с това име:",
+    "duplicateFound": "Това може да е клиент, който вече имате. Проверете маркираните полета или запазете отново, за да го запазите въпреки това.",
     "taxIdHint": "Показва се във фактурите и офертите, когато този клиент е купувачът.",
     "taxExempt": "Освободен от данък",
     "taxExemptHint": "Когато е включено, новите фактури и оферти за този клиент няма да включват данък.",

+ 6 - 0
messages/bg/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Проверка",
     "decodeShort": "Декодиране",
     "vinLength": "{count} от {total} знака",
+    "plateDuplicate": "Друго превозно средство има този регистрационен номер:",
+    "plateDuplicateMarine": "Друга лодка има този регистрационен номер:",
+    "plateDuplicateFound": "Друго превозно средство има този регистрационен номер. Проверете го или запазете отново, за да го запазите въпреки това.",
+    "plateDuplicateFoundMarine": "Друга лодка има този регистрационен номер. Проверете го или запазете отново, за да го запазите въпреки това.",
+    "vinUnusual": "Това не прилича на VIN от 17 знака. Можете да запазите въпреки това.",
+    "duplicateNoOwner": "Без собственик",
     "notSet": "Не е зададено",
     "fromRegistry": "От регистъра",
     "removePhoto": "Премахване на снимката",

+ 1 - 0
messages/de/common.json

@@ -339,6 +339,7 @@
     "tooLarge": "Darf höchstens {limit} sein.",
     "notNumber": "Geben Sie eine Zahl ein.",
     "wholeNumber": "Geben Sie eine ganze Zahl ein.",
+    "phone": "Geben Sie eine Telefonnummer ein: nur Ziffern, Leerzeichen und + - ( ) .",
     "invalid": "Dieser Wert ist ungültig.",
     "notSaved": "Nicht gespeichert. Prüfen Sie die markierten Felder.",
     "withLabel": "{label}: {problem}",

+ 7 - 3
messages/de/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Name *",
     "namePlaceholder": "Max Mustermann",
     "emailPlaceholder": "max@beispiel.de",
-    "phonePlaceholder": "+49 151 12345678",
+    "phonePlaceholder": "Telefonnummer",
     "companyPlaceholder": "Firmenname",
-    "addressPlaceholder": "Musterstraße 1, 12345 Musterstadt",
+    "addressPlaceholder": "Straße, PLZ, Ort",
     "taxId": "Steuer-/USt-IdNr.",
-    "taxIdPlaceholder": "z.B. DE123456789",
+    "taxIdPlaceholder": "USt-IdNr. oder Steuernummer",
+    "duplicateEmail": "Ein anderer Kunde hat diese E-Mail-Adresse:",
+    "duplicatePhone": "Ein anderer Kunde hat diese Telefonnummer:",
+    "duplicateName": "Ein Kunde mit diesem Namen existiert bereits:",
+    "duplicateFound": "Das könnte ein Kunde sein, den Sie schon haben. Prüfen Sie die markierten Felder oder speichern Sie erneut, um ihn trotzdem zu behalten.",
     "taxIdHint": "Wird auf Rechnungen und Angeboten angezeigt, wenn dieser Kunde der Käufer ist.",
     "taxExempt": "Steuerbefreit",
     "taxExemptHint": "Wenn aktiviert, enthalten neue Rechnungen und Angebote für diesen Kunden keine Steuer.",

+ 6 - 0
messages/de/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Abfragen",
     "decodeShort": "Dekodieren",
     "vinLength": "{count} von {total} Zeichen",
+    "plateDuplicate": "Ein anderes Fahrzeug hat dieses Kennzeichen:",
+    "plateDuplicateMarine": "Ein anderes Boot hat diese Registrierungsnummer:",
+    "plateDuplicateFound": "Ein anderes Fahrzeug hat dieses Kennzeichen. Prüfen Sie es oder speichern Sie erneut, um es trotzdem zu behalten.",
+    "plateDuplicateFoundMarine": "Ein anderes Boot hat diese Registrierungsnummer. Prüfen Sie sie oder speichern Sie erneut, um sie trotzdem zu behalten.",
+    "vinUnusual": "Das sieht nicht nach einer 17-stelligen FIN aus. Sie können trotzdem speichern.",
+    "duplicateNoOwner": "Kein Halter",
     "notSet": "Nicht festgelegt",
     "fromRegistry": "Aus dem Register",
     "removePhoto": "Foto entfernen",

+ 1 - 0
messages/en/common.json

@@ -339,6 +339,7 @@
     "tooLarge": "Must be {limit} or less.",
     "notNumber": "Enter a number.",
     "wholeNumber": "Enter a whole number.",
+    "phone": "Enter a phone number: digits, spaces and + - ( ) . only.",
     "invalid": "This value isn't valid.",
     "notSaved": "Not saved. Check the marked fields.",
     "withLabel": "{label}: {problem}",

+ 7 - 3
messages/en/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Name *",
     "namePlaceholder": "John Doe",
     "emailPlaceholder": "john@example.com",
-    "phonePlaceholder": "(555) 123-4567",
+    "phonePlaceholder": "Phone number",
     "companyPlaceholder": "Company name",
-    "addressPlaceholder": "123 Main St, City, State",
+    "addressPlaceholder": "Street, postcode, city",
     "taxId": "Tax / VAT number",
-    "taxIdPlaceholder": "e.g. NO123456789MVA, DE123456789",
+    "taxIdPlaceholder": "VAT or tax number",
+    "duplicateEmail": "Another customer has this email:",
+    "duplicatePhone": "Another customer has this phone number:",
+    "duplicateName": "A customer with this name already exists:",
+    "duplicateFound": "This may be a customer you already have. Check the marked fields, or save again to keep it anyway.",
     "taxIdHint": "Shown on invoices and quotes when this customer is the buyer.",
     "taxExempt": "Tax exempt",
     "taxExemptHint": "When enabled, new invoices and quotes for this customer will not include tax.",

+ 6 - 0
messages/en/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Look up",
     "decodeShort": "Decode",
     "vinLength": "{count} of {total} characters",
+    "plateDuplicate": "Another vehicle has this plate:",
+    "plateDuplicateMarine": "Another boat has this registration number:",
+    "plateDuplicateFound": "Another vehicle has this plate. Check it, or save again to keep it anyway.",
+    "plateDuplicateFoundMarine": "Another boat has this registration number. Check it, or save again to keep it anyway.",
+    "vinUnusual": "This doesn't look like a 17-character VIN. You can still save it.",
+    "duplicateNoOwner": "No owner",
     "notSet": "Not set",
     "fromRegistry": "From the registry",
     "removePhoto": "Remove photo",

+ 1 - 0
messages/es/common.json

@@ -339,6 +339,7 @@
     "tooLarge": "Debe ser {limit} o menos.",
     "notNumber": "Introduce un número.",
     "wholeNumber": "Introduce un número entero.",
+    "phone": "Escribe un número de teléfono: solo dígitos, espacios y + - ( ) .",
     "invalid": "Este valor no es válido.",
     "notSaved": "No se ha guardado. Revisa los campos marcados.",
     "withLabel": "{label}: {problem}",

+ 7 - 3
messages/es/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Nombre *",
     "namePlaceholder": "Juan García",
     "emailPlaceholder": "juan@ejemplo.com",
-    "phonePlaceholder": "(55) 1234-5678",
+    "phonePlaceholder": "Número de teléfono",
     "companyPlaceholder": "Nombre de la empresa",
-    "addressPlaceholder": "Calle Principal 123, Ciudad, Estado",
+    "addressPlaceholder": "Calle, código postal, ciudad",
     "taxId": "NIF / CIF",
-    "taxIdPlaceholder": "p. ej. ESB12345678",
+    "taxIdPlaceholder": "Número de IVA o fiscal",
+    "duplicateEmail": "Otro cliente tiene este correo:",
+    "duplicatePhone": "Otro cliente tiene este número de teléfono:",
+    "duplicateName": "Ya existe un cliente con este nombre:",
+    "duplicateFound": "Puede que ya tengas este cliente. Revisa los campos marcados o guarda de nuevo para conservarlo de todos modos.",
     "taxIdHint": "Se muestra en facturas y presupuestos cuando este cliente es el comprador.",
     "taxExempt": "Exento de impuestos",
     "taxExemptHint": "Cuando está activado, las nuevas facturas y presupuestos para este cliente no incluirán impuesto.",

+ 6 - 0
messages/es/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Buscar",
     "decodeShort": "Decodificar",
     "vinLength": "{count} de {total} caracteres",
+    "plateDuplicate": "Otro vehículo tiene esta placa:",
+    "plateDuplicateMarine": "Otra embarcación tiene este número de registro:",
+    "plateDuplicateFound": "Otro vehículo tiene esta placa. Revísala o guarda de nuevo para conservarla de todos modos.",
+    "plateDuplicateFoundMarine": "Otra embarcación tiene este número de registro. Revísalo o guarda de nuevo para conservarlo de todos modos.",
+    "vinUnusual": "Esto no parece un VIN de 17 caracteres. Puedes guardarlo igualmente.",
+    "duplicateNoOwner": "Sin propietario",
     "notSet": "Sin definir",
     "fromRegistry": "Del registro",
     "removePhoto": "Quitar foto",

+ 1 - 0
messages/fr/common.json

@@ -339,6 +339,7 @@
     "tooLarge": "Doit être {limit} ou moins.",
     "notNumber": "Saisissez un nombre.",
     "wholeNumber": "Saisissez un nombre entier.",
+    "phone": "Saisissez un numéro de téléphone : chiffres, espaces et + - ( ) . uniquement.",
     "invalid": "Cette valeur n'est pas valide.",
     "notSaved": "Non enregistré. Vérifiez les champs signalés.",
     "withLabel": "{label} : {problem}",

+ 7 - 3
messages/fr/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Nom *",
     "namePlaceholder": "Jean Dupont",
     "emailPlaceholder": "jean@exemple.fr",
-    "phonePlaceholder": "01 23 45 67 89",
+    "phonePlaceholder": "Numéro de téléphone",
     "companyPlaceholder": "Nom de l'entreprise",
-    "addressPlaceholder": "12 rue de la Paix, 75001 Paris",
+    "addressPlaceholder": "Rue, code postal, ville",
     "taxId": "Numéro TVA",
-    "taxIdPlaceholder": "p. ex. FR12345678901",
+    "taxIdPlaceholder": "Numéro de TVA ou fiscal",
+    "duplicateEmail": "Un autre client a cet e-mail :",
+    "duplicatePhone": "Un autre client a ce numéro de téléphone :",
+    "duplicateName": "Un client portant ce nom existe déjà :",
+    "duplicateFound": "Ce client existe peut-être déjà. Vérifiez les champs signalés, ou enregistrez à nouveau pour le garder quand même.",
     "taxIdHint": "Affiché sur les factures et devis lorsque ce client est l acheteur.",
     "taxExempt": "Exonéré de taxe",
     "taxExemptHint": "Lorsque activé, les nouvelles factures et devis pour ce client n incluront pas de taxe.",

+ 6 - 0
messages/fr/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Rechercher",
     "decodeShort": "Décoder",
     "vinLength": "{count} sur {total} caractères",
+    "plateDuplicate": "Un autre véhicule a cette plaque :",
+    "plateDuplicateMarine": "Un autre bateau a ce numéro d'immatriculation :",
+    "plateDuplicateFound": "Un autre véhicule a cette plaque. Vérifiez-la, ou enregistrez à nouveau pour la garder quand même.",
+    "plateDuplicateFoundMarine": "Un autre bateau a ce numéro d'immatriculation. Vérifiez-le, ou enregistrez à nouveau pour le garder quand même.",
+    "vinUnusual": "Cela ne ressemble pas à un NIV de 17 caractères. Vous pouvez quand même enregistrer.",
+    "duplicateNoOwner": "Sans propriétaire",
     "notSet": "Non défini",
     "fromRegistry": "D'après le registre",
     "removePhoto": "Supprimer la photo",

+ 1 - 0
messages/it/common.json

@@ -339,6 +339,7 @@
     "tooLarge": "Deve essere {limit} o meno.",
     "notNumber": "Inserisci un numero.",
     "wholeNumber": "Inserisci un numero intero.",
+    "phone": "Inserisci un numero di telefono: solo cifre, spazi e + - ( ) .",
     "invalid": "Questo valore non è valido.",
     "notSaved": "Non salvato. Controlla i campi evidenziati.",
     "withLabel": "{label}: {problem}",

+ 7 - 3
messages/it/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Nome *",
     "namePlaceholder": "Mario Rossi",
     "emailPlaceholder": "mario@esempio.it",
-    "phonePlaceholder": "333 1234567",
+    "phonePlaceholder": "Numero di telefono",
     "companyPlaceholder": "Nome azienda",
-    "addressPlaceholder": "Via Roma 1, 00100 Roma",
+    "addressPlaceholder": "Via, CAP, città",
     "taxId": "Partita IVA / CF",
-    "taxIdPlaceholder": "es. IT12345678901",
+    "taxIdPlaceholder": "Partita IVA o codice fiscale",
+    "duplicateEmail": "Un altro cliente ha questa email:",
+    "duplicatePhone": "Un altro cliente ha questo numero di telefono:",
+    "duplicateName": "Esiste già un cliente con questo nome:",
+    "duplicateFound": "Potrebbe essere un cliente che hai già. Controlla i campi segnalati o salva di nuovo per tenerlo comunque.",
     "taxIdHint": "Mostrato su fatture e preventivi quando questo cliente è l acquirente.",
     "taxExempt": "Esente da imposta",
     "taxExemptHint": "Quando abilitato, le nuove fatture e preventivi per questo cliente non includeranno l imposta.",

+ 6 - 0
messages/it/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Cerca",
     "decodeShort": "Decodifica",
     "vinLength": "{count} di {total} caratteri",
+    "plateDuplicate": "Un altro veicolo ha questa targa:",
+    "plateDuplicateMarine": "Un'altra imbarcazione ha questo numero di registrazione:",
+    "plateDuplicateFound": "Un altro veicolo ha questa targa. Controllala o salva di nuovo per tenerla comunque.",
+    "plateDuplicateFoundMarine": "Un'altra imbarcazione ha questo numero di registrazione. Controllalo o salva di nuovo per tenerlo comunque.",
+    "vinUnusual": "Non sembra un VIN di 17 caratteri. Puoi salvarlo comunque.",
+    "duplicateNoOwner": "Nessun proprietario",
     "notSet": "Non impostata",
     "fromRegistry": "Dal registro",
     "removePhoto": "Rimuovi foto",

+ 1 - 0
messages/lt/common.json

@@ -339,6 +339,7 @@
     "tooLarge": "Turi būti {limit} arba mažiau.",
     "notNumber": "Įveskite skaičių.",
     "wholeNumber": "Įveskite sveikąjį skaičių.",
+    "phone": "Įveskite telefono numerį: tik skaitmenys, tarpai ir + - ( ) .",
     "invalid": "Ši reikšmė netinkama.",
     "notSaved": "Neišsaugota. Patikrinkite pažymėtus laukus.",
     "withLabel": "{label}: {problem}",

+ 7 - 3
messages/lt/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Vardas *",
     "namePlaceholder": "Jonas Jonaitis",
     "emailPlaceholder": "jonas@example.com",
-    "phonePlaceholder": "+370 600 12345",
+    "phonePlaceholder": "Telefono numeris",
     "companyPlaceholder": "Įmonės pavadinimas",
-    "addressPlaceholder": "Gatvės g. 1, Miestas",
+    "addressPlaceholder": "Gatvė, pašto kodas, miestas",
     "taxId": "PVM kodas",
-    "taxIdPlaceholder": "pvz. LT123456789",
+    "taxIdPlaceholder": "PVM arba mokesčių kodas",
+    "duplicateEmail": "Kitas klientas turi šį el. paštą:",
+    "duplicatePhone": "Kitas klientas turi šį telefono numerį:",
+    "duplicateName": "Klientas tokiu vardu jau yra:",
+    "duplicateFound": "Galbūt šis klientas jau yra. Patikrinkite pažymėtus laukus arba išsaugokite dar kartą, kad vis tiek išsaugotumėte.",
     "taxIdHint": "Rodomas sąskaitose ir pasiūlymuose, kai šis klientas yra pirkėjas.",
     "taxExempt": "Atleistas nuo mokesčio",
     "taxExemptHint": "Kai įjungta, naujose sąskaitose ir pasiūlymuose šiam klientui nebus pridėtas mokestis.",

+ 6 - 0
messages/lt/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Ieškoti",
     "decodeShort": "Dekoduoti",
     "vinLength": "{count} iš {total} simbolių",
+    "plateDuplicate": "Kita transporto priemonė turi šį numerį:",
+    "plateDuplicateMarine": "Kitas laivas turi šį registracijos numerį:",
+    "plateDuplicateFound": "Kita transporto priemonė turi šį numerį. Patikrinkite jį arba išsaugokite dar kartą, kad vis tiek išsaugotumėte.",
+    "plateDuplicateFoundMarine": "Kitas laivas turi šį registracijos numerį. Patikrinkite jį arba išsaugokite dar kartą, kad vis tiek išsaugotumėte.",
+    "vinUnusual": "Tai nepanašu į 17 simbolių VIN. Vis tiek galite išsaugoti.",
+    "duplicateNoOwner": "Be savininko",
     "notSet": "Nenustatyta",
     "fromRegistry": "Iš registro",
     "removePhoto": "Pašalinti nuotrauką",

+ 1 - 0
messages/nb/common.json

@@ -339,6 +339,7 @@
     "tooLarge": "Må være {limit} eller mindre.",
     "notNumber": "Skriv inn et tall.",
     "wholeNumber": "Skriv inn et heltall.",
+    "phone": "Skriv et telefonnummer: bare sifre, mellomrom og + - ( ) .",
     "invalid": "Denne verdien er ikke gyldig.",
     "notSaved": "Ikke lagret. Sjekk de merkede feltene.",
     "withLabel": "{label}: {problem}",

+ 7 - 3
messages/nb/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Navn *",
     "namePlaceholder": "Ola Nordmann",
     "emailPlaceholder": "ola@eksempel.no",
-    "phonePlaceholder": "123 45 678",
+    "phonePlaceholder": "Telefonnummer",
     "companyPlaceholder": "Bedriftsnavn",
-    "addressPlaceholder": "Storgata 1, 0001 Oslo",
+    "addressPlaceholder": "Gate, postnummer, sted",
     "taxId": "Org.nr / MVA-nr",
-    "taxIdPlaceholder": "f.eks. NO123456789MVA",
+    "taxIdPlaceholder": "MVA- eller org.nummer",
+    "duplicateEmail": "En annen kunde har denne e-postadressen:",
+    "duplicatePhone": "En annen kunde har dette telefonnummeret:",
+    "duplicateName": "Det finnes allerede en kunde med dette navnet:",
+    "duplicateFound": "Dette kan være en kunde du allerede har. Sjekk de merkede feltene, eller lagre igjen for å beholde den likevel.",
     "taxIdHint": "Vises på fakturaer og tilbud når denne kunden er kjøper.",
     "taxExempt": "Avgiftsfritatt",
     "taxExemptHint": "Når dette er på, vil nye fakturaer og tilbud for denne kunden ikke inneholde avgift.",

+ 6 - 0
messages/nb/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Slå opp",
     "decodeShort": "Dekode",
     "vinLength": "{count} av {total} tegn",
+    "plateDuplicate": "Et annet kjøretøy har dette registreringsnummeret:",
+    "plateDuplicateMarine": "En annen båt har dette registreringsnummeret:",
+    "plateDuplicateFound": "Et annet kjøretøy har dette registreringsnummeret. Sjekk det, eller lagre igjen for å beholde det likevel.",
+    "plateDuplicateFoundMarine": "En annen båt har dette registreringsnummeret. Sjekk det, eller lagre igjen for å beholde det likevel.",
+    "vinUnusual": "Dette ser ikke ut som et VIN på 17 tegn. Du kan likevel lagre.",
+    "duplicateNoOwner": "Ingen eier",
     "notSet": "Ikke satt",
     "fromRegistry": "Fra registeret",
     "removePhoto": "Fjern bilde",

+ 1 - 0
messages/nl/common.json

@@ -339,6 +339,7 @@
     "tooLarge": "Moet {limit} of minder zijn.",
     "notNumber": "Vul een getal in.",
     "wholeNumber": "Vul een heel getal in.",
+    "phone": "Vul een telefoonnummer in: alleen cijfers, spaties en + - ( ) .",
     "invalid": "Deze waarde is niet geldig.",
     "notSaved": "Niet opgeslagen. Controleer de gemarkeerde velden.",
     "withLabel": "{label}: {problem}",

+ 7 - 3
messages/nl/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Naam *",
     "namePlaceholder": "Jan de Vries",
     "emailPlaceholder": "jan@voorbeeld.nl",
-    "phonePlaceholder": "06 12345678",
+    "phonePlaceholder": "Telefoonnummer",
     "companyPlaceholder": "Bedrijfsnaam",
-    "addressPlaceholder": "Hoofdstraat 1, 1000 AA Amsterdam",
+    "addressPlaceholder": "Straat, postcode, plaats",
     "taxId": "Btw-nummer",
-    "taxIdPlaceholder": "bijv. NL123456789B01",
+    "taxIdPlaceholder": "Btw- of belastingnummer",
+    "duplicateEmail": "Een andere klant heeft dit e-mailadres:",
+    "duplicatePhone": "Een andere klant heeft dit telefoonnummer:",
+    "duplicateName": "Er bestaat al een klant met deze naam:",
+    "duplicateFound": "Dit is misschien een klant die u al heeft. Controleer de gemarkeerde velden, of sla opnieuw op om toch te bewaren.",
     "taxIdHint": "Wordt weergegeven op facturen en offertes wanneer deze klant de koper is.",
     "taxExempt": "Belastingvrijgesteld",
     "taxExemptHint": "Wanneer ingeschakeld, bevatten nieuwe facturen en offertes voor deze klant geen belasting.",

+ 6 - 0
messages/nl/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Opzoeken",
     "decodeShort": "Decoderen",
     "vinLength": "{count} van {total} tekens",
+    "plateDuplicate": "Een ander voertuig heeft dit kenteken:",
+    "plateDuplicateMarine": "Een andere boot heeft dit registratienummer:",
+    "plateDuplicateFound": "Een ander voertuig heeft dit kenteken. Controleer het, of sla opnieuw op om toch te bewaren.",
+    "plateDuplicateFoundMarine": "Een andere boot heeft dit registratienummer. Controleer het, of sla opnieuw op om toch te bewaren.",
+    "vinUnusual": "Dit lijkt geen VIN van 17 tekens. U kunt het toch opslaan.",
+    "duplicateNoOwner": "Geen eigenaar",
     "notSet": "Niet ingesteld",
     "fromRegistry": "Uit het register",
     "removePhoto": "Foto verwijderen",

+ 1 - 0
messages/pl/common.json

@@ -339,6 +339,7 @@
     "tooLarge": "Musi wynosić {limit} lub mniej.",
     "notNumber": "Wpisz liczbę.",
     "wholeNumber": "Wpisz liczbę całkowitą.",
+    "phone": "Wpisz numer telefonu: tylko cyfry, spacje i + - ( ) .",
     "invalid": "Ta wartość jest nieprawidłowa.",
     "notSaved": "Nie zapisano. Sprawdź zaznaczone pola.",
     "withLabel": "{label}: {problem}",

+ 7 - 3
messages/pl/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Imię i nazwisko *",
     "namePlaceholder": "Jan Kowalski",
     "emailPlaceholder": "jan@przyklad.pl",
-    "phonePlaceholder": "123 456 789",
+    "phonePlaceholder": "Numer telefonu",
     "companyPlaceholder": "Nazwa firmy",
-    "addressPlaceholder": "ul. Główna 1, 00-001 Warszawa",
+    "addressPlaceholder": "Ulica, kod pocztowy, miasto",
     "taxId": "NIP",
-    "taxIdPlaceholder": "np. PL1234567890",
+    "taxIdPlaceholder": "Numer VAT lub podatkowy",
+    "duplicateEmail": "Inny klient ma ten adres e-mail:",
+    "duplicatePhone": "Inny klient ma ten numer telefonu:",
+    "duplicateName": "Klient o tej nazwie już istnieje:",
+    "duplicateFound": "To może być klient, którego już masz. Sprawdź oznaczone pola lub zapisz ponownie, aby mimo to zachować.",
     "taxIdHint": "Wyświetlany na fakturach i ofertach, gdy ten klient jest nabywcą.",
     "taxExempt": "Zwolniony z podatku",
     "taxExemptHint": "Gdy włączone, nowe faktury i oferty dla tego klienta nie będą zawierać podatku.",

+ 6 - 0
messages/pl/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Sprawdź",
     "decodeShort": "Dekoduj",
     "vinLength": "{count} z {total} znaków",
+    "plateDuplicate": "Inny pojazd ma ten numer rejestracyjny:",
+    "plateDuplicateMarine": "Inna łódź ma ten numer rejestracyjny:",
+    "plateDuplicateFound": "Inny pojazd ma ten numer rejestracyjny. Sprawdź go lub zapisz ponownie, aby mimo to zachować.",
+    "plateDuplicateFoundMarine": "Inna łódź ma ten numer rejestracyjny. Sprawdź go lub zapisz ponownie, aby mimo to zachować.",
+    "vinUnusual": "To nie wygląda na 17-znakowy VIN. Możesz mimo to zapisać.",
+    "duplicateNoOwner": "Brak właściciela",
     "notSet": "Nie ustawiono",
     "fromRegistry": "Z rejestru",
     "removePhoto": "Usuń zdjęcie",

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

@@ -339,6 +339,7 @@
     "tooLarge": "Deve ser {limit} ou menos.",
     "notNumber": "Digite um número.",
     "wholeNumber": "Digite um número inteiro.",
+    "phone": "Digite um número de telefone: apenas dígitos, espaços e + - ( ) .",
     "invalid": "Este valor não é válido.",
     "notSaved": "Não salvo. Verifique os campos marcados.",
     "withLabel": "{label}: {problem}",

+ 7 - 3
messages/pt-BR/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Nome *",
     "namePlaceholder": "João Silva",
     "emailPlaceholder": "joão@exemplo.com.br",
-    "phonePlaceholder": "(11) 91234-5678",
+    "phonePlaceholder": "Número de telefone",
     "companyPlaceholder": "Nome da empresa",
-    "addressPlaceholder": "Rua Principal 123, São Paulo, SP",
+    "addressPlaceholder": "Rua, CEP, cidade",
     "taxId": "CNPJ / CPF",
-    "taxIdPlaceholder": "ex. 12.345.678/0001-90",
+    "taxIdPlaceholder": "Número fiscal ou de IVA",
+    "duplicateEmail": "Outro cliente tem este e-mail:",
+    "duplicatePhone": "Outro cliente tem este telefone:",
+    "duplicateName": "Já existe um cliente com este nome:",
+    "duplicateFound": "Este pode ser um cliente que você já tem. Confira os campos marcados ou salve de novo para manter assim mesmo.",
     "taxIdHint": "Exibido em faturas e orçamentos quando este cliente é o comprador.",
     "taxExempt": "Isento de imposto",
     "taxExemptHint": "Quando ativado, novas faturas e orçamentos para este cliente não incluirão imposto.",

+ 6 - 0
messages/pt-BR/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Consultar",
     "decodeShort": "Decodificar",
     "vinLength": "{count} de {total} caracteres",
+    "plateDuplicate": "Outro veículo tem esta placa:",
+    "plateDuplicateMarine": "Outra embarcação tem este número de registro:",
+    "plateDuplicateFound": "Outro veículo tem esta placa. Confira ou salve de novo para manter assim mesmo.",
+    "plateDuplicateFoundMarine": "Outra embarcação tem este número de registro. Confira ou salve de novo para manter assim mesmo.",
+    "vinUnusual": "Isto não parece um chassi (VIN) de 17 caracteres. Você ainda pode salvar.",
+    "duplicateNoOwner": "Sem proprietário",
     "notSet": "Não definida",
     "fromRegistry": "Do registro",
     "removePhoto": "Remover foto",

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

@@ -339,6 +339,7 @@
     "tooLarge": "Tem de ser {limit} ou menos.",
     "notNumber": "Introduza um número.",
     "wholeNumber": "Introduza um número inteiro.",
+    "phone": "Introduza um número de telefone: apenas dígitos, espaços e + - ( ) .",
     "invalid": "Este valor não é válido.",
     "notSaved": "Não guardado. Verifique os campos assinalados.",
     "withLabel": "{label}: {problem}",

+ 7 - 3
messages/pt-PT/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Nome *",
     "namePlaceholder": "João Silva",
     "emailPlaceholder": "joao@exemplo.pt",
-    "phonePlaceholder": "912 345 678",
+    "phonePlaceholder": "Número de telefone",
     "companyPlaceholder": "Nome da empresa",
-    "addressPlaceholder": "Rua Principal 123, 1000-001 Lisboa",
+    "addressPlaceholder": "Rua, código postal, localidade",
     "taxId": "NIF",
-    "taxIdPlaceholder": "ex.: 123456789 ou PT123456789",
+    "taxIdPlaceholder": "Número de IVA ou fiscal",
+    "duplicateEmail": "Outro cliente tem este email:",
+    "duplicatePhone": "Outro cliente tem este telefone:",
+    "duplicateName": "Já existe um cliente com este nome:",
+    "duplicateFound": "Este pode ser um cliente que já tem. Verifique os campos assinalados ou guarde novamente para o manter na mesma.",
     "taxIdHint": "Apresentado nas faturas e orçamentos quando este cliente é o adquirente.",
     "taxExempt": "Isento de IVA",
     "taxExemptHint": "Quando ativado, as novas faturas e orçamentos deste cliente não incluem IVA.",

+ 6 - 0
messages/pt-PT/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Consultar",
     "decodeShort": "Descodificar",
     "vinLength": "{count} de {total} caracteres",
+    "plateDuplicate": "Outro veículo tem esta matrícula:",
+    "plateDuplicateMarine": "Outra embarcação tem este número de registo:",
+    "plateDuplicateFound": "Outro veículo tem esta matrícula. Verifique-a ou guarde novamente para a manter na mesma.",
+    "plateDuplicateFoundMarine": "Outra embarcação tem este número de registo. Verifique-o ou guarde novamente para o manter na mesma.",
+    "vinUnusual": "Isto não parece um VIN de 17 caracteres. Pode guardar na mesma.",
+    "duplicateNoOwner": "Sem proprietário",
     "notSet": "Não definida",
     "fromRegistry": "Do registo automóvel",
     "removePhoto": "Remover fotografia",

+ 1 - 0
messages/ru/common.json

@@ -339,6 +339,7 @@
     "tooLarge": "Должно быть не больше {limit}.",
     "notNumber": "Введите число.",
     "wholeNumber": "Введите целое число.",
+    "phone": "Введите номер телефона: только цифры, пробелы и + - ( ) .",
     "invalid": "Недопустимое значение.",
     "notSaved": "Не сохранено. Проверьте отмеченные поля.",
     "withLabel": "{label}: {problem}",

+ 7 - 3
messages/ru/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Имя *",
     "namePlaceholder": "Иван Иванов",
     "emailPlaceholder": "ivan@example.com",
-    "phonePlaceholder": "+7 (999) 123-45-67",
+    "phonePlaceholder": "Номер телефона",
     "companyPlaceholder": "Название компании",
-    "addressPlaceholder": "ул. Главная, 123, Москва",
+    "addressPlaceholder": "Улица, индекс, город",
     "taxId": "ИНН / КПП",
-    "taxIdPlaceholder": "напр. 7707083893",
+    "taxIdPlaceholder": "НДС или налоговый номер",
+    "duplicateEmail": "У другого клиента такой же email:",
+    "duplicatePhone": "У другого клиента такой же номер телефона:",
+    "duplicateName": "Клиент с таким именем уже есть:",
+    "duplicateFound": "Возможно, этот клиент у вас уже есть. Проверьте отмеченные поля или сохраните ещё раз, чтобы всё равно оставить.",
     "taxIdHint": "Отображается в счетах и коммерческих предложениях, когда этот клиент является покупателем.",
     "taxExempt": "Освобожден от налога",
     "taxExemptHint": "Когда включено, новые счета и коммерческие предложения для этого клиента не будут содержать налог.",

+ 6 - 0
messages/ru/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Найти",
     "decodeShort": "Расшифровать",
     "vinLength": "{count} из {total} символов",
+    "plateDuplicate": "У другого автомобиля такой же госномер:",
+    "plateDuplicateMarine": "У другого судна такой же регистрационный номер:",
+    "plateDuplicateFound": "У другого автомобиля такой же госномер. Проверьте его или сохраните ещё раз, чтобы всё равно оставить.",
+    "plateDuplicateFoundMarine": "У другого судна такой же регистрационный номер. Проверьте его или сохраните ещё раз, чтобы всё равно оставить.",
+    "vinUnusual": "Это не похоже на VIN из 17 символов. Сохранить всё равно можно.",
+    "duplicateNoOwner": "Без владельца",
     "notSet": "Не указано",
     "fromRegistry": "Из реестра",
     "removePhoto": "Удалить фото",

+ 1 - 0
messages/tr/common.json

@@ -339,6 +339,7 @@
     "tooLarge": "{limit} veya daha az olmalı.",
     "notNumber": "Bir sayı girin.",
     "wholeNumber": "Tam sayı girin.",
+    "phone": "Bir telefon numarası girin: yalnızca rakam, boşluk ve + - ( ) .",
     "invalid": "Bu değer geçerli değil.",
     "notSaved": "Kaydedilmedi. İşaretli alanları kontrol edin.",
     "withLabel": "{label}: {problem}",

+ 7 - 3
messages/tr/customers.json

@@ -82,11 +82,15 @@
     "nameRequired": "Ad Soyad *",
     "namePlaceholder": "Ahmet Yılmaz",
     "emailPlaceholder": "ahmet@ornek.com.tr",
-    "phonePlaceholder": "0532 123 4567",
+    "phonePlaceholder": "Telefon numarası",
     "companyPlaceholder": "Şirket adı",
-    "addressPlaceholder": "Atatürk Cad. No:1, 34000 İstanbul",
+    "addressPlaceholder": "Sokak, posta kodu, şehir",
     "taxId": "Vergi numarası",
-    "taxIdPlaceholder": "örn. 1234567890",
+    "taxIdPlaceholder": "KDV veya vergi numarası",
+    "duplicateEmail": "Başka bir müşteri bu e-postaya sahip:",
+    "duplicatePhone": "Başka bir müşteri bu telefon numarasına sahip:",
+    "duplicateName": "Bu adla bir müşteri zaten var:",
+    "duplicateFound": "Bu zaten kayıtlı bir müşteri olabilir. İşaretli alanları kontrol edin veya yine de tutmak için tekrar kaydedin.",
     "taxIdHint": "Bu müşteri alıcı olduğunda faturalar ve tekliflerde gösterilir.",
     "taxExempt": "Vergiden muaf",
     "taxExemptHint": "Etkinleştirildiğinde, bu müşteri için yeni faturalar ve teklifler vergi içermez.",

+ 6 - 0
messages/tr/vehicles.json

@@ -465,6 +465,12 @@
     "lookupShort": "Sorgula",
     "decodeShort": "Çözümle",
     "vinLength": "{total} karakterden {count} tanesi",
+    "plateDuplicate": "Başka bir araç bu plakaya sahip:",
+    "plateDuplicateMarine": "Başka bir tekne bu tescil numarasına sahip:",
+    "plateDuplicateFound": "Başka bir araç bu plakaya sahip. Kontrol edin veya yine de tutmak için tekrar kaydedin.",
+    "plateDuplicateFoundMarine": "Başka bir tekne bu tescil numarasına sahip. Kontrol edin veya yine de tutmak için tekrar kaydedin.",
+    "vinUnusual": "Bu 17 karakterlik bir VIN'e benzemiyor. Yine de kaydedebilirsiniz.",
+    "duplicateNoOwner": "Sahibi yok",
     "notSet": "Belirlenmedi",
     "fromRegistry": "Sicilden alındı",
     "removePhoto": "Fotoğrafı kaldır",

+ 217 - 0
src/__tests__/features/customers/customer-duplicates.test.tsx

@@ -0,0 +1,217 @@
+/**
+ * The customer form says when another customer of the workshop already has
+ * the email, the phone number or the name being typed, names them with a
+ * link and lets the person save anyway. A phone number with letters in it
+ * is refused under the field. The placeholders name what goes in a field
+ * rather than an American example.
+ */
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ refresh: vi.fn(), push: vi.fn(), replace: vi.fn() }),
+  usePathname: () => '/customers',
+  useSearchParams: () => new URLSearchParams(),
+}))
+vi.mock('@/components/glass-modal', () => ({ useGlassModal: () => ({ open: vi.fn() }) }))
+vi.mock('@/lib/analytics', () => ({ track: vi.fn() }))
+vi.mock('sonner', () => ({
+  toast: { error: vi.fn(), success: vi.fn(), loading: vi.fn(), warning: vi.fn() },
+}))
+vi.mock('@/features/invoice-designer/Actions/documentDesignActions', () => ({
+  listDesignOptions: vi.fn(async () => ({ success: true, data: [] })),
+}))
+vi.mock('@/features/customers/Actions/customerActions', () => ({
+  createCustomer: vi.fn(),
+  updateCustomer: vi.fn(),
+}))
+vi.mock('@/features/customers/Actions/findCustomerDuplicates', () => ({
+  findCustomerDuplicates: vi.fn(),
+}))
+vi.mock('@/features/vehicles/Actions/vehicleActions', () => ({ createVehicle: vi.fn() }))
+vi.mock('@/features/vehicles/Components/ScanDocumentButton', () => ({
+  ScanDocumentButton: () => null,
+}))
+
+import { toast } from 'sonner'
+import { TooltipProvider } from '@/components/ui/tooltip'
+import { CustomerForm } from '@/features/customers/Components/CustomerForm'
+import { createCustomer, updateCustomer } from '@/features/customers/Actions/customerActions'
+import { findCustomerDuplicates } from '@/features/customers/Actions/findCustomerDuplicates'
+
+const NONE = { email: [], phone: [], name: [] }
+const KARI = { id: 'cust-kari', name: 'ZZ Kari Testvik', company: 'ZZ Testvik AS' }
+
+function renderForm(customer?: React.ComponentProps<typeof CustomerForm>['customer']) {
+  const onOpenChange = vi.fn()
+  render(
+    <TooltipProvider>
+      <CustomerForm open onOpenChange={onOpenChange} customer={customer} />
+    </TooltipProvider>
+  )
+  return { onOpenChange }
+}
+
+const submit = async () => {
+  const form = screen.getByRole('dialog').querySelector('form') as HTMLFormElement
+  await act(async () => {
+    fireEvent.submit(form)
+  })
+}
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  const nothing = () => undefined
+  globalThis.ResizeObserver = class {
+    observe = nothing
+    unobserve = nothing
+    disconnect = nothing
+  }
+  vi.mocked(findCustomerDuplicates).mockResolvedValue({ success: true, data: NONE })
+  vi.mocked(createCustomer).mockResolvedValue({
+    success: true,
+    data: { id: 'cust-new', name: 'ZZ Kari Testvik', company: null },
+  } as never)
+})
+
+describe('another customer with the same details', () => {
+  it('names them under the email with a link, once the field is left', async () => {
+    vi.mocked(findCustomerDuplicates).mockResolvedValue({
+      success: true,
+      data: { ...NONE, email: [KARI] },
+    })
+    renderForm()
+    const email = screen.getByLabelText('Email')
+    fireEvent.change(email, { target: { value: 'kari@testvik.example' } })
+    fireEvent.blur(email)
+
+    expect(await screen.findByText('Another customer has this email:')).toBeInTheDocument()
+    const link = screen.getByRole('link', { name: 'ZZ Kari Testvik (ZZ Testvik AS)' })
+    expect(link).toHaveAttribute('href', '/customers/cust-kari')
+    // A new tab, so what was typed here is not lost.
+    expect(link).toHaveAttribute('target', '_blank')
+    expect(email).toHaveAccessibleDescription(/Another customer has this email/)
+    expect(findCustomerDuplicates).toHaveBeenCalledWith(
+      expect.objectContaining({ email: 'kari@testvik.example' })
+    )
+  })
+
+  it('does not put a late answer about an earlier email under the new one', async () => {
+    let answer: (value: unknown) => void = () => undefined
+    vi.mocked(findCustomerDuplicates).mockImplementationOnce(
+      () => new Promise((resolve) => (answer = resolve)) as never
+    )
+    renderForm()
+    const email = screen.getByLabelText('Email')
+    fireEvent.change(email, { target: { value: 'kari@testvik.example' } })
+    fireEvent.blur(email)
+    // Changed again while the first check is still out.
+    fireEvent.change(email, { target: { value: 'someone.else@testvik.example' } })
+    await act(async () => {
+      answer({ success: true, data: { ...NONE, email: [KARI] } })
+    })
+    expect(screen.queryByText('Another customer has this email:')).not.toBeInTheDocument()
+    expect(screen.queryByRole('link', { name: /ZZ Kari Testvik/ })).not.toBeInTheDocument()
+
+    // The new value is asked about on its own when the field is left.
+    fireEvent.blur(email)
+    expect(findCustomerDuplicates).toHaveBeenLastCalledWith(
+      expect.objectContaining({ email: 'someone.else@testvik.example' })
+    )
+  })
+
+  it('stops the first save to show them, and saves on the second', async () => {
+    vi.mocked(findCustomerDuplicates).mockResolvedValue({
+      success: true,
+      data: { ...NONE, name: [KARI], phone: [KARI] },
+    })
+    const { onOpenChange } = renderForm()
+    fireEvent.change(screen.getByLabelText('Name *'), { target: { value: 'ZZ Kari Testvik' } })
+    fireEvent.change(screen.getByLabelText('Phone'), { target: { value: '+00 912 34 567' } })
+
+    await submit()
+    expect(createCustomer).not.toHaveBeenCalled()
+    expect(toast.warning).toHaveBeenCalledWith(
+      'This may be a customer you already have. Check the marked fields, or save again to keep it anyway.'
+    )
+    expect(screen.getByText('A customer with this name already exists:')).toBeInTheDocument()
+    expect(screen.getByText('Another customer has this phone number:')).toBeInTheDocument()
+
+    await submit()
+    expect(createCustomer).toHaveBeenCalledTimes(1)
+    await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false))
+  })
+
+  it('saves straight away when nobody matches', async () => {
+    renderForm()
+    fireEvent.change(screen.getByLabelText('Name *'), { target: { value: 'ZZ Unique Person' } })
+    await submit()
+    expect(createCustomer).toHaveBeenCalledTimes(1)
+    expect(toast.warning).not.toHaveBeenCalled()
+  })
+
+  it('saves anyway when the check fails', async () => {
+    vi.mocked(findCustomerDuplicates).mockRejectedValue(new Error('offline'))
+    renderForm()
+    fireEvent.change(screen.getByLabelText('Name *'), { target: { value: 'ZZ Unique Person' } })
+    await submit()
+    expect(createCustomer).toHaveBeenCalledTimes(1)
+  })
+
+  it('does not ask about what an edit left as it was', async () => {
+    vi.mocked(updateCustomer).mockResolvedValue({ success: true } as never)
+    renderForm({ id: 'cust-1', name: 'ZZ Kari Testvik', email: 'kari@testvik.example' })
+    fireEvent.change(screen.getByLabelText('Phone'), { target: { value: '912 34 567' } })
+    await submit()
+    expect(findCustomerDuplicates).toHaveBeenCalledWith({
+      name: '',
+      email: '',
+      phone: '912 34 567',
+      excludeId: 'cust-1',
+    })
+    expect(updateCustomer).toHaveBeenCalledTimes(1)
+  })
+})
+
+describe('a phone number', () => {
+  it('with letters in it is refused under the field, and nothing is sent', async () => {
+    renderForm()
+    fireEvent.change(screen.getByLabelText('Name *'), { target: { value: 'ZZ Kari Testvik' } })
+    const phone = screen.getByLabelText('Phone')
+    fireEvent.change(phone, { target: { value: 'abc-not-a-phone!!' } })
+    await submit()
+
+    const message = screen.getByText('Enter a phone number: digits, spaces and + - ( ) . only.')
+    expect(phone).toHaveAttribute('aria-invalid', 'true')
+    expect(phone.getAttribute('aria-describedby')).toContain(message.id)
+    expect(phone).toHaveFocus()
+    expect(createCustomer).not.toHaveBeenCalled()
+    expect(toast.error).toHaveBeenCalledWith('Not saved. Check the marked fields.')
+  })
+
+  it('written with spaces, a plus, brackets, dots and hyphens is saved', async () => {
+    renderForm()
+    fireEvent.change(screen.getByLabelText('Name *'), { target: { value: 'ZZ Kari Testvik' } })
+    fireEvent.change(screen.getByLabelText('Phone'), { target: { value: '+00 (0)12-345.678' } })
+    await submit()
+    expect(createCustomer).toHaveBeenCalledWith(
+      expect.objectContaining({ phone: '+00 (0)12-345.678' })
+    )
+  })
+})
+
+describe('the placeholders', () => {
+  it('say what goes in a field, not an American example', () => {
+    renderForm()
+    expect(screen.getByLabelText('Phone')).toHaveAttribute('placeholder', 'Phone number')
+    expect(screen.getByLabelText('Address')).toHaveAttribute(
+      'placeholder',
+      'Street, postcode, city'
+    )
+    expect(screen.getByLabelText('Tax / VAT number')).toHaveAttribute(
+      'placeholder',
+      'VAT or tax number'
+    )
+    expect(screen.queryByPlaceholderText(/555|Main St|NO123456789/)).not.toBeInTheDocument()
+  })
+})

+ 152 - 0
src/__tests__/features/customers/find-customer-duplicates.test.ts

@@ -0,0 +1,152 @@
+/**
+ * The duplicate checks read only this workshop's records, never the record
+ * being edited, and compare the way people write: an email without case, a
+ * phone number by its digits, a plate without spaces and hyphens. A phone
+ * number with letters in it is refused by the customer's own rules.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}))
+vi.mock('@/lib/db', () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    $queryRaw: vi.fn(),
+    vehicle: { findMany: vi.fn() },
+  },
+}))
+
+import type { Prisma } from '@/generated/prisma/client'
+import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
+import { db } from '@/lib/db'
+import { findCustomerDuplicates } from '@/features/customers/Actions/findCustomerDuplicates'
+import { findVehiclesWithPlate } from '@/features/vehicles/Actions/findVehiclesWithPlate'
+import {
+  createCustomerSchema,
+  updateCustomerSchema,
+} from '@/features/customers/Schema/customerSchema'
+import { fieldErrorsFromZod } from '@/lib/field-errors'
+import { looksLikeVin } from '@/features/vehicles/Lib/vehicleIdentifiers'
+
+const ORG = 'org-a'
+
+/** Each raw query the action ran, with the values bound into it. */
+const queries = () =>
+  vi.mocked(db.$queryRaw).mock.calls.map((call) => {
+    const sql = call[0] as unknown as Prisma.Sql
+    return { text: sql.sql, values: sql.values }
+  })
+
+beforeEach(() => {
+  vi.resetAllMocks()
+  vi.mocked(getCachedSession).mockResolvedValue({
+    user: { id: 'user-a', email: 'a@example.com' },
+  } as never)
+  vi.mocked(getCachedMembership).mockResolvedValue({
+    organizationId: ORG,
+    role: 'owner',
+    roleId: null,
+    customRole: null,
+  } as never)
+  vi.mocked(db.user.findUnique).mockResolvedValue({ isSuperAdmin: false } as never)
+  vi.mocked(db.$queryRaw).mockResolvedValue([] as never)
+})
+
+describe('findCustomerDuplicates', () => {
+  it('asks only within this workshop, leaving out the customer being edited', async () => {
+    const result = await findCustomerDuplicates({
+      name: '  ZZ  Kari   Testvik ',
+      email: ' Kari@Testvik.Example ',
+      phone: '+00 (912) 34-567',
+      excludeId: 'cust-1',
+    })
+    expect(result).toEqual({ success: true, data: { email: [], phone: [], name: [] } })
+    const asked = queries()
+    expect(asked).toHaveLength(3)
+    for (const query of asked) {
+      expect(query.text).toContain('"organizationId" =')
+      expect(query.values).toContain(ORG)
+      expect(query.values).toContain('cust-1')
+    }
+    expect(asked[0].values).toContain('kari@testvik.example')
+    expect(asked[1].values).toContain('0091234567')
+    expect(asked[2].values).toContain('zz kari testvik')
+  })
+
+  it('does not compare a phone number too short to tell people apart', async () => {
+    await findCustomerDuplicates({ phone: '12' })
+    expect(db.$queryRaw).not.toHaveBeenCalled()
+  })
+
+  it('hands back who matched each field', async () => {
+    const kari = { id: 'cust-kari', name: 'ZZ Kari Testvik', company: null }
+    vi.mocked(db.$queryRaw).mockResolvedValueOnce([kari] as never)
+    const result = await findCustomerDuplicates({ email: 'kari@testvik.example' })
+    expect(result.data).toEqual({ email: [kari], phone: [], name: [] })
+  })
+})
+
+describe('findVehiclesWithPlate', () => {
+  it('compares the plate without spaces and hyphens, in this workshop only', async () => {
+    const other = {
+      id: 'veh-2',
+      year: 2011,
+      make: 'BMW',
+      model: '520d',
+      licensePlate: 'ZZ 10001',
+      customer: { id: 'cust-kari', name: 'ZZ Kari Testvik' },
+    }
+    vi.mocked(db.$queryRaw).mockResolvedValue([{ id: 'veh-2' }] as never)
+    vi.mocked(db.vehicle.findMany).mockResolvedValue([other] as never)
+
+    const result = await findVehiclesWithPlate({ plate: 'zz-100 01', excludeId: 'veh-1' })
+
+    expect(result).toEqual({ success: true, data: [other] })
+    const [query] = queries()
+    expect(query.values).toEqual(expect.arrayContaining([ORG, 'veh-1', 'ZZ10001']))
+    expect(vi.mocked(db.vehicle.findMany).mock.calls[0][0]?.where).toMatchObject({
+      organizationId: ORG,
+    })
+  })
+
+  it('asks nothing for an empty plate', async () => {
+    const result = await findVehiclesWithPlate({ plate: ' - ' })
+    expect(result).toEqual({ success: true, data: [] })
+    expect(db.$queryRaw).not.toHaveBeenCalled()
+  })
+})
+
+describe('the customer rules for a phone number', () => {
+  it('refuse letters and signs, said as a phone problem', () => {
+    const parsed = createCustomerSchema.safeParse({ name: 'ZZ Kari', phone: 'abc-not-a-phone!!' })
+    expect(parsed.success).toBe(false)
+    if (parsed.success) return
+    expect(fieldErrorsFromZod(parsed.error)).toEqual([{ field: 'phone', issue: 'phone' }])
+  })
+
+  it('refuse a number with no digits at all', () => {
+    expect(createCustomerSchema.safeParse({ name: 'ZZ Kari', phone: '+ ( ) -' }).success).toBe(
+      false
+    )
+  })
+
+  it('take a number however it is grouped, and an emptied field on an edit', () => {
+    for (const phone of ['+47 912 34 567', '(020) 7946-0000', '030.1234.56', '']) {
+      expect(createCustomerSchema.safeParse({ name: 'ZZ Kari', phone }).success).toBe(true)
+    }
+    expect(updateCustomerSchema.safeParse({ id: 'c', phone: '' }).success).toBe(true)
+  })
+})
+
+describe('a VIN', () => {
+  it('looks like one at seventeen letters and digits without I, O or Q', () => {
+    expect(looksLikeVin('WBA5A71070G123456')).toBe(true)
+    expect(looksLikeVin('wba5a71070g123456')).toBe(true)
+    expect(looksLikeVin('')).toBe(true)
+    expect(looksLikeVin('NOTAVIN-IOQ')).toBe(false)
+    expect(looksLikeVin('WBA5A71070G12345')).toBe(false)
+    expect(looksLikeVin('WBA5A71070G12345O')).toBe(false)
+  })
+})

+ 250 - 0
src/__tests__/features/vehicles/vehicle-duplicates.test.tsx

@@ -0,0 +1,250 @@
+/**
+ * The vehicle form says when another vehicle of the workshop already has
+ * the plate being typed, names it and its owner with a link, and lets the
+ * person save anyway. A VIN that is not seventeen letters and digits is
+ * said under the field, never refused, and not at all in a boat workshop,
+ * where the field holds a hull number.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ refresh: vi.fn(), push: vi.fn(), replace: vi.fn() }),
+  usePathname: () => '/vehicles',
+  useSearchParams: () => new URLSearchParams(),
+}))
+vi.mock('@/components/glass-modal', () => ({ useGlassModal: () => ({ open: vi.fn() }) }))
+vi.mock('@/features/vehicles/Actions/vehicleActions', () => ({
+  createVehicle: vi.fn(),
+  updateVehicle: vi.fn(),
+}))
+vi.mock('@/features/vehicles/Actions/findVehiclesWithPlate', () => ({
+  findVehiclesWithPlate: vi.fn(),
+}))
+vi.mock('sonner', () => ({
+  toast: { error: vi.fn(), success: vi.fn(), loading: vi.fn(), warning: vi.fn() },
+}))
+vi.mock('@/features/customers/Actions/customerActions', () => ({
+  createCustomer: vi.fn(),
+  findOwnerCandidates: vi.fn(async () => ({ success: true, data: [] })),
+  getCustomerOption: vi.fn(async () => ({ success: true, data: null })),
+  searchCustomers: vi.fn(async () => ({ success: true, data: [] })),
+}))
+vi.mock('@/features/vehicles/Actions/aiAnalyzeVehicleDocument', () => ({
+  aiAnalyzeVehicleDocument: vi.fn(),
+  getVehicleScanAvailability: vi.fn(async () => ({ success: true, data: false })),
+}))
+vi.mock('@/features/integrations/Actions/vehicleLookupActions', () => ({
+  getVehicleLookupAvailability: vi.fn(async () => ({ success: true, data: {} })),
+  lookupVehicle: vi.fn(),
+}))
+vi.mock('@/features/vehicles/Actions/photoHandoffActions', () => ({
+  countPhotosSince: vi.fn(),
+  createPhotoHandoffLink: vi.fn(),
+  createVehiclePhotoHandoffLink: vi.fn(),
+  getVehiclePhotoUrl: vi.fn(),
+}))
+vi.mock('@/features/inspections/Actions/attachmentActions', () => ({
+  countInspectionMedia: vi.fn(),
+  createInspectionHandoffLink: vi.fn(),
+}))
+
+import { toast } from 'sonner'
+import { TooltipProvider } from '@/components/ui/tooltip'
+import { ServiceTypeProvider } from '@/components/service-type-context'
+import { VehicleForm } from '@/features/vehicles/Components/VehicleForm'
+import { createVehicle, updateVehicle } from '@/features/vehicles/Actions/vehicleActions'
+import { findVehiclesWithPlate } from '@/features/vehicles/Actions/findVehiclesWithPlate'
+
+const OTHER = {
+  id: 'veh-other',
+  year: 2011,
+  make: 'BMW',
+  model: '520d',
+  licensePlate: 'ZZ 10001',
+  customer: { id: 'cust-kari', name: 'ZZ Kari Testvik' },
+}
+
+const SAVED = {
+  id: 'veh-1',
+  make: 'Volvo',
+  model: 'V70',
+  year: 2015,
+  vin: null,
+  licensePlate: 'ZZ 20002',
+  color: null,
+  mileage: 120000,
+  fuelType: 'diesel',
+  transmission: 'automatic',
+  engineSize: null,
+  engineCode: null,
+  imageUrl: null,
+  customerId: null,
+  customer: null,
+  inspectionStatus: null,
+}
+
+function renderForm(over: { vehicle?: typeof SAVED; marine?: boolean } = {}): {
+  onOpenChange: ReturnType<typeof vi.fn>
+} {
+  const onOpenChange = vi.fn()
+  const form = (
+    <TooltipProvider>
+      <VehicleForm open onOpenChange={onOpenChange} vehicle={over.vehicle} distanceUnit="km" />
+    </TooltipProvider>
+  )
+  render(
+    over.marine ? <ServiceTypeProvider serviceType="marine">{form}</ServiceTypeProvider> : form
+  )
+  return { onOpenChange }
+}
+
+const field = (name: string) => document.querySelector(`[name="${name}"]`) as HTMLInputElement
+
+const fillNew = () => {
+  fireEvent.input(field('make'), { target: { value: 'Volvo' } })
+  fireEvent.input(field('model'), { target: { value: 'V70' } })
+  fireEvent.input(field('year'), { target: { value: '2015' } })
+}
+
+const submit = async () => {
+  const form = screen.getByRole('dialog').querySelector('form') as HTMLFormElement
+  await act(async () => {
+    fireEvent.submit(form)
+  })
+}
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  vi.mocked(findVehiclesWithPlate).mockResolvedValue({ success: true, data: [] })
+  vi.mocked(createVehicle).mockResolvedValue({
+    success: true,
+    data: { id: 'veh-new', make: 'Volvo', model: 'V70', year: 2015, licensePlate: 'ZZ10001' },
+  } as never)
+  vi.mocked(updateVehicle).mockResolvedValue({ success: true } as never)
+})
+
+describe('a plate another vehicle has', () => {
+  it('names that vehicle and its owner under the plate, with a link', async () => {
+    vi.mocked(findVehiclesWithPlate).mockResolvedValue({ success: true, data: [OTHER] })
+    renderForm()
+    const plate = field('licensePlate')
+    fireEvent.input(plate, { target: { value: 'zz-10001' } })
+    fireEvent.blur(plate)
+
+    expect(await screen.findByText('Another vehicle has this plate:')).toBeInTheDocument()
+    const link = screen.getByRole('link', { name: '2011 BMW 520d (ZZ Kari Testvik)' })
+    expect(link).toHaveAttribute('href', '/vehicles/veh-other')
+    expect(link).toHaveAttribute('target', '_blank')
+    expect(findVehiclesWithPlate).toHaveBeenCalledWith({ plate: 'ZZ10001', excludeId: undefined })
+  })
+
+  it('stops the first save to show it, and saves on the second', async () => {
+    vi.mocked(findVehiclesWithPlate).mockResolvedValue({ success: true, data: [OTHER] })
+    renderForm()
+    fillNew()
+    fireEvent.input(field('licensePlate'), { target: { value: 'ZZ 10001' } })
+
+    await submit()
+    expect(createVehicle).not.toHaveBeenCalled()
+    expect(toast.warning).toHaveBeenCalledWith(
+      'Another vehicle has this plate. Check it, or save again to keep it anyway.'
+    )
+    expect(screen.getByText('Another vehicle has this plate:')).toBeInTheDocument()
+
+    await submit()
+    expect(createVehicle).toHaveBeenCalledTimes(1)
+  })
+
+  it('does not put a late answer about an earlier plate under the new one', async () => {
+    let answer: (value: unknown) => void = () => undefined
+    vi.mocked(findVehiclesWithPlate).mockImplementationOnce(
+      () => new Promise((resolve) => (answer = resolve)) as never
+    )
+    renderForm()
+    const plate = field('licensePlate')
+    fireEvent.input(plate, { target: { value: 'ZZ 10001' } })
+    fireEvent.blur(plate)
+    // Changed again while the first check is still out.
+    fireEvent.input(plate, { target: { value: 'ZZ 77777' } })
+    await act(async () => {
+      answer({ success: true, data: [OTHER] })
+    })
+    expect(screen.queryByText('Another vehicle has this plate:')).not.toBeInTheDocument()
+
+    // Saving asks about the plate now in the field, and goes ahead when nobody has it.
+    fillNew()
+    await submit()
+    expect(findVehiclesWithPlate).toHaveBeenLastCalledWith({
+      plate: 'ZZ77777',
+      excludeId: undefined,
+    })
+    expect(createVehicle).toHaveBeenCalledTimes(1)
+  })
+
+  it('goes away when the plate is changed', async () => {
+    vi.mocked(findVehiclesWithPlate).mockResolvedValue({ success: true, data: [OTHER] })
+    renderForm()
+    const plate = field('licensePlate')
+    fireEvent.input(plate, { target: { value: 'ZZ 10001' } })
+    fireEvent.blur(plate)
+    await screen.findByText('Another vehicle has this plate:')
+    fireEvent.change(plate, { target: { value: 'ZZ 10002' } })
+    expect(screen.queryByText('Another vehicle has this plate:')).not.toBeInTheDocument()
+  })
+
+  it('is not asked about when an edit left the plate as it was', async () => {
+    renderForm({ vehicle: SAVED })
+    await submit()
+    expect(findVehiclesWithPlate).not.toHaveBeenCalled()
+    expect(updateVehicle).toHaveBeenCalledTimes(1)
+  })
+
+  it('speaks of a registration number in a boat workshop', async () => {
+    vi.mocked(findVehiclesWithPlate).mockResolvedValue({ success: true, data: [OTHER] })
+    renderForm({ marine: true })
+    const plate = field('licensePlate')
+    fireEvent.input(plate, { target: { value: 'NB-4521-E' } })
+    fireEvent.blur(plate)
+    expect(
+      await screen.findByText('Another boat has this registration number:')
+    ).toBeInTheDocument()
+  })
+})
+
+describe('a VIN that does not look like one', () => {
+  const NOTICE = "This doesn't look like a 17-character VIN. You can still save it."
+
+  it('is said under the field once it is left, and the vehicle still saves', async () => {
+    const { onOpenChange } = renderForm()
+    fillNew()
+    const vin = field('vin')
+    fireEvent.input(vin, { target: { value: 'NOTAVIN-IOQ' } })
+    expect(screen.queryByText(NOTICE)).not.toBeInTheDocument()
+    fireEvent.blur(vin)
+    expect(screen.getByText(NOTICE)).toBeInTheDocument()
+    expect(vin).toHaveAccessibleDescription(NOTICE)
+    expect(vin).not.toHaveAttribute('aria-invalid')
+
+    await submit()
+    expect(createVehicle).toHaveBeenCalledWith(expect.objectContaining({ vin: 'NOTAVIN-IOQ' }))
+    await waitFor(() => expect(onOpenChange).toHaveBeenCalledWith(false))
+  })
+
+  it('says nothing for a real VIN', () => {
+    renderForm()
+    const vin = field('vin')
+    fireEvent.input(vin, { target: { value: 'WBA5A71070G123456' } })
+    fireEvent.blur(vin)
+    expect(screen.queryByText(NOTICE)).not.toBeInTheDocument()
+  })
+
+  it('says nothing in a boat workshop, where it is a hull number', () => {
+    renderForm({ marine: true })
+    const vin = field('vin')
+    fireEvent.input(vin, { target: { value: 'BWC12345A606' } })
+    fireEvent.blur(vin)
+    expect(screen.queryByText(NOTICE)).not.toBeInTheDocument()
+  })
+})

+ 10 - 0
src/__tests__/features/vehicles/work-order-reading-notices.test.tsx

@@ -121,6 +121,16 @@ describe('the reading on a work order', () => {
     expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
   })
 
+  it('shows the last known reading as the hint in the empty field', () => {
+    renderCard()
+    expect(screen.getByLabelText('Mileage')).toHaveAttribute('placeholder', '412380')
+  })
+
+  it('shows no made-up reading as the hint when none is known', () => {
+    renderCard({ lastReading: null })
+    expect(screen.getByLabelText('Mileage')).not.toHaveAttribute('placeholder')
+  })
+
   it('says nothing when no reading is known for the vehicle', () => {
     renderCard({ lastReading: null })
     fireEvent.change(screen.getByLabelText('Mileage'), { target: { value: '5' } })

+ 64 - 0
src/components/duplicate-warning.tsx

@@ -0,0 +1,64 @@
+'use client'
+
+import Link from 'next/link'
+import { TriangleAlert } from 'lucide-react'
+
+/**
+ * A warning under a field that another record of the workshop already has
+ * what was typed: what it is, then each record by name with a link. The
+ * link opens in a new tab so the form, and what was typed into it, stays.
+ * Nothing is refused; the form saves anyway.
+ */
+export function DuplicateWarning({
+  id,
+  message,
+  records,
+}: {
+  /** For the field's aria-describedby. */
+  id: string
+  message: string
+  records: { id: string; href: string; label: string }[]
+}) {
+  if (records.length === 0) return null
+  return (
+    <div
+      id={id}
+      role="status"
+      className="flex gap-1.5 text-xs text-amber-700 dark:text-amber-400"
+      data-duplicate-warning
+    >
+      <TriangleAlert className="mt-px h-3.5 w-3.5 shrink-0" aria-hidden />
+      <p className="min-w-0">
+        {message}{' '}
+        {records.map((record, index) => (
+          <span key={record.id}>
+            {index > 0 && ', '}
+            <Link
+              href={record.href}
+              target="_blank"
+              rel="noopener noreferrer"
+              className="font-medium underline underline-offset-2 hover:text-foreground"
+            >
+              {record.label}
+            </Link>
+          </span>
+        ))}
+      </p>
+    </div>
+  )
+}
+
+/** A non-blocking note under a field: said, not refused. */
+export function FieldNotice({ id, message }: { id: string; message: string }) {
+  return (
+    <p
+      id={id}
+      role="status"
+      className="flex gap-1.5 text-xs text-amber-700 dark:text-amber-400"
+      data-field-notice
+    >
+      <TriangleAlert className="mt-px h-3.5 w-3.5 shrink-0" aria-hidden />
+      <span>{message}</span>
+    </p>
+  )
+}

+ 7 - 1
src/components/vehicle-picker-dialog.tsx

@@ -25,6 +25,7 @@ import { createCustomer } from '@/features/customers/Actions/customerActions'
 import { toast } from 'sonner'
 import { useTranslations } from 'next-intl'
 import { handleGated } from '@/components/upgrade-gate'
+import { useFieldErrorText } from '@/components/field-errors'
 import { useServiceType } from '@/components/service-type-context'
 import { vehicleName } from '@/lib/vehicle-name'
 
@@ -64,6 +65,7 @@ export function VehiclePickerDialog({
   const go = useGuardedPush()
   const t = useTranslations('workOrders.vehiclePicker')
   const tc = useTranslations('common.buttons')
+  const fieldErrorText = useFieldErrorText()
   const isMarine = useServiceType() === 'marine'
   // Every caller's own title speaks of vehicles, so a marine workshop gets the
   // picker's vessel title whatever was passed.
@@ -170,7 +172,11 @@ export function VehiclePickerDialog({
         })
         if (!customerResult.success || !customerResult.data) {
           if (!handleGated(customerResult)) {
-            toast.error(customerResult.error || t('failedCreateCustomer'))
+            // A phone number that is not one, said in the person's words.
+            const refused = customerResult.fieldErrors?.[0]
+            toast.error(
+              refused ? fieldErrorText(refused) : customerResult.error || t('failedCreateCustomer')
+            )
           }
           setCreating(false)
           return

+ 82 - 0
src/features/customers/Actions/findCustomerDuplicates.ts

@@ -0,0 +1,82 @@
+'use server'
+
+import { z } from 'zod'
+import { db } from '@/lib/db'
+import { withAuth } from '@/lib/with-auth'
+import { PermissionAction, PermissionSubject } from '@/lib/permissions'
+import { Prisma } from '@/generated/prisma/client'
+import { PHONE_MATCH_MIN_DIGITS, phoneDigits } from '../Lib/phoneNumber'
+
+/** A customer the one being typed may be, as the warning names and links it. */
+export interface CustomerDuplicate {
+  id: string
+  name: string
+  company: string | null
+}
+
+export interface CustomerDuplicates {
+  email: CustomerDuplicate[]
+  phone: CustomerDuplicate[]
+  name: CustomerDuplicate[]
+}
+
+/** Enough to name who it may be; the link shows the rest. */
+const SHOWN = 3
+
+const inputSchema = z.object({
+  name: z.string().max(500).optional(),
+  email: z.string().max(500).optional(),
+  phone: z.string().max(100).optional(),
+  /** The customer being edited, who is never a duplicate of themselves. */
+  excludeId: z.string().optional(),
+})
+
+/**
+ * Other customers of this workshop with the same email, the same phone
+ * number or the same name as the one being typed, so the form can say so
+ * before a second record for one person is made. It only reads: the form
+ * warns and the person can save anyway, since two people can share a name
+ * and a family can share a number.
+ *
+ * An email is compared without case, a phone number by its digits alone
+ * ("+47 912 34 567" is "+4791234567"), a name without case and with runs of
+ * spaces as one.
+ */
+export async function findCustomerDuplicates(input: unknown) {
+  return withAuth(
+    async ({ organizationId }): Promise<CustomerDuplicates> => {
+      const { name, email, phone, excludeId } = inputSchema.parse(input)
+      const notSelf = excludeId ? Prisma.sql`AND c.id <> ${excludeId}` : Prisma.empty
+      const select = (where: Prisma.Sql) =>
+        db.$queryRaw<CustomerDuplicate[]>(Prisma.sql`
+          SELECT c.id, c.name, c.company
+          FROM "public"."customers" c
+          WHERE c."organizationId" = ${organizationId} ${notSelf} AND ${where}
+          ORDER BY c."updatedAt" DESC
+          LIMIT ${SHOWN}
+        `)
+
+      const emailKey = (email ?? '').trim().toLowerCase()
+      const digits = phoneDigits(phone)
+      const nameKey = (name ?? '').replace(/\s+/g, ' ').trim().toLowerCase()
+
+      const [byEmail, byPhone, byName] = await Promise.all([
+        emailKey ? select(Prisma.sql`lower(trim(c.email)) = ${emailKey}`) : [],
+        digits.length >= PHONE_MATCH_MIN_DIGITS
+          ? select(Prisma.sql`regexp_replace(c.phone, '[^0-9]', '', 'g') = ${digits}`)
+          : [],
+        nameKey
+          ? select(
+              Prisma.sql`lower(regexp_replace(trim(c.name), '[[:space:]]+', ' ', 'g')) = ${nameKey}`
+            )
+          : [],
+      ])
+      return { email: byEmail, phone: byPhone, name: byName }
+    },
+    {
+      requiredPermissions: [
+        { action: PermissionAction.READ, subject: PermissionSubject.CUSTOMERS },
+      ],
+    }
+  )
+}

+ 153 - 4
src/features/customers/Components/CustomerForm.tsx

@@ -48,6 +48,19 @@ import {
 import { customFieldsRefusal } from '@/features/custom-fields/Lib/customFieldsRefusal'
 import type { CustomFieldError } from '@/features/custom-fields/Lib/customFieldValueRules'
 import { useFieldErrors } from '@/components/field-errors'
+import { DuplicateWarning } from '@/components/duplicate-warning'
+import { type CustomerDuplicates, findCustomerDuplicates } from '../Actions/findCustomerDuplicates'
+import { isPhoneNumber } from '../Lib/phoneNumber'
+
+/** The fields another customer may already have. */
+type DuplicateField = keyof CustomerDuplicates
+const DUPLICATE_FIELDS: DuplicateField[] = ['email', 'phone', 'name']
+const NO_DUPLICATES: CustomerDuplicates = { email: [], phone: [], name: [] }
+/** How long the check may take before the form goes on without it. */
+const DUPLICATE_CHECK_TIMEOUT_MS = 4000
+
+const hasDuplicates = (found: CustomerDuplicates) =>
+  DUPLICATE_FIELDS.some((field) => found[field].length > 0)
 
 interface CustomerFormProps {
   open: boolean
@@ -137,6 +150,94 @@ export function CustomerForm({
     if (open) setPoRequired(openCustomerPoRequired)
   }, [open, openCustomerId, openCustomerPoRequired])
   const formRef = useRef<HTMLFormElement>(null)
+
+  // Another customer of the workshop with this email, phone number or name:
+  // said under the field with a link, never refused. Asked when a field is
+  // left, and before saving values not yet asked about; a save that finds
+  // some stops once to show them, and the next save goes ahead.
+  const [duplicates, setDuplicates] = useState<CustomerDuplicates>(NO_DUPLICATES)
+  const duplicateCheck = useRef<{ key: string; answer: Promise<CustomerDuplicates> } | null>(null)
+  const duplicatesShownFor = useRef<string | null>(null)
+  useEffect(() => {
+    if (open) return
+    setDuplicates(NO_DUPLICATES)
+    duplicateCheck.current = null
+    duplicatesShownFor.current = null
+  }, [open])
+  /**
+   * What to ask about: the three fields as typed, leaving out any an edit
+   * did not change, so a customer who already shares a name with another is
+   * not warned about it on every save.
+   */
+  const duplicateQuery = () => {
+    const form = formRef.current
+    const value = (name: DuplicateField) =>
+      ((form?.elements.namedItem(name) as HTMLInputElement | null)?.value ?? '').trim()
+    const changed = (name: DuplicateField) => {
+      const typed = value(name)
+      const saved = (customer?.[name] ?? '').trim()
+      return !customer || typed.toLowerCase() !== saved.toLowerCase() ? typed : ''
+    }
+    const query = {
+      name: changed('name'),
+      email: changed('email'),
+      // A number that is not one is refused anyway; nothing to compare.
+      phone: isPhoneNumber(value('phone')) ? changed('phone') : '',
+      excludeId: customer?.id,
+    }
+    return { query, key: JSON.stringify(query) }
+  }
+  const checkDuplicates = (): { key: string; answer: Promise<CustomerDuplicates> } => {
+    const { query, key } = duplicateQuery()
+    const asked = duplicateCheck.current
+    if (asked?.key === key) {
+      // Back to values already asked about: their answer is shown again.
+      asked.answer.then((found) => {
+        if (isCurrentCheck(asked)) setDuplicates(found)
+      })
+      return asked
+    }
+    const answer =
+      query.name || query.email || query.phone
+        ? Promise.race([
+            findCustomerDuplicates(query).then((result) =>
+              result.success && result.data ? result.data : NO_DUPLICATES
+            ),
+            // A slow or failed check never holds the form up.
+            new Promise<CustomerDuplicates>((resolve) =>
+              setTimeout(() => resolve(NO_DUPLICATES), DUPLICATE_CHECK_TIMEOUT_MS)
+            ),
+          ]).catch(() => NO_DUPLICATES)
+        : Promise.resolve(NO_DUPLICATES)
+    const check = { key, answer }
+    duplicateCheck.current = check
+    answer.then((found) => {
+      // Only the answer about what the fields hold now is shown: one that
+      // arrives after a field was changed again is about other values.
+      if (!isCurrentCheck(check)) return
+      setDuplicates(found)
+      if (hasDuplicates(found)) duplicatesShownFor.current = key
+    })
+    return check
+  }
+  /** Whether a check is still the newest one and about what the fields hold now. */
+  const isCurrentCheck = (check: { key: string }) =>
+    duplicateCheck.current === check && duplicateQuery().key === check.key
+  const duplicateId = (field: DuplicateField) => `duplicate-${field}`
+  const duplicateWarning = (field: DuplicateField, message: string) => (
+    <DuplicateWarning
+      id={duplicateId(field)}
+      message={message}
+      records={duplicates[field].map((other) => ({
+        id: other.id,
+        href: `/customers/${other.id}`,
+        label: other.company ? `${other.name} (${other.company})` : other.name,
+      }))}
+    />
+  )
+  const duplicateDescribedBy = (field: DuplicateField) =>
+    duplicates[field].length > 0 ? duplicateId(field) : undefined
+
   /** Vehicle details from a scanned document, offered once the customer exists. */
   const [scannedVehicle, setScannedVehicle] = useState<VehicleDocumentScan | null>(null)
   const [addVehicle, setAddVehicle] = useState(true)
@@ -168,6 +269,33 @@ export function CustomerForm({
     e.preventDefault()
     const formData = new FormData(e.currentTarget)
 
+    // A phone number with letters in it is said under the field here, in
+    // the person's language, before anything is sent.
+    if (!isPhoneNumber(String(formData.get('phone') ?? ''))) {
+      fieldErrors.report(formRef.current, [{ field: 'phone', issue: 'phone' }])
+      toast.error(tc('fieldErrors.notSaved'))
+      return
+    }
+
+    // Values that match another customer and have not been shown yet are
+    // shown first; saving again keeps them.
+    const check = checkDuplicates()
+    if (duplicatesShownFor.current !== check.key) {
+      setLoading(true)
+      const found = await check.answer
+      setLoading(false)
+      // Changed while the check was out: nothing is saved on an answer
+      // about other values; the next save asks about these.
+      if (!isCurrentCheck(check)) return
+      if (hasDuplicates(found)) {
+        duplicatesShownFor.current = check.key
+        toast.warning(t('duplicateFound'))
+        const first = DUPLICATE_FIELDS.find((field) => found[field].length > 0)
+        if (first) (formRef.current?.elements.namedItem(first) as HTMLElement | null)?.focus()
+        return
+      }
+    }
+
     // The workshop's own fields first: one left empty that must not be stops
     // the save here, marked and named on the form. The values then go with
     // the customer's own save, which checks them again and writes both or
@@ -308,7 +436,20 @@ export function CustomerForm({
           ref={formRef}
           onSubmit={handleSubmit}
           // A refused field's mark goes as soon as it is changed.
-          onChange={(e) => fieldErrors.clear((e.target as Element).getAttribute('name') ?? '')}
+          onChange={(e) => {
+            const name = (e.target as Element).getAttribute('name') ?? ''
+            fieldErrors.clear(name)
+            // What another customer has was about what was typed before,
+            // and so is a check still on its way: it is dropped, so its
+            // answer cannot put an old warning under the new value.
+            if ((DUPLICATE_FIELDS as string[]).includes(name)) {
+              duplicateCheck.current = null
+              duplicatesShownFor.current = null
+              setDuplicates((prev) =>
+                prev[name as DuplicateField].length ? { ...prev, [name]: [] } : prev
+              )
+            }
+          }}
           className="flex min-h-0 flex-1 flex-col"
         >
           <DialogBody className="grid content-start gap-x-8 gap-y-4 md:grid-cols-2">
@@ -342,12 +483,14 @@ export function CustomerForm({
                     id="name"
                     name="name"
                     maxLength={NAME_MAX_LENGTH}
-                    {...fieldErrors.invalidProps('name')}
+                    {...fieldErrors.invalidProps('name', duplicateDescribedBy('name'))}
                     placeholder={t('namePlaceholder')}
                     defaultValue={customer?.name ?? defaults?.name ?? ''}
+                    onBlur={() => checkDuplicates()}
                     required
                   />
                   {fieldErrors.message('name')}
+                  {duplicateWarning('name', t('duplicateName'))}
                 </div>
                 <div className="space-y-2">
                   <Label htmlFor="customerNumber">{t('customerNumber')}</Label>
@@ -370,12 +513,14 @@ export function CustomerForm({
                     id="email"
                     name="email"
                     maxLength={EMAIL_MAX_LENGTH}
-                    {...fieldErrors.invalidProps('email')}
+                    {...fieldErrors.invalidProps('email', duplicateDescribedBy('email'))}
                     type="email"
                     placeholder={t('emailPlaceholder')}
                     defaultValue={customer?.email ?? ''}
+                    onBlur={() => checkDuplicates()}
                   />
                   {fieldErrors.message('email')}
+                  {duplicateWarning('email', t('duplicateEmail'))}
                 </div>
                 <div className="space-y-2">
                   <Label htmlFor="phone">{tc('form.phone')}</Label>
@@ -383,11 +528,15 @@ export function CustomerForm({
                     id="phone"
                     name="phone"
                     maxLength={SHORT_TEXT_MAX_LENGTH}
-                    {...fieldErrors.invalidProps('phone')}
+                    {...fieldErrors.invalidProps('phone', duplicateDescribedBy('phone'))}
+                    type="tel"
+                    inputMode="tel"
                     placeholder={t('phonePlaceholder')}
                     defaultValue={customer?.phone ?? ''}
+                    onBlur={() => checkDuplicates()}
                   />
                   {fieldErrors.message('phone')}
+                  {duplicateWarning('phone', t('duplicatePhone'))}
                 </div>
               </div>
 

+ 22 - 0
src/features/customers/Lib/phoneNumber.ts

@@ -0,0 +1,22 @@
+/**
+ * What a phone number may be written with, in any country: digits, spaces
+ * and the marks people group them with, "+47 912 34 567", "(0)20 7946 0000",
+ * "030-1234.56". Letters and other signs mean something else was typed into
+ * the box, and a text sent to it would go nowhere.
+ */
+const PHONE_CHARACTERS = /^[\d\s+\-().]+$/
+
+/** True for a phone number as people write one; an empty box is fine. */
+export function isPhoneNumber(value: string | null | undefined): boolean {
+  const trimmed = (value ?? '').trim()
+  if (!trimmed) return true
+  return PHONE_CHARACTERS.test(trimmed) && /\d/.test(trimmed)
+}
+
+/** The digits of a phone number, how two ways of writing one are compared. */
+export function phoneDigits(value: string | null | undefined): string {
+  return (value ?? '').replace(/\D/g, '')
+}
+
+/** Fewer digits than this is not enough to say two customers share a number. */
+export const PHONE_MATCH_MIN_DIGITS = 5

+ 12 - 1
src/features/customers/Schema/customerSchema.ts

@@ -7,11 +7,22 @@ import {
   SHORT_TEXT_MAX_LENGTH,
 } from '@/lib/input-limits'
 
+import { isPhoneNumber } from '../Lib/phoneNumber'
+
 export const createCustomerSchema = z.object({
   customerNumber: z.string().max(20).optional(),
   name: z.string().min(1, 'Name is required').max(NAME_MAX_LENGTH),
   email: z.string().max(EMAIL_MAX_LENGTH).email('Invalid email').optional().or(z.literal('')),
-  phone: z.string().max(SHORT_TEXT_MAX_LENGTH).optional(),
+  // Digits and the marks a number is written with; anything else was not a
+  // phone number. Said under the field as `phone` (src/lib/field-errors.ts).
+  phone: z
+    .string()
+    .max(SHORT_TEXT_MAX_LENGTH)
+    .refine(isPhoneNumber, {
+      message: 'Enter a phone number: digits, spaces and + - ( ) .',
+      params: { fieldIssue: 'phone' },
+    })
+    .optional(),
   address: z.string().max(ADDRESS_MAX_LENGTH).optional(),
   company: z.string().max(NAME_MAX_LENGTH).optional(),
   taxId: z.string().max(SHORT_TEXT_MAX_LENGTH).optional(),

+ 72 - 0
src/features/vehicles/Actions/findVehiclesWithPlate.ts

@@ -0,0 +1,72 @@
+'use server'
+
+import { z } from 'zod'
+import { db } from '@/lib/db'
+import { withAuth } from '@/lib/with-auth'
+import { PermissionAction, PermissionSubject } from '@/lib/permissions'
+import { Prisma } from '@/generated/prisma/client'
+import { plateMatchKey } from '../Lib/vehicleIdentifiers'
+
+/** Another vehicle with the plate being typed, as the warning names and links it. */
+export interface PlateDuplicate {
+  id: string
+  year: number
+  make: string
+  model: string
+  licensePlate: string | null
+  customer: { id: string; name: string } | null
+}
+
+/** Enough to name which it is; the link shows the rest. */
+const SHOWN = 3
+
+const inputSchema = z.object({
+  plate: z.string().max(100),
+  /** The vehicle being edited, which is never a duplicate of itself. */
+  excludeId: z.string().optional(),
+})
+
+/**
+ * The workshop's other vehicles that carry the plate being typed, so the
+ * form can say so before a second record for one vehicle is made. It only
+ * reads: a plate moves to another vehicle when one is sold or re-plated,
+ * so the form warns and the person can save anyway.
+ *
+ * Plates compare without case and without the spaces, dots and hyphens
+ * people group them with: "AB 12-345" is "ab12345".
+ */
+export async function findVehiclesWithPlate(input: unknown) {
+  return withAuth(
+    async ({ organizationId }): Promise<PlateDuplicate[]> => {
+      const { plate, excludeId } = inputSchema.parse(input)
+      const key = plateMatchKey(plate)
+      if (key.length < 2) return []
+      const notSelf = excludeId ? Prisma.sql`AND v.id <> ${excludeId}` : Prisma.empty
+      const hits = await db.$queryRaw<{ id: string }[]>(Prisma.sql`
+        SELECT v.id
+        FROM "public"."vehicles" v
+        WHERE v."organizationId" = ${organizationId} ${notSelf}
+          AND upper(regexp_replace(v."licensePlate", '[[:space:].-]+', '', 'g')) = ${key}
+        ORDER BY v."updatedAt" DESC
+        LIMIT ${SHOWN}
+      `)
+      if (hits.length === 0) return []
+      const vehicles = await db.vehicle.findMany({
+        where: { id: { in: hits.map((hit) => hit.id) }, organizationId },
+        select: {
+          id: true,
+          year: true,
+          make: true,
+          model: true,
+          licensePlate: true,
+          customer: { select: { id: true, name: true } },
+        },
+        orderBy: { updatedAt: 'desc' },
+      })
+      return vehicles
+    },
+    {
+      requiredPermissions: [{ action: PermissionAction.READ, subject: PermissionSubject.VEHICLES }],
+    }
+  )
+}

+ 1 - 1
src/features/vehicles/Components/ServiceForm.tsx

@@ -118,7 +118,7 @@ export function ServiceForm({ vehicleId, open, onOpenChange }: ServiceFormProps)
               </div>
               <div className="space-y-2">
                 <Label htmlFor="mileage">Mileage</Label>
-                <Input id="mileage" name="mileage" type="number" placeholder="50000" />
+                <Input id="mileage" name="mileage" type="number" />
               </div>
             </div>
 

+ 113 - 4
src/features/vehicles/Components/VehicleForm.tsx

@@ -67,6 +67,9 @@ import { PhotoHandoffButton } from './service-page/PhotoHandoffButton'
 import { ReadingNotice, useReadingNotice } from './ReadingNotice'
 import { ReadingConfirmDialog } from './ReadingConfirmDialog'
 import { readingNeedsAnswer } from '../Lib/vehicleReading'
+import { looksLikeVin, plateMatchKey, VIN_LENGTH } from '../Lib/vehicleIdentifiers'
+import { findVehiclesWithPlate, type PlateDuplicate } from '../Actions/findVehiclesWithPlate'
+import { DuplicateWarning, FieldNotice } from '@/components/duplicate-warning'
 
 /**
  * How alike two names must read before the scanned keeper is offered as an
@@ -259,6 +262,15 @@ export function VehicleForm({
   const mileageBeforeEdit = useRef('')
   const [inspectionDraft, setInspectionDraft] = useState(openedInspectionDue)
   const [vinDraft, setVinDraft] = useState(vehicle?.vin ?? '')
+  // A VIN that is not seventeen letters and digits is said once the field
+  // is left, never refused: older vehicles have shorter numbers.
+  const [vinLeft, setVinLeft] = useState(false)
+  // Other vehicles of the workshop with this plate: said under the field
+  // with a link, never refused. Asked when the field is left and before a
+  // save; a save that finds some stops once to show them.
+  const [plateDuplicates, setPlateDuplicates] = useState<PlateDuplicate[]>([])
+  const plateCheck = useRef<{ key: string; answer: Promise<PlateDuplicate[]> } | null>(null)
+  const plateShownFor = useRef<string | null>(null)
   const [colorDraft, setColorDraft] = useState(vehicle?.color ?? '')
   // Mileage is not read back here: both places that edit it set it directly,
   // and reading the field during an edit in the header would undo the edit.
@@ -276,9 +288,55 @@ export function VehicleForm({
     setReadingToConfirm(null)
     setInspectionDraft(openedInspectionDue)
     setVinDraft(vehicle?.vin ?? '')
+    setVinLeft(false)
+    setPlateDuplicates([])
+    plateCheck.current = null
+    plateShownFor.current = null
     setColorDraft(vehicle?.color ?? '')
   }
 
+  /**
+   * Asks which other vehicles carry the plate in the field. A plate an edit
+   * did not change is not asked about, and a slow or failed answer is
+   * taken as none: the check never holds the form up.
+   */
+  const checkPlate = (): { key: string; answer: Promise<PlateDuplicate[]> } => {
+    const key = plateMatchKey(fieldValue('licensePlate'))
+    const asked = plateCheck.current
+    if (asked?.key === key) {
+      // Back to a plate already asked about: its answer is shown again.
+      asked.answer.then((found) => {
+        if (isCurrentPlateCheck(asked)) setPlateDuplicates(found)
+      })
+      return asked
+    }
+    const unchanged = Boolean(vehicle) && key === plateMatchKey(vehicle?.licensePlate)
+    const answer: Promise<PlateDuplicate[]> =
+      key.length < 2 || unchanged
+        ? Promise.resolve([])
+        : Promise.race([
+            findVehiclesWithPlate({ plate: key, excludeId: vehicle?.id }).then((result) =>
+              result.success && result.data ? result.data : []
+            ),
+            new Promise<PlateDuplicate[]>((resolve) =>
+              setTimeout(() => resolve([]), PLATE_CHECK_TIMEOUT_MS)
+            ),
+          ]).catch(() => [])
+    const check = { key, answer }
+    plateCheck.current = check
+    answer.then((found) => {
+      // Only the answer about the plate in the field now is shown: one that
+      // arrives after the plate was changed again is about another plate.
+      if (!isCurrentPlateCheck(check)) return
+      setPlateDuplicates(found)
+      if (found.length > 0) plateShownFor.current = key
+    })
+    return check
+  }
+  /** Whether a plate check is still the newest one and about the plate in the field. */
+  const isCurrentPlateCheck = (check: { key: string }) =>
+    plateCheck.current === check && plateMatchKey(fieldValue('licensePlate')) === check.key
+
   // Sync state when vehicle prop changes (e.g. opening edit for a different vehicle)
   useEffect(() => {
     setSelectedCustomerId(vehicle?.customerId || defaultCustomerId || 'none')
@@ -571,6 +629,26 @@ export function VehicleForm({
       return
     }
     const formData = new FormData(e.currentTarget)
+    // Said, not refused: a VIN that does not look like one.
+    setVinLeft(true)
+
+    // A plate another vehicle already has, not shown yet, is shown first;
+    // saving again keeps it.
+    const plate = checkPlate()
+    if (plateShownFor.current !== plate.key) {
+      setLoading(true)
+      const found = await plate.answer
+      setLoading(false)
+      // Changed while the check was out: nothing is saved on an answer
+      // about another plate; the next save asks about this one.
+      if (!isCurrentPlateCheck(plate)) return
+      if (found.length > 0) {
+        plateShownFor.current = plate.key
+        toast.warning(isMarine ? t('plateDuplicateFoundMarine') : t('plateDuplicateFound'))
+        document.getElementById('licensePlate')?.focus()
+        return
+      }
+    }
 
     // Caught here rather than by the server, which could only answer in English.
     if (showTypeKey) {
@@ -812,6 +890,8 @@ export function VehicleForm({
     vehicle.inspectionStatus.source !== 'manual' &&
     inspectionDraft === openedInspectionDue
   const vinLength = vinDraft.trim().length
+  // Boats carry a hull number, older vehicles shorter numbers: neither is warned about.
+  const vinUnusual = !isMarine && vinLeft && !looksLikeVin(vinDraft)
   const addTitle = isMarine ? t('addTitleMarine') : t('addTitle')
   const swatch = cssColor(colorDraft)
 
@@ -880,7 +960,18 @@ export function VehicleForm({
             onSubmit={handleSubmit}
             onInput={readDrafts}
             // A refused field's mark goes as soon as it is changed.
-            onChange={(e) => fieldErrors.clear((e.target as Element).getAttribute('name') ?? '')}
+            onChange={(e) => {
+              const name = (e.target as Element).getAttribute('name') ?? ''
+              fieldErrors.clear(name)
+              // The vehicles found were for the plate as it was before, and
+              // so is a check still on its way: it is dropped, so its answer
+              // cannot put an old warning under the new plate.
+              if (name === 'licensePlate') {
+                plateCheck.current = null
+                plateShownFor.current = null
+                setPlateDuplicates((prev) => (prev.length ? [] : prev))
+              }
+            }}
             className="flex min-h-0 flex-1 flex-col"
           >
             <DialogBody className="space-y-4">
@@ -1158,10 +1249,14 @@ export function VehicleForm({
                         id="licensePlate"
                         name="licensePlate"
                         maxLength={SHORT_TEXT_MAX_LENGTH}
-                        {...fieldErrors.invalidProps('licensePlate')}
+                        {...fieldErrors.invalidProps(
+                          'licensePlate',
+                          plateDuplicates.length > 0 ? 'duplicate-licensePlate' : undefined
+                        )}
                         placeholder="ABC-1234"
                         defaultValue={vehicle?.licensePlate ?? ''}
                         className="flex-1"
+                        onBlur={() => checkPlate()}
                         // Enter in the plate asks the registry, where one is
                         // connected, instead of trying to save half a form.
                         onKeyDown={(e) => {
@@ -1191,6 +1286,17 @@ export function VehicleForm({
                       )}
                     </div>
                     {fieldErrors.message('licensePlate')}
+                    <DuplicateWarning
+                      id="duplicate-licensePlate"
+                      message={isMarine ? t('plateDuplicateMarine') : t('plateDuplicate')}
+                      records={plateDuplicates.map((other) => ({
+                        id: other.id,
+                        href: `/vehicles/${other.id}`,
+                        label: `${[other.year, other.make, other.model].filter(Boolean).join(' ')} (${
+                          other.customer?.name ?? t('duplicateNoOwner')
+                        })`,
+                      }))}
+                    />
                   </div>
 
                   <div className="space-y-2">
@@ -1223,9 +1329,10 @@ export function VehicleForm({
                         id="vin"
                         name="vin"
                         maxLength={SHORT_TEXT_MAX_LENGTH}
-                        {...fieldErrors.invalidProps('vin')}
+                        {...fieldErrors.invalidProps('vin', vinUnusual ? 'vin-notice' : undefined)}
                         placeholder="1HGCM82633A004352"
                         defaultValue={vehicle?.vin ?? ''}
+                        onBlur={() => setVinLeft(true)}
                         autoComplete="off"
                         spellCheck={false}
                         className="flex-1 font-mono"
@@ -1241,6 +1348,7 @@ export function VehicleForm({
                       )}
                     </div>
                     {fieldErrors.message('vin')}
+                    {vinUnusual && <FieldNotice id="vin-notice" message={t('vinUnusual')} />}
                   </div>
 
                   {/* Under both fields, since either button may have answered */}
@@ -1643,7 +1751,8 @@ function EngineSizeInput({ defaultValue }: { defaultValue: string }) {
   )
 }
 
-const VIN_LENGTH = 17
+/** How long the plate check may take before the form goes on without it. */
+const PLATE_CHECK_TIMEOUT_MS = 4000
 
 /** The options, and the stored value too when it is none of them, so it still shows as chosen. */
 function withCurrent(options: string[], current: string): string[] {

+ 7 - 1
src/features/vehicles/Components/service-page/modern/JobFactsCard.tsx

@@ -447,7 +447,13 @@ export function JobFactsCard({
                     type="number"
                     min={0}
                     max={READING_MAX}
-                    placeholder="50000"
+                    // The last reading known for this vehicle, so the one
+                    // typed can be read against it; none when nothing is known.
+                    placeholder={
+                      !vehicleChanged && initialData.lastReading != null
+                        ? String(initialData.lastReading)
+                        : undefined
+                    }
                     className="h-8 w-32"
                     defaultValue={initialData.mileage ?? ''}
                     onChange={(e) => setReadingTyped(e.target.value)}

+ 22 - 0
src/features/vehicles/Lib/vehicleIdentifiers.ts

@@ -0,0 +1,22 @@
+/**
+ * A VIN as ISO 3779 writes it since 1981: seventeen letters and digits,
+ * never I, O or Q, which read as 1 and 0. Older vehicles and boats carry
+ * other identifiers, so a VIN that is not one is said, never refused.
+ */
+export const VIN_LENGTH = 17
+const VIN_PATTERN = /^[A-HJ-NPR-Z0-9]{17}$/
+
+/** True for an empty box or a well-formed VIN; spaces and case are forgiven. */
+export function looksLikeVin(value: string | null | undefined): boolean {
+  const compact = (value ?? '').replace(/\s+/g, '').toUpperCase()
+  return compact === '' || VIN_PATTERN.test(compact)
+}
+
+/**
+ * A plate as it is compared with the workshop's other vehicles: "AB 12-345"
+ * and "ab12345" are the same plate. Only the marks people group a plate with
+ * are dropped, so a plate in any script still compares.
+ */
+export function plateMatchKey(value: string | null | undefined): string {
+  return (value ?? '').replace(/[\s.\-]+/g, '').toUpperCase()
+}

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

@@ -22,6 +22,7 @@ export type FieldIssue =
   | 'tooLarge'
   | 'notNumber'
   | 'wholeNumber'
+  | 'phone'
   | 'invalid'
 
 export interface FieldError {
@@ -34,6 +35,9 @@ export interface FieldError {
 
 type Issue = ZodError['issues'][number]
 
+/** The kinds a rule of the app's own may name, beyond what zod reports itself. */
+const NAMED_ISSUES = new Set<FieldIssue>(['phone'])
+
 function issueOf(issue: Issue): Pick<FieldError, 'issue' | 'limit'> {
   switch (issue.code) {
     case 'too_small': {
@@ -59,6 +63,14 @@ function issueOf(issue: Issue): Pick<FieldError, 'issue' | 'limit'> {
       // A number box sent empty or with letters arrives as undefined or NaN.
       if (issue.expected === 'number') return { issue: 'notNumber' }
       return { issue: 'invalid' }
+    case 'custom': {
+      // A rule of the app's own names the kind of problem it is, so the
+      // form can say it: `refine(check, { params: { fieldIssue: 'phone' } })`.
+      const named = (issue.params as { fieldIssue?: unknown } | undefined)?.fieldIssue
+      return typeof named === 'string' && NAMED_ISSUES.has(named as FieldIssue)
+        ? { issue: named as FieldIssue }
+        : { issue: 'invalid' }
+    }
     default:
       return { issue: 'invalid' }
   }