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

Let a corrected job reading bring the vehicle back down, and ask before saving a reading far above the last one (#646)

* Let a corrected job reading bring the vehicle back down, and warn about a reading far above the last one

* Ask before saving a reading far above the last one

* Hold reading decisions on the vehicle's row lock, and fix the review findings

* Answer the reading question in the work order facts spec
Bernt Christian Egeland 2 дней назад
Родитель
Сommit
664404b59e
54 измененных файлов с 2368 добавлено и 551 удалено
  1. 6 0
      .github/workflows/restore-tenancy.yml
  2. 11 2
      e2e/specs/work-orders/modern-page.spec.ts
  3. 17 0
      e2e/support/db.ts
  4. 9 0
      messages/de/vehicles.json
  5. 9 0
      messages/en/vehicles.json
  6. 9 0
      messages/es/vehicles.json
  7. 9 0
      messages/fr/vehicles.json
  8. 9 0
      messages/it/vehicles.json
  9. 9 0
      messages/lt/vehicles.json
  10. 9 0
      messages/nb/vehicles.json
  11. 9 0
      messages/nl/vehicles.json
  12. 9 0
      messages/pl/vehicles.json
  13. 9 0
      messages/pt-BR/vehicles.json
  14. 9 0
      messages/pt-PT/vehicles.json
  15. 9 0
      messages/ru/vehicles.json
  16. 9 0
      messages/tr/vehicles.json
  17. 15 0
      prisma/migrations/20261119210605_vehicle_reading_job/migration.sql
  18. 2 0
      prisma/schema/service-records.prisma
  19. 8 0
      prisma/schema/vehicles.prisma
  20. 35 3
      src/__tests__/api/tech-checkin.test.ts
  21. 484 0
      src/__tests__/db/vehicle-reading.db.test.ts
  22. 7 1
      src/__tests__/features/backup/restore-map-fields.test.ts
  23. 10 2
      src/__tests__/features/counter-sales.test.ts
  24. 5 1
      src/__tests__/features/forms/clear-optional-fields.test.ts
  25. 84 9
      src/__tests__/features/import/commit.test.ts
  26. 33 4
      src/__tests__/features/inspections/link-work-order.test.ts
  27. 3 0
      src/__tests__/features/tax/taxable-lines-save.test.ts
  28. 133 0
      src/__tests__/features/vehicles/vehicle-form-dialog.test.tsx
  29. 41 219
      src/__tests__/features/vehicles/vehicle-reading.test.ts
  30. 0 127
      src/__tests__/features/vehicles/work-order-lower-reading.test.tsx
  31. 243 0
      src/__tests__/features/vehicles/work-order-reading-notices.test.tsx
  32. 212 0
      src/__tests__/features/vehicles/work-order-reading-question.test.tsx
  33. 24 3
      src/__tests__/features/vehicles/work-order-reading-update.test.ts
  34. 38 10
      src/__tests__/features/workorders/create-workorder.test.ts
  35. 5 1
      src/__tests__/multitenancy/service-record-isolation.test.ts
  36. 32 19
      src/app/api/v1/tech/jobs/[id]/checkin/route.ts
  37. 4 0
      src/features/ai/tools/workshop-columns.ts
  38. 38 26
      src/features/import/Actions/importActions.ts
  39. 13 2
      src/features/inspections/Actions/inspectionActions.ts
  40. 39 23
      src/features/vehicles/Actions/serviceActions.ts
  41. 8 0
      src/features/vehicles/Actions/vehicleActions.ts
  42. 0 48
      src/features/vehicles/Components/LowerReadingNotice.tsx
  43. 93 0
      src/features/vehicles/Components/ReadingConfirmDialog.tsx
  44. 51 0
      src/features/vehicles/Components/ReadingNotice.tsx
  45. 73 0
      src/features/vehicles/Components/ReadingQuestion.tsx
  46. 47 9
      src/features/vehicles/Components/VehicleForm.tsx
  47. 1 1
      src/features/vehicles/Components/service-page/ServiceRecordPage.tsx
  48. 48 7
      src/features/vehicles/Components/service-page/modern/JobFactsCard.tsx
  49. 2 0
      src/features/vehicles/Components/service-page/modern/ModernDetails.tsx
  50. 39 2
      src/features/vehicles/Components/service-page/useServiceActions.ts
  51. 37 0
      src/features/vehicles/Components/service-page/useServiceFormState.ts
  52. 291 32
      src/features/vehicles/Lib/vehicleReading.ts
  53. 14 0
      src/lib/backup/import.ts
  54. 5 0
      src/lib/backup/tenancy-schema.ts

+ 6 - 0
.github/workflows/restore-tenancy.yml

@@ -14,6 +14,12 @@ on:
       - 'src/__tests__/db/**'
       # Job numbering reads the database with a raw pattern query.
       - 'src/lib/job-number.ts'
+      # A vehicle's reading is moved and corrected in the database's own
+      # WHERE, under a row lock; the rule and every writer of it.
+      - 'src/features/vehicles/Lib/vehicleReading.ts'
+      - 'src/features/vehicles/Actions/serviceActions.ts'
+      - 'src/features/vehicles/Actions/vehicleActions.ts'
+      - 'src/app/api/v1/tech/jobs/*/checkin/route.ts'
       - 'prisma/**'
       - 'vitest.db.config.ts'
       - '.github/workflows/restore-tenancy.yml'

+ 11 - 2
e2e/specs/work-orders/modern-page.spec.ts

@@ -1,6 +1,7 @@
 import { expect, type Locator, type Page, test } from '@playwright/test'
 import {
   deleteTechnicians,
+  highestReadingForJob,
   insertTechnician,
   jobAssignment,
   ownerOrganizationId,
@@ -107,13 +108,21 @@ test.describe('the overhauled work order page', () => {
       await expect(page.getByRole('option', { name: 'Repair' })).toBeVisible({ timeout: 2_000 })
     }).toPass({ timeout: 30_000 })
     await page.getByRole('option', { name: 'Repair' }).click()
-    await fillSettled(page.locator('#mileage'), '123456')
+    // Far above anything the car has read, so the page asks whether it is
+    // right before saving it, and the answer is yes. Read from the database,
+    // so a second run (the car already moved on) is asked the same.
+    const reading = String((await highestReadingForJob(jobIdOf(factsJob))) + 150_000)
+    await fillSettled(page.locator('#mileage'), reading)
+    const question = page.getByTestId('reading-question')
+    await expect(question).toContainText('Are you sure this reading is correct?')
+    await question.getByRole('button', { name: 'Yes, it is correct' }).click()
+    await expect(question).toHaveCount(0)
     await saveWorkOrder(page)
 
     await page.reload()
     await settle(page)
     await expect(page.getByTestId('service-type')).toContainText('Repair')
-    await expect(page.locator('#mileage')).toHaveValue('123456')
+    await expect(page.locator('#mileage')).toHaveValue(reading)
   })
 
   test('shows the whole customer and vehicle under "More info", with the VIN one click from the clipboard', async ({

+ 17 - 0
e2e/support/db.ts

@@ -265,6 +265,23 @@ export async function stockedPart(organizationId: string, atLeast = 10): Promise
   })
 }
 
+/**
+ * The highest reading known for a job's vehicle: its own, or any job's on it.
+ * A reading typed far above this is asked about before it is saved.
+ */
+export async function highestReadingForJob(serviceRecordId: string): Promise<number> {
+  return withDb(async (db) => {
+    const result = await db.query<{ highest: number | null }>(
+      `select greatest(v.mileage, (select max(s.mileage) from service_records s where s."vehicleId" = v.id)) as highest
+         from service_records r join vehicles v on v.id = r."vehicleId"
+        where r.id = $1`,
+      [serviceRecordId]
+    )
+    if (!result.rows[0]) throw new Error(`no vehicle for job ${serviceRecordId}`)
+    return Number(result.rows[0].highest ?? 0)
+  })
+}
+
 /** What one inventory part has on hand. */
 export async function partQuantity(partId: string): Promise<number> {
   return withDb(async (db) => {

+ 9 - 0
messages/de/vehicles.json

@@ -463,6 +463,15 @@
     "editMileageMarine": "Betriebsstunden ändern",
     "lowerReading": "Niedriger als der letzte Stand ({reading}). Sie können trotzdem speichern.",
     "lowerReadingMarine": "Niedriger als der letzte Stand ({hours} Stunden). Sie können trotzdem speichern.",
+    "muchHigherReading": "Viel höher als der letzte Stand ({reading}). Bitte auf Tippfehler prüfen. Sie können trotzdem speichern.",
+    "muchHigherReadingMarine": "Viel höher als der letzte Stand ({hours} Stunden). Bitte auf Tippfehler prüfen. Sie können trotzdem speichern.",
+    "readingConfirmTitle": "Ist dieser Stand wirklich korrekt?",
+    "readingConfirmBody": "{entered} ist viel höher als der letzte Stand, {last}.",
+    "readingConfirmBodyMarine": "{entered} Stunden sind viel höher als der letzte Stand, {last} Stunden.",
+    "readingConfirmYes": "Ja, stimmt",
+    "readingConfirmChange": "Ändern",
+    "readingConfirmHeld": "Der Stand wird gespeichert, sobald Sie antworten. Der Rest des Auftrags wird wie gewohnt gespeichert.",
+    "readingConfirmWaiting": "Der Stand ist noch nicht gespeichert. Beantworten Sie zuerst die Frage darunter.",
     "bookAppointment": "Termin buchen",
     "addTitleMarine": "Neues Wasserfahrzeug hinzufügen"
   },

+ 9 - 0
messages/en/vehicles.json

@@ -463,6 +463,15 @@
     "editMileageMarine": "Change engine hours",
     "lowerReading": "Lower than the last reading ({reading}). You can still save it.",
     "lowerReadingMarine": "Lower than the last reading ({hours} hours). You can still save it.",
+    "muchHigherReading": "Much higher than the last reading ({reading}). Check for a typo. You can still save it.",
+    "muchHigherReadingMarine": "Much higher than the last reading ({hours} hours). Check for a typo. You can still save it.",
+    "readingConfirmTitle": "Are you sure this reading is correct?",
+    "readingConfirmBody": "{entered} is much higher than the last reading, {last}.",
+    "readingConfirmBodyMarine": "{entered} hours is much higher than the last reading, {last} hours.",
+    "readingConfirmYes": "Yes, it is correct",
+    "readingConfirmChange": "Change it",
+    "readingConfirmHeld": "The reading is saved once you answer. The rest of the work order saves as usual.",
+    "readingConfirmWaiting": "The reading is not saved yet. Answer the question under it first.",
     "bookAppointment": "Book appointment",
     "addTitleMarine": "Add New Vessel"
   },

+ 9 - 0
messages/es/vehicles.json

@@ -463,6 +463,15 @@
     "editMileageMarine": "Cambiar horas de motor",
     "lowerReading": "Inferior a la última lectura ({reading}). Aun así puedes guardar.",
     "lowerReadingMarine": "Inferior a la última lectura ({hours} horas). Aun así puedes guardar.",
+    "muchHigherReading": "Muy superior a la última lectura ({reading}). Revisa si hay un error al escribir. Aun así puedes guardar.",
+    "muchHigherReadingMarine": "Muy superior a la última lectura ({hours} horas). Revisa si hay un error al escribir. Aun así puedes guardar.",
+    "readingConfirmTitle": "¿Seguro que esta lectura es correcta?",
+    "readingConfirmBody": "{entered} es muy superior a la última lectura, {last}.",
+    "readingConfirmBodyMarine": "{entered} horas es muy superior a la última lectura, {last} horas.",
+    "readingConfirmYes": "Sí, es correcta",
+    "readingConfirmChange": "Cambiarla",
+    "readingConfirmHeld": "La lectura se guarda en cuanto respondas. El resto de la orden de trabajo se guarda como siempre.",
+    "readingConfirmWaiting": "La lectura aún no se ha guardado. Responde primero a la pregunta que aparece debajo.",
     "bookAppointment": "Reservar cita",
     "addTitleMarine": "Agregar nueva embarcación"
   },

+ 9 - 0
messages/fr/vehicles.json

@@ -463,6 +463,15 @@
     "editMileageMarine": "Changer les heures moteur",
     "lowerReading": "Inférieur au dernier relevé ({reading}). Vous pouvez quand même enregistrer.",
     "lowerReadingMarine": "Inférieur au dernier relevé ({hours} heures). Vous pouvez quand même enregistrer.",
+    "muchHigherReading": "Bien supérieur au dernier relevé ({reading}). Vérifiez qu'il n'y a pas de faute de frappe. Vous pouvez quand même enregistrer.",
+    "muchHigherReadingMarine": "Bien supérieur au dernier relevé ({hours} heures). Vérifiez qu'il n'y a pas de faute de frappe. Vous pouvez quand même enregistrer.",
+    "readingConfirmTitle": "Ce relevé est-il vraiment correct ?",
+    "readingConfirmBody": "{entered} est bien supérieur au dernier relevé, {last}.",
+    "readingConfirmBodyMarine": "{entered} heures, c'est bien supérieur au dernier relevé, {last} heures.",
+    "readingConfirmYes": "Oui, c'est correct",
+    "readingConfirmChange": "Modifier",
+    "readingConfirmHeld": "Le relevé est enregistré dès que vous répondez. Le reste de l'ordre de travail s'enregistre normalement.",
+    "readingConfirmWaiting": "Le relevé n'est pas encore enregistré. Répondez d'abord à la question en dessous.",
     "bookAppointment": "Prendre rendez-vous",
     "addTitleMarine": "Ajouter un nouveau navire"
   },

+ 9 - 0
messages/it/vehicles.json

@@ -463,6 +463,15 @@
     "editMileageMarine": "Cambia ore motore",
     "lowerReading": "Inferiore all'ultima lettura ({reading}). Puoi comunque salvare.",
     "lowerReadingMarine": "Inferiore all'ultima lettura ({hours} ore). Puoi comunque salvare.",
+    "muchHigherReading": "Molto superiore all'ultima lettura ({reading}). Controlla che non ci sia un errore di battitura. Puoi comunque salvare.",
+    "muchHigherReadingMarine": "Molto superiore all'ultima lettura ({hours} ore). Controlla che non ci sia un errore di battitura. Puoi comunque salvare.",
+    "readingConfirmTitle": "Sei sicuro che questa lettura sia corretta?",
+    "readingConfirmBody": "{entered} è molto superiore all'ultima lettura, {last}.",
+    "readingConfirmBodyMarine": "{entered} ore è molto superiore all'ultima lettura, {last} ore.",
+    "readingConfirmYes": "Sì, è corretta",
+    "readingConfirmChange": "Modifica",
+    "readingConfirmHeld": "La lettura viene salvata appena rispondi. Il resto dell'ordine di lavoro si salva come al solito.",
+    "readingConfirmWaiting": "La lettura non è ancora salvata. Prima rispondi alla domanda qui sotto.",
     "bookAppointment": "Prenota appuntamento",
     "addTitleMarine": "Aggiungi Nuova Imbarcazione"
   },

+ 9 - 0
messages/lt/vehicles.json

@@ -463,6 +463,15 @@
     "editMileageMarine": "Pakeisti variklio valandas",
     "lowerReading": "Mažiau nei paskutinis rodmuo ({reading}). Vis tiek galite išsaugoti.",
     "lowerReadingMarine": "Mažiau nei paskutinis rodmuo ({hours} val.). Vis tiek galite išsaugoti.",
+    "muchHigherReading": "Daug daugiau nei paskutinis rodmuo ({reading}). Patikrinkite, ar nesuklydote vesdami. Vis tiek galite išsaugoti.",
+    "muchHigherReadingMarine": "Daug daugiau nei paskutinis rodmuo ({hours} val.). Patikrinkite, ar nesuklydote vesdami. Vis tiek galite išsaugoti.",
+    "readingConfirmTitle": "Ar tikrai šis rodmuo teisingas?",
+    "readingConfirmBody": "{entered} yra daug daugiau nei paskutinis rodmuo, {last}.",
+    "readingConfirmBodyMarine": "{entered} val. yra daug daugiau nei paskutinis rodmuo, {last} val.",
+    "readingConfirmYes": "Taip, teisingas",
+    "readingConfirmChange": "Pakeisti",
+    "readingConfirmHeld": "Rodmuo bus išsaugotas, kai atsakysite. Likusi užsakymo dalis išsaugoma kaip įprasta.",
+    "readingConfirmWaiting": "Rodmuo dar neišsaugotas. Pirmiausia atsakykite į klausimą po juo.",
     "bookAppointment": "Užregistruoti vizitą",
     "addTitleMarine": "Pridėti naują laivą"
   },

+ 9 - 0
messages/nb/vehicles.json

@@ -463,6 +463,15 @@
     "editMileageMarine": "Endre motortimer",
     "lowerReading": "Lavere enn forrige avlesning ({reading}). Du kan likevel lagre.",
     "lowerReadingMarine": "Lavere enn forrige avlesning ({hours} timer). Du kan likevel lagre.",
+    "muchHigherReading": "Mye høyere enn forrige avlesning ({reading}). Sjekk at det ikke er en tastefeil. Du kan likevel lagre.",
+    "muchHigherReadingMarine": "Mye høyere enn forrige avlesning ({hours} timer). Sjekk at det ikke er en tastefeil. Du kan likevel lagre.",
+    "readingConfirmTitle": "Er du sikker på at avlesningen er riktig?",
+    "readingConfirmBody": "{entered} er mye høyere enn forrige avlesning, {last}.",
+    "readingConfirmBodyMarine": "{entered} timer er mye høyere enn forrige avlesning, {last} timer.",
+    "readingConfirmYes": "Ja, den er riktig",
+    "readingConfirmChange": "Endre",
+    "readingConfirmHeld": "Avlesningen lagres når du har svart. Resten av arbeidsordren lagres som vanlig.",
+    "readingConfirmWaiting": "Avlesningen er ikke lagret ennå. Svar på spørsmålet under den først.",
     "bookAppointment": "Book time",
     "addTitleMarine": "Legg til nytt fartøy"
   },

+ 9 - 0
messages/nl/vehicles.json

@@ -463,6 +463,15 @@
     "editMileageMarine": "Motoruren wijzigen",
     "lowerReading": "Lager dan de vorige stand ({reading}). U kunt toch opslaan.",
     "lowerReadingMarine": "Lager dan de vorige stand ({hours} uur). U kunt toch opslaan.",
+    "muchHigherReading": "Veel hoger dan de vorige stand ({reading}). Controleer op een typefout. U kunt toch opslaan.",
+    "muchHigherReadingMarine": "Veel hoger dan de vorige stand ({hours} uur). Controleer op een typefout. U kunt toch opslaan.",
+    "readingConfirmTitle": "Weet u zeker dat deze stand klopt?",
+    "readingConfirmBody": "{entered} is veel hoger dan de vorige stand, {last}.",
+    "readingConfirmBodyMarine": "{entered} uur is veel hoger dan de vorige stand, {last} uur.",
+    "readingConfirmYes": "Ja, dit klopt",
+    "readingConfirmChange": "Wijzigen",
+    "readingConfirmHeld": "De stand wordt opgeslagen zodra u antwoordt. De rest van de werkorder wordt gewoon opgeslagen.",
+    "readingConfirmWaiting": "De stand is nog niet opgeslagen. Beantwoord eerst de vraag eronder.",
     "bookAppointment": "Afspraak inplannen",
     "addTitleMarine": "Nieuw vaartuig toevoegen"
   },

+ 9 - 0
messages/pl/vehicles.json

@@ -463,6 +463,15 @@
     "editMileageMarine": "Zmień godziny pracy silnika",
     "lowerReading": "Mniej niż ostatni odczyt ({reading}). Mimo to możesz zapisać.",
     "lowerReadingMarine": "Mniej niż ostatni odczyt ({hours} godz.). Mimo to możesz zapisać.",
+    "muchHigherReading": "Znacznie więcej niż ostatni odczyt ({reading}). Sprawdź, czy nie ma literówki. Mimo to możesz zapisać.",
+    "muchHigherReadingMarine": "Znacznie więcej niż ostatni odczyt ({hours} godz.). Sprawdź, czy nie ma literówki. Mimo to możesz zapisać.",
+    "readingConfirmTitle": "Czy na pewno ten odczyt jest prawidłowy?",
+    "readingConfirmBody": "{entered} to znacznie więcej niż ostatni odczyt, {last}.",
+    "readingConfirmBodyMarine": "{entered} godz. to znacznie więcej niż ostatni odczyt, {last} godz.",
+    "readingConfirmYes": "Tak, jest prawidłowy",
+    "readingConfirmChange": "Zmień",
+    "readingConfirmHeld": "Odczyt zostanie zapisany, gdy odpowiesz. Reszta zlecenia zapisuje się jak zwykle.",
+    "readingConfirmWaiting": "Odczyt nie jest jeszcze zapisany. Najpierw odpowiedz na pytanie pod nim.",
     "bookAppointment": "Umów wizytę",
     "addTitleMarine": "Dodaj nową jednostkę"
   },

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

@@ -463,6 +463,15 @@
     "editMileageMarine": "Alterar horas de motor",
     "lowerReading": "Menor que a última leitura ({reading}). Você ainda pode salvar.",
     "lowerReadingMarine": "Menor que a última leitura ({hours} horas). Você ainda pode salvar.",
+    "muchHigherReading": "Muito maior que a última leitura ({reading}). Confira se não houve erro de digitação. Você ainda pode salvar.",
+    "muchHigherReadingMarine": "Muito maior que a última leitura ({hours} horas). Confira se não houve erro de digitação. Você ainda pode salvar.",
+    "readingConfirmTitle": "Tem certeza de que esta leitura está correta?",
+    "readingConfirmBody": "{entered} é muito maior que a última leitura, {last}.",
+    "readingConfirmBodyMarine": "{entered} horas é muito maior que a última leitura, {last} horas.",
+    "readingConfirmYes": "Sim, está correta",
+    "readingConfirmChange": "Alterar",
+    "readingConfirmHeld": "A leitura é salva assim que você responder. O resto da ordem de serviço é salvo normalmente.",
+    "readingConfirmWaiting": "A leitura ainda não foi salva. Responda primeiro à pergunta abaixo dela.",
     "bookAppointment": "Agendar horário",
     "addTitleMarine": "Adicionar Nova Embarcação"
   },

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

@@ -463,6 +463,15 @@
     "editMileageMarine": "Alterar horas de motor",
     "lowerReading": "Inferior à última leitura ({reading}). Pode guardar na mesma.",
     "lowerReadingMarine": "Inferior à última leitura ({hours} horas). Pode guardar na mesma.",
+    "muchHigherReading": "Muito superior à última leitura ({reading}). Verifique se não há uma gralha. Pode guardar na mesma.",
+    "muchHigherReadingMarine": "Muito superior à última leitura ({hours} horas). Verifique se não há uma gralha. Pode guardar na mesma.",
+    "readingConfirmTitle": "Tem a certeza de que esta leitura está correta?",
+    "readingConfirmBody": "{entered} é muito superior à última leitura, {last}.",
+    "readingConfirmBodyMarine": "{entered} horas é muito superior à última leitura, {last} horas.",
+    "readingConfirmYes": "Sim, está correta",
+    "readingConfirmChange": "Alterar",
+    "readingConfirmHeld": "A leitura é guardada assim que responder. O resto da ordem de serviço é guardado normalmente.",
+    "readingConfirmWaiting": "A leitura ainda não foi guardada. Responda primeiro à pergunta por baixo dela.",
     "bookAppointment": "Fazer marcação",
     "addTitleMarine": "Adicionar Nova Embarcação"
   },

+ 9 - 0
messages/ru/vehicles.json

@@ -463,6 +463,15 @@
     "editMileageMarine": "Изменить моточасы",
     "lowerReading": "Меньше последнего показания ({reading}). Сохранить всё равно можно.",
     "lowerReadingMarine": "Меньше последнего показания ({hours} ч). Сохранить всё равно можно.",
+    "muchHigherReading": "Намного больше последнего показания ({reading}). Проверьте, нет ли опечатки. Сохранить всё равно можно.",
+    "muchHigherReadingMarine": "Намного больше последнего показания ({hours} ч). Проверьте, нет ли опечатки. Сохранить всё равно можно.",
+    "readingConfirmTitle": "Вы уверены, что показание верное?",
+    "readingConfirmBody": "{entered} намного больше последнего показания, {last}.",
+    "readingConfirmBodyMarine": "{entered} ч намного больше последнего показания, {last} ч.",
+    "readingConfirmYes": "Да, верно",
+    "readingConfirmChange": "Изменить",
+    "readingConfirmHeld": "Показание сохранится, как только вы ответите. Остальной заказ-наряд сохраняется как обычно.",
+    "readingConfirmWaiting": "Показание ещё не сохранено. Сначала ответьте на вопрос под ним.",
     "bookAppointment": "Создать запись",
     "addTitleMarine": "Добавить новое судно"
   },

+ 9 - 0
messages/tr/vehicles.json

@@ -463,6 +463,15 @@
     "editMileageMarine": "Motor saatlerini değiştir",
     "lowerReading": "Son okumadan düşük ({reading}). Yine de kaydedebilirsiniz.",
     "lowerReadingMarine": "Son okumadan düşük ({hours} saat). Yine de kaydedebilirsiniz.",
+    "muchHigherReading": "Son okumadan çok daha yüksek ({reading}). Yazım hatası olup olmadığını kontrol edin. Yine de kaydedebilirsiniz.",
+    "muchHigherReadingMarine": "Son okumadan çok daha yüksek ({hours} saat). Yazım hatası olup olmadığını kontrol edin. Yine de kaydedebilirsiniz.",
+    "readingConfirmTitle": "Bu okumanın doğru olduğundan emin misiniz?",
+    "readingConfirmBody": "{entered}, son okuma olan {last} değerinden çok daha yüksek.",
+    "readingConfirmBodyMarine": "{entered} saat, son okuma olan {last} saatten çok daha yüksek.",
+    "readingConfirmYes": "Evet, doğru",
+    "readingConfirmChange": "Değiştir",
+    "readingConfirmHeld": "Okuma, yanıt verdiğinizde kaydedilir. İş emrinin geri kalanı her zamanki gibi kaydedilir.",
+    "readingConfirmWaiting": "Okuma henüz kaydedilmedi. Önce altındaki soruyu yanıtlayın.",
     "bookAppointment": "Randevu oluştur",
     "addTitleMarine": "Yeni Tekne Ekle"
   },

+ 15 - 0
prisma/migrations/20261119210605_vehicle_reading_job/migration.sql

@@ -0,0 +1,15 @@
+/*
+  Warnings:
+
+  - A unique constraint covering the columns `[readingJobId]` on the table `vehicles` will be added. If there are existing duplicate values, this will fail.
+
+*/
+-- AlterTable
+ALTER TABLE "vehicles" ADD COLUMN     "readingBeforeJob" INTEGER,
+ADD COLUMN     "readingJobId" TEXT;
+
+-- CreateIndex
+CREATE UNIQUE INDEX "vehicles_readingJobId_key" ON "vehicles"("readingJobId");
+
+-- AddForeignKey
+ALTER TABLE "vehicles" ADD CONSTRAINT "vehicles_readingJobId_fkey" FOREIGN KEY ("readingJobId") REFERENCES "service_records"("id") ON DELETE SET NULL ON UPDATE CASCADE;

+ 2 - 0
prisma/schema/service-records.prisma

@@ -147,6 +147,8 @@ model ServiceRecord {
   /// (or neither, for anonymous walk-in sales)
   vehicleId String?
   vehicle   Vehicle? @relation(fields: [vehicleId], references: [id], onDelete: Cascade)
+  /// The vehicle whose current reading this job set, if it still is.
+  readingOfVehicle Vehicle? @relation("VehicleReadingJob")
 
   /// Direct customer for records without a vehicle. Vehicle-linked records
   /// leave this null and resolve the customer through the vehicle, so

+ 8 - 0
prisma/schema/vehicles.prisma

@@ -7,6 +7,14 @@ model Vehicle {
   licensePlate           String?
   color                  String?
   mileage                Int                  @default(0)
+  /// The job whose reading the vehicle's reading is, when a job set it
+  /// (vehicleReading.ts). Correcting that job's reading brings the vehicle
+  /// back down; anything that writes the reading directly clears it.
+  readingJobId           String?              @unique
+  readingJob             ServiceRecord?       @relation("VehicleReadingJob", fields: [readingJobId], references: [id], onDelete: SetNull)
+  /// What the vehicle read before that job set it: where a correction of the
+  /// job may take it back to. Means nothing without readingJobId.
+  readingBeforeJob       Int?
   fuelType               String?              @default("gasoline")
   transmission           String?              @default("automatic")
   engineSize             String?

+ 35 - 3
src/__tests__/api/tech-checkin.test.ts

@@ -67,6 +67,9 @@ const state = {
     licensePlate: 'AB12345',
     mileage: 120000,
     bodyType: null as string | null,
+    /** The job that set the reading, and what the vehicle read before it. */
+    readingJobId: null as string | null,
+    readingBeforeJob: null as number | null,
   },
   attachments: [] as {
     id: string
@@ -146,6 +149,13 @@ vi.mock('@/lib/db', () => {
           return { ...job }
         }
       ),
+      // The highest reading on the vehicle's other jobs.
+      aggregate: vi.fn(async ({ where }: { where: Record<string, unknown> }) => {
+        const readings = jobs
+          .filter((j) => matches(j as Record<string, unknown>, where))
+          .map((j) => j.mileage as number)
+        return { _max: { mileage: readings.length ? Math.max(...readings) : null } }
+      }),
       update: vi.fn(async ({ data }: { data: { mileage: number | null } }) => {
         JOB.mileage = data.mileage
         return JOB
@@ -166,6 +176,9 @@ vi.mock('@/lib/db', () => {
       ),
     },
     vehicle: {
+      findFirst: vi.fn(async ({ where }: { where: Record<string, unknown> }) =>
+        matches(state.vehicle as Record<string, unknown>, where) ? { ...state.vehicle } : null
+      ),
       updateMany: vi.fn(
         async ({
           where,
@@ -251,7 +264,12 @@ vi.mock('@/lib/db', () => {
       ),
     },
     $transaction: vi.fn(async (run: (tx: unknown) => Promise<unknown>) => run(db)),
-    $queryRaw: vi.fn(async () => []),
+    // The job's row lock: what the job read before this save.
+    $queryRaw: vi.fn(async (_sql: TemplateStringsArray, jobId: string) =>
+      jobs
+        .filter((j) => j.id === jobId)
+        .map((j) => ({ mileage: j.mileage, vehicleId: state.vehicle.id }))
+    ),
   }
   return { db }
 })
@@ -310,6 +328,8 @@ beforeEach(() => {
   state.attachments = []
   state.vehicle.mileage = 120000
   state.vehicle.bodyType = null
+  state.vehicle.readingJobId = null
+  state.vehicle.readingBeforeJob = null
   state.ctx = {
     userId: 'user-1',
     organizationId: 'org-1',
@@ -379,13 +399,25 @@ describe('a booking checked in', () => {
 })
 
 describe('mileage and body', () => {
-  it('records the mileage on the job and raises the vehicle’s, never lowers it', async () => {
+  it('records the mileage on the job and raises the vehicle’s', async () => {
     await PATCH(req({ mileage: 125400 }), job())
     expect(JOB.mileage).toBe(125400)
     expect(state.vehicle.mileage).toBe(125400)
+    // A typo corrected on the visit that raised it takes the vehicle back,
+    // never below what it read before.
+    await PATCH(req({ mileage: 1254000 }), job())
+    expect(state.vehicle.mileage).toBe(1254000)
+    await PATCH(req({ mileage: 125500 }), job())
+    expect(state.vehicle.mileage).toBe(125500)
     await PATCH(req({ mileage: 99 }), job())
     expect(JOB.mileage).toBe(99)
-    expect(state.vehicle.mileage).toBe(125400)
+    expect(state.vehicle.mileage).toBe(120000)
+  })
+
+  it('never lowers the vehicle from a visit that did not set its reading', async () => {
+    await PATCH(req({ mileage: 99 }), job())
+    expect(JOB.mileage).toBe(99)
+    expect(state.vehicle.mileage).toBe(120000)
   })
 
   it('keeps an equal reading without touching the vehicle', async () => {

+ 484 - 0
src/__tests__/db/vehicle-reading.db.test.ts

@@ -0,0 +1,484 @@
+/**
+ * A vehicle's reading and the readings on its jobs, on a real PostgreSQL
+ * (`npm run test:db` with E2E_DATABASE_URL set).
+ *
+ * The rule (src/features/vehicles/Lib/vehicleReading.ts) compares and sets
+ * in the database's own WHERE, which a mocked client cannot say anything
+ * about, so this runs the real save actions against a real database: the
+ * work order save, a new job, the vehicle form, deleting a job, moving it,
+ * and the technician app's check-in. What a workshop would see is the
+ * vehicle's reading afterwards, and whether the reading field warns.
+ *
+ * It makes two workshops of its own and removes them again; it empties nothing.
+ */
+import { randomUUID } from 'node:crypto'
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const url = process.env.E2E_DATABASE_URL ?? ''
+const databaseName = url.split('/').pop()?.split('?')[0]?.toLowerCase() ?? ''
+if (url && !/test|e2e/.test(databaseName)) {
+  throw new Error(
+    `Refusing to use database "${databaseName}": its name must say test or e2e, like the rest of this suite.`
+  )
+}
+
+// Set before the app's modules load, so the client connects to the test database.
+process.env.DATABASE_URL = url
+
+/** Who is signed in: the session the actions see. */
+const who = vi.hoisted(() => ({ userId: '', organizationId: '' }))
+
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn(), revalidateTag: vi.fn() }))
+vi.mock('next/headers', () => ({
+  headers: async () => new Headers(),
+  cookies: async () => ({ get: () => undefined, getAll: () => [] }),
+}))
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: async () => ({ user: { id: who.userId }, session: {} }),
+  getCachedMembership: async () => ({
+    organizationId: who.organizationId,
+    role: 'owner',
+    roleId: null,
+    customRole: null,
+  }),
+}))
+// The technician app: signed in as an owner of the workshop, with the job on
+// their list. Who may check a job in is tested with the route itself.
+vi.mock('@/lib/with-api-auth', async (importOriginal) => ({
+  ...(await importOriginal<typeof import('@/lib/with-api-auth')>()),
+  withApiAuth: async (_request: Request, handler: (ctx: unknown) => Promise<Response>) =>
+    handler({
+      userId: who.userId,
+      organizationId: who.organizationId,
+      role: 'owner',
+      isSuperAdmin: false,
+      isAdmin: true,
+      technicianIds: [],
+    }),
+}))
+vi.mock('@/features/condition-map/Lib/checkinAccess.server', async (importOriginal) => {
+  const real =
+    await importOriginal<typeof import('@/features/condition-map/Lib/checkinAccess.server')>()
+  const { db } = await import('@/lib/db')
+  return {
+    ...real,
+    checkinJobFor: async (ctx: { organizationId: string }, id: string) => {
+      const job = await db.serviceRecord.findFirst({
+        where: { id, organizationId: ctx.organizationId, vehicleId: { not: null } },
+        select: { id: true, vehicleId: true, status: true, title: true },
+      })
+      return job ? { ...job, vehicleId: job.vehicleId as string, ref: job.title } : null
+    },
+  }
+})
+
+const stamp = randomUUID().slice(0, 8)
+
+let db: typeof import('@/lib/db')['db']
+let actions: typeof import('@/features/vehicles/Actions/serviceActions')
+let vehicleActions: typeof import('@/features/vehicles/Actions/vehicleActions')
+let reading: typeof import('@/features/vehicles/Lib/vehicleReading')
+let checkin: typeof import('@/app/api/v1/tech/jobs/[id]/checkin/route')
+
+const workshops: { userId: string; organizationId: string }[] = []
+
+async function makeWorkshop(name: string) {
+  const user = await db.user.create({
+    data: { name: `${name} ${stamp}`, email: `reading-${name}-${stamp}@example.com` },
+  })
+  const organization = await db.organization.create({ data: { name: `${name} ${stamp}` } })
+  await db.organizationMember.create({
+    data: { userId: user.id, organizationId: organization.id, role: 'owner' },
+  })
+  const workshop = { userId: user.id, organizationId: organization.id }
+  workshops.push(workshop)
+  return workshop
+}
+
+let home: { userId: string; organizationId: string }
+let other: { userId: string; organizationId: string }
+
+function signIn(workshop: { userId: string; organizationId: string }) {
+  who.userId = workshop.userId
+  who.organizationId = workshop.organizationId
+}
+
+/** A vehicle as the vehicle form left it: a reading that is nobody's job's. */
+async function makeVehicle(mileage: number, workshop = home) {
+  const vehicle = await db.vehicle.create({
+    data: {
+      make: 'ZZ Toyota',
+      model: 'Hilux',
+      year: 2015,
+      mileage,
+      userId: workshop.userId,
+      organizationId: workshop.organizationId,
+    },
+  })
+  return vehicle.id
+}
+
+function ok<T>(result: { success: boolean; data?: T; error?: string }): T {
+  expect(result.success, result.error).toBe(true)
+  return result.data as T
+}
+
+/** A new job through the action, as the new work order page saves it. */
+async function newJob(vehicleId: string, date: string, mileage?: number | null) {
+  const job = ok(
+    await actions.createServiceRecord({
+      vehicleId,
+      title: `ZZ job ${date}`,
+      serviceDate: `${date}T09:00:00.000Z`,
+      ...(mileage !== undefined ? { mileage } : {}),
+    })
+  )
+  return job.id
+}
+
+/** A save of the work order page, which sends the reading with everything else. */
+async function saveJob(id: string, fields: Record<string, unknown>) {
+  ok(await actions.updateServiceRecord({ id, ...fields }))
+}
+
+async function vehicleOf(id: string) {
+  return db.vehicle.findUniqueOrThrow({
+    where: { id },
+    select: { mileage: true, readingJobId: true, readingBeforeJob: true },
+  })
+}
+
+/** What the work order's reading field compares a typed reading with. */
+async function lastReadingFor(jobId: string) {
+  const job = await db.serviceRecord.findUniqueOrThrow({
+    where: { id: jobId },
+    select: {
+      id: true,
+      organizationId: true,
+      vehicleId: true,
+      startDateTime: true,
+      serviceDate: true,
+      vehicle: { select: { mileage: true, readingJobId: true, readingBeforeJob: true } },
+    },
+  })
+  if (!job.vehicle || !job.vehicleId || !job.organizationId) throw new Error('No vehicle')
+  return reading.lastReadingBeforeJob(db, {
+    organizationId: job.organizationId,
+    vehicleId: job.vehicleId,
+    jobId: job.id,
+    jobDate: reading.jobReadingDate(job),
+    vehicle: job.vehicle,
+  })
+}
+
+beforeAll(async () => {
+  ;({ db } = await import('@/lib/db'))
+  actions = await import('@/features/vehicles/Actions/serviceActions')
+  vehicleActions = await import('@/features/vehicles/Actions/vehicleActions')
+  reading = await import('@/features/vehicles/Lib/vehicleReading')
+  checkin = await import('@/app/api/v1/tech/jobs/[id]/checkin/route')
+  home = await makeWorkshop('ZZ Reading Home')
+  other = await makeWorkshop('ZZ Reading Other')
+})
+
+beforeEach(() => signIn(home))
+
+afterAll(async () => {
+  if (db) {
+    // Vehicles, jobs and audit rows go with the workshop.
+    for (const { organizationId, userId } of workshops) {
+      await db.organization.delete({ where: { id: organizationId } }).catch(() => undefined)
+      await db.user.delete({ where: { id: userId } }).catch(() => undefined)
+    }
+    await db.$disconnect()
+  }
+})
+
+describe('a typo on the job that set the vehicle’s reading', () => {
+  it('brings the vehicle back down when the job is corrected', async () => {
+    const car = await makeVehicle(148_000)
+    // One digit too many.
+    const job = await newJob(car, '2026-11-19', 1_490_000)
+    expect(await vehicleOf(car)).toEqual({
+      mileage: 1_490_000,
+      readingJobId: job,
+      readingBeforeJob: 148_000,
+    })
+
+    await saveJob(job, { mileage: 149_000 })
+    expect(await vehicleOf(car)).toMatchObject({ mileage: 149_000, readingJobId: job })
+    // The reading field does not warn the job about its own typo: it compares
+    // with what the vehicle read before this job.
+    expect(await lastReadingFor(job)).toBe(148_000)
+  })
+
+  it('never puts the vehicle below another job’s reading', async () => {
+    const car = await makeVehicle(100_000)
+    await newJob(car, '2026-10-01', 150_000)
+    const job = await newJob(car, '2026-11-19', 1_500_000)
+    expect((await vehicleOf(car)).mileage).toBe(1_500_000)
+
+    await saveJob(job, { mileage: 149_000 })
+    // The other job read 150,000: the vehicle stays there, and its reading is
+    // no longer this job's to correct.
+    expect(await vehicleOf(car)).toEqual({
+      mileage: 150_000,
+      readingJobId: null,
+      readingBeforeJob: null,
+    })
+  })
+
+  it('never puts the vehicle below what it read before the job', async () => {
+    const car = await makeVehicle(148_000)
+    const job = await newJob(car, '2026-11-19', 1_480_000)
+    // Corrected, but to a second typo that is now too low.
+    await saveJob(job, { mileage: 14_800 })
+    expect(await vehicleOf(car)).toMatchObject({ mileage: 148_000, readingJobId: null })
+    // Corrected again, right this time: up by the usual rule.
+    await saveJob(job, { mileage: 148_500 })
+    expect(await vehicleOf(car)).toMatchObject({ mileage: 148_500, readingJobId: job })
+  })
+
+  it('goes back to what the vehicle read before, when the job’s reading is cleared', async () => {
+    const car = await makeVehicle(148_000)
+    const job = await newJob(car, '2026-11-19', 1_490_000)
+    await saveJob(job, { mileage: null })
+    expect(await vehicleOf(car)).toEqual({
+      mileage: 148_000,
+      readingJobId: null,
+      readingBeforeJob: null,
+    })
+  })
+
+  it('goes to the highest other job when the cleared job had raised it', async () => {
+    const car = await makeVehicle(0)
+    await newJob(car, '2026-09-01', 120_000)
+    const job = await newJob(car, '2026-11-19', 1_250_000)
+    await saveJob(job, { mileage: null })
+    expect((await vehicleOf(car)).mileage).toBe(120_000)
+  })
+
+  it('remembers what the vehicle read before the job when the same job raises it again', async () => {
+    const car = await makeVehicle(148_000)
+    const job = await newJob(car, '2026-11-19', 149_000)
+    await saveJob(job, { mileage: 1_490_000 })
+    expect(await vehicleOf(car)).toMatchObject({ mileage: 1_490_000, readingBeforeJob: 148_000 })
+    await saveJob(job, { mileage: 149_500 })
+    expect((await vehicleOf(car)).mileage).toBe(149_500)
+  })
+})
+
+describe('a job that did not set the vehicle’s reading', () => {
+  it('never lowers the vehicle', async () => {
+    const car = await makeVehicle(100_000)
+    const old = await newJob(car, '2026-03-01', 120_000)
+    const newest = await newJob(car, '2026-11-19', 180_000)
+    expect((await vehicleOf(car)).readingJobId).toBe(newest)
+
+    await saveJob(old, { mileage: 90_000 })
+    expect((await vehicleOf(car)).mileage).toBe(180_000)
+    await saveJob(old, { mileage: null })
+    expect((await vehicleOf(car)).mileage).toBe(180_000)
+  })
+
+  it('leaves alone a vehicle whose reading was set before jobs were remembered', async () => {
+    // A job saved before this change: the vehicle carries its reading but
+    // does not know it was that job's.
+    const car = await makeVehicle(1_490_000)
+    const job = await newJob(car, '2026-11-19')
+    await db.serviceRecord.update({ where: { id: job }, data: { mileage: 1_490_000 } })
+    await saveJob(job, { mileage: 149_000 })
+    expect((await vehicleOf(car)).mileage).toBe(1_490_000)
+  })
+
+  it('does not let an old job being edited push today’s reading forward', async () => {
+    const car = await makeVehicle(100_000)
+    const old = await newJob(car, '2026-03-01', 90_000)
+    await newJob(car, '2026-10-01', 100_000)
+    await saveJob(old, { mileage: 900_000 })
+    expect((await vehicleOf(car)).mileage).toBe(100_000)
+  })
+
+  it('is not held back by a later booking without a reading', async () => {
+    const car = await makeVehicle(100_000)
+    await newJob(car, '2026-12-10')
+    const today = await newJob(car, '2026-11-19')
+    await saveJob(today, { mileage: 104_500 })
+    expect(await vehicleOf(car)).toMatchObject({ mileage: 104_500, readingJobId: today })
+  })
+})
+
+describe('writes that end a job’s claim on the reading', () => {
+  it('a reading changed on the vehicle form is the vehicle’s own from then on', async () => {
+    const car = await makeVehicle(148_000)
+    const job = await newJob(car, '2026-11-19', 1_490_000)
+
+    // Saved with another field changed and the reading as it was: still the job's.
+    ok(await vehicleActions.updateVehicle({ id: car, color: 'Red', mileage: 1_490_000 }))
+    expect((await vehicleOf(car)).readingJobId).toBe(job)
+
+    ok(await vehicleActions.updateVehicle({ id: car, mileage: 1_500_000 }))
+    expect(await vehicleOf(car)).toEqual({
+      mileage: 1_500_000,
+      readingJobId: null,
+      readingBeforeJob: null,
+    })
+    // So correcting the job no longer moves it.
+    await saveJob(job, { mileage: 149_000 })
+    expect((await vehicleOf(car)).mileage).toBe(1_500_000)
+  })
+
+  it('a deleted job leaves the vehicle on its reading, which is nobody’s job’s', async () => {
+    const car = await makeVehicle(148_000)
+    const job = await newJob(car, '2026-11-19', 1_490_000)
+    ok(await actions.deleteServiceRecord(job))
+    expect((await vehicleOf(car)).mileage).toBe(1_490_000)
+    expect((await vehicleOf(car)).readingJobId).toBeNull()
+  })
+
+  it('a job moved to another vehicle leaves the first on its reading and speaks for the second', async () => {
+    const first = await makeVehicle(148_000)
+    const second = await makeVehicle(30_000)
+    const job = await newJob(first, '2026-11-19', 1_490_000)
+
+    await saveJob(job, { vehicleId: second, mileage: 1_490_000 })
+    expect(await vehicleOf(first)).toMatchObject({ mileage: 1_490_000, readingJobId: null })
+    expect(await vehicleOf(second)).toEqual({
+      mileage: 1_490_000,
+      readingJobId: job,
+      readingBeforeJob: 30_000,
+    })
+    // Corrected on its new vehicle, that vehicle follows.
+    await saveJob(job, { mileage: 31_000 })
+    expect((await vehicleOf(second)).mileage).toBe(31_000)
+    expect((await vehicleOf(first)).mileage).toBe(1_490_000)
+  })
+})
+
+describe('the technician app’s check-in', () => {
+  async function checkIn(jobId: string, mileage: number | null) {
+    const response = await checkin.PATCH(
+      new Request(`http://localhost/api/v1/tech/jobs/${jobId}/checkin`, {
+        method: 'PATCH',
+        body: JSON.stringify({ mileage }),
+        headers: { 'content-type': 'application/json' },
+      }),
+      { params: Promise.resolve({ id: jobId }) }
+    )
+    expect(response.status).toBe(200)
+    // The answer is as it was: the reading the app sent.
+    expect(await response.json()).toMatchObject({ data: { mileage: mileage ?? undefined } })
+  }
+
+  it('follows the same rule: a typo moves the vehicle up, the correction brings it back', async () => {
+    const car = await makeVehicle(148_000)
+    const job = await newJob(car, '2026-11-19')
+    await checkIn(job, 1_490_000)
+    expect(await vehicleOf(car)).toMatchObject({ mileage: 1_490_000, readingJobId: job })
+    await checkIn(job, 149_000)
+    expect((await vehicleOf(car)).mileage).toBe(149_000)
+  })
+})
+
+describe('two saves at once', () => {
+  it('leave the vehicle on the job’s final reading', async () => {
+    for (let round = 0; round < 5; round++) {
+      const car = await makeVehicle(148_000)
+      const job = await newJob(car, '2026-11-19', 1_490_000)
+      await Promise.all([saveJob(job, { mileage: 149_000 }), saveJob(job, { mileage: 150_000 })])
+      const saved = await db.serviceRecord.findUniqueOrThrow({
+        where: { id: job },
+        select: { mileage: true },
+      })
+      expect((await vehicleOf(car)).mileage).toBe(saved.mileage)
+    }
+  })
+
+  it('on two jobs never leave the lower of two raises behind', async () => {
+    for (let round = 0; round < 5; round++) {
+      const car = await makeVehicle(100_000)
+      const a = await newJob(car, '2026-11-19')
+      const b = await newJob(car, '2026-11-19')
+      await Promise.all([saveJob(a, { mileage: 110_000 }), saveJob(b, { mileage: 120_000 })])
+      expect(await vehicleOf(car)).toMatchObject({
+        mileage: 120_000,
+        readingJobId: b,
+        readingBeforeJob: expect.any(Number),
+      })
+    }
+  })
+})
+
+describe('a correction and another job’s reading at the same moment', () => {
+  it('leaves the vehicle on the other job’s reading when it is the higher one', async () => {
+    // Job A set the vehicle to 1,490,000 by mistake; job B, on the same day,
+    // has no reading yet.
+    const car = await makeVehicle(148_000)
+    const a = await newJob(car, '2026-11-19', 1_490_000)
+    const b = await newJob(car, '2026-11-19')
+
+    // A is corrected to 149,000 and its transaction is held open after the
+    // rule has run. While it is open, B is saved with 160,000: before A has
+    // committed, B can only see the vehicle at 1,490,000.
+    let corrected!: () => void
+    const correctedNow = new Promise<void>((resolve) => {
+      corrected = resolve
+    })
+    const holdA = db.$transaction(
+      async (tx) => {
+        await reading.lockJobReading(tx, { organizationId: home.organizationId, jobId: a })
+        await tx.serviceRecord.update({ where: { id: a }, data: { mileage: 149_000 } })
+        await reading.applyJobReading(tx, {
+          organizationId: home.organizationId,
+          vehicleId: car,
+          jobId: a,
+          jobDate: new Date('2026-11-19T09:00:00Z'),
+          reading: 149_000,
+          previousReading: 1_490_000,
+        })
+        corrected()
+        await new Promise((resolve) => setTimeout(resolve, 1500))
+      },
+      { timeout: 20_000 }
+    )
+    await correctedNow
+    const saveB = saveJob(b, { mileage: 160_000 })
+    await Promise.all([holdA, saveB])
+
+    // B waited for A, then saw 149,000 and moved the vehicle on.
+    expect(await vehicleOf(car)).toMatchObject({ mileage: 160_000, readingJobId: b })
+  })
+})
+
+describe('another workshop', () => {
+  it('cannot correct, move or read this workshop’s vehicle through a job id', async () => {
+    const car = await makeVehicle(148_000)
+    const job = await newJob(car, '2026-11-19', 1_490_000)
+
+    signIn(other)
+    const theirs = await makeVehicle(10, other)
+    const result = await actions.updateServiceRecord({ id: job, mileage: 149_000 })
+    expect(result.success).toBe(false)
+    const moved = await actions.updateServiceRecord({ id: job, vehicleId: theirs })
+    expect(moved.success).toBe(false)
+    // The rule asked directly with the other workshop's id changes nothing either.
+    expect(
+      await reading.applyJobReading(db, {
+        organizationId: other.organizationId,
+        vehicleId: car,
+        jobId: job,
+        jobDate: new Date('2026-11-19T09:00:00Z'),
+        reading: 149_000,
+        previousReading: 1_490_000,
+      })
+    ).toBe(false)
+    await reading.forgetJobReading(db, { organizationId: other.organizationId, jobId: job })
+
+    expect(await vehicleOf(car)).toEqual({
+      mileage: 1_490_000,
+      readingJobId: job,
+      readingBeforeJob: 148_000,
+    })
+    expect((await vehicleOf(theirs)).mileage).toBe(10)
+  })
+})

+ 7 - 1
src/__tests__/features/backup/restore-map-fields.test.ts

@@ -98,7 +98,11 @@ const NOT_IN_THE_MAP: Readonly<Record<string, Readonly<Record<string, string>>>>
     tireSetId: LINKED_LATER,
   },
   Customer: { importBatchId: IMPORT_BATCH },
-  Vehicle: { importBatchId: IMPORT_BATCH },
+  Vehicle: {
+    importBatchId: IMPORT_BATCH,
+    readingJobId: LINKED_LATER,
+    readingBeforeJob: LINKED_LATER,
+  },
 }
 
 describe.each([...layoutModels()].sort())('%s restore', (model) => {
@@ -159,6 +163,8 @@ describe('the links written after the rows they point at exist', () => {
     { link: 'inspectionId: q.inspectionId as string', created: 'tx.inspection.create(' },
     { link: 'tireSetId: sr.tireSetId as string', created: 'tx.tireSet.create(' },
     { link: 'tireSetId: q.tireSetId as string', created: 'tx.tireSet.create(' },
+    // The job whose reading the vehicle's is, once the vehicle's jobs are in.
+    { link: 'readingJobId: v.readingJobId as string', created: 'importServiceRecordTree(tx, sr' },
   ]
 
   it.each(links)('$link', ({ link, created }) => {

+ 10 - 2
src/__tests__/features/counter-sales.test.ts

@@ -198,7 +198,11 @@ describe('updateServiceRecord — counter sale semantics', () => {
     } as any)
     const txUpdate = vi.fn().mockResolvedValue({ id: 'sr-a', status: 'pending', title: 'x' })
     vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
-      fn({ serviceRecord: { update: txUpdate } })
+      fn({
+        $queryRaw: async () => [],
+        vehicle: { findFirst: async () => null, updateMany: async () => ({ count: 0 }) },
+        serviceRecord: { update: txUpdate },
+      })
     )
 
     const result = await updateServiceRecord({ id: 'sr-a', vehicleId: null, title: 'x' })
@@ -249,7 +253,11 @@ describe('updateServiceRecord — counter sale semantics', () => {
     vi.mocked(db.vehicle.findFirst).mockResolvedValue({ id: 'veh-a' } as any)
     const txUpdate = vi.fn().mockResolvedValue({ id: 'sr-a', status: 'pending', title: 'x' })
     vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
-      fn({ serviceRecord: { update: txUpdate } })
+      fn({
+        $queryRaw: async () => [],
+        vehicle: { findFirst: async () => null, updateMany: async () => ({ count: 0 }) },
+        serviceRecord: { update: txUpdate },
+      })
     )
 
     const result = await updateServiceRecord({ id: 'sr-a', vehicleId: 'veh-a' })

+ 5 - 1
src/__tests__/features/forms/clear-optional-fields.test.ts

@@ -255,7 +255,11 @@ describe('updateServiceRecord', () => {
   function runTransaction() {
     const update = vi.fn().mockResolvedValue({ ...existing })
     vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
-      fn({ serviceRecord: { update } })
+      fn({
+        $queryRaw: async () => [],
+        vehicle: { findFirst: async () => null, updateMany: async () => ({ count: 0 }) },
+        serviceRecord: { update },
+      })
     )
     return update
   }

+ 84 - 9
src/__tests__/features/import/commit.test.ts

@@ -15,6 +15,10 @@ interface Store {
 
 let committed: Store
 let seq = 0
+/** What the import wrote over vehicles that were already there. */
+let vehicleUpdates: { where: { id: string }; data: Record<string, unknown> }[] = []
+/** Vehicles the workshop already has, for a vehicle sheet to match. */
+let existingVehicles: Record<string, unknown>[] = []
 
 /** A transaction client that keeps its writes aside until the transaction succeeds. */
 function txClient(pending: Store) {
@@ -28,7 +32,10 @@ function txClient(pending: Store) {
     customer: { create: create(pending.customers, 'c'), update: vi.fn() },
     vehicle: {
       create: create(pending.vehicles, 'v'),
-      update: vi.fn(),
+      update: vi.fn(async (args: { where: { id: string }; data: Record<string, unknown> }) => {
+        vehicleUpdates.push(args)
+        return { id: args.where.id }
+      }),
       updateMany: vi.fn(async () => ({ count: 0 })),
     },
     serviceRecord: {
@@ -46,7 +53,20 @@ function txClient(pending: Store) {
 const db = {
   $transaction: vi.fn(async (fn: (tx: ReturnType<typeof txClient>) => Promise<unknown>) => {
     const pending: Store = { customers: [], vehicles: [], services: [] }
-    const result = await fn(txClient(pending))
+    // A row chunk writes through the transaction client; the readings, settled
+    // afterwards, read and write the vehicles as they are (the db below), under
+    // the vehicle's row lock.
+    const tx = txClient(pending)
+    const result = await fn({
+      ...tx,
+      $queryRaw: async () => [],
+      serviceRecord: { ...tx.serviceRecord, findFirst: db.serviceRecord.findFirst },
+      vehicle: {
+        ...tx.vehicle,
+        findFirst: db.vehicle.findFirst,
+        updateMany: db.vehicle.updateMany,
+      },
+    } as never)
     committed.customers.push(...pending.customers)
     committed.vehicles.push(...pending.vehicles)
     committed.services.push(...pending.services)
@@ -54,20 +74,30 @@ const db = {
   }),
   customer: { findMany: vi.fn(async () => []) },
   vehicle: {
-    findMany: vi.fn(async () => []),
-    // A reading moved up, once the rows are in.
+    findMany: vi.fn(async () => existingVehicles),
+    // The rule reads the vehicle, then moves it up only as it was read.
+    findFirst: vi.fn(async ({ where }: { where: { id: string } }) => {
+      const car = committed.vehicles.find((v) => v.id === where.id)
+      return car
+        ? {
+            mileage: (car.mileage as number | undefined) ?? 0,
+            readingJobId: (car.readingJobId as string | undefined) ?? null,
+            readingBeforeJob: (car.readingBeforeJob as number | undefined) ?? null,
+          }
+        : null
+    }),
     updateMany: vi.fn(
       async ({
         where,
         data,
       }: {
-        where: { id: string; mileage: { lt: number } }
-        data: { mileage: number }
+        where: { id: string; mileage: number }
+        data: { mileage: number; readingJobId: string; readingBeforeJob: number | null }
       }) => {
         const car = committed.vehicles.find((v) => v.id === where.id)
-        if (!car || ((car.mileage as number | undefined) ?? 0) >= where.mileage.lt)
+        if (!car || ((car.mileage as number | undefined) ?? 0) !== where.mileage)
           return { count: 0 }
-        car.mileage = data.mileage
+        Object.assign(car, data)
         return { count: 1 }
       }
     ),
@@ -140,12 +170,13 @@ vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
 const TOKEN = '6f1c2b0e-8d4a-4c7e-9a3b-2f5d6e7a8b9c'
 const HEADER = ['Date', 'Rego', 'Make', 'Model', 'Year', 'Job']
 let rows: string[][] = []
+let stagedEntity = 'services'
 vi.mock('@/features/import/Lib/staging', () => ({
   readStagedImport: async () => ({
     token: TOKEN,
     organizationId: 'org',
     fileName: 'history.csv',
-    entity: 'services',
+    entity: stagedEntity,
     presetId: null,
     sheet: { format: 'csv', columns: HEADER, rows },
     createdAt: new Date().toISOString(),
@@ -186,6 +217,9 @@ async function run() {
 beforeEach(() => {
   committed = { customers: [], vehicles: [], services: [] }
   seq = 0
+  vehicleUpdates = []
+  existingVehicles = []
+  stagedEntity = 'services'
 })
 
 describe('commitImport', () => {
@@ -245,5 +279,46 @@ describe('commitImport', () => {
       ['ABC123', 152000],
       ['OVB334', 101000],
     ])
+    // Each vehicle knows which job set its reading, so correcting that job
+    // later brings the vehicle with it.
+    const jobOf = (title: string, mileage: number) =>
+      committed.services.find((s) => s.title === title && s.mileage === mileage)?.id
+    expect(committed.vehicles.map((v) => v.readingJobId)).toEqual([
+      jobOf('Brakes', 152000),
+      jobOf('Service', 101000),
+    ])
+  })
+
+  it('makes a reading from a vehicle sheet the vehicle’s own, no longer a job’s', async () => {
+    stagedEntity = 'vehicles'
+    existingVehicles = [
+      {
+        id: 'v-existing',
+        licensePlate: 'ABC123',
+        vin: null,
+        make: 'Toyota',
+        model: 'Hilux',
+        year: 2000,
+        customerId: null,
+      },
+    ]
+    rows = [['', 'ABC123', 'Toyota', 'Hilux', '2000', '', '149000']]
+    const res = await commitImport({
+      ...input,
+      mapping: {
+        '1': 'vehicle.licensePlate',
+        '2': 'vehicle.make',
+        '3': 'vehicle.model',
+        '4': 'vehicle.year',
+        '6': 'vehicle.mileage',
+      },
+      options: { ...input.options, entity: 'vehicles' },
+    })
+    if (!('data' in res) || !res.data) throw new Error(`import failed: ${res.error}`)
+    expect(vehicleUpdates).toHaveLength(1)
+    expect(vehicleUpdates[0]).toMatchObject({
+      where: { id: 'v-existing' },
+      data: { mileage: 149000, readingJobId: null, readingBeforeJob: null },
+    })
   })
 })

+ 33 - 4
src/__tests__/features/inspections/link-work-order.test.ts

@@ -8,8 +8,18 @@ const { db, tx } = vi.hoisted(() => {
   const tx = {
     // findFirst: whether a later job on the vehicle already has a reading.
     serviceRecord: { update: vi.fn(), findFirst: vi.fn(async () => null) },
-    // The vehicle's reading, moved up when the job's is news to it.
-    vehicle: { updateMany: vi.fn(async () => ({ count: 1 })) },
+    // The vehicle's reading, moved up when the job's is news to it: read,
+    // then set only as it was read.
+    vehicle: {
+      findFirst: vi.fn(async () => ({
+        mileage: 100000,
+        readingJobId: null,
+        readingBeforeJob: null,
+      })),
+      updateMany: vi.fn(async () => ({ count: 1 })),
+    },
+    // The job's row lock, and what it read before.
+    $queryRaw: vi.fn(async () => [{ mileage: null, vehicleId: 'veh-1' }]),
     serviceLabor: { createMany: vi.fn() },
     // The workshop's tax rule for labor; none set, so the lines are taxed.
     appSetting: { findMany: vi.fn(async () => []) },
@@ -87,6 +97,25 @@ describe('the jobs an inspection can land on', () => {
 })
 
 describe('linking to a booked job', () => {
+  it('refuses a job that moved to another vehicle after it was looked up', async () => {
+    db.serviceRecord.findFirst.mockResolvedValue({
+      id: 'job-1',
+      vehicleId: 'veh-1',
+      invoiceNumber: '2026-1007',
+      inspectionId: null,
+      mileage: null,
+      startDateTime: new Date('2026-11-19T09:00:00Z'),
+      serviceDate: new Date('2026-11-19T09:00:00Z'),
+      laborItems: [],
+    })
+    // Under the row lock the job is on another vehicle now.
+    tx.$queryRaw.mockResolvedValueOnce([{ mileage: null, vehicleId: 'veh-2' }])
+    const result = await linkWorkOrderToInspection('insp-1', 'job-1', { includeDefects: true })
+    expect(result.success).toBe(false)
+    expect(tx.serviceRecord.update).not.toHaveBeenCalled()
+    expect(tx.vehicle.updateMany).not.toHaveBeenCalled()
+  })
+
   it('links the job and adds the inspection line and the defects, worst first', async () => {
     db.serviceRecord.findFirst.mockResolvedValue({
       id: 'job-1',
@@ -106,8 +135,8 @@ describe('linking to a booked job', () => {
     })
     // The inspection's reading reaches the vehicle with the link, upwards only.
     expect(tx.vehicle.updateMany).toHaveBeenCalledWith({
-      where: { id: 'veh-1', organizationId: 'org', mileage: { lt: 120000 } },
-      data: { mileage: 120000 },
+      where: { id: 'veh-1', organizationId: 'org', mileage: 100000, readingJobId: null },
+      data: { mileage: 120000, readingJobId: 'job-1', readingBeforeJob: 100000 },
     })
     expect(
       tx.serviceLabor.createMany.mock.calls[0][0].data.map(

+ 3 - 0
src/__tests__/features/tax/taxable-lines-save.test.ts

@@ -128,6 +128,9 @@ function transaction(extra: Record<string, unknown> = {}) {
     serviceConcern: { createMany: vi.fn(), findMany: vi.fn().mockResolvedValue([]) },
     serviceAttachment: { createMany: vi.fn(), deleteMany: vi.fn() },
     inventoryPart: { findFirst: vi.fn().mockResolvedValue(null) },
+    // The job's row lock, and a vehicle whose reading nothing here moves.
+    $queryRaw: async () => [],
+    vehicle: { findFirst: async () => null, updateMany: async () => ({ count: 0 }) },
     ...extra,
   }
   vi.mocked(db.$transaction).mockImplementation((async (fn: (client: typeof tx) => unknown) =>

+ 133 - 0
src/__tests__/features/vehicles/vehicle-form-dialog.test.tsx

@@ -452,3 +452,136 @@ describe('a reading lowered on the vehicle form', () => {
     ).toBeGreaterThan(0)
   })
 })
+
+describe('a reading far above the last one on the vehicle form', () => {
+  const NOTICE =
+    'Much higher than the last reading (225,040 km). Check for a typo. You can still save it.'
+  const field = () => screen.getByLabelText('Mileage', { selector: 'input#mileage' })
+
+  it('says so beside the field while typing, and asks on Save before saving it', async () => {
+    renderForm()
+    await screen.findByRole('dialog')
+    fireEvent.change(field(), { target: { value: '2250400' } })
+    // Under the field and under the figure at the top, which is the same reading.
+    expect(screen.getAllByText(NOTICE)).toHaveLength(2)
+    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
+    expect(field()).toHaveAccessibleDescription(NOTICE.replace(' km', '\u00a0km'))
+
+    fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
+    const ask = await screen.findByRole('alertdialog')
+    expect(ask).toHaveTextContent('Are you sure this reading is correct?')
+    expect(ask).toHaveTextContent('2,250,400 km is much higher than the last reading, 225,040 km.')
+    // Nothing is saved until the answer.
+    expect(updateVehicle).not.toHaveBeenCalled()
+
+    fireEvent.click(screen.getByRole('button', { name: 'Yes, it is correct' }))
+    await waitFor(() => expect(updateVehicle).toHaveBeenCalledTimes(1))
+    expect(vi.mocked(updateVehicle).mock.calls[0][0]).toMatchObject({ mileage: 2250400 })
+    expect(toast.error).not.toHaveBeenCalled()
+  })
+
+  it('Change it goes back to the field and saves nothing', async () => {
+    renderForm()
+    await screen.findByRole('dialog')
+    fireEvent.change(field(), { target: { value: '2250400' } })
+    fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
+    await screen.findByRole('alertdialog')
+    fireEvent.click(screen.getByRole('button', { name: 'Change it' }))
+    await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
+    await waitFor(() => expect(field()).toHaveFocus())
+    expect(updateVehicle).not.toHaveBeenCalled()
+
+    // Corrected, it saves without a question.
+    fireEvent.change(field(), { target: { value: '225400' } })
+    fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
+    await waitFor(() => expect(updateVehicle).toHaveBeenCalledTimes(1))
+    expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+    expect(vi.mocked(updateVehicle).mock.calls[0][0]).toMatchObject({ mileage: 225400 })
+  })
+
+  it('asks again for the same value on another vehicle', async () => {
+    const view = renderForm()
+    await screen.findByRole('dialog')
+    fireEvent.change(field(), { target: { value: '2250400' } })
+    fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
+    await screen.findByRole('alertdialog')
+    fireEvent.click(screen.getByRole('button', { name: 'Yes, it is correct' }))
+    await waitFor(() => expect(updateVehicle).toHaveBeenCalledTimes(1))
+
+    // The list opens the same form for another vehicle.
+    view.rerender(
+      <TooltipProvider>
+        <VehicleForm
+          open
+          onOpenChange={vi.fn()}
+          vehicle={{ ...VEHICLE, id: 'veh-other' }}
+          distanceUnit="km"
+        />
+      </TooltipProvider>
+    )
+    await waitFor(() => expect(field()).toHaveValue(225040))
+    fireEvent.change(field(), { target: { value: '2250400' } })
+    fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
+    expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
+    expect(updateVehicle).toHaveBeenCalledTimes(1)
+  })
+
+  it('asks once for a value, and again for another', async () => {
+    vi.mocked(updateVehicle).mockResolvedValue({ success: false, error: 'Network' } as never)
+    renderForm()
+    await screen.findByRole('dialog')
+    fireEvent.change(field(), { target: { value: '2250400' } })
+    fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
+    await screen.findByRole('alertdialog')
+    fireEvent.click(screen.getByRole('button', { name: 'Yes, it is correct' }))
+    await waitFor(() => expect(updateVehicle).toHaveBeenCalledTimes(1))
+
+    // The save failed and is tried again: the same value is not asked again.
+    fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
+    await waitFor(() => expect(updateVehicle).toHaveBeenCalledTimes(2))
+    expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+
+    fireEvent.change(field(), { target: { value: '2250500' } })
+    fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
+    expect(await screen.findByRole('alertdialog')).toBeInTheDocument()
+    expect(updateVehicle).toHaveBeenCalledTimes(2)
+  })
+
+  it('says nothing up to 100,000 above the last reading, and goes away when fixed', async () => {
+    renderForm()
+    await screen.findByRole('dialog')
+    fireEvent.change(field(), { target: { value: '325040' } })
+    expect(screen.queryByTestId('higher-reading-notice')).not.toBeInTheDocument()
+    fireEvent.change(field(), { target: { value: '325041' } })
+    expect(screen.getAllByTestId('higher-reading-notice').length).toBeGreaterThan(0)
+    fireEvent.change(field(), { target: { value: '231500' } })
+    expect(screen.queryByTestId('higher-reading-notice')).not.toBeInTheDocument()
+  })
+
+  it('has nothing to compare with on a new vehicle or one that reads 0', async () => {
+    renderForm({ vehicle: { ...VEHICLE, mileage: 0 } })
+    await screen.findByRole('dialog')
+    fireEvent.change(field(), { target: { value: '9000000' } })
+    expect(screen.queryByTestId('higher-reading-notice')).not.toBeInTheDocument()
+  })
+
+  it('uses the engine hours limit in a boat workshop', async () => {
+    render(
+      <ServiceTypeProvider serviceType="marine">
+        <TooltipProvider>
+          <VehicleForm open onOpenChange={vi.fn()} vehicle={{ ...VEHICLE, mileage: 1240 }} />
+        </TooltipProvider>
+      </ServiceTypeProvider>
+    )
+    await screen.findByRole('dialog')
+    const hours = screen.getByLabelText('Engine Hours', { selector: 'input#mileage' })
+    fireEvent.change(hours, { target: { value: '6240' } })
+    expect(screen.queryByTestId('higher-reading-notice')).not.toBeInTheDocument()
+    fireEvent.change(hours, { target: { value: '12400' } })
+    expect(
+      screen.getAllByText(
+        'Much higher than the last reading (1,240 hours). Check for a typo. You can still save it.'
+      ).length
+    ).toBeGreaterThan(0)
+  })
+})

+ 41 - 219
src/__tests__/features/vehicles/vehicle-reading.test.ts

@@ -1,230 +1,18 @@
 /**
  * @vitest-environment node
  *
- * When a job's reading becomes the vehicle's current reading.
- *
- * Every writer of a job's reading asks the same question (vehicleReading.ts),
- * so a workshop sees one behaviour whether the reading was typed on the work
- * order, sent by the technician app, raised from an inspection or imported:
- * the newest reading moves the vehicle forward, and nothing winds it back.
+ * What a reading field calls lower, or so much higher that a digit may have
+ * slipped in. The rule that moves the vehicle's reading runs in the database
+ * and is tested there: src/__tests__/db/vehicle-reading.db.test.ts.
  */
-import { beforeEach, describe, expect, it } from 'vitest'
+import { describe, expect, it } from 'vitest'
 import {
-  applyJobReading,
   isLowerReading,
-  jobReadingDate,
-  lastReadingBeforeJob,
+  isMuchHigherReading,
+  MUCH_HIGHER_READING,
+  readingNotice,
 } from '@/features/vehicles/Lib/vehicleReading'
 
-type Job = {
-  id: string
-  organizationId: string
-  vehicleId: string
-  mileage: number | null
-  startDateTime: Date | null
-  serviceDate: Date
-}
-
-const ORG = 'org-1'
-const VEHICLE = 'veh-1'
-const day = (d: string) => new Date(`${d}T09:00:00Z`)
-
-const state = {
-  vehicles: [] as { id: string; organizationId: string; mileage: number }[],
-  jobs: [] as Job[],
-}
-
-/** Enough of Prisma's `where` for the queries the rule makes. */
-function matches(row: Record<string, unknown>, where: Record<string, unknown>): boolean {
-  return Object.entries(where).every(([key, cond]) => {
-    if (key === 'OR') return (cond as Record<string, unknown>[]).some((c) => matches(row, c))
-    const value = row[key]
-    if (cond === null || typeof cond !== 'object' || cond instanceof Date) return value === cond
-    const c = cond as { not?: unknown; gt?: number | Date; lt?: number | Date }
-    if ('not' in c) return value !== c.not
-    if (value == null) return false
-    if (c.gt !== undefined) return (value as number | Date) > c.gt
-    if (c.lt !== undefined) return (value as number | Date) < c.lt
-    throw new Error(`Unhandled condition on ${key}`)
-  })
-}
-
-const client = {
-  serviceRecord: {
-    findFirst: async ({ where }: { where: Record<string, unknown> }) =>
-      state.jobs.find((j) => matches(j, where)) ?? null,
-    aggregate: async ({ where }: { where: Record<string, unknown> }) => {
-      const readings = state.jobs.filter((j) => matches(j, where)).map((j) => j.mileage as number)
-      return { _max: { mileage: readings.length ? Math.max(...readings) : null } }
-    },
-  },
-  vehicle: {
-    updateMany: async ({
-      where,
-      data,
-    }: {
-      where: Record<string, unknown>
-      data: { mileage: number }
-    }) => {
-      const hit = state.vehicles.filter((v) => matches(v, where))
-      for (const v of hit) v.mileage = data.mileage
-      return { count: hit.length }
-    },
-  },
-} as unknown as Parameters<typeof applyJobReading>[0]
-
-function job(id: string, date: string, mileage: number | null, over: Partial<Job> = {}): Job {
-  const row = {
-    id,
-    organizationId: ORG,
-    vehicleId: VEHICLE,
-    mileage,
-    startDateTime: day(date),
-    serviceDate: day(date),
-    ...over,
-  }
-  state.jobs.push(row)
-  return row
-}
-
-const vehicle = () => state.vehicles[0]
-
-/** A reading saved on a job, the way each writer reports it. */
-function save(j: Job, reading: number | null, previousReading?: number | null) {
-  j.mileage = reading
-  return applyJobReading(client, {
-    organizationId: ORG,
-    vehicleId: j.vehicleId,
-    jobId: j.id,
-    jobDate: jobReadingDate(j),
-    reading,
-    previousReading,
-  })
-}
-
-beforeEach(() => {
-  state.vehicles = [{ id: VEHICLE, organizationId: ORG, mileage: 100_000 }]
-  state.jobs = []
-})
-
-describe('a job reading and the vehicle', () => {
-  it('moves the vehicle forward when the newest job reads higher', async () => {
-    job('old', '2026-03-01', 90_000)
-    const today = job('today', '2026-11-19', null)
-    expect(await save(today, 104_500, null)).toBe(true)
-    expect(vehicle().mileage).toBe(104_500)
-  })
-
-  it('leaves the vehicle alone when the reading is lower', async () => {
-    const today = job('today', '2026-11-19', null)
-    expect(await save(today, 99_000, null)).toBe(false)
-    expect(vehicle().mileage).toBe(100_000)
-  })
-
-  it('leaves the vehicle alone when the reading is the same', async () => {
-    const today = job('today', '2026-11-19', null)
-    expect(await save(today, 100_000, null)).toBe(false)
-    expect(vehicle().mileage).toBe(100_000)
-  })
-
-  it('gives a vehicle with no reading its first one', async () => {
-    vehicle().mileage = 0
-    const first = job('first', '2026-11-19', null)
-    expect(await save(first, 12_345)).toBe(true)
-    expect(vehicle().mileage).toBe(12_345)
-  })
-
-  it('says nothing for a cleared reading or a zero', async () => {
-    const today = job('today', '2026-11-19', 104_500)
-    expect(await save(today, null, 104_500)).toBe(false)
-    expect(await save(today, 0, null)).toBe(false)
-    expect(vehicle().mileage).toBe(100_000)
-  })
-
-  it('does not let an old job being edited push today’s reading forward', async () => {
-    const old = job('old', '2026-03-01', 90_000)
-    job('newer', '2026-10-01', 100_000)
-    // A slip of the finger on the March job: one digit too many.
-    expect(await save(old, 900_000, 90_000)).toBe(false)
-    expect(vehicle().mileage).toBe(100_000)
-  })
-
-  it('is not held back by a later booking that has no reading yet', async () => {
-    const today = job('today', '2026-11-19', null)
-    job('booked', '2026-12-10', null)
-    expect(await save(today, 104_500, null)).toBe(true)
-    expect(vehicle().mileage).toBe(104_500)
-  })
-
-  it('does not undo a reading corrected by hand when the job is saved again', async () => {
-    // The cluster was replaced on this job: 180 000 on the way in, and the
-    // vehicle set to the new odometer's 5 on the vehicle form.
-    const today = job('today', '2026-11-19', 180_000)
-    vehicle().mileage = 5
-    expect(await save(today, 180_000, 180_000)).toBe(false)
-    expect(vehicle().mileage).toBe(5)
-  })
-
-  it('counts a later job that reads zero, as after a new odometer', async () => {
-    // The cluster was replaced: the newest job and the vehicle both read 0.
-    vehicle().mileage = 0
-    const old = job('old', '2026-03-01', null)
-    job('newer', '2026-10-01', 0)
-    expect(await save(old, 180_000, null)).toBe(false)
-    expect(vehicle().mileage).toBe(0)
-  })
-
-  it('dates a job without a start by its service date', async () => {
-    const undated = job('undated', '2026-03-01', null, { startDateTime: null })
-    job('newer', '2026-10-01', 100_000, { startDateTime: null })
-    expect(await save(undated, 150_000, null)).toBe(false)
-    const latest = job('latest', '2026-11-19', null, { startDateTime: null })
-    expect(await save(latest, 150_000, null)).toBe(true)
-    expect(vehicle().mileage).toBe(150_000)
-  })
-
-  it('never touches another workshop’s vehicle or reads its jobs', async () => {
-    state.vehicles.push({ id: VEHICLE, organizationId: 'org-2', mileage: 10 })
-    job('theirs', '2026-12-01', 500_000, { organizationId: 'org-2' })
-    const today = job('today', '2026-11-19', null)
-    expect(await save(today, 104_500, null)).toBe(true)
-    expect(state.vehicles[1].mileage).toBe(10)
-  })
-})
-
-describe('the last reading a job is compared with', () => {
-  const lastFor = (j: Job) =>
-    lastReadingBeforeJob(client, {
-      organizationId: ORG,
-      vehicleId: VEHICLE,
-      jobId: j.id,
-      jobDate: jobReadingDate(j),
-      vehicleReading: vehicle().mileage,
-    })
-
-  it('is the vehicle’s for the newest job', async () => {
-    job('old', '2026-03-01', 90_000)
-    expect(await lastFor(job('today', '2026-11-19', null))).toBe(100_000)
-  })
-
-  it('is an earlier job’s when that is higher than the vehicle’s', async () => {
-    job('old', '2026-03-01', 120_000)
-    expect(await lastFor(job('today', '2026-11-19', null))).toBe(120_000)
-  })
-
-  it('is the earlier job’s for an old job, not today’s reading', async () => {
-    job('first', '2025-01-10', 60_000)
-    const old = job('old', '2026-03-01', 90_000)
-    job('newer', '2026-10-01', 100_000)
-    expect(await lastFor(old)).toBe(60_000)
-  })
-
-  it('is nothing when nothing is known', async () => {
-    vehicle().mileage = 0
-    expect(await lastFor(job('today', '2026-11-19', null))).toBeNull()
-  })
-})
-
 describe('what counts as a lower reading in the field', () => {
   it('is a number below the last one', () => {
     expect(isLowerReading('99999', 100_000)).toBe(true)
@@ -241,3 +29,37 @@ describe('what counts as a lower reading in the field', () => {
     expect(isLowerReading('5', 0)).toBe(false)
   })
 })
+
+describe('what counts as much higher in the field', () => {
+  it('is more than 100,000 above for a distance, kilometres and miles alike', () => {
+    expect(MUCH_HIGHER_READING.distance).toBe(100_000)
+    expect(isMuchHigherReading('1490000', 148_000, 'distance')).toBe(true)
+    expect(isMuchHigherReading('248001', 148_000, 'distance')).toBe(true)
+    expect(isMuchHigherReading('248000', 148_000, 'distance')).toBe(false)
+    expect(isMuchHigherReading('149000', 148_000, 'distance')).toBe(false)
+  })
+
+  it('is more than 5,000 above for engine hours', () => {
+    expect(MUCH_HIGHER_READING.hours).toBe(5_000)
+    expect(isMuchHigherReading('6241', 1_240, 'hours')).toBe(true)
+    expect(isMuchHigherReading('6240', 1_240, 'hours')).toBe(false)
+    // The distance limit does not apply to hours, nor the hours one to distance.
+    expect(isMuchHigherReading('12400', 1_240, 'distance')).toBe(false)
+  })
+
+  it('is nothing without a last reading, with a last reading of 0, or an empty field', () => {
+    expect(isMuchHigherReading('9000000', null, 'distance')).toBe(false)
+    expect(isMuchHigherReading('9000000', 0, 'distance')).toBe(false)
+    expect(isMuchHigherReading('', 148_000, 'distance')).toBe(false)
+    expect(isMuchHigherReading('abc', 148_000, 'distance')).toBe(false)
+  })
+})
+
+describe('the one notice a reading field shows', () => {
+  it('is lower, much higher, or nothing, never two', () => {
+    expect(readingNotice('100', 148_000, 'distance')).toBe('lower')
+    expect(readingNotice('1480000', 148_000, 'distance')).toBe('higher')
+    expect(readingNotice('152000', 148_000, 'distance')).toBeNull()
+    expect(readingNotice('148000', 148_000, 'distance')).toBeNull()
+  })
+})

+ 0 - 127
src/__tests__/features/vehicles/work-order-lower-reading.test.tsx

@@ -1,127 +0,0 @@
-/**
- * The reading on the work order: typing one below the last known reading says
- * so beside the field, and never anything when readings only go up. It is a
- * notice, not a stop: the field stays as typed, for the save to send.
- */
-
-import { describe, expect, it, vi } from 'vitest'
-import { fireEvent, render, screen } from '@testing-library/react'
-
-vi.mock('@/features/quotes/Components/VehicleCombobox', () => ({ VehicleCombobox: () => null }))
-
-import { ServiceTypeProvider } from '@/components/service-type-context'
-import { JobFactsCard } from '@/features/vehicles/Components/service-page/modern/JobFactsCard'
-
-type Props = React.ComponentProps<typeof JobFactsCard>
-
-const VEHICLE = {
-  id: 'veh-1',
-  make: 'Scania',
-  model: 'R 450',
-  year: 2019,
-  vin: null,
-  licensePlate: 'ZZ19 TST',
-  mileage: 412380,
-  customer: null,
-}
-
-function renderCard(
-  over: { mileage?: number | null; lastReading?: number | null; marine?: boolean } = {}
-) {
-  const initialData = {
-    id: 'job-1',
-    mileage: over.mileage === undefined ? null : over.mileage,
-    lastReading: over.lastReading === undefined ? 412380 : over.lastReading,
-  } as Props['initialData']
-  const card = (
-    <JobFactsCard
-      record={{ id: 'job-1', vehicle: VEHICLE, customer: null } as unknown as Props['record']}
-      currencyCode="GBP"
-      initialData={initialData}
-      vehicleName="2019 Scania R 450"
-      selectedVehicleId="veh-1"
-      setSelectedVehicleId={vi.fn()}
-      techName=""
-      distanceUnit="km"
-    />
-  )
-  return render(
-    over.marine ? <ServiceTypeProvider serviceType="marine">{card}</ServiceTypeProvider> : card
-  )
-}
-
-const NOTICE = 'Lower than the last reading (412,380 km). You can still save it.'
-
-describe('the reading on a work order', () => {
-  it('says nothing on a page as it loads, even with a saved reading below the last one', () => {
-    renderCard({ mileage: 400000 })
-    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
-  })
-
-  it('says nothing when the reading typed is higher or the same', () => {
-    renderCard()
-    const field = screen.getByLabelText('Mileage')
-    fireEvent.change(field, { target: { value: '415000' } })
-    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
-    fireEvent.change(field, { target: { value: '412380' } })
-    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
-    expect(field).not.toHaveAttribute('aria-describedby')
-  })
-
-  it('says a lower reading is lower, beside the field, and leaves it as typed', () => {
-    renderCard()
-    const field = screen.getByLabelText('Mileage')
-    fireEvent.change(field, { target: { value: '41238' } })
-    expect(screen.getByRole('status')).toHaveTextContent(NOTICE)
-    expect(field).toHaveAccessibleDescription(NOTICE.replace(' km', '\u00a0km'))
-    // Nothing is refused: the field holds what was typed and is not marked invalid.
-    expect(field).toHaveValue(41238)
-    expect(field).toBeValid()
-    expect(field).toBeEnabled()
-  })
-
-  it('is still there after the page has saved the reading by itself', () => {
-    const view = renderCard()
-    fireEvent.change(screen.getByLabelText('Mileage'), { target: { value: '41238' } })
-    // The autosave lands and the page hands the card the saved job.
-    view.rerender(
-      <JobFactsCard
-        record={{ id: 'job-1', vehicle: VEHICLE, customer: null } as unknown as Props['record']}
-        currencyCode="GBP"
-        initialData={{ id: 'job-1', mileage: 41238, lastReading: 412380 } as Props['initialData']}
-        vehicleName="2019 Scania R 450"
-        selectedVehicleId="veh-1"
-        setSelectedVehicleId={vi.fn()}
-        techName=""
-        distanceUnit="km"
-      />
-    )
-    expect(screen.getByRole('status')).toHaveTextContent(NOTICE)
-  })
-
-  it('goes quiet again when the field is emptied or corrected upwards', () => {
-    renderCard()
-    const field = screen.getByLabelText('Mileage')
-    fireEvent.change(field, { target: { value: '100' } })
-    expect(screen.getByTestId('lower-reading-notice')).toBeInTheDocument()
-    fireEvent.change(field, { target: { value: '' } })
-    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
-    fireEvent.change(field, { target: { value: '100' } })
-    fireEvent.change(field, { target: { value: '413000' } })
-    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
-  })
-
-  it('says nothing when no reading is known for the vehicle', () => {
-    renderCard({ lastReading: null })
-    fireEvent.change(screen.getByLabelText('Mileage'), { target: { value: '5' } })
-    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
-  })
-
-  it('speaks of engine hours in a boat workshop', () => {
-    renderCard({ lastReading: 1240, marine: true })
-    fireEvent.change(screen.getByLabelText('Engine Hours'), { target: { value: '900' } })
-    expect(screen.getByRole('status')).toHaveTextContent(
-      'Lower than the last reading (1,240 hours). You can still save it.'
-    )
-  })
-})

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

@@ -0,0 +1,243 @@
+/**
+ * The reading on the work order. Typing one below the last known reading says
+ * so quietly beside the field; one so far above it that a digit may have
+ * slipped in is asked about under the field, and the save holds it back until
+ * it is answered (work-order-reading-question.test.tsx). Nothing at all when
+ * readings go up by a normal amount.
+ */
+
+import { describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen } from '@testing-library/react'
+
+vi.mock('@/features/quotes/Components/VehicleCombobox', () => ({ VehicleCombobox: () => null }))
+
+import { ServiceTypeProvider } from '@/components/service-type-context'
+import { JobFactsCard } from '@/features/vehicles/Components/service-page/modern/JobFactsCard'
+
+type Props = React.ComponentProps<typeof JobFactsCard>
+
+const VEHICLE = {
+  id: 'veh-1',
+  make: 'Scania',
+  model: 'R 450',
+  year: 2019,
+  vin: null,
+  licensePlate: 'ZZ19 TST',
+  mileage: 412380,
+  customer: null,
+}
+
+function renderCard(
+  over: { mileage?: number | null; lastReading?: number | null; marine?: boolean } = {}
+) {
+  const initialData = {
+    id: 'job-1',
+    mileage: over.mileage === undefined ? null : over.mileage,
+    lastReading: over.lastReading === undefined ? 412380 : over.lastReading,
+  } as Props['initialData']
+  const card = (
+    <JobFactsCard
+      record={{ id: 'job-1', vehicle: VEHICLE, customer: null } as unknown as Props['record']}
+      currencyCode="GBP"
+      initialData={initialData}
+      vehicleName="2019 Scania R 450"
+      selectedVehicleId="veh-1"
+      setSelectedVehicleId={vi.fn()}
+      techName=""
+      distanceUnit="km"
+    />
+  )
+  return render(
+    over.marine ? <ServiceTypeProvider serviceType="marine">{card}</ServiceTypeProvider> : card
+  )
+}
+
+const NOTICE = 'Lower than the last reading (412,380 km). You can still save it.'
+
+describe('the reading on a work order', () => {
+  it('says nothing on a page as it loads, even with a saved reading below the last one', () => {
+    renderCard({ mileage: 400000 })
+    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
+  })
+
+  it('says nothing when the reading typed is higher or the same', () => {
+    renderCard()
+    const field = screen.getByLabelText('Mileage')
+    fireEvent.change(field, { target: { value: '415000' } })
+    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
+    fireEvent.change(field, { target: { value: '412380' } })
+    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
+    expect(field).not.toHaveAttribute('aria-describedby')
+  })
+
+  it('says a lower reading is lower, beside the field, and leaves it as typed', () => {
+    renderCard()
+    const field = screen.getByLabelText('Mileage')
+    fireEvent.change(field, { target: { value: '41238' } })
+    expect(screen.getByRole('status')).toHaveTextContent(NOTICE)
+    expect(field).toHaveAccessibleDescription(NOTICE.replace(' km', '\u00a0km'))
+    // Nothing is refused: the field holds what was typed and is not marked invalid.
+    expect(field).toHaveValue(41238)
+    expect(field).toBeValid()
+    expect(field).toBeEnabled()
+  })
+
+  it('is still there after the page has saved the reading by itself', () => {
+    const view = renderCard()
+    fireEvent.change(screen.getByLabelText('Mileage'), { target: { value: '41238' } })
+    // The autosave lands and the page hands the card the saved job.
+    view.rerender(
+      <JobFactsCard
+        record={{ id: 'job-1', vehicle: VEHICLE, customer: null } as unknown as Props['record']}
+        currencyCode="GBP"
+        initialData={{ id: 'job-1', mileage: 41238, lastReading: 412380 } as Props['initialData']}
+        vehicleName="2019 Scania R 450"
+        selectedVehicleId="veh-1"
+        setSelectedVehicleId={vi.fn()}
+        techName=""
+        distanceUnit="km"
+      />
+    )
+    expect(screen.getByRole('status')).toHaveTextContent(NOTICE)
+  })
+
+  it('goes quiet again when the field is emptied or corrected upwards', () => {
+    renderCard()
+    const field = screen.getByLabelText('Mileage')
+    fireEvent.change(field, { target: { value: '100' } })
+    expect(screen.getByTestId('lower-reading-notice')).toBeInTheDocument()
+    fireEvent.change(field, { target: { value: '' } })
+    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
+    fireEvent.change(field, { target: { value: '100' } })
+    fireEvent.change(field, { target: { value: '413000' } })
+    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
+  })
+
+  it('says nothing when no reading is known for the vehicle', () => {
+    renderCard({ lastReading: null })
+    fireEvent.change(screen.getByLabelText('Mileage'), { target: { value: '5' } })
+    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
+  })
+
+  it('speaks of engine hours in a boat workshop', () => {
+    renderCard({ lastReading: 1240, marine: true })
+    fireEvent.change(screen.getByLabelText('Engine Hours'), { target: { value: '900' } })
+    expect(screen.getByRole('status')).toHaveTextContent(
+      'Lower than the last reading (1,240 hours). You can still save it.'
+    )
+  })
+})
+
+describe('a reading far above the last one on a work order', () => {
+  const ASK = 'Are you sure this reading is correct?'
+  const BODY = '4,123,800 km is much higher than the last reading, 412,380 km.'
+
+  function renderAsking(over: { confirmedReading?: number | null; marine?: boolean } = {}) {
+    const onConfirmReading = vi.fn()
+    const card = (
+      <JobFactsCard
+        record={{ id: 'job-1', vehicle: VEHICLE, customer: null } as unknown as Props['record']}
+        currencyCode="GBP"
+        initialData={
+          {
+            id: 'job-1',
+            mileage: null,
+            lastReading: over.marine ? 1240 : 412380,
+          } as Props['initialData']
+        }
+        vehicleName="2019 Scania R 450"
+        selectedVehicleId="veh-1"
+        setSelectedVehicleId={vi.fn()}
+        techName=""
+        distanceUnit="km"
+        confirmedReading={over.confirmedReading ?? null}
+        onConfirmReading={onConfirmReading}
+      />
+    )
+    const view = render(
+      over.marine ? <ServiceTypeProvider serviceType="marine">{card}</ServiceTypeProvider> : card
+    )
+    return { onConfirmReading, view }
+  }
+
+  it('asks under the field, with both readings, and only that', () => {
+    renderAsking()
+    const field = screen.getByLabelText('Mileage')
+    fireEvent.change(field, { target: { value: '4123800' } })
+    const question = screen.getByTestId('reading-question')
+    expect(question).toHaveTextContent(ASK)
+    expect(question).toHaveTextContent(BODY)
+    expect(screen.queryByTestId('higher-reading-notice')).not.toBeInTheDocument()
+    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
+    // Nothing pops up over the field: it keeps what was typed.
+    expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+    expect(field).toHaveValue(4123800)
+  })
+
+  it('Yes, it is correct says yes to that value', () => {
+    const { onConfirmReading } = renderAsking()
+    fireEvent.change(screen.getByLabelText('Mileage'), { target: { value: '4123800' } })
+    fireEvent.click(screen.getByRole('button', { name: 'Yes, it is correct' }))
+    expect(onConfirmReading).toHaveBeenCalledWith(4123800)
+  })
+
+  it('Change it goes back to the field, with the value ready to type over', () => {
+    const { onConfirmReading } = renderAsking()
+    const field = screen.getByLabelText('Mileage') as HTMLInputElement
+    fireEvent.change(field, { target: { value: '4123800' } })
+    fireEvent.click(screen.getByRole('button', { name: 'Change it' }))
+    expect(field).toHaveFocus()
+    expect(onConfirmReading).not.toHaveBeenCalled()
+    fireEvent.change(field, { target: { value: '413800' } })
+    expect(screen.queryByTestId('reading-question')).not.toBeInTheDocument()
+  })
+
+  it('is asked once for a value: not again once confirmed, again for another', () => {
+    renderAsking({ confirmedReading: 4123800 })
+    const field = screen.getByLabelText('Mileage')
+    fireEvent.change(field, { target: { value: '4123800' } })
+    expect(screen.queryByTestId('reading-question')).not.toBeInTheDocument()
+    fireEvent.change(field, { target: { value: '4123900' } })
+    expect(screen.getByTestId('reading-question')).toBeInTheDocument()
+  })
+
+  it('is not asked up to 100,000 above, nor without a last reading', () => {
+    renderAsking()
+    const field = screen.getByLabelText('Mileage')
+    fireEvent.change(field, { target: { value: '512380' } })
+    expect(screen.queryByTestId('reading-question')).not.toBeInTheDocument()
+    fireEvent.change(field, { target: { value: '512381' } })
+    expect(screen.getByTestId('reading-question')).toBeInTheDocument()
+  })
+
+  it('stays after the page saved the rest by itself', () => {
+    const { view } = renderAsking()
+    fireEvent.change(screen.getByLabelText('Mileage'), { target: { value: '4123800' } })
+    view.rerender(
+      <JobFactsCard
+        record={{ id: 'job-1', vehicle: VEHICLE, customer: null } as unknown as Props['record']}
+        currencyCode="GBP"
+        initialData={{ id: 'job-1', mileage: null, lastReading: 412380 } as Props['initialData']}
+        vehicleName="2019 Scania R 450"
+        selectedVehicleId="veh-1"
+        setSelectedVehicleId={vi.fn()}
+        techName=""
+        distanceUnit="km"
+        confirmedReading={null}
+        onConfirmReading={vi.fn()}
+      />
+    )
+    expect(screen.getByTestId('reading-question')).toBeInTheDocument()
+  })
+
+  it('uses 5,000 engine hours, in hours, in a boat workshop', () => {
+    renderAsking({ marine: true })
+    const field = screen.getByLabelText('Engine Hours')
+    fireEvent.change(field, { target: { value: '6240' } })
+    expect(screen.queryByTestId('reading-question')).not.toBeInTheDocument()
+    fireEvent.change(field, { target: { value: '12400' } })
+    expect(screen.getByTestId('reading-question')).toHaveTextContent(
+      '12,400 hours is much higher than the last reading, 1,240 hours.'
+    )
+  })
+})

+ 212 - 0
src/__tests__/features/vehicles/work-order-reading-question.test.tsx

@@ -0,0 +1,212 @@
+/**
+ * A reading far above the last one, and the work order's save.
+ *
+ * The page saves by itself five seconds after an edit, so the question about
+ * the reading is asked under the field (ReadingQuestion), not in a dialog.
+ * Until it is answered, every save (the autosave, the Save button and the
+ * save a link waits for) writes the rest of the work order and holds back
+ * only the reading. The page stays unsaved and says why, so a link waiting
+ * on the save asks the person to stay and answer.
+ */
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }),
+  usePathname: () => '/vehicles/v1/service/job1',
+}))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/components/confirm-dialog', async (importOriginal) => ({
+  ...(await importOriginal<typeof import('@/components/confirm-dialog')>()),
+  useConfirm: () => vi.fn(async () => true),
+}))
+const updateServiceRecord = vi.fn()
+vi.mock('@/features/vehicles/Actions/serviceActions', () => ({
+  updateServiceRecord: (input: unknown) => updateServiceRecord(input),
+  deleteServiceRecord: vi.fn(),
+  deleteServiceAttachment: vi.fn(),
+  toggleManuallyPaid: vi.fn(),
+}))
+vi.mock('@/features/payments/Actions/paymentActions', () => ({
+  createPayment: vi.fn(),
+  deletePayment: vi.fn(),
+}))
+vi.mock('@/features/sms/Actions/smsActions', () => ({ getSmsTemplates: vi.fn() }))
+
+import { useServiceActions } from '@/features/vehicles/Components/service-page/useServiceActions'
+
+type Options = Parameters<typeof useServiceActions>[0]
+
+const WAITING = 'The reading is not saved yet. Answer the question under it first.'
+
+afterEach(() => {
+  cleanup()
+  document.body.innerHTML = ''
+})
+
+beforeEach(() => {
+  updateServiceRecord.mockReset().mockResolvedValue({ success: true })
+})
+
+/** The work order as the page holds it: last reading 148,000, nothing saved on the job yet. */
+function page(over: { confirmed?: number | null; saved?: number | null } = {}) {
+  const form = {
+    selectedVehicleId: 'v1',
+    type: 'repair',
+    status: 'in-progress',
+    concerns: [],
+    partItems: [],
+    laborItems: [],
+    partItemsForSave: [],
+    laborItemsForSave: [],
+    commitLaborAddedElsewhere: vi.fn(),
+    commitPartsAddedElsewhere: vi.fn(),
+    subtotal: 0,
+    taxRate: 0,
+    taxInclusive: false,
+    taxAmount: 0,
+    totalAmount: 0,
+    discountType: 'none',
+    discountValue: 0,
+    discountAmount: 0,
+    warranty: {},
+    isSavingRef: { current: false },
+    autosaveTimer: { current: null },
+    autosaveRunRef: { current: false },
+    leavingRef: { current: false },
+    lastSaveErrorRef: { current: null as string | null },
+    editRevisionRef: { current: 3 },
+    customFieldsSaveRef: { current: null },
+    setLoading: vi.fn(),
+    setHasUnsavedChanges: vi.fn(),
+    flashSaved: vi.fn(),
+    markSaved: vi.fn(),
+    markDirty: vi.fn(),
+    notesRef: { current: { description: '', diagnosticNotes: '', invoiceNotes: '' } },
+    initialData: { id: 'job1', mileage: over.saved ?? null, lastReading: 148000 },
+    confirmedReadingRef: { current: over.confirmed ?? null },
+    acknowledgeSavedLines: vi.fn(),
+  }
+  const hook = renderHook(() =>
+    useServiceActions({
+      record: { id: 'job1' } as unknown as Options['record'],
+      vehicleId: 'v1',
+      currencyCode: 'GBP',
+      formState: form as unknown as Options['formState'],
+    })
+  )
+
+  // The page's form: the title and the reading as typed, and the question
+  // under the reading.
+  const el = document.createElement('form')
+  el.innerHTML = `
+    <input name="title" value="ZZ Brakes" />
+    <input name="mileage" value="1490000" />
+    <div id="reading-question"><button type="button" data-reading-confirm>Yes</button></div>`
+  document.body.appendChild(el)
+  const reading = el.querySelector<HTMLInputElement>('input[name="mileage"]') as HTMLInputElement
+
+  const save = (how: { autosave?: boolean; leaving?: boolean } = {}) => {
+    form.autosaveRunRef.current = how.autosave ?? false
+    form.leavingRef.current = how.leaving ?? false
+    return act(() =>
+      hook.result.current.handleSubmit({
+        preventDefault: () => undefined,
+        currentTarget: el,
+      } as unknown as React.FormEvent<HTMLFormElement>)
+    )
+  }
+  return { form, save, reading }
+}
+
+const sent = () => updateServiceRecord.mock.calls.at(-1)?.[0] as Record<string, unknown>
+
+describe('a reading far above the last one, not yet answered', () => {
+  it('an autosave writes the rest of the work order and not the reading', async () => {
+    const { form, save } = page()
+    await save({ autosave: true })
+    expect(updateServiceRecord).toHaveBeenCalledTimes(1)
+    expect(sent()).toMatchObject({ id: 'job1', title: 'ZZ Brakes' })
+    // Left out, the job keeps the reading it had.
+    expect(sent().mileage).toBeUndefined()
+    // The page stays unsaved, and says why.
+    expect(form.markSaved).not.toHaveBeenCalled()
+    expect(form.setHasUnsavedChanges).not.toHaveBeenCalled()
+    expect(form.flashSaved).not.toHaveBeenCalled()
+    expect(form.lastSaveErrorRef.current).toBe(WAITING)
+    // Nothing moves the person away from what they are typing.
+    expect(document.activeElement).toBe(document.body)
+    expect(form.isSavingRef.current).toBe(false)
+    // The lines it sent are the server's now: the refresh after the save must
+    // not bring them back as lines added elsewhere, to be saved a second time.
+    expect(form.acknowledgeSavedLines).toHaveBeenCalledWith({
+      parts: sent().partItems,
+      labor: sent().laborItems,
+    })
+  })
+
+  it('the Save button does the same, and takes the person to the question', async () => {
+    const { form, save } = page()
+    await save()
+    expect(sent().mileage).toBeUndefined()
+    expect(sent().title).toBe('ZZ Brakes')
+    expect(form.markSaved).not.toHaveBeenCalled()
+    expect(document.activeElement).toHaveAttribute('data-reading-confirm')
+  })
+
+  it('a link waiting on the save is told why the page is still unsaved', async () => {
+    const { form, save } = page()
+    await save({ leaving: true })
+    expect(sent().mileage).toBeUndefined()
+    expect(form.markSaved).not.toHaveBeenCalled()
+    // The leave dialog reads this and offers to stay.
+    expect(form.lastSaveErrorRef.current).toBe(WAITING)
+    expect(document.activeElement).toBe(document.body)
+  })
+
+  it('does not queue another autosave unless something else was edited meanwhile', async () => {
+    const { form, save } = page()
+    await save({ autosave: true })
+    expect(form.markDirty).not.toHaveBeenCalled()
+
+    // An edit made while the save ran is newer and gets a save of its own.
+    updateServiceRecord.mockImplementationOnce(async () => {
+      form.editRevisionRef.current += 1
+      return { success: true }
+    })
+    await save({ autosave: true })
+    expect(form.markDirty).toHaveBeenCalledTimes(1)
+  })
+})
+
+describe('once answered, or when nothing needs asking', () => {
+  it('a reading the person said yes to is saved, and the page is saved', async () => {
+    const { form, save } = page({ confirmed: 1490000 })
+    await save({ autosave: true })
+    expect(sent().mileage).toBe(1490000)
+    expect(form.markSaved).toHaveBeenCalledWith(3)
+    expect(form.lastSaveErrorRef.current).toBeNull()
+  })
+
+  it('a different far-higher value is held back again', async () => {
+    const { save, reading } = page({ confirmed: 1490000 })
+    reading.value = '1590000'
+    await save({ autosave: true })
+    expect(sent().mileage).toBeUndefined()
+  })
+
+  it('a reading changed back to a normal one is saved as usual', async () => {
+    const { form, save, reading } = page()
+    reading.value = '149000'
+    await save({ autosave: true })
+    expect(sent().mileage).toBe(149000)
+    expect(form.markSaved).toHaveBeenCalled()
+  })
+
+  it('a reading already saved on the job is not asked about again', async () => {
+    const { form, save } = page({ saved: 1490000 })
+    await save({ autosave: true })
+    expect(sent().mileage).toBe(1490000)
+    expect(form.markSaved).toHaveBeenCalled()
+  })
+})

+ 24 - 3
src/__tests__/features/vehicles/work-order-reading-update.test.ts

@@ -73,8 +73,18 @@ beforeEach(() => {
   } as any)
   vi.mocked(db.user.findUnique).mockResolvedValue({ isSuperAdmin: false } as any)
   vi.mocked(db.appSetting.findMany).mockResolvedValue([])
-  vi.mocked(db.vehicle.findFirst).mockImplementation((async ({ where }: any) =>
-    where.organizationId === ORG && where.id in state.vehicles ? { id: where.id } : null) as any)
+  vi.mocked(db.vehicle.findFirst).mockImplementation((async ({ where }: any) => {
+    if (where.organizationId !== ORG || !(where.id in state.vehicles)) return null
+    // No vehicle here remembers a job: the correction of one that does is
+    // tested on a real database (src/__tests__/db/vehicle-reading.db.test.ts).
+    if (where.readingJobId) return null
+    return {
+      id: where.id,
+      mileage: state.vehicles[where.id],
+      readingJobId: null,
+      readingBeforeJob: null,
+    }
+  }) as any)
   vi.mocked(db.serviceRecord.findFirst).mockImplementation((async ({ where }: any) => {
     // The rule's question: another job on the vehicle, later, with a reading.
     if (where.mileage && 'not' in where.mileage) {
@@ -89,14 +99,25 @@ beforeEach(() => {
       : null
   }) as any)
   vi.mocked(db.vehicle.updateMany).mockImplementation((async ({ where, data }: any) => {
-    if (where.organizationId !== ORG || !(state.vehicles[where.id] < where.mileage.lt))
+    // Moved up only as it was read (compare and set).
+    if (
+      where.organizationId !== ORG ||
+      data.mileage === undefined ||
+      state.vehicles[where.id] !== where.mileage
+    )
       return { count: 0 }
     state.vehicles[where.id] = data.mileage
     return { count: 1 }
   }) as any)
   vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
     fn({
+      // The job's row lock, and what it read before the save.
+      $queryRaw: vi.fn(async () => [
+        { mileage: state.job.mileage, vehicleId: state.job.vehicleId },
+      ]),
+      vehicle: db.vehicle,
       serviceRecord: {
+        findFirst: db.serviceRecord.findFirst,
         update: vi.fn(async ({ data }: any) => {
           if (data.mileage !== undefined) state.job.mileage = data.mileage
           if (data.vehicleId) state.job.vehicleId = data.vehicleId

+ 38 - 10
src/__tests__/features/workorders/create-workorder.test.ts

@@ -70,7 +70,13 @@ const USER_ID = 'user-1'
 const VEHICLE_ID = 'veh-1'
 const TECH_ID = 'tech-1'
 
-const VEHICLE = { id: VEHICLE_ID, organizationId: ORG, mileage: 50000 }
+const VEHICLE = {
+  id: VEHICLE_ID,
+  organizationId: ORG,
+  mileage: 50000,
+  readingJobId: null,
+  readingBeforeJob: null,
+}
 
 function setupAuth() {
   mockSession.mockResolvedValue({ user: { id: USER_ID, email: 'user@example.com' } } as any)
@@ -90,10 +96,10 @@ function setupCommonMocks() {
   vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(null) // no previous records
   vi.mocked(db.$queryRaw).mockResolvedValue([{ highest: null }] as any)
   vi.mocked(db.vehicle.update).mockResolvedValue(VEHICLE as any)
-  // The vehicle's reading is moved by the shared rule, which compares in the
-  // database: this stands in for "the reading is higher than the vehicle's".
+  // The vehicle's reading is moved by the shared rule, which sets it only on
+  // the vehicle as it read it (compare and set).
   vi.mocked(db.vehicle.updateMany).mockImplementation((async ({ where, data }: any) => ({
-    count: VEHICLE.mileage < where.mileage.lt && data.mileage === where.mileage.lt ? 1 : 0,
+    count: where.mileage === VEHICLE.mileage && data.mileage > VEHICLE.mileage ? 1 : 0,
   })) as any)
 }
 
@@ -473,7 +479,15 @@ describe('createServiceRecord — vehicle mileage', () => {
       .mockResolvedValue({ id, vehicleId: VEHICLE_ID, startDateTime: START, serviceDate: START })
     vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
       fn({
-        serviceRecord: { create: mockCreate },
+        // The vehicle's reading is decided in a transaction of its own,
+        // under the vehicle's row lock; it reads the same tables.
+        $queryRaw: async () => [],
+        serviceRecord: {
+          create: mockCreate,
+          findFirst: db.serviceRecord.findFirst,
+          aggregate: vi.fn(async () => ({ _max: { mileage: null } })),
+        },
+        vehicle: db.vehicle,
         servicePart: { createMany: vi.fn() },
         serviceLabor: { createMany: vi.fn() },
         serviceAttachment: { createMany: vi.fn() },
@@ -487,7 +501,7 @@ describe('createServiceRecord — vehicle mileage', () => {
     const moved = vi
       .mocked(db.vehicle.updateMany)
       .mock.calls.map(([args]) => args as any)
-      .filter((args) => VEHICLE.mileage < args.where.mileage.lt)
+      .filter((args) => args.data.mileage > VEHICLE.mileage)
     return moved.length ? moved[0].data.mileage : null
   }
 
@@ -504,10 +518,16 @@ describe('createServiceRecord — vehicle mileage', () => {
 
     expect(result.success).toBe(true)
     expect(movedTo()).toBe(55000)
-    // Scoped to the workshop, and only ever upwards.
+    // Scoped to the workshop, set only on the vehicle as it was read, and
+    // remembering the job that set it and what the vehicle read before.
     expect(vi.mocked(db.vehicle.updateMany)).toHaveBeenCalledWith({
-      where: { id: VEHICLE_ID, organizationId: ORG, mileage: { lt: 55000 } },
-      data: { mileage: 55000 },
+      where: {
+        id: VEHICLE_ID,
+        organizationId: ORG,
+        mileage: VEHICLE.mileage,
+        readingJobId: null,
+      },
+      data: { mileage: 55000, readingJobId: 'sr-mile', readingBeforeJob: VEHICLE.mileage },
     })
   })
 
@@ -572,7 +592,15 @@ describe('createServiceRecord — labor items', () => {
     const mockLaborCreateMany = vi.fn()
     vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
       fn({
-        serviceRecord: { create: mockCreate },
+        // The vehicle's reading is decided in a transaction of its own,
+        // under the vehicle's row lock; it reads the same tables.
+        $queryRaw: async () => [],
+        serviceRecord: {
+          create: mockCreate,
+          findFirst: db.serviceRecord.findFirst,
+          aggregate: vi.fn(async () => ({ _max: { mileage: null } })),
+        },
+        vehicle: db.vehicle,
         servicePart: { createMany: vi.fn() },
         serviceLabor: { createMany: mockLaborCreateMany },
         serviceAttachment: { createMany: vi.fn() },

+ 5 - 1
src/__tests__/multitenancy/service-record-isolation.test.ts

@@ -158,7 +158,11 @@ describe('updateServiceRecord — cross-org isolation', () => {
     vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(ORG_A_RECORD as any)
     const updatedRecord = { ...ORG_A_RECORD, title: 'Brake Pads' }
     vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
-      fn({ serviceRecord: { update: vi.fn().mockResolvedValue(updatedRecord) } })
+      fn({
+        $queryRaw: async () => [],
+        vehicle: { findFirst: async () => null, updateMany: async () => ({ count: 0 }) },
+        serviceRecord: { update: vi.fn().mockResolvedValue(updatedRecord) },
+      })
     )
     const result = await updateServiceRecord({ id: 'sr-a', title: 'Brake Pads' })
     expect(result.success).toBe(true)

+ 32 - 19
src/app/api/v1/tech/jobs/[id]/checkin/route.ts

@@ -5,7 +5,11 @@ import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { apiError, apiOk, withApiAuth } from '@/lib/with-api-auth'
 import { BODY_TYPES } from '@/features/condition-map/Lib/drawingTypes'
 import { loadCheckin } from '@/features/condition-map/Lib/checkin.server'
-import { applyJobReading, jobReadingDate } from '@/features/vehicles/Lib/vehicleReading'
+import {
+  applyJobReading,
+  jobReadingDate,
+  lockJobReading,
+} from '@/features/vehicles/Lib/vehicleReading'
 import {
   appLocale,
   checkinJobFor,
@@ -67,27 +71,36 @@ export async function PATCH(request: Request, { params }: { params: Promise<{ id
       await noteArrival(ctx.organizationId, job)
 
       if (mileage !== undefined) {
-        const before = await db.serviceRecord.findFirst({
-          where: { id: job.id, organizationId: ctx.organizationId },
-          select: { mileage: true, startDateTime: true, serviceDate: true },
-        })
-        await db.serviceRecord.updateMany({
-          where: { id: job.id, organizationId: ctx.organizationId },
-          data: { mileage },
-        })
-        // A lower reading is kept on the job and never winds the vehicle
-        // back; whether a higher one moves it is the same rule as on the web
-        // (vehicleReading.ts).
-        if (before) {
-          await applyJobReading(db, {
+        // The same rule as on the web (vehicleReading.ts): a higher reading
+        // may move the vehicle on, a lower one is kept on the job, and a
+        // correction of the job that set the vehicle's reading brings the
+        // vehicle with it. Under the job's row lock, as the web save is.
+        await db.$transaction(async (tx) => {
+          const locked = await lockJobReading(tx, {
             organizationId: ctx.organizationId,
-            vehicleId: job.vehicleId,
             jobId: job.id,
-            jobDate: jobReadingDate(before),
-            reading: mileage,
-            previousReading: before.mileage,
           })
-        }
+          const before = await tx.serviceRecord.findFirst({
+            where: { id: job.id, organizationId: ctx.organizationId },
+            select: { startDateTime: true, serviceDate: true },
+          })
+          await tx.serviceRecord.updateMany({
+            where: { id: job.id, organizationId: ctx.organizationId },
+            data: { mileage },
+          })
+          // The vehicle the job is on now, under the lock: it may have been
+          // moved since the job was looked up.
+          if (locked?.vehicleId && before) {
+            await applyJobReading(tx, {
+              organizationId: ctx.organizationId,
+              vehicleId: locked.vehicleId,
+              jobId: job.id,
+              jobDate: jobReadingDate(before),
+              reading: mileage,
+              previousReading: locked.mileage,
+            })
+          }
+        })
       }
       if (bodyType) {
         await db.vehicle.updateMany({

+ 4 - 0
src/features/ai/tools/workshop-columns.ts

@@ -23,6 +23,10 @@ export const HIDDEN_COLUMNS: readonly string[] = [
   'concernId',
   'telegramChatId',
   'bookingToken',
+  // Bookkeeping of the vehicle's reading rule (vehicleReading.ts), not a
+  // fact about the vehicle: the reading itself is `mileage`.
+  'readingJobId',
+  'readingBeforeJob',
 ]
 
 export const TABLE_COLUMNS: Readonly<Record<string, readonly string[]>> = {

+ 38 - 26
src/features/import/Actions/importActions.ts

@@ -42,7 +42,11 @@ import {
   detectDecimalSeparator,
 } from '../Lib/normalize'
 import { releaseFiles } from '@/lib/files/manager'
-import { applyJobReading, jobReadingDate } from '@/features/vehicles/Lib/vehicleReading'
+import {
+  applyJobReading,
+  jobReadingDate,
+  READING_SET_BY_HAND,
+} from '@/features/vehicles/Lib/vehicleReading'
 import { escapeHtml } from '@/features/email/Render/escape'
 import { organizationTranslator } from '@/i18n/organization-translator'
 import { serviceRecordFileUrls, vehicleFileUrls } from '@/lib/files/collect'
@@ -457,13 +461,16 @@ async function settleReadings(state: CommitState): Promise<void> {
         if (at > best || (at === best && (job.mileage ?? 0) > (newest.mileage ?? 0))) newest = job
       }
       if (!newest) continue
-      await applyJobReading(db, {
-        organizationId,
-        vehicleId,
-        jobId: newest.id,
-        jobDate: jobReadingDate(newest),
-        reading: newest.mileage,
-      })
+      const job = newest
+      await db.$transaction((tx) =>
+        applyJobReading(tx, {
+          organizationId,
+          vehicleId,
+          jobId: job.id,
+          jobDate: jobReadingDate(job),
+          reading: job.mileage,
+        })
+      )
     } catch {
       // The history is in; a reading that could not be settled stays as it was.
     }
@@ -529,24 +536,29 @@ async function writeRow(tx: Tx, state: CommitState, row: RowPlan): Promise<void>
       if (entity === 'vehicles' && row.action === 'update') {
         await tx.vehicle.update({
           where: { id: vehicleId },
-          data: definedOnly({
-            make: v.make,
-            model: v.model,
-            year: v.year,
-            vin: v.vin,
-            licensePlate: v.licensePlate,
-            color: v.color,
-            mileage: v.mileage,
-            fuelType: v.fuelType,
-            transmission: v.transmission,
-            engineSize: v.engineSize,
-            engineCode: v.engineCode,
-            hsn: v.hsn,
-            tsn: v.tsn,
-            purchaseDate: v.purchaseDate ? new Date(v.purchaseDate) : null,
-            purchasePrice: v.purchasePrice,
-            customerId,
-          }),
+          data: {
+            // A reading from the file is the vehicle's own, no longer a job's
+            // that a correction on the job could take back (vehicleReading.ts).
+            ...(v.mileage != null ? READING_SET_BY_HAND : {}),
+            ...definedOnly({
+              make: v.make,
+              model: v.model,
+              year: v.year,
+              vin: v.vin,
+              licensePlate: v.licensePlate,
+              color: v.color,
+              mileage: v.mileage,
+              fuelType: v.fuelType,
+              transmission: v.transmission,
+              engineSize: v.engineSize,
+              engineCode: v.engineCode,
+              hsn: v.hsn,
+              tsn: v.tsn,
+              purchaseDate: v.purchaseDate ? new Date(v.purchaseDate) : null,
+              purchasePrice: v.purchasePrice,
+              customerId,
+            }),
+          },
         })
       } else if (customerId) {
         // A history row names the owner: attach it when the car has none.

+ 13 - 2
src/features/inspections/Actions/inspectionActions.ts

@@ -16,7 +16,11 @@ import {
 } from '@/features/signatures/Lib/memberSignature.server'
 import { liveCertificateDesign } from '../Pdf/certificateDesign'
 import { loadTaxApplies } from '@/features/settings/Lib/loadTaxApplies'
-import { applyJobReading, jobReadingDate } from '@/features/vehicles/Lib/vehicleReading'
+import {
+  applyJobReading,
+  jobReadingDate,
+  lockJobReading,
+} from '@/features/vehicles/Lib/vehicleReading'
 import { retotalServiceRecord } from '@/features/vehicles/Lib/retotalServiceRecord'
 import { OPEN_SERVICE_STATUSES } from '@/lib/service-record'
 import { defectLineText, defectsWorstFirst } from '../Lib/conversion'
@@ -1016,6 +1020,13 @@ export async function linkWorkOrderToInspection(
       const laborRate = Number(rate?.value) || 0
 
       await db.$transaction(async (tx) => {
+        // What the job read before, under its row lock (vehicleReading.ts).
+        const before = await lockJobReading(tx, { organizationId, jobId: job.id })
+        // Moved to another vehicle since it was looked up: it is no longer a
+        // job this inspection may land on.
+        if (!before || before.vehicleId !== inspection.vehicleId) {
+          throw new Error('Work order not found')
+        }
         await tx.serviceRecord.update({
           where: { id: job.id },
           data: { inspectionId: inspection.id, mileage: inspection.mileage ?? undefined },
@@ -1029,7 +1040,7 @@ export async function linkWorkOrderToInspection(
             jobId: job.id,
             jobDate: jobReadingDate(job),
             reading: inspection.mileage,
-            previousReading: job.mileage,
+            previousReading: before.mileage,
           })
         }
         const lines = [

+ 39 - 23
src/features/vehicles/Actions/serviceActions.ts

@@ -40,7 +40,12 @@ import { assertInvoiceEditable, getDocumentLockSettings } from '@/lib/document-l
 import { DocumentLockedError, invoiceLockState } from '@/lib/document-lock'
 import { deleteCustomFieldValuesOf } from '@/features/custom-fields/Lib/deleteCustomFieldValues'
 import { typeKeySearch } from '@/features/vehicles/Lib/typeKeySetting'
-import { applyJobReading, jobReadingDate } from '@/features/vehicles/Lib/vehicleReading'
+import {
+  applyJobReading,
+  forgetJobReading,
+  jobReadingDate,
+  lockJobReading,
+} from '@/features/vehicles/Lib/vehicleReading'
 import { ACTIVE_HELPERS } from '@/features/workboard/Lib/jobTeam'
 import { FRESH_SHARE_LINK } from '@/lib/share-expiry'
 
@@ -311,6 +316,9 @@ export async function getServiceRecord(recordId: string) {
               vin: true,
               licensePlate: true,
               mileage: true,
+              // Whose reading the vehicle's is: the reading field's notices.
+              readingJobId: true,
+              readingBeforeJob: true,
               // The facts card's "More info": what the desk would otherwise
               // open the vehicle page to read (and copy) mid-job.
               color: true,
@@ -614,13 +622,15 @@ export async function createServiceRecord(input: unknown) {
           where: { id: vehicle.id },
           data: { maintenanceDismissed: false, maintenanceDismissedAt: null },
         })
-        await applyJobReading(db, {
-          organizationId,
-          vehicleId: vehicle.id,
-          jobId: record.id,
-          jobDate: jobReadingDate(record),
-          reading: data.mileage,
-        })
+        await db.$transaction((tx) =>
+          applyJobReading(tx, {
+            organizationId,
+            vehicleId: vehicle.id,
+            jobId: record.id,
+            jobDate: jobReadingDate(record),
+            reading: data.mileage,
+          })
+        )
       }
 
       revalidatePath('/')
@@ -805,6 +815,9 @@ export async function updateServiceRecord(input: unknown) {
       }
 
       const record = await db.$transaction(async (tx) => {
+        // What the job read before this save, under its row lock, so two
+        // saves of the job at once take turns on the vehicle's reading too.
+        const before = await lockJobReading(tx, { organizationId, jobId: id })
         const updated = await tx.serviceRecord.update({
           where: { id },
           data: {
@@ -977,25 +990,28 @@ export async function updateServiceRecord(input: unknown) {
           }
         }
 
-        return updated
-      })
-
-      // The job's reading may become the vehicle's: the rule is in
-      // vehicleReading.ts. A job that moved to another vehicle in this save
-      // speaks for that vehicle, with whatever reading it now carries.
-      if (record.vehicleId) {
-        const sameVehicle = record.vehicleId === existing.vehicleId
-        if (recordData.mileage !== undefined || !sameVehicle) {
-          await applyJobReading(db, {
+        // The job's reading may become the vehicle's, or correct it: the rule
+        // is in vehicleReading.ts. A job that moved to another vehicle in this
+        // save speaks for that vehicle, with whatever reading it now carries;
+        // the vehicle it left keeps its reading, which is no longer the job's.
+        const vehicleBefore = before ? before.vehicleId : existing.vehicleId
+        const sameVehicle = updated.vehicleId === vehicleBefore
+        if (!sameVehicle && vehicleBefore) {
+          await forgetJobReading(tx, { organizationId, jobId: id })
+        }
+        if (updated.vehicleId && (recordData.mileage !== undefined || !sameVehicle)) {
+          await applyJobReading(tx, {
             organizationId,
-            vehicleId: record.vehicleId,
+            vehicleId: updated.vehicleId,
             jobId: id,
-            jobDate: jobReadingDate(record),
-            reading: record.mileage,
-            previousReading: sameVehicle ? existing.mileage : undefined,
+            jobDate: jobReadingDate(updated),
+            reading: updated.mileage,
+            previousReading: sameVehicle ? (before ? before.mileage : existing.mileage) : undefined,
           })
         }
-      }
+
+        return updated
+      })
 
       // Files of removed attachments, let go after the transaction committed.
       await releaseFiles(removedFileUrls, {

+ 8 - 0
src/features/vehicles/Actions/vehicleActions.ts

@@ -26,6 +26,7 @@ import { auditDetails } from '@/lib/audit'
 import { searchYear } from '@/features/vehicles/Lib/searchYear'
 import { searchWordsOf, typeKeySearchTerms } from '../Lib/typeKey'
 import { isTypeKeyEnabled } from '../Lib/typeKeySetting'
+import { READING_SET_BY_HAND } from '../Lib/vehicleReading'
 import { vehicleName } from '@/lib/vehicle-name'
 
 export async function getVehicles() {
@@ -359,6 +360,7 @@ export async function updateVehicle(input: unknown) {
           licensePlate: true,
           vin: true,
           imageUrl: true,
+          mileage: true,
         },
       })
       if (!before) throw new Error('Vehicle not found')
@@ -384,6 +386,12 @@ export async function updateVehicle(input: unknown) {
           customerId: data.customerId !== undefined ? data.customerId || null : undefined,
           // An emptied photo is no photo, not an empty address.
           imageUrl: data.imageUrl !== undefined ? data.imageUrl || null : undefined,
+          // A reading typed here is the vehicle's own, no longer a job's that
+          // a correction on the job could take back (vehicleReading.ts). The
+          // form sends the reading with every save; only a changed one counts.
+          ...(data.mileage !== undefined && data.mileage !== before.mileage
+            ? READING_SET_BY_HAND
+            : {}),
         },
       })
       if (updateResult.count === 0) throw new Error('Vehicle not found')

+ 0 - 48
src/features/vehicles/Components/LowerReadingNotice.tsx

@@ -1,48 +0,0 @@
-'use client'
-
-import { useFormatter, useTranslations } from 'next-intl'
-import { useServiceType } from '@/components/service-type-context'
-import { cn } from '@/lib/utils'
-import { isLowerReading } from '../Lib/vehicleReading'
-
-interface LowerReadingNoticeProps {
-  /** What is in the reading field right now. */
-  entered: string
-  /** The last known reading; nothing is said without one. */
-  last: number | null | undefined
-  /** "km" or "mi", where the caller knows it. */
-  unit?: string
-  id?: string
-  className?: string
-}
-
-/**
- * Says that the reading being typed is below the last known one. It never
- * stops a save: odometers are replaced and typos are corrected. Renders
- * nothing at all otherwise, so a reading that goes up changes nothing.
- */
-export function LowerReadingNotice({
-  entered,
-  last,
-  unit,
-  id,
-  className,
-}: LowerReadingNoticeProps) {
-  const t = useTranslations('vehicles.form')
-  const format = useFormatter()
-  const isMarine = useServiceType() === 'marine'
-  if (last == null || !isLowerReading(entered, last)) return null
-  const reading = format.number(last)
-  return (
-    <p
-      id={id}
-      role="status"
-      data-testid="lower-reading-notice"
-      className={cn('text-xs text-amber-600 dark:text-amber-500', className)}
-    >
-      {isMarine
-        ? t('lowerReadingMarine', { hours: reading })
-        : t('lowerReading', { reading: unit ? `${reading}\u00a0${unit}` : reading })}
-    </p>
-  )
-}

+ 93 - 0
src/features/vehicles/Components/ReadingConfirmDialog.tsx

@@ -0,0 +1,93 @@
+'use client'
+
+import { useRef } from 'react'
+import { useFormatter, useTranslations } from 'next-intl'
+import {
+  AlertDialog,
+  AlertDialogAction,
+  AlertDialogCancel,
+  AlertDialogContent,
+  AlertDialogDescription,
+  AlertDialogFooter,
+  AlertDialogHeader,
+  AlertDialogTitle,
+} from '@/components/ui/alert-dialog'
+import { useServiceType } from '@/components/service-type-context'
+
+interface ReadingConfirmDialogProps {
+  /** The reading being saved, or null while nothing is asked. */
+  entered: number | null
+  /** The last known reading it is far above. */
+  last: number
+  /** "km" or "mi", where the caller knows it. */
+  unit?: string
+  onConfirm: () => void
+  /** Closed without a yes: nothing is saved. */
+  onChange: () => void
+  /** Puts the person back in the reading field, once the dialog has let go of the focus. */
+  focusField: () => void
+}
+
+/**
+ * Asked on Save when a reading is far above the last one (readingNeedsAnswer):
+ * yes saves it, "Change it" goes back to the field with nothing saved.
+ */
+export function ReadingConfirmDialog({
+  entered,
+  last,
+  unit,
+  onConfirm,
+  onChange,
+  focusField,
+}: ReadingConfirmDialogProps) {
+  const t = useTranslations('vehicles.form')
+  const format = useFormatter()
+  const isMarine = useServiceType() === 'marine'
+  // Closing by Yes is an answer; closing any other way (Change it, Escape,
+  // a click outside) goes back to the field.
+  const confirmed = useRef(false)
+  const backToField = useRef(false)
+  const withUnit = (value: number) =>
+    unit && !isMarine ? `${format.number(value)} ${unit}` : format.number(value)
+  return (
+    <AlertDialog
+      open={entered != null}
+      onOpenChange={(open) => {
+        if (open) return
+        backToField.current = !confirmed.current
+        if (!confirmed.current) onChange()
+        confirmed.current = false
+      }}
+    >
+      <AlertDialogContent
+        onCloseAutoFocus={(e) => {
+          e.preventDefault()
+          if (backToField.current) focusField()
+          backToField.current = false
+        }}
+      >
+        <AlertDialogHeader>
+          <AlertDialogTitle>{t('readingConfirmTitle')}</AlertDialogTitle>
+          <AlertDialogDescription>
+            {entered != null &&
+              t(isMarine ? 'readingConfirmBodyMarine' : 'readingConfirmBody', {
+                entered: withUnit(entered),
+                last: withUnit(last),
+              })}
+          </AlertDialogDescription>
+        </AlertDialogHeader>
+        <AlertDialogFooter>
+          <AlertDialogCancel>{t('readingConfirmChange')}</AlertDialogCancel>
+          <AlertDialogAction
+            onClick={() => {
+              confirmed.current = true
+              onConfirm()
+            }}
+          >
+            {t('readingConfirmYes')}
+          </AlertDialogAction>
+        </AlertDialogFooter>
+      </AlertDialogContent>
+    </AlertDialog>
+  )
+}

+ 51 - 0
src/features/vehicles/Components/ReadingNotice.tsx

@@ -0,0 +1,51 @@
+'use client'
+
+import { useFormatter, useTranslations } from 'next-intl'
+import { useServiceType } from '@/components/service-type-context'
+import { cn } from '@/lib/utils'
+import { readingNotice } from '../Lib/vehicleReading'
+
+interface ReadingNoticeProps {
+  /** What is in the reading field right now. */
+  entered: string
+  /** The last known reading; nothing is said without one. */
+  last: number | null | undefined
+  /** "km" or "mi", where the caller knows it. */
+  unit?: string
+  id?: string
+  className?: string
+}
+
+/** Which notice the reading field shows, for its aria-describedby. */
+export function useReadingNotice(entered: string, last: number | null | undefined) {
+  const isMarine = useServiceType() === 'marine'
+  return readingNotice(entered, last, isMarine ? 'hours' : 'distance')
+}
+
+/**
+ * Says that the reading being typed is below the last known one, or so far
+ * above it that a digit may have slipped in. It never stops a save:
+ * odometers are replaced and typos are corrected. Renders nothing at all
+ * otherwise, so a reading that goes up by a normal amount changes nothing.
+ */
+export function ReadingNotice({ entered, last, unit, id, className }: ReadingNoticeProps) {
+  const t = useTranslations('vehicles.form')
+  const format = useFormatter()
+  const isMarine = useServiceType() === 'marine'
+  const notice = useReadingNotice(entered, last)
+  if (last == null || notice == null) return null
+  const reading = format.number(last)
+  const key = notice === 'lower' ? 'lowerReading' : 'muchHigherReading'
+  return (
+    <p
+      id={id}
+      role="status"
+      data-testid={notice === 'lower' ? 'lower-reading-notice' : 'higher-reading-notice'}
+      className={cn('text-xs text-amber-600 dark:text-amber-500', className)}
+    >
+      {isMarine
+        ? t(`${key}Marine`, { hours: reading })
+        : t(key, { reading: unit ? `${reading} ${unit}` : reading })}
+    </p>
+  )
+}

+ 73 - 0
src/features/vehicles/Components/ReadingQuestion.tsx

@@ -0,0 +1,73 @@
+'use client'
+
+import { useFormatter, useTranslations } from 'next-intl'
+import { Button } from '@/components/ui/button'
+import { useServiceType } from '@/components/service-type-context'
+import { cn } from '@/lib/utils'
+
+interface ReadingQuestionProps {
+  /** The reading typed. */
+  entered: number
+  /** The last known reading it is far above. */
+  last: number
+  /** "km" or "mi", where the caller knows it. */
+  unit?: string
+  onConfirm: () => void
+  onChange: () => void
+  id?: string
+  className?: string
+}
+
+/**
+ * Asks, under a reading field, whether a reading far above the last one is
+ * right. Inline rather than a dialog: the page saves by itself while the
+ * person types, and a dialog would jump up under their fingers. Until it is
+ * answered the reading is held back from the save (useServiceActions).
+ */
+export function ReadingQuestion({
+  entered,
+  last,
+  unit,
+  onConfirm,
+  onChange,
+  id = 'reading-question',
+  className,
+}: ReadingQuestionProps) {
+  const t = useTranslations('vehicles.form')
+  const format = useFormatter()
+  const isMarine = useServiceType() === 'marine'
+  const withUnit = (value: number) =>
+    unit && !isMarine ? `${format.number(value)} ${unit}` : format.number(value)
+  return (
+    <div
+      id={id}
+      role="group"
+      aria-labelledby={`${id}-title`}
+      aria-describedby={`${id}-body`}
+      data-testid="reading-question"
+      className={cn(
+        'max-w-sm space-y-2 rounded-md border border-amber-500/40 bg-amber-500/10 p-3',
+        className
+      )}
+    >
+      <p id={`${id}-title`} className="text-sm font-medium">
+        {t('readingConfirmTitle')}
+      </p>
+      <p id={`${id}-body`} className="text-xs text-muted-foreground">
+        {t(isMarine ? 'readingConfirmBodyMarine' : 'readingConfirmBody', {
+          entered: withUnit(entered),
+          last: withUnit(last),
+        })}{' '}
+        {t('readingConfirmHeld')}
+      </p>
+      <div className="flex flex-wrap gap-2">
+        <Button type="button" size="sm" onClick={onConfirm} data-reading-confirm>
+          {t('readingConfirmYes')}
+        </Button>
+        <Button type="button" size="sm" variant="outline" onClick={onChange}>
+          {t('readingConfirmChange')}
+        </Button>
+      </div>
+    </div>
+  )
+}

+ 47 - 9
src/features/vehicles/Components/VehicleForm.tsx

@@ -51,8 +51,9 @@ import { PlateChip } from '@/components/plate-chip'
 import { StatusLamp, type LampTone } from '@/components/status-lamp'
 import { cn } from '@/lib/utils'
 import { PhotoHandoffButton } from './service-page/PhotoHandoffButton'
-import { LowerReadingNotice } from './LowerReadingNotice'
-import { isLowerReading } from '../Lib/vehicleReading'
+import { ReadingNotice, useReadingNotice } from './ReadingNotice'
+import { ReadingConfirmDialog } from './ReadingConfirmDialog'
+import { readingNeedsAnswer } from '../Lib/vehicleReading'
 
 /**
  * How alike two names must read before the scanned keeper is offered as an
@@ -208,6 +209,10 @@ export function VehicleForm({
   // length and the colour swatch. The fields themselves stay uncontrolled:
   // scans and lookups write into them directly, then call readDrafts.
   const [mileageDraft, setMileageDraft] = useState(vehicle ? String(vehicle.mileage) : '')
+  /** A reading far above the saved one, waiting for the person's answer on Save. */
+  const [readingToConfirm, setReadingToConfirm] = useState<number | null>(null)
+  /** The reading they said yes to: not asked about again. */
+  const confirmedReadingRef = useRef<number | null>(null)
   // The mileage in the summary can be changed where it is read, without
   // going down to the field: a reading is the one thing changed every visit.
   const [editingMileage, setEditingMileage] = useState(false)
@@ -226,6 +231,9 @@ export function VehicleForm({
   const resetDrafts = () => {
     setEditingMileage(false)
     setMileageDraft(vehicle ? String(vehicle.mileage) : '')
+    // A yes was for that vehicle and that reading; the next one is asked again.
+    confirmedReadingRef.current = null
+    setReadingToConfirm(null)
     setInspectionDraft(openedInspectionDue)
     setVinDraft(vehicle?.vin ?? '')
     setColorDraft(vehicle?.color ?? '')
@@ -469,6 +477,22 @@ export function VehicleForm({
     e.preventDefault()
     // The save shortcut and Enter reach here past the disabled button
     if (ownerLookupPending) return
+    // A changed reading far above the saved one is asked about first; the
+    // answer Yes saves the form again with it, "Change it" saves nothing.
+    const typedReading = mileageDraft.trim() === '' ? null : Number(mileageDraft)
+    if (
+      vehicle &&
+      readingNeedsAnswer({
+        value: typedReading,
+        saved: vehicle.mileage,
+        last: vehicle.mileage,
+        kind: isMarine ? 'hours' : 'distance',
+        confirmed: confirmedReadingRef.current,
+      })
+    ) {
+      setReadingToConfirm(typedReading)
+      return
+    }
     const formData = new FormData(e.currentTarget)
 
     // Caught here rather than by the server, which could only answer in English.
@@ -643,6 +667,8 @@ export function VehicleForm({
   const mileageLabel = isMarine ? t('mileageMarine') : t('mileage')
   const unit = distanceUnit
   const mileageShown = mileageDraft.trim() === '' ? null : Number(mileageDraft)
+  const readingNotice = useReadingNotice(mileageDraft, vehicle?.mileage)
+  const mileageInputRef = useRef<HTMLInputElement>(null)
   const inspectionShown = inspectionDraft
     ? {
         // A date key, read at noon UTC so it names the same day everywhere.
@@ -708,6 +734,21 @@ export function VehicleForm({
             </div>
           </DialogHeader>
 
+          <ReadingConfirmDialog
+            entered={readingToConfirm}
+            last={vehicle?.mileage ?? 0}
+            unit={unit}
+            onConfirm={() => {
+              confirmedReadingRef.current = readingToConfirm
+              setReadingToConfirm(null)
+              formRef.current?.requestSubmit()
+            }}
+            onChange={() => setReadingToConfirm(null)}
+            focusField={() => {
+              mileageInputRef.current?.focus()
+              mileageInputRef.current?.select()
+            }}
+          />
           <form
             ref={formRef}
             onSubmit={handleSubmit}
@@ -902,7 +943,7 @@ export function VehicleForm({
                           </button>
                         )}
                       </dd>
-                      <LowerReadingNotice
+                      <ReadingNotice
                         entered={mileageDraft}
                         last={vehicle?.mileage}
                         unit={unit}
@@ -1246,17 +1287,14 @@ export function VehicleForm({
                       <Label htmlFor="mileage">{mileageLabel}</Label>
                       <div className="relative">
                         <Input
+                          ref={mileageInputRef}
                           id="mileage"
                           name="mileage"
                           type="number"
                           placeholder="0"
                           value={mileageDraft}
                           onChange={(e) => setMileageDraft(e.target.value)}
-                          aria-describedby={
-                            isLowerReading(mileageDraft, vehicle?.mileage)
-                              ? 'mileage-notice'
-                              : undefined
-                          }
+                          aria-describedby={readingNotice ? 'mileage-notice' : undefined}
                           // No spinner: it would sit on top of the unit, and
                           // nobody steps an odometer reading one at a time.
                           className={cn(
@@ -1273,7 +1311,7 @@ export function VehicleForm({
                           </span>
                         )}
                       </div>
-                      <LowerReadingNotice
+                      <ReadingNotice
                         id="mileage-notice"
                         entered={mileageDraft}
                         last={vehicle?.mileage}

+ 1 - 1
src/features/vehicles/Components/service-page/ServiceRecordPage.tsx

@@ -261,7 +261,7 @@ export async function ServiceRecordPage({
             startDateTime: isRenderable(record.startDateTime) ? record.startDateTime : null,
             serviceDate: record.serviceDate,
           }),
-          vehicleReading: record.vehicle.mileage,
+          vehicle: record.vehicle,
         })
       : null
 

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

@@ -1,6 +1,6 @@
 'use client'
 
-import { useEffect, useState } from 'react'
+import { useEffect, useRef, useState } from 'react'
 import Link from 'next/link'
 import { useTranslations } from 'next-intl'
 import { Check, ChevronDown } from 'lucide-react'
@@ -19,8 +19,9 @@ import type { InitialData } from '../../service-edit/form-types'
 import { formatTypeKey } from '../../../Lib/typeKey'
 import { useTypeKeyEnabled } from '@/components/type-key-context'
 import { vehicleName as vehicleNameOf } from '@/lib/vehicle-name'
-import { LowerReadingNotice } from '../../LowerReadingNotice'
-import { isLowerReading } from '../../../Lib/vehicleReading'
+import { ReadingNotice, useReadingNotice } from '../../ReadingNotice'
+import { ReadingQuestion } from '../../ReadingQuestion'
+import { readingNeedsAnswer } from '../../../Lib/vehicleReading'
 
 interface JobFactsCardProps {
   record: ServiceDetail
@@ -38,6 +39,10 @@ interface JobFactsCardProps {
   techName: string
   /** "km" or "mi", for the notice under the reading. */
   distanceUnit?: string
+  /** The far-higher reading the person said yes to (useServiceFormState). */
+  confirmedReading?: number | null
+  /** Says yes to a far-higher reading: it is saved then. */
+  onConfirmReading?: (value: number) => void
   initialVehicle?: {
     id: string
     make: string
@@ -131,6 +136,8 @@ export function JobFactsCard({
   techName,
   initialVehicle,
   distanceUnit,
+  confirmedReading = null,
+  onConfirmReading,
 }: JobFactsCardProps) {
   const t = useTranslations('service')
   const tv = useTranslations('vehicles.form')
@@ -144,6 +151,7 @@ export function JobFactsCard({
   const [changingVehicle, setChangingVehicle] = useState(false)
   // What was typed in the reading field since the page loaded; null until then.
   const [readingTyped, setReadingTyped] = useState<string | null>(null)
+  const readingInput = useRef<HTMLInputElement>(null)
 
   // Closed on the server and on the first paint, then as this browser left it:
   // localStorage is not readable before hydration.
@@ -170,10 +178,30 @@ export function JobFactsCard({
   // The picker can point the job at another vehicle before the save; the facts
   // on this card describe the saved one, so say which is which while they differ.
   const vehicleChanged = Boolean(vehicle && selectedVehicleId && selectedVehicleId !== vehicle.id)
-  const showReadingNotice =
+  // A reading typed on this visit, on the vehicle the last reading was read
+  // for: far above it is a question to answer before it is saved; below it
+  // is a quiet notice.
+  const readingKind = serviceType === 'marine' ? 'hours' : 'distance'
+  const typedValue =
+    readingTyped === null || readingTyped.trim() === '' ? null : Number(readingTyped)
+  const askReading =
     readingTyped !== null &&
     !vehicleChanged &&
-    isLowerReading(readingTyped, initialData.lastReading)
+    initialData.lastReading != null &&
+    readingNeedsAnswer({
+      value: typedValue,
+      saved: initialData.mileage,
+      last: initialData.lastReading,
+      kind: readingKind,
+      confirmed: confirmedReading,
+    })
+  const readingNotice = useReadingNotice(readingTyped ?? '', initialData.lastReading)
+  const showReadingNotice = readingTyped !== null && !vehicleChanged && readingNotice === 'lower'
+  const readingDescribedBy = askReading
+    ? 'reading-question'
+    : showReadingNotice
+      ? 'mileage-notice'
+      : undefined
 
   return (
     <section
@@ -348,14 +376,27 @@ export function JobFactsCard({
                     className="h-8 w-32"
                     defaultValue={initialData.mileage ?? ''}
                     onChange={(e) => setReadingTyped(e.target.value)}
-                    aria-describedby={showReadingNotice ? 'mileage-notice' : undefined}
+                    ref={readingInput}
+                    aria-describedby={readingDescribedBy}
                   />
                 </div>
                 {/* Only for a reading typed on this visit, on the vehicle
                     the last reading was read for. It stays after the page
                     saves by itself, or it would be gone in five seconds. */}
+                {askReading && typedValue != null && initialData.lastReading != null && (
+                  <ReadingQuestion
+                    entered={typedValue}
+                    last={initialData.lastReading}
+                    unit={distanceUnit}
+                    onConfirm={() => onConfirmReading?.(typedValue)}
+                    onChange={() => {
+                      readingInput.current?.focus()
+                      readingInput.current?.select()
+                    }}
+                  />
+                )}
                 {showReadingNotice && (
-                  <LowerReadingNotice
+                  <ReadingNotice
                     id="mileage-notice"
                     entered={readingTyped ?? ''}
                     last={initialData.lastReading}

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

@@ -324,6 +324,8 @@ export function ModernDetails(props: ModernDetailsProps) {
                   techName={formState.techName}
                   initialVehicle={props.initialVehicle}
                   distanceUnit={unitSystem === 'metric' ? 'km' : 'mi'}
+                  confirmedReading={formState.confirmedReading}
+                  onConfirmReading={formState.confirmReading}
                 />
 
                 <Lockable locked={locked}>

+ 39 - 2
src/features/vehicles/Components/service-page/useServiceActions.ts

@@ -18,6 +18,8 @@ import { SMS_TEMPLATE_DEFAULTS, interpolateSmsTemplate } from '@/lib/sms-templat
 import { formatCurrency } from '@/lib/format'
 import { findServiceFormProblem } from '@/features/vehicles/Lib/validateServiceForm'
 import { WARRANTY_NONE } from '@/lib/warranty'
+import { useServiceType } from '@/components/service-type-context'
+import { readingNeedsAnswer } from '@/features/vehicles/Lib/vehicleReading'
 import type { ServiceDetail } from '../service-detail/types'
 import type { useServiceFormState } from './useServiceFormState'
 
@@ -39,6 +41,8 @@ export function useServiceActions({
   const confirm = useConfirm()
   const t = useTranslations('service')
   const tc = useTranslations('common')
+  const tv = useTranslations('vehicles.form')
+  const readingKind = useServiceType() === 'marine' ? 'hours' : 'distance'
 
   const [carouselIndex, setCarouselIndex] = useState<number | null>(null)
   const [downloading, setDownloading] = useState(false)
@@ -83,6 +87,9 @@ export function useServiceActions({
     autosaveRunRef,
     editRevisionRef,
     markSaved,
+    markDirty,
+    confirmedReadingRef,
+    acknowledgeSavedLines,
   } = formState
 
   /**
@@ -182,6 +189,20 @@ export function useServiceActions({
         : rawMileage.trim() === ''
           ? null
           : mileageNumber
+    // A reading far above the last one waits for the person's answer under
+    // the field (ReadingQuestion). Only the reading: the rest of the work
+    // order saves, and the page stays unsaved until it is answered. The last
+    // reading belongs to the saved vehicle, so a job being moved to another
+    // one is not asked about.
+    const holdReading =
+      selectedVehicleId === vehicleId &&
+      readingNeedsAnswer({
+        value: parsedMileage,
+        saved: initialData.mileage,
+        last: initialData.lastReading,
+        kind: readingKind,
+        confirmed: confirmedReadingRef.current,
+      })
     // The editor reports an emptied box as one empty paragraph.
     const richText = (html: string) => (html === '<p></p>' ? '' : html)
 
@@ -196,7 +217,8 @@ export function useServiceActions({
       type,
       status,
       cost: totalAmount,
-      mileage: parsedMileage,
+      // Left out, the job keeps the reading it has.
+      mileage: holdReading ? undefined : parsedMileage,
       serviceDate: getVisible('serviceDate') || new Date().toISOString(),
       // techName intentionally omitted: it has no UI in the form (read-only),
       // and the Schedule card writes it directly via assignTechnician. Sending
@@ -256,7 +278,22 @@ export function useServiceActions({
       throw err
     }
 
-    if (result.success) {
+    if (result.success && holdReading) {
+      commitLaborAddedElsewhere()
+      commitPartsAddedElsewhere()
+      acknowledgeSavedLines({ parts: payload.partItems, labor: payload.laborItems })
+      // Saved but for the reading: the page stays unsaved, without another
+      // autosave unless something else is edited, and a link waiting on this
+      // save asks the person to stay and answer.
+      if (editRevisionRef.current !== revision) markDirty()
+      lastSaveErrorRef.current = tv('readingConfirmWaiting')
+      if (!autosave && !leavingRef.current) {
+        // A save they asked for takes them to the question.
+        const question = document.getElementById('reading-question')
+        question?.scrollIntoView?.({ block: 'center', behavior: 'smooth' })
+        question?.querySelector<HTMLButtonElement>('[data-reading-confirm]')?.focus()
+      }
+    } else if (result.success) {
       commitLaborAddedElsewhere()
       commitPartsAddedElsewhere()
       markSaved(revision)

+ 37 - 0
src/features/vehicles/Components/service-page/useServiceFormState.ts

@@ -223,6 +223,20 @@ export function useServiceFormState({
     if (added.length > 0) setPartsAddedElsewhere((current) => [...current, ...added])
   }, [savedPartsKey])
 
+  /**
+   * A save went through while the page stays unsaved (a reading held back for
+   * its question): the lines it sent are the server's now. Without this the
+   * refresh after it brought them back as lines added elsewhere, and the next
+   * save sent them twice.
+   */
+  const acknowledgeSavedLines = useCallback(
+    (lines: { parts: ServicePartInput[]; labor: ServiceLaborInput[] }) => {
+      syncedPartsRef.current = lines.parts
+      syncedLaborRef.current = lines.labor
+    },
+    []
+  )
+
   useEffect(() => {
     if (!locked) return
     if (autosaveTimer.current) {
@@ -289,6 +303,25 @@ export function useServiceFormState({
     },
   })
 
+  /**
+   * The reading the person said yes to, when it was far above the last one
+   * (readingNeedsAnswer). Until then the save holds the reading back and the
+   * page stays unsaved; the ref is what a save started this instant reads.
+   */
+  const [confirmedReading, setConfirmedReading] = useState<number | null>(null)
+  const confirmedReadingRef = useRef<number | null>(null)
+  const confirmReading = useCallback(
+    (value: number) => {
+      confirmedReadingRef.current = value
+      setConfirmedReading(value)
+      // Saved now: the answer is the last thing the reading waited for.
+      markDirty()
+      if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
+      if (!isSavingRef.current && formRef.current) formRef.current.requestSubmit()
+    },
+    [markDirty]
+  )
+
   // Custom fields save callback ref
   const customFieldsSaveRef = useRef<CustomFieldsSave | null>(null)
 
@@ -603,6 +636,10 @@ export function useServiceFormState({
     markSaved,
     editRevisionRef,
     saveNow,
+    confirmedReading,
+    confirmedReadingRef,
+    confirmReading,
+    acknowledgeSavedLines,
     /**
      * Whether edits are still unsaved, read at the moment of the call. For
      * code that awaits saveNow and has to know whether the save went

+ 291 - 32
src/features/vehicles/Lib/vehicleReading.ts

@@ -12,26 +12,50 @@ import type { Prisma } from '@/generated/prisma/client'
  *     1. this save gave the job a reading it did not already have,
  *     2. the reading is higher than the vehicle's current one, and
  *     3. no later-dated job on the vehicle carries a reading of its own.
+ *   The vehicle then remembers that job (`readingJobId`) and what it read
+ *   before (`readingBeforeJob`).
  *
- * So the newest reading moves the vehicle forward, and nothing else does: a
- * lower reading never winds the vehicle back (a typo on a job must not), an
- * old job being edited cannot push today's reading about, and saving a job
- * again without touching its reading leaves a vehicle that was corrected by
- * hand alone. A job is dated by when it starts, else by its service date. A
- * booked job without a reading is not in the way of today's. History written
- * in bulk (the importer) asks once per vehicle, for its newest imported job,
- * after every row is in: asked row by row, the answer would follow the order
- * of the file.
+ *   When the job the vehicle remembers is saved with a lower reading, or with
+ *   none, the vehicle follows the correction: it reads what it would have
+ *   read had the job been typed right the first time. That is the highest of
+ *   the job's new reading, every other job's reading on the vehicle, and what
+ *   the vehicle read before the job set it. The vehicle keeps remembering the
+ *   job only while the job's own reading is the one it shows.
  *
- * The vehicle's reading is lowered in one place only, the vehicle form, where
- * the person sees a notice and saves anyway (odometers are replaced).
+ * So the newest reading moves the vehicle forward, a slip on the job that
+ * moved it can be corrected on that job, and nothing else winds the vehicle
+ * back: a lower reading on any other job never does, an old job being edited
+ * cannot push today's reading about, and saving a job again without touching
+ * its reading leaves a vehicle that was corrected by hand alone. A job is
+ * dated by when it starts, else by its service date. A booked job without a
+ * reading is not in the way of today's. History written in bulk (the
+ * importer) asks once per vehicle, for its newest imported job, after every
+ * row is in: asked row by row, the answer would follow the order of the file.
+ *
+ * Anything that writes the vehicle's reading itself (the vehicle form, an
+ * imported vehicle row, a restore of an older backup) forgets the job
+ * (`READING_SET_BY_HAND`): from then on the reading is nobody's job's. So does
+ * moving the job to another vehicle (`forgetJobReading`), and deleting it (the
+ * column is set to null by the database). In both cases the vehicle keeps the
+ * reading it has.
  */
 
+/** What the rule reads and writes on the vehicle. */
+const VEHICLE_READING = { mileage: true, readingJobId: true, readingBeforeJob: true } as const
+
+interface VehicleReadingRow {
+  mileage: number
+  readingJobId: string | null
+  readingBeforeJob: number | null
+}
+
 /**
- * The three queries the rule makes, so the app's client, a transaction and a
- * test double all fit without the rule importing the database itself.
+ * The queries the rule makes, so the app's client and a transaction both fit
+ * without the rule importing the database itself.
  */
 export interface ReadingClient {
+  /** For the vehicle's row lock (lockVehicleReading). */
+  $queryRaw: Prisma.TransactionClient['$queryRaw']
   serviceRecord: {
     findFirst(args: {
       where: Prisma.ServiceRecordWhereInput
@@ -43,13 +67,23 @@ export interface ReadingClient {
     }): PromiseLike<{ _max: { mileage: number | null } }>
   }
   vehicle: {
+    findFirst(args: {
+      where: Prisma.VehicleWhereInput
+      select: typeof VEHICLE_READING
+    }): PromiseLike<VehicleReadingRow | null>
     updateMany(args: {
       where: Prisma.VehicleWhereInput
-      data: { mileage: number }
+      data: { mileage?: number; readingJobId?: string | null; readingBeforeJob?: number | null }
     }): PromiseLike<{ count: number }>
   }
 }
 
+/**
+ * For the data of a write that sets the vehicle's reading itself: after it,
+ * the reading is no longer the job's that set it.
+ */
+export const READING_SET_BY_HAND = { readingJobId: null, readingBeforeJob: null } as const
+
 export interface JobReading {
   organizationId: string
   vehicleId: string
@@ -71,6 +105,11 @@ export function jobReadingDate(job: { startDateTime?: Date | null; serviceDate:
   return job.startDateTime ?? job.serviceDate
 }
 
+/** A reading that says something: a number above zero. */
+function readingOf(value: number | null | undefined): number | null {
+  return value != null && Number.isFinite(value) && value > 0 ? value : null
+}
+
 /** Other jobs on the vehicle, dated after this one, that carry a reading. */
 function laterJobsWithReading(
   job: Pick<JobReading, 'organizationId' | 'vehicleId' | 'jobId' | 'jobDate'>
@@ -90,12 +129,34 @@ function laterJobsWithReading(
 
 /**
  * Applies the rule above after a job's reading was written. Answers whether
- * the vehicle moved. Takes the transaction when the writer has one.
+ * the vehicle's reading changed. Runs in the writer's transaction, which
+ * holds the vehicle's row lock from here until it commits.
  */
 export async function applyJobReading(client: ReadingClient, job: JobReading): Promise<boolean> {
-  const { reading } = job
-  if (reading == null || !Number.isFinite(reading) || reading <= 0) return false
-  if (job.previousReading != null && job.previousReading === reading) return false
+  const reading = readingOf(job.reading)
+  if (job.previousReading !== undefined && (job.previousReading ?? null) === (job.reading ?? null))
+    return false
+  // Nothing to raise and nothing a correction could start from.
+  if (reading == null && readingOf(job.previousReading) == null) return false
+
+  // Every decision about this vehicle's reading takes turns, the ones that
+  // leave it alone included: a job that decides "not higher" while another
+  // job's correction is lowering the vehicle would otherwise leave the
+  // vehicle below its reading.
+  await lockVehicleReading(client, job)
+
+  // The job had a reading on this vehicle and now reads lower, or nothing:
+  // a correction, if the vehicle's reading is this job's.
+  if (readingOf(job.previousReading) != null) {
+    const vehicle = await client.vehicle.findFirst({
+      where: { id: job.vehicleId, organizationId: job.organizationId, readingJobId: job.jobId },
+      select: VEHICLE_READING,
+    })
+    if (vehicle && (reading == null || reading < vehicle.mileage)) {
+      return correctJobReading(client, job, reading, vehicle)
+    }
+  }
+  if (reading == null) return false
 
   const later = await client.serviceRecord.findFirst({
     where: laterJobsWithReading(job),
@@ -103,25 +164,153 @@ export async function applyJobReading(client: ReadingClient, job: JobReading): P
   })
   if (later) return false
 
-  // The comparison is the database's, so two saves at once cannot leave the
-  // lower of two readings behind.
+  // Compare and set, so two saves at once cannot leave the lower of two
+  // readings behind, nor remember the wrong job: the update only lands on
+  // the vehicle as it was read, and is asked again otherwise.
+  for (let attempt = 0; attempt < 3; attempt++) {
+    const current = await client.vehicle.findFirst({
+      where: { id: job.vehicleId, organizationId: job.organizationId },
+      select: VEHICLE_READING,
+    })
+    if (!current || current.mileage >= reading) return false
+    const moved = await client.vehicle.updateMany({
+      where: {
+        id: job.vehicleId,
+        organizationId: job.organizationId,
+        mileage: current.mileage,
+        // Null, never undefined: undefined would drop the condition.
+        readingJobId: current.readingJobId ?? null,
+      },
+      data: {
+        mileage: reading,
+        readingJobId: job.jobId,
+        // Raised again by the same job, the reading before it stays the one
+        // from before its first.
+        readingBeforeJob:
+          current.readingJobId === job.jobId ? current.readingBeforeJob : current.mileage,
+      },
+    })
+    if (moved.count > 0) return true
+  }
+  return false
+}
+
+/**
+ * The job that set the vehicle's reading now reads lower, or nothing: the
+ * vehicle reads what it would have, had the job been typed right.
+ */
+async function correctJobReading(
+  client: ReadingClient,
+  job: JobReading,
+  reading: number | null,
+  vehicle: VehicleReadingRow
+): Promise<boolean> {
+  const others = await client.serviceRecord.aggregate({
+    where: {
+      organizationId: job.organizationId,
+      vehicleId: job.vehicleId,
+      id: { not: job.jobId },
+      mileage: { gt: 0 },
+    },
+    _max: { mileage: true },
+  })
+  const floor = Math.max(vehicle.readingBeforeJob ?? 0, others._max.mileage ?? 0)
+  const stillTheJobs = reading != null && reading > floor
+  const target = stillTheJobs ? reading : floor
+  // Only on the vehicle as it was read: another job that moved it meanwhile
+  // has the newer word. Two saves of this job take turns on its row lock
+  // (lockJobReading), so the later one corrects after the earlier.
   const moved = await client.vehicle.updateMany({
-    where: { id: job.vehicleId, organizationId: job.organizationId, mileage: { lt: reading } },
-    data: { mileage: reading },
+    where: {
+      id: job.vehicleId,
+      organizationId: job.organizationId,
+      readingJobId: job.jobId,
+      mileage: vehicle.mileage,
+    },
+    data: stillTheJobs ? { mileage: target } : { mileage: target, ...READING_SET_BY_HAND },
+  })
+  if (moved.count === 0) return false
+
+  // Another job's reading saved while this one was corrected never ends up
+  // above the vehicle's: up to it, and the reading is no longer this job's.
+  const since = await client.serviceRecord.aggregate({
+    where: {
+      organizationId: job.organizationId,
+      vehicleId: job.vehicleId,
+      id: { not: job.jobId },
+      mileage: { gt: target },
+    },
+    _max: { mileage: true },
+  })
+  const above = since._max.mileage
+  if (above != null) {
+    await client.vehicle.updateMany({
+      where: { id: job.vehicleId, organizationId: job.organizationId, mileage: { lt: above } },
+      data: { mileage: above, ...READING_SET_BY_HAND },
+    })
+  }
+  return true
+}
+
+/**
+ * Locks the job's row until the writer's transaction ends, and reads the
+ * reading it carries before this save. Every writer that changes the reading
+ * of an existing job calls it first in its transaction, then applies the rule
+ * in the same transaction: two saves of one job at once then take turns, and
+ * the vehicle ends on the reading the job ends on.
+ */
+export async function lockJobReading(
+  tx: Pick<Prisma.TransactionClient, '$queryRaw'>,
+  job: { organizationId: string; jobId: string }
+): Promise<{ mileage: number | null; vehicleId: string | null } | null> {
+  const rows = await tx.$queryRaw<{ mileage: number | null; vehicleId: string | null }[]>`
+    SELECT "mileage", "vehicleId" FROM "public"."service_records"
+    WHERE "id" = ${job.jobId} AND "organizationId" = ${job.organizationId}
+    FOR UPDATE`
+  return rows[0] ?? null
+}
+
+/**
+ * Locks the vehicle's row until the writer's transaction ends. The rule's
+ * reads come after it, so they see what the writer before it committed.
+ * Called inside the writer's transaction: outside one it is let go at once.
+ */
+async function lockVehicleReading(
+  client: Pick<ReadingClient, '$queryRaw'>,
+  job: { organizationId: string; vehicleId: string }
+): Promise<void> {
+  await client.$queryRaw`
+    SELECT "id" FROM "public"."vehicles"
+    WHERE "id" = ${job.vehicleId} AND "organizationId" = ${job.organizationId}
+    FOR UPDATE`
+}
+
+/**
+ * A job leaves its vehicle (moved to another one): the vehicle keeps its
+ * reading, and it is no longer that job's to correct.
+ */
+export async function forgetJobReading(
+  client: Pick<ReadingClient, 'vehicle'>,
+  job: { organizationId: string; jobId: string }
+): Promise<void> {
+  await client.vehicle.updateMany({
+    where: { organizationId: job.organizationId, readingJobId: job.jobId },
+    data: READING_SET_BY_HAND,
   })
-  return moved.count > 0
 }
 
 /**
  * The reading a person typing this job's reading should not be below: the
  * highest on an earlier job, and the vehicle's own unless a later job has
- * already moved it on. Null when nothing is known, so nothing is said.
+ * already moved it on. When the vehicle's reading is this job's own, it is
+ * what the vehicle read before the job, so the job is not warned about
+ * itself. Null when nothing is known, so nothing is said.
  */
 export async function lastReadingBeforeJob(
-  client: ReadingClient,
+  client: Pick<ReadingClient, 'serviceRecord'>,
   job: Pick<JobReading, 'organizationId' | 'vehicleId' | 'jobId' | 'jobDate'> & {
-    /** The vehicle's current reading, which the caller has already loaded. */
-    vehicleReading: number
+    /** The vehicle as the caller has already loaded it. */
+    vehicle: VehicleReadingRow
   }
 ): Promise<number | null> {
   const [later, earlier] = await Promise.all([
@@ -140,10 +329,34 @@ export async function lastReadingBeforeJob(
       _max: { mileage: true },
     }),
   ])
-  const last = Math.max(later ? 0 : job.vehicleReading, earlier._max.mileage ?? 0)
+  const vehicleReading =
+    job.vehicle.readingJobId === job.jobId
+      ? (job.vehicle.readingBeforeJob ?? 0)
+      : job.vehicle.mileage
+  const last = Math.max(later ? 0 : vehicleReading, earlier._max.mileage ?? 0)
   return last > 0 ? last : null
 }
 
+/**
+ * How far above the last known reading a new one may go before the screen
+ * asks whether a digit slipped in. One extra digit on a six-figure odometer
+ * is a jump of hundreds of thousands; a year of hard driving is well under
+ * the distance limit, and a year of engine hours well under the hours one.
+ * Kilometres and miles share the distance limit. Constants for now: a
+ * workshop setting can take their place later.
+ */
+export const MUCH_HIGHER_READING = { distance: 100_000, hours: 5_000 } as const
+
+export type ReadingKind = keyof typeof MUCH_HIGHER_READING
+
+/** What is typed in a reading field, as a number, or null when it is not one. */
+function enteredReading(entered: string): number | null {
+  const text = entered.trim()
+  if (text === '') return null
+  const value = Number(text)
+  return Number.isFinite(value) && value >= 0 ? value : null
+}
+
 /**
  * Whether what is typed in a reading field is below the last known reading.
  * An empty or unreadable field is not a reading, and neither is "nothing is
@@ -151,8 +364,54 @@ export async function lastReadingBeforeJob(
  */
 export function isLowerReading(entered: string, last: number | null | undefined): boolean {
   if (last == null || last <= 0) return false
-  const text = entered.trim()
-  if (text === '') return false
-  const value = Number(text)
-  return Number.isFinite(value) && value >= 0 && value < last
+  const value = enteredReading(entered)
+  return value != null && value < last
+}
+
+/**
+ * Whether what is typed is so far above the last known reading that it is
+ * more likely a typo than driving: see MUCH_HIGHER_READING.
+ */
+export function isMuchHigherReading(
+  entered: string,
+  last: number | null | undefined,
+  kind: ReadingKind
+): boolean {
+  if (last == null || last <= 0) return false
+  const value = enteredReading(entered)
+  return value != null && value - last > MUCH_HIGHER_READING[kind]
+}
+
+/** Which notice a reading field shows, if any: never two at once. */
+export function readingNotice(
+  entered: string,
+  last: number | null | undefined,
+  kind: ReadingKind
+): 'lower' | 'higher' | null {
+  if (isLowerReading(entered, last)) return 'lower'
+  if (isMuchHigherReading(entered, last, kind)) return 'higher'
+  return null
+}
+
+/**
+ * Whether a reading about to be saved must first be confirmed by the person
+ * at the screen: much higher than the last known one (MUCH_HIGHER_READING),
+ * new on this record, and not already confirmed at this value. Only a
+ * question for the screen: the server takes any reading, as the technician
+ * app and the API send it.
+ */
+export function readingNeedsAnswer(reading: {
+  /** What would be saved: null for an emptied field. */
+  value: number | null | undefined
+  /** What the record holds now: a value already saved is not asked about again. */
+  saved: number | null | undefined
+  last: number | null | undefined
+  kind: ReadingKind
+  /** The value the person last said yes to. */
+  confirmed: number | null
+}): boolean {
+  const { value } = reading
+  if (value == null || !Number.isFinite(value)) return false
+  if (value === reading.saved || value === reading.confirmed) return false
+  return isMuchHigherReading(String(value), reading.last, reading.kind)
 }

+ 14 - 0
src/lib/backup/import.ts

@@ -1242,6 +1242,20 @@ export async function restoreBackup(
               }
             }
 
+            // The job whose reading the vehicle's is, once that job is in. Only
+            // one of this vehicle's own jobs from the file: anything else would
+            // let a correction on some other job move this vehicle.
+            if (v.readingJobId && serviceRecords?.some((sr) => sr.id === v.readingJobId)) {
+              await tx.vehicle.updateMany({
+                where: { id: v.id as string, organizationId: ctx.organizationId },
+                data: {
+                  readingJobId: v.readingJobId as string,
+                  readingBeforeJob: numberOr(v.readingBeforeJob, null),
+                  updatedAt: toSafeDate(v.updatedAt as string),
+                },
+              })
+            }
+
             // What else a vehicle owns. All of it is deleted with the vehicle,
             // so leaving any of it out makes a restore a one-way loss.
             await restoreRows(

+ 5 - 0
src/lib/backup/tenancy-schema.ts

@@ -1544,6 +1544,11 @@ export const TENANCY_SCHEMA: SchemaGraph = {
   Vehicle: {
     organizationId: true,
     foreignKeys: {
+      readingJobId: {
+        target: 'ServiceRecord',
+        required: false,
+        relation: 'readingJob',
+      },
       userId: {
         target: 'User',
         required: true,