Ver código fonte

Warn about a lower mileage reading and update the vehicle's reading by one rule (#641)

* Warn about a lower mileage reading and move the vehicle's reading by one rule

* Keep the lower reading notice after the work order saves itself

* Type the reading rule's client by the queries it makes

* Settle imported readings after every row, apply the rule when an inspection is linked, count a zero reading
Bernt Christian Egeland 2 dias atrás
pai
commit
06ac781cf6
32 arquivos alterados com 1225 adições e 87 exclusões
  1. 2 0
      messages/de/vehicles.json
  2. 2 0
      messages/en/vehicles.json
  3. 2 0
      messages/es/vehicles.json
  4. 2 0
      messages/fr/vehicles.json
  5. 2 0
      messages/it/vehicles.json
  6. 2 0
      messages/lt/vehicles.json
  7. 2 0
      messages/nb/vehicles.json
  8. 2 0
      messages/nl/vehicles.json
  9. 2 0
      messages/pl/vehicles.json
  10. 2 0
      messages/pt-BR/vehicles.json
  11. 2 0
      messages/pt-PT/vehicles.json
  12. 2 0
      messages/ru/vehicles.json
  13. 2 0
      messages/tr/vehicles.json
  14. 39 2
      src/__tests__/api/tech-checkin.test.ts
  15. 76 4
      src/__tests__/features/import/commit.test.ts
  16. 12 1
      src/__tests__/features/inspections/link-work-order.test.ts
  17. 66 0
      src/__tests__/features/vehicles/vehicle-form-dialog.test.tsx
  18. 243 0
      src/__tests__/features/vehicles/vehicle-reading.test.ts
  19. 127 0
      src/__tests__/features/vehicles/work-order-lower-reading.test.tsx
  20. 171 0
      src/__tests__/features/vehicles/work-order-reading-update.test.ts
  21. 68 27
      src/__tests__/features/workorders/create-workorder.test.ts
  22. 16 10
      src/app/api/v1/tech/jobs/[id]/checkin/route.ts
  23. 47 7
      src/features/import/Actions/importActions.ts
  24. 25 0
      src/features/inspections/Actions/inspectionActions.ts
  25. 24 24
      src/features/vehicles/Actions/serviceActions.ts
  26. 48 0
      src/features/vehicles/Components/LowerReadingNotice.tsx
  27. 19 0
      src/features/vehicles/Components/VehicleForm.tsx
  28. 2 0
      src/features/vehicles/Components/service-edit/form-types.ts
  29. 17 0
      src/features/vehicles/Components/service-page/ServiceRecordPage.tsx
  30. 40 12
      src/features/vehicles/Components/service-page/modern/JobFactsCard.tsx
  31. 1 0
      src/features/vehicles/Components/service-page/modern/ModernDetails.tsx
  32. 158 0
      src/features/vehicles/Lib/vehicleReading.ts

+ 2 - 0
messages/de/vehicles.json

@@ -461,6 +461,8 @@
     "deleteVehicleMarine": "Boot löschen",
     "deleteVehicleMarine": "Boot löschen",
     "editMileage": "Kilometerstand ändern",
     "editMileage": "Kilometerstand ändern",
     "editMileageMarine": "Betriebsstunden ändern",
     "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.",
     "bookAppointment": "Termin buchen",
     "bookAppointment": "Termin buchen",
     "addTitleMarine": "Neues Wasserfahrzeug hinzufügen"
     "addTitleMarine": "Neues Wasserfahrzeug hinzufügen"
   },
   },

+ 2 - 0
messages/en/vehicles.json

@@ -461,6 +461,8 @@
     "deleteVehicleMarine": "Delete boat",
     "deleteVehicleMarine": "Delete boat",
     "editMileage": "Change mileage",
     "editMileage": "Change mileage",
     "editMileageMarine": "Change engine hours",
     "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.",
     "bookAppointment": "Book appointment",
     "bookAppointment": "Book appointment",
     "addTitleMarine": "Add New Vessel"
     "addTitleMarine": "Add New Vessel"
   },
   },

+ 2 - 0
messages/es/vehicles.json

@@ -461,6 +461,8 @@
     "deleteVehicleMarine": "Eliminar embarcación",
     "deleteVehicleMarine": "Eliminar embarcación",
     "editMileage": "Cambiar kilometraje",
     "editMileage": "Cambiar kilometraje",
     "editMileageMarine": "Cambiar horas de motor",
     "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.",
     "bookAppointment": "Reservar cita",
     "bookAppointment": "Reservar cita",
     "addTitleMarine": "Agregar nueva embarcación"
     "addTitleMarine": "Agregar nueva embarcación"
   },
   },

+ 2 - 0
messages/fr/vehicles.json

@@ -461,6 +461,8 @@
     "deleteVehicleMarine": "Supprimer le bateau",
     "deleteVehicleMarine": "Supprimer le bateau",
     "editMileage": "Changer le kilométrage",
     "editMileage": "Changer le kilométrage",
     "editMileageMarine": "Changer les heures moteur",
     "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.",
     "bookAppointment": "Prendre rendez-vous",
     "bookAppointment": "Prendre rendez-vous",
     "addTitleMarine": "Ajouter un nouveau navire"
     "addTitleMarine": "Ajouter un nouveau navire"
   },
   },

+ 2 - 0
messages/it/vehicles.json

@@ -461,6 +461,8 @@
     "deleteVehicleMarine": "Elimina imbarcazione",
     "deleteVehicleMarine": "Elimina imbarcazione",
     "editMileage": "Cambia chilometraggio",
     "editMileage": "Cambia chilometraggio",
     "editMileageMarine": "Cambia ore motore",
     "editMileageMarine": "Cambia ore motore",
+    "lowerReading": "Inferiore all'ultima lettura ({reading}). Puoi comunque salvare.",
+    "lowerReadingMarine": "Inferiore all'ultima lettura ({hours} ore). Puoi comunque salvare.",
     "bookAppointment": "Prenota appuntamento",
     "bookAppointment": "Prenota appuntamento",
     "addTitleMarine": "Aggiungi Nuova Imbarcazione"
     "addTitleMarine": "Aggiungi Nuova Imbarcazione"
   },
   },

+ 2 - 0
messages/lt/vehicles.json

@@ -461,6 +461,8 @@
     "deleteVehicleMarine": "Ištrinti valtį",
     "deleteVehicleMarine": "Ištrinti valtį",
     "editMileage": "Pakeisti ridą",
     "editMileage": "Pakeisti ridą",
     "editMileageMarine": "Pakeisti variklio valandas",
     "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.",
     "bookAppointment": "Užregistruoti vizitą",
     "bookAppointment": "Užregistruoti vizitą",
     "addTitleMarine": "Pridėti naują laivą"
     "addTitleMarine": "Pridėti naują laivą"
   },
   },

+ 2 - 0
messages/nb/vehicles.json

@@ -461,6 +461,8 @@
     "deleteVehicleMarine": "Slett båt",
     "deleteVehicleMarine": "Slett båt",
     "editMileage": "Endre kilometerstand",
     "editMileage": "Endre kilometerstand",
     "editMileageMarine": "Endre motortimer",
     "editMileageMarine": "Endre motortimer",
+    "lowerReading": "Lavere enn forrige avlesning ({reading}). Du kan likevel lagre.",
+    "lowerReadingMarine": "Lavere enn forrige avlesning ({hours} timer). Du kan likevel lagre.",
     "bookAppointment": "Book time",
     "bookAppointment": "Book time",
     "addTitleMarine": "Legg til nytt fartøy"
     "addTitleMarine": "Legg til nytt fartøy"
   },
   },

+ 2 - 0
messages/nl/vehicles.json

@@ -461,6 +461,8 @@
     "deleteVehicleMarine": "Boot verwijderen",
     "deleteVehicleMarine": "Boot verwijderen",
     "editMileage": "Kilometerstand wijzigen",
     "editMileage": "Kilometerstand wijzigen",
     "editMileageMarine": "Motoruren wijzigen",
     "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.",
     "bookAppointment": "Afspraak inplannen",
     "bookAppointment": "Afspraak inplannen",
     "addTitleMarine": "Nieuw vaartuig toevoegen"
     "addTitleMarine": "Nieuw vaartuig toevoegen"
   },
   },

+ 2 - 0
messages/pl/vehicles.json

@@ -461,6 +461,8 @@
     "deleteVehicleMarine": "Usuń łódź",
     "deleteVehicleMarine": "Usuń łódź",
     "editMileage": "Zmień przebieg",
     "editMileage": "Zmień przebieg",
     "editMileageMarine": "Zmień godziny pracy silnika",
     "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ć.",
     "bookAppointment": "Umów wizytę",
     "bookAppointment": "Umów wizytę",
     "addTitleMarine": "Dodaj nową jednostkę"
     "addTitleMarine": "Dodaj nową jednostkę"
   },
   },

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

@@ -461,6 +461,8 @@
     "deleteVehicleMarine": "Excluir embarcação",
     "deleteVehicleMarine": "Excluir embarcação",
     "editMileage": "Alterar quilometragem",
     "editMileage": "Alterar quilometragem",
     "editMileageMarine": "Alterar horas de motor",
     "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.",
     "bookAppointment": "Agendar horário",
     "bookAppointment": "Agendar horário",
     "addTitleMarine": "Adicionar Nova Embarcação"
     "addTitleMarine": "Adicionar Nova Embarcação"
   },
   },

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

@@ -461,6 +461,8 @@
     "deleteVehicleMarine": "Eliminar embarcação",
     "deleteVehicleMarine": "Eliminar embarcação",
     "editMileage": "Alterar quilometragem",
     "editMileage": "Alterar quilometragem",
     "editMileageMarine": "Alterar horas de motor",
     "editMileageMarine": "Alterar horas de motor",
+    "lowerReading": "Inferior à última leitura ({reading}). Pode guardar na mesma.",
+    "lowerReadingMarine": "Inferior à última leitura ({hours} horas). Pode guardar na mesma.",
     "bookAppointment": "Fazer marcação",
     "bookAppointment": "Fazer marcação",
     "addTitleMarine": "Adicionar Nova Embarcação"
     "addTitleMarine": "Adicionar Nova Embarcação"
   },
   },

+ 2 - 0
messages/ru/vehicles.json

@@ -461,6 +461,8 @@
     "deleteVehicleMarine": "Удалить лодку",
     "deleteVehicleMarine": "Удалить лодку",
     "editMileage": "Изменить пробег",
     "editMileage": "Изменить пробег",
     "editMileageMarine": "Изменить моточасы",
     "editMileageMarine": "Изменить моточасы",
+    "lowerReading": "Меньше последнего показания ({reading}). Сохранить всё равно можно.",
+    "lowerReadingMarine": "Меньше последнего показания ({hours} ч). Сохранить всё равно можно.",
     "bookAppointment": "Создать запись",
     "bookAppointment": "Создать запись",
     "addTitleMarine": "Добавить новое судно"
     "addTitleMarine": "Добавить новое судно"
   },
   },

+ 2 - 0
messages/tr/vehicles.json

@@ -461,6 +461,8 @@
     "deleteVehicleMarine": "Tekneyi sil",
     "deleteVehicleMarine": "Tekneyi sil",
     "editMileage": "Kilometreyi değiştir",
     "editMileage": "Kilometreyi değiştir",
     "editMileageMarine": "Motor saatlerini değiştir",
     "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.",
     "bookAppointment": "Randevu oluştur",
     "bookAppointment": "Randevu oluştur",
     "addTitleMarine": "Yeni Tekne Ekle"
     "addTitleMarine": "Yeni Tekne Ekle"
   },
   },

+ 39 - 2
src/__tests__/api/tech-checkin.test.ts

@@ -45,8 +45,16 @@ const JOB = {
   inspectionId: null,
   inspectionId: null,
   invoiceNumber: 'WO-1',
   invoiceNumber: 'WO-1',
   createdAt: new Date('2026-11-09T08:00:00Z'),
   createdAt: new Date('2026-11-09T08:00:00Z'),
+  startDateTime: new Date('2026-11-09T08:00:00Z') as Date | null,
+  serviceDate: new Date('2026-11-09T08:00:00Z'),
+}
+const OLD_JOB = {
+  ...JOB,
+  id: 'job-0',
+  createdAt: new Date('2026-05-01T08:00:00Z'),
+  startDateTime: new Date('2026-05-01T08:00:00Z') as Date | null,
+  serviceDate: new Date('2026-05-01T08:00:00Z'),
 }
 }
-const OLD_JOB = { ...JOB, id: 'job-0', createdAt: new Date('2026-05-01T08:00:00Z') }
 
 
 const state = {
 const state = {
   marks: [] as Mark[],
   marks: [] as Mark[],
@@ -109,6 +117,8 @@ const matches = (row: Record<string, unknown>, where: Record<string, unknown>):
       return row[k] !== (v as { not: unknown }).not
       return row[k] !== (v as { not: unknown }).not
     if (v && typeof v === 'object' && 'lt' in (v as object))
     if (v && typeof v === 'object' && 'lt' in (v as object))
       return (row[k] as number) < (v as { lt: number }).lt
       return (row[k] as number) < (v as { lt: number }).lt
+    if (v && typeof v === 'object' && 'gt' in (v as object))
+      return row[k] != null && (row[k] as number | Date) > (v as { gt: number | Date }).gt
     return row[k] === v
     return row[k] === v
   })
   })
 
 
@@ -132,7 +142,8 @@ vi.mock('@/lib/db', () => {
               attachments: state.attachments.filter((a) => a.category === 'dropoff'),
               attachments: state.attachments.filter((a) => a.category === 'dropoff'),
             }
             }
           }
           }
-          return job
+          // A row as it was read, not the one a later write changes.
+          return { ...job }
         }
         }
       ),
       ),
       update: vi.fn(async ({ data }: { data: { mileage: number | null } }) => {
       update: vi.fn(async ({ data }: { data: { mileage: number | null } }) => {
@@ -307,6 +318,7 @@ beforeEach(() => {
   }
   }
   JOB.mileage = null
   JOB.mileage = null
   JOB.status = 'scheduled'
   JOB.status = 'scheduled'
+  OLD_JOB.mileage = null
 })
 })
 
 
 describe('reading a check-in', () => {
 describe('reading a check-in', () => {
@@ -376,6 +388,31 @@ describe('mileage and body', () => {
     expect(state.vehicle.mileage).toBe(125400)
     expect(state.vehicle.mileage).toBe(125400)
   })
   })
 
 
+  it('keeps an equal reading without touching the vehicle', async () => {
+    await PATCH(req({ mileage: 120000 }), job())
+    expect(JOB.mileage).toBe(120000)
+    expect(state.vehicle.mileage).toBe(120000)
+  })
+
+  it('does not let an earlier visit checked in late push today’s reading on', async () => {
+    // This visit already read 125 400; the May job is filled in afterwards
+    // with a digit too many.
+    await PATCH(req({ mileage: 125400 }), job())
+    state.ctx.isAdmin = true
+    const res = await PATCH(req({ mileage: 1189000 }), {
+      params: Promise.resolve({ id: OLD_JOB.id }),
+    })
+    expect(res.status).toBe(200)
+    expect(OLD_JOB.mileage).toBe(1189000)
+    expect(state.vehicle.mileage).toBe(125400)
+  })
+
+  it('answers a lower reading as it always has', async () => {
+    const { status, body } = await read(await PATCH(req({ mileage: 99 }), job()))
+    expect(status).toBe(200)
+    expect(body.data).toEqual({ mileage: 99 })
+  })
+
   it('chooses the drawing the vehicle is marked on', async () => {
   it('chooses the drawing the vehicle is marked on', async () => {
     await PATCH(req({ bodyType: 'pickup' }), job())
     await PATCH(req({ bodyType: 'pickup' }), job())
     expect(state.vehicle.bodyType).toBe('pickup')
     expect(state.vehicle.bodyType).toBe('pickup')

+ 76 - 4
src/__tests__/features/import/commit.test.ts

@@ -35,8 +35,9 @@ function txClient(pending: Store) {
       create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {
       create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {
         // Stands in for a row the database refuses.
         // Stands in for a row the database refuses.
         if (data.title === 'Refused') throw new Error('write refused')
         if (data.title === 'Refused') throw new Error('write refused')
-        pending.services.push(data)
-        return { id: `s${++seq}` }
+        const id = `s${++seq}`
+        pending.services.push({ id, ...data })
+        return { id }
       }),
       }),
     },
     },
   }
   }
@@ -52,8 +53,51 @@ const db = {
     return result
     return result
   }),
   }),
   customer: { findMany: vi.fn(async () => []) },
   customer: { findMany: vi.fn(async () => []) },
-  vehicle: { findMany: vi.fn(async () => []) },
-  serviceRecord: { findMany: vi.fn(async () => []) },
+  vehicle: {
+    findMany: vi.fn(async () => []),
+    // A reading moved up, once the rows are in.
+    updateMany: vi.fn(
+      async ({
+        where,
+        data,
+      }: {
+        where: { id: string; mileage: { lt: number } }
+        data: { mileage: number }
+      }) => {
+        const car = committed.vehicles.find((v) => v.id === where.id)
+        if (!car || ((car.mileage as number | undefined) ?? 0) >= where.mileage.lt)
+          return { count: 0 }
+        car.mileage = data.mileage
+        return { count: 1 }
+      }
+    ),
+  },
+  serviceRecord: {
+    // The plan reads what exists (nothing); the readings are settled from
+    // what this import wrote.
+    findMany: vi.fn(async (args?: { where?: { vehicleId?: string; importBatchId?: string } }) =>
+      args?.where?.importBatchId
+        ? committed.services.filter(
+            (s) => s.vehicleId === args.where?.vehicleId && ((s.mileage as number | null) ?? 0) > 0
+          )
+        : []
+    ),
+    // The rule's one question: a later job on the vehicle with a reading?
+    findFirst: vi.fn(
+      async ({
+        where,
+      }: {
+        where: { vehicleId: string; id: { not: string }; OR: [{ startDateTime: { gt: Date } }] }
+      }) =>
+        committed.services.find(
+          (s) =>
+            s.vehicleId === where.vehicleId &&
+            s.id !== where.id.not &&
+            s.mileage != null &&
+            (s.startDateTime as Date) > where.OR[0].startDateTime.gt
+        ) ?? null
+    ),
+  },
   importBatch: {
   importBatch: {
     create: vi.fn(async () => ({ id: 'batch' })),
     create: vi.fn(async () => ({ id: 'batch' })),
     update: vi.fn(async () => ({})),
     update: vi.fn(async () => ({})),
@@ -174,4 +218,32 @@ describe('commitImport', () => {
       ['Brakes', carId],
       ['Brakes', carId],
     ])
     ])
   })
   })
+
+  it('leaves each vehicle on its newest reading, whatever order the rows come in', async () => {
+    rows = [
+      ['2015-06-01', 'ABC123', 'Toyota', 'Hilux', '2000', 'Brakes', '152000'],
+      ['2014-12-10', 'ABC123', 'Toyota', 'Hilux', '2000', 'Oil change', '148000'],
+      // A slip in an old row: a digit too many, on a job before the newest.
+      ['2015-01-15', 'ABC123', 'Toyota', 'Hilux', '2000', 'Tyres', '1490000'],
+      // Oldest first on the other car, with the same slip in the middle: it
+      // must not stick just because it was written before the newest row.
+      ['2014-03-01', 'OVB334', 'Land Rover', 'Discovery', '1998', 'Service', '90000'],
+      ['2014-09-01', 'OVB334', 'Land Rover', 'Discovery', '1998', 'Service', '950000'],
+      ['2015-03-01', 'OVB334', 'Land Rover', 'Discovery', '1998', 'Service', '101000'],
+    ]
+    const res = await commitImport({
+      ...input,
+      mapping: { ...input.mapping, '6': 'service.mileage' },
+    })
+    if (!('data' in res) || !res.data) throw new Error(`import failed: ${res.error}`)
+    expect(res.data).toMatchObject({ created: 6, failed: 0 })
+    // Every reading is kept on its job, as the file had it.
+    expect(committed.services.map((s) => s.mileage)).toEqual([
+      152000, 148000, 1490000, 90000, 950000, 101000,
+    ])
+    expect(committed.vehicles.map((v) => [v.licensePlate, v.mileage])).toEqual([
+      ['ABC123', 152000],
+      ['OVB334', 101000],
+    ])
+  })
 })
 })

+ 12 - 1
src/__tests__/features/inspections/link-work-order.test.ts

@@ -6,7 +6,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
 
 
 const { db, tx } = vi.hoisted(() => {
 const { db, tx } = vi.hoisted(() => {
   const tx = {
   const tx = {
-    serviceRecord: { update: vi.fn() },
+    // 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 })) },
     serviceLabor: { createMany: vi.fn() },
     serviceLabor: { createMany: vi.fn() },
     // The workshop's tax rule for labor; none set, so the lines are taxed.
     // The workshop's tax rule for labor; none set, so the lines are taxed.
     appSetting: { findMany: vi.fn(async () => []) },
     appSetting: { findMany: vi.fn(async () => []) },
@@ -90,6 +93,9 @@ describe('linking to a booked job', () => {
       vehicleId: 'veh-1',
       vehicleId: 'veh-1',
       invoiceNumber: '2026-1007',
       invoiceNumber: '2026-1007',
       inspectionId: null,
       inspectionId: null,
+      mileage: null,
+      startDateTime: new Date('2026-11-19T09:00:00Z'),
+      serviceDate: new Date('2026-11-19T09:00:00Z'),
       laborItems: [],
       laborItems: [],
     })
     })
     const result = await linkWorkOrderToInspection('insp-1', 'job-1', { includeDefects: true })
     const result = await linkWorkOrderToInspection('insp-1', 'job-1', { includeDefects: true })
@@ -98,6 +104,11 @@ describe('linking to a booked job', () => {
       where: { id: 'job-1' },
       where: { id: 'job-1' },
       data: { inspectionId: 'insp-1', mileage: 120000 },
       data: { inspectionId: 'insp-1', mileage: 120000 },
     })
     })
+    // 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 },
+    })
     expect(
     expect(
       tx.serviceLabor.createMany.mock.calls[0][0].data.map(
       tx.serviceLabor.createMany.mock.calls[0][0].data.map(
         (l: { description: string }) => l.description
         (l: { description: string }) => l.description

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

@@ -53,6 +53,7 @@ import { toast } from 'sonner'
 import { TooltipProvider } from '@/components/ui/tooltip'
 import { TooltipProvider } from '@/components/ui/tooltip'
 import { BOOKING_EVENT, BookingAccessProvider } from '@/components/booking-launcher'
 import { BOOKING_EVENT, BookingAccessProvider } from '@/components/booking-launcher'
 import { VehicleForm } from '@/features/vehicles/Components/VehicleForm'
 import { VehicleForm } from '@/features/vehicles/Components/VehicleForm'
+import { ServiceTypeProvider } from '@/components/service-type-context'
 import { createVehicle, updateVehicle } from '@/features/vehicles/Actions/vehicleActions'
 import { createVehicle, updateVehicle } from '@/features/vehicles/Actions/vehicleActions'
 
 
 const VEHICLE = {
 const VEHICLE = {
@@ -386,3 +387,68 @@ describe('adding a vehicle', () => {
     expect(screen.getByLabelText('License Plate')).toHaveFocus()
     expect(screen.getByLabelText('License Plate')).toHaveFocus()
   })
   })
 })
 })
+
+describe('a reading lowered on the vehicle form', () => {
+  const NOTICE = 'Lower than the last reading (225,040 km). You can still save it.'
+  const field = () => screen.getByLabelText('Mileage', { selector: 'input#mileage' })
+
+  it('says nothing while the reading is as saved or goes up', async () => {
+    renderForm()
+    await screen.findByRole('dialog')
+    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
+    fireEvent.change(field(), { target: { value: '231500' } })
+    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
+    fireEvent.change(field(), { target: { value: '' } })
+    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
+  })
+
+  it('says so beside the field when it goes down, and saves it all the same', async () => {
+    renderForm()
+    await screen.findByRole('dialog')
+    fireEvent.change(field(), { target: { value: '22504' } })
+    // Under the field and under the figure at the top, which is the same reading.
+    expect(screen.getAllByText(NOTICE)).toHaveLength(2)
+    expect(field()).toHaveAccessibleDescription(NOTICE.replace(' km', '\u00a0km'))
+
+    fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }))
+    await waitFor(() => expect(updateVehicle).toHaveBeenCalled())
+    expect(vi.mocked(updateVehicle).mock.calls[0][0]).toMatchObject({ mileage: 22504 })
+    expect(toast.error).not.toHaveBeenCalled()
+  })
+
+  it('goes away when the reading is put back', async () => {
+    renderForm()
+    await screen.findByRole('dialog')
+    fireEvent.change(field(), { target: { value: '100' } })
+    expect(screen.getAllByTestId('lower-reading-notice').length).toBeGreaterThan(0)
+    fireEvent.change(field(), { target: { value: '225040' } })
+    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
+  })
+
+  it('has nothing to compare with on a new vehicle', async () => {
+    renderForm({ vehicle: undefined })
+    await screen.findByRole('dialog')
+    fireEvent.change(screen.getByLabelText('Mileage', { selector: 'input#mileage' }), {
+      target: { value: '5' },
+    })
+    expect(screen.queryByTestId('lower-reading-notice')).not.toBeInTheDocument()
+  })
+
+  it('speaks of engine hours 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')
+    fireEvent.change(screen.getByLabelText('Engine Hours', { selector: 'input#mileage' }), {
+      target: { value: '900' },
+    })
+    expect(
+      screen.getAllByText('Lower than the last reading (1,240 hours). You can still save it.')
+        .length
+    ).toBeGreaterThan(0)
+  })
+})

+ 243 - 0
src/__tests__/features/vehicles/vehicle-reading.test.ts

@@ -0,0 +1,243 @@
+/**
+ * @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.
+ */
+import { beforeEach, describe, expect, it } from 'vitest'
+import {
+  applyJobReading,
+  isLowerReading,
+  jobReadingDate,
+  lastReadingBeforeJob,
+} 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)
+    expect(isLowerReading('0', 100_000)).toBe(true)
+  })
+
+  it('is not an equal or higher one, an empty field, or an unknown last reading', () => {
+    expect(isLowerReading('100000', 100_000)).toBe(false)
+    expect(isLowerReading('100001', 100_000)).toBe(false)
+    expect(isLowerReading('', 100_000)).toBe(false)
+    expect(isLowerReading('  ', 100_000)).toBe(false)
+    expect(isLowerReading('abc', 100_000)).toBe(false)
+    expect(isLowerReading('5', null)).toBe(false)
+    expect(isLowerReading('5', 0)).toBe(false)
+  })
+})

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

@@ -0,0 +1,127 @@
+/**
+ * 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.'
+    )
+  })
+})

+ 171 - 0
src/__tests__/features/vehicles/work-order-reading-update.test.ts

@@ -0,0 +1,171 @@
+/**
+ * Saving a work order and the vehicle's reading.
+ *
+ * The work order page sends the reading with every save, so the save has to
+ * tell a reading that was just typed from one that was already there, and the
+ * newest job from an old one being tidied up. The rule itself is tested in
+ * vehicle-reading.test.ts; this is the action asking it the right question.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}))
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
+vi.mock('@/lib/notification-bus', () => ({ notificationBus: { emit: vi.fn() } }))
+vi.mock('@/lib/document-lock.server', () => ({
+  assertInvoiceEditable: vi.fn().mockResolvedValue(undefined),
+  getDocumentLockSettings: vi.fn().mockResolvedValue({}),
+}))
+vi.mock('@/lib/db', () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    appSetting: { findMany: vi.fn().mockResolvedValue([]) },
+    vehicle: { findFirst: vi.fn(), update: vi.fn(), updateMany: vi.fn() },
+    serviceRecord: { findFirst: vi.fn(), findMany: vi.fn(), update: vi.fn() },
+    $transaction: vi.fn(),
+  },
+}))
+
+import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
+import { db } from '@/lib/db'
+import { updateServiceRecord } from '@/features/vehicles/Actions/serviceActions'
+
+const ORG = 'org-a'
+const START = new Date('2026-11-19T09:00:00Z')
+
+const state = {
+  /** Current readings by vehicle. */
+  vehicles: {} as Record<string, number>,
+  /** Whether a later-dated job on the vehicle carries a reading. */
+  laterReading: false,
+  job: {
+    id: 'sr-a',
+    organizationId: ORG,
+    vehicleId: 'veh-a' as string,
+    customerId: null,
+    title: 'Brake pads',
+    status: 'pending',
+    mileage: null as number | null,
+    startDateTime: START,
+    serviceDate: START,
+    attachments: [],
+  },
+}
+
+beforeEach(() => {
+  vi.resetAllMocks()
+  state.vehicles = { 'veh-a': 100_000, 'veh-b': 30_000 }
+  state.laterReading = false
+  state.job.vehicleId = 'veh-a'
+  state.job.mileage = null
+
+  vi.mocked(getCachedSession).mockResolvedValue({
+    user: { id: 'user-a', email: 'a@example.com' },
+  } as any)
+  vi.mocked(getCachedMembership).mockResolvedValue({
+    organizationId: ORG,
+    role: 'owner',
+    roleId: null,
+    customRole: null,
+  } 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.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) {
+      expect(where.organizationId).toBe(ORG)
+      return state.laterReading ? { id: 'sr-later' } : null
+    }
+    return where.id === state.job.id && where.organizationId === ORG
+      ? {
+          ...state.job,
+          vehicle: { id: state.job.vehicleId, mileage: state.vehicles[state.job.vehicleId] },
+        }
+      : null
+  }) as any)
+  vi.mocked(db.vehicle.updateMany).mockImplementation((async ({ where, data }: any) => {
+    if (where.organizationId !== ORG || !(state.vehicles[where.id] < where.mileage.lt))
+      return { count: 0 }
+    state.vehicles[where.id] = data.mileage
+    return { count: 1 }
+  }) as any)
+  vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
+    fn({
+      serviceRecord: {
+        update: vi.fn(async ({ data }: any) => {
+          if (data.mileage !== undefined) state.job.mileage = data.mileage
+          if (data.vehicleId) state.job.vehicleId = data.vehicleId
+          return { ...state.job }
+        }),
+      },
+    })
+  )
+})
+
+async function save(input: Record<string, unknown>) {
+  const result = await updateServiceRecord({ id: 'sr-a', ...input })
+  expect(result.success, result.error).toBe(true)
+}
+
+describe('saving a work order', () => {
+  it('moves the vehicle on when a higher reading is typed on its newest job', async () => {
+    await save({ mileage: 104_500 })
+    expect(state.job.mileage).toBe(104_500)
+    expect(state.vehicles['veh-a']).toBe(104_500)
+  })
+
+  it('saves a lower reading on the job and leaves the vehicle where it was', async () => {
+    await save({ mileage: 99_000 })
+    expect(state.job.mileage).toBe(99_000)
+    expect(state.vehicles['veh-a']).toBe(100_000)
+  })
+
+  it('saves an equal reading without touching the vehicle', async () => {
+    await save({ mileage: 100_000 })
+    expect(state.job.mileage).toBe(100_000)
+    expect(state.vehicles['veh-a']).toBe(100_000)
+  })
+
+  it('does not let an older job being edited push the vehicle forward', async () => {
+    state.laterReading = true
+    await save({ mileage: 900_000 })
+    expect(state.job.mileage).toBe(900_000)
+    expect(state.vehicles['veh-a']).toBe(100_000)
+    expect(db.vehicle.updateMany).not.toHaveBeenCalled()
+  })
+
+  it('leaves a vehicle corrected by hand alone when the job is saved again unchanged', async () => {
+    // The job read 180 000 on the way in; the cluster was replaced and the
+    // vehicle set to 5 on the vehicle form. The page still sends 180 000.
+    state.job.mileage = 180_000
+    state.vehicles['veh-a'] = 5
+    await save({ mileage: 180_000, title: 'Instrument cluster' })
+    expect(state.vehicles['veh-a']).toBe(5)
+  })
+
+  it('does not ask at all when the save says nothing about the reading', async () => {
+    state.job.mileage = 180_000
+    await save({ title: 'Brake pads, front' })
+    expect(db.vehicle.updateMany).not.toHaveBeenCalled()
+    expect(state.vehicles['veh-a']).toBe(100_000)
+  })
+
+  it('clears a reading without touching the vehicle', async () => {
+    state.job.mileage = 100_000
+    await save({ mileage: null })
+    expect(state.job.mileage).toBeNull()
+    expect(state.vehicles['veh-a']).toBe(100_000)
+  })
+
+  it('speaks for the vehicle the job is moved to, not the one it left', async () => {
+    state.job.mileage = 120_000
+    await save({ vehicleId: 'veh-b', mileage: 120_000 })
+    expect(state.vehicles['veh-b']).toBe(120_000)
+    expect(state.vehicles['veh-a']).toBe(100_000)
+  })
+})

+ 68 - 27
src/__tests__/features/workorders/create-workorder.test.ts

@@ -40,7 +40,7 @@ vi.mock('@/lib/invoice-utils', async (importOriginal) => ({
 vi.mock('@/lib/db', () => ({
 vi.mock('@/lib/db', () => ({
   db: {
   db: {
     user: { findUnique: vi.fn() },
     user: { findUnique: vi.fn() },
-    vehicle: { findFirst: vi.fn(), update: vi.fn() },
+    vehicle: { findFirst: vi.fn(), update: vi.fn(), updateMany: vi.fn() },
     appSetting: { findMany: vi.fn(), updateMany: vi.fn() },
     appSetting: { findMany: vi.fn(), updateMany: vi.fn() },
     organization: { findUnique: vi.fn() },
     organization: { findUnique: vi.fn() },
     // findMany: a draft with no stated time is placed in the first free slot,
     // findMany: a draft with no stated time is placed in the first free slot,
@@ -90,6 +90,11 @@ function setupCommonMocks() {
   vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(null) // no previous records
   vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(null) // no previous records
   vi.mocked(db.$queryRaw).mockResolvedValue([{ highest: null }] as any)
   vi.mocked(db.$queryRaw).mockResolvedValue([{ highest: null }] as any)
   vi.mocked(db.vehicle.update).mockResolvedValue(VEHICLE 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".
+  vi.mocked(db.vehicle.updateMany).mockImplementation((async ({ where, data }: any) => ({
+    count: VEHICLE.mileage < where.mileage.lt && data.mileage === where.mileage.lt ? 1 : 0,
+  })) as any)
 }
 }
 
 
 beforeEach(() => {
 beforeEach(() => {
@@ -460,11 +465,12 @@ describe('createServiceRecord — parts and inventory', () => {
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------
 
 
 describe('createServiceRecord — vehicle mileage', () => {
 describe('createServiceRecord — vehicle mileage', () => {
-  it('updates vehicle mileage when service mileage is higher', async () => {
-    setupAuth()
-    setupCommonMocks()
+  const START = new Date('2026-11-19T09:00:00Z')
 
 
-    const mockCreate = vi.fn().mockResolvedValue({ id: 'sr-mile' })
+  function createdJob(id: string) {
+    const mockCreate = vi
+      .fn()
+      .mockResolvedValue({ id, vehicleId: VEHICLE_ID, startDateTime: START, serviceDate: START })
     vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
     vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
       fn({
       fn({
         serviceRecord: { create: mockCreate },
         serviceRecord: { create: mockCreate },
@@ -474,48 +480,83 @@ describe('createServiceRecord — vehicle mileage', () => {
         inventoryPart: { findFirst: vi.fn(), update: vi.fn() },
         inventoryPart: { findFirst: vi.fn(), update: vi.fn() },
       })
       })
     )
     )
+  }
 
 
-    await createServiceRecord({
+  /** What the vehicle's reading was set to, if it was. */
+  const movedTo = () => {
+    const moved = vi
+      .mocked(db.vehicle.updateMany)
+      .mock.calls.map(([args]) => args as any)
+      .filter((args) => VEHICLE.mileage < args.where.mileage.lt)
+    return moved.length ? moved[0].data.mileage : null
+  }
+
+  it('updates vehicle mileage when service mileage is higher', async () => {
+    setupAuth()
+    setupCommonMocks()
+    createdJob('sr-mile')
+
+    const result = await createServiceRecord({
       vehicleId: VEHICLE_ID,
       vehicleId: VEHICLE_ID,
       title: 'Service',
       title: 'Service',
       mileage: 55000, // higher than vehicle's 50000
       mileage: 55000, // higher than vehicle's 50000
     })
     })
 
 
-    expect(vi.mocked(db.vehicle.update)).toHaveBeenCalledWith(
-      expect.objectContaining({
-        data: expect.objectContaining({ mileage: 55000 }),
-      })
-    )
+    expect(result.success).toBe(true)
+    expect(movedTo()).toBe(55000)
+    // Scoped to the workshop, and only ever upwards.
+    expect(vi.mocked(db.vehicle.updateMany)).toHaveBeenCalledWith({
+      where: { id: VEHICLE_ID, organizationId: ORG, mileage: { lt: 55000 } },
+      data: { mileage: 55000 },
+    })
   })
   })
 
 
   it('does not downgrade vehicle mileage when service mileage is lower', async () => {
   it('does not downgrade vehicle mileage when service mileage is lower', async () => {
     setupAuth()
     setupAuth()
     setupCommonMocks()
     setupCommonMocks()
+    createdJob('sr-low')
 
 
-    const mockCreate = vi.fn().mockResolvedValue({ id: 'sr-low' })
-    vi.mocked(db.$transaction).mockImplementation(async (fn: any) =>
-      fn({
-        serviceRecord: { create: mockCreate },
-        servicePart: { createMany: vi.fn() },
-        serviceLabor: { createMany: vi.fn() },
-        serviceAttachment: { createMany: vi.fn() },
-        inventoryPart: { findFirst: vi.fn(), update: vi.fn() },
-      })
-    )
-
-    await createServiceRecord({
+    const result = await createServiceRecord({
       vehicleId: VEHICLE_ID,
       vehicleId: VEHICLE_ID,
       title: 'Service',
       title: 'Service',
       mileage: 40000, // lower than vehicle's 50000
       mileage: 40000, // lower than vehicle's 50000
     })
     })
 
 
-    // Should NOT include mileage in the update
+    // Saved all the same: a lower reading is never refused.
+    expect(result.success).toBe(true)
+    expect(movedTo()).toBeNull()
     expect(vi.mocked(db.vehicle.update)).toHaveBeenCalledWith(
     expect(vi.mocked(db.vehicle.update)).toHaveBeenCalledWith(
-      expect.objectContaining({
-        data: expect.not.objectContaining({ mileage: 40000 }),
-      })
+      expect.objectContaining({ data: expect.not.objectContaining({ mileage: 40000 }) })
     )
     )
   })
   })
+
+  it('leaves the vehicle alone when a later job already carries a reading', async () => {
+    setupAuth()
+    setupCommonMocks()
+    createdJob('sr-backdated')
+    // The only job the rule asks about is one dated after this, with a reading.
+    vi.mocked(db.serviceRecord.findFirst).mockImplementation((async ({ where }: any) =>
+      where?.mileage && 'not' in where.mileage ? { id: 'sr-later' } : null) as any)
+
+    const result = await createServiceRecord({
+      vehicleId: VEHICLE_ID,
+      title: 'Service',
+      mileage: 55000,
+    })
+
+    expect(result.success).toBe(true)
+    expect(vi.mocked(db.vehicle.updateMany)).not.toHaveBeenCalled()
+  })
+
+  it('writes no reading for a job created without one', async () => {
+    setupAuth()
+    setupCommonMocks()
+    createdJob('sr-none')
+
+    await createServiceRecord({ vehicleId: VEHICLE_ID, title: 'Service' })
+
+    expect(vi.mocked(db.vehicle.updateMany)).not.toHaveBeenCalled()
+  })
 })
 })
 
 
 // ---------------------------------------------------------------------------
 // ---------------------------------------------------------------------------

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

@@ -5,6 +5,7 @@ import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { apiError, apiOk, withApiAuth } from '@/lib/with-api-auth'
 import { apiError, apiOk, withApiAuth } from '@/lib/with-api-auth'
 import { BODY_TYPES } from '@/features/condition-map/Lib/drawingTypes'
 import { BODY_TYPES } from '@/features/condition-map/Lib/drawingTypes'
 import { loadCheckin } from '@/features/condition-map/Lib/checkin.server'
 import { loadCheckin } from '@/features/condition-map/Lib/checkin.server'
+import { applyJobReading, jobReadingDate } from '@/features/vehicles/Lib/vehicleReading'
 import {
 import {
   appLocale,
   appLocale,
   checkinJobFor,
   checkinJobFor,
@@ -66,20 +67,25 @@ export async function PATCH(request: Request, { params }: { params: Promise<{ id
       await noteArrival(ctx.organizationId, job)
       await noteArrival(ctx.organizationId, job)
 
 
       if (mileage !== undefined) {
       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({
         await db.serviceRecord.updateMany({
           where: { id: job.id, organizationId: ctx.organizationId },
           where: { id: job.id, organizationId: ctx.organizationId },
           data: { mileage },
           data: { mileage },
         })
         })
-        // The vehicle's reading only ever goes up, as it does when the job is
-        // saved on the web: a typo on an old job must not wind the clock back.
-        if (mileage !== null) {
-          await db.vehicle.updateMany({
-            where: {
-              id: job.vehicleId,
-              organizationId: ctx.organizationId,
-              mileage: { lt: mileage },
-            },
-            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, {
+            organizationId: ctx.organizationId,
+            vehicleId: job.vehicleId,
+            jobId: job.id,
+            jobDate: jobReadingDate(before),
+            reading: mileage,
+            previousReading: before.mileage,
           })
           })
         }
         }
       }
       }

+ 47 - 7
src/features/import/Actions/importActions.ts

@@ -38,6 +38,7 @@ import {
   detectDecimalSeparator,
   detectDecimalSeparator,
 } from '../Lib/normalize'
 } from '../Lib/normalize'
 import { releaseFiles } from '@/lib/files/manager'
 import { releaseFiles } from '@/lib/files/manager'
+import { applyJobReading, jobReadingDate } from '@/features/vehicles/Lib/vehicleReading'
 import { escapeHtml } from '@/features/email/Render/escape'
 import { escapeHtml } from '@/features/email/Render/escape'
 import { organizationTranslator } from '@/i18n/organization-translator'
 import { organizationTranslator } from '@/i18n/organization-translator'
 import { serviceRecordFileUrls, vehicleFileUrls } from '@/lib/files/collect'
 import { serviceRecordFileUrls, vehicleFileUrls } from '@/lib/files/collect'
@@ -358,6 +359,8 @@ interface CommitState {
   /** Row index → id of the customer/vehicle that row created, for rows that share it. */
   /** Row index → id of the customer/vehicle that row created, for rows that share it. */
   customerIds: Map<number, string>
   customerIds: Map<number, string>
   vehicleIds: Map<number, string>
   vehicleIds: Map<number, string>
+  /** Vehicles that got a job with a reading, settled once every row is written. */
+  readingVehicleIds: Set<string>
   nextCustomerNumber: number
   nextCustomerNumber: number
 }
 }
 
 
@@ -426,6 +429,43 @@ function forgetRow(state: CommitState, row: RowPlan) {
   }
   }
 }
 }
 
 
+/**
+ * The vehicles' readings, once every row is written. The newest imported job
+ * on each vehicle speaks for it, by the rule every job reading follows
+ * (vehicleReading.ts); asked row by row, a slip in an old row could become
+ * the vehicle's reading just because of where it sat in the file.
+ */
+async function settleReadings(state: CommitState): Promise<void> {
+  const { organizationId, batchId } = state
+  for (const vehicleId of state.readingVehicleIds) {
+    try {
+      const jobs = await db.serviceRecord.findMany({
+        where: { organizationId, vehicleId, importBatchId: batchId, mileage: { gt: 0 } },
+        select: { id: true, mileage: true, startDateTime: true, serviceDate: true },
+      })
+      let newest: (typeof jobs)[number] | null = null
+      for (const job of jobs) {
+        if (!newest) {
+          newest = job
+          continue
+        }
+        const [at, best] = [jobReadingDate(job).getTime(), jobReadingDate(newest).getTime()]
+        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,
+      })
+    } catch {
+      // The history is in; a reading that could not be settled stays as it was.
+    }
+  }
+}
+
 async function writeRow(tx: Tx, state: CommitState, row: RowPlan): Promise<void> {
 async function writeRow(tx: Tx, state: CommitState, row: RowPlan): Promise<void> {
   const { organizationId, userId, batchId, entity } = state
   const { organizationId, userId, batchId, entity } = state
 
 
@@ -523,7 +563,9 @@ async function writeRow(tx: Tx, state: CommitState, row: RowPlan): Promise<void>
           vin: v.vin,
           vin: v.vin,
           licensePlate: v.licensePlate,
           licensePlate: v.licensePlate,
           color: v.color,
           color: v.color,
-          mileage: v.mileage ?? row.service?.mileage ?? 0,
+          // A reading on the job comes to the vehicle once every row is
+          // in (settleReadings), not from whichever row happens to be first.
+          mileage: v.mileage ?? 0,
           // Unknown fuel and gearbox take the schema defaults rather than a guess stored as fact.
           // Unknown fuel and gearbox take the schema defaults rather than a guess stored as fact.
           ...(v.fuelType && { fuelType: v.fuelType }),
           ...(v.fuelType && { fuelType: v.fuelType }),
           ...(v.transmission && { transmission: v.transmission }),
           ...(v.transmission && { transmission: v.transmission }),
@@ -579,12 +621,7 @@ async function writeRow(tx: Tx, state: CommitState, row: RowPlan): Promise<void>
         importBatchId: batchId,
         importBatchId: batchId,
       },
       },
     })
     })
-    if (s.mileage != null) {
-      await tx.vehicle.updateMany({
-        where: { id: vehicleId, mileage: { lt: s.mileage } },
-        data: { mileage: s.mileage },
-      })
-    }
+    if (s.mileage != null && s.mileage > 0) state.readingVehicleIds.add(vehicleId)
   }
   }
 }
 }
 
 
@@ -635,6 +672,7 @@ export async function commitImport(raw: unknown) {
         entity,
         entity,
         customerIds: new Map(),
         customerIds: new Map(),
         vehicleIds: new Map(),
         vehicleIds: new Map(),
+        readingVehicleIds: new Set(),
         nextCustomerNumber: await nextCustomerNumberStart(organizationId, plan.rows),
         nextCustomerNumber: await nextCustomerNumberStart(organizationId, plan.rows),
       }
       }
 
 
@@ -689,6 +727,8 @@ export async function commitImport(raw: unknown) {
         await writeImportProgress(organizationId, input.token, { phase: 'writing', done, total })
         await writeImportProgress(organizationId, input.token, { phase: 'writing', done, total })
       }
       }
 
 
+      await settleReadings(state)
+
       const skipped = plan.summary.skip
       const skipped = plan.summary.skip
       const failed = plan.summary.error + failures.length
       const failed = plan.summary.error + failures.length
       await db.importBatch.update({
       await db.importBatch.update({

+ 25 - 0
src/features/inspections/Actions/inspectionActions.ts

@@ -16,6 +16,7 @@ import {
 } from '@/features/signatures/Lib/memberSignature.server'
 } from '@/features/signatures/Lib/memberSignature.server'
 import { liveCertificateDesign } from '../Pdf/certificateDesign'
 import { liveCertificateDesign } from '../Pdf/certificateDesign'
 import { loadTaxApplies } from '@/features/settings/Lib/loadTaxApplies'
 import { loadTaxApplies } from '@/features/settings/Lib/loadTaxApplies'
+import { applyJobReading, jobReadingDate } from '@/features/vehicles/Lib/vehicleReading'
 import { retotalServiceRecord } from '@/features/vehicles/Lib/retotalServiceRecord'
 import { retotalServiceRecord } from '@/features/vehicles/Lib/retotalServiceRecord'
 import { OPEN_SERVICE_STATUSES } from '@/lib/service-record'
 import { OPEN_SERVICE_STATUSES } from '@/lib/service-record'
 import { defectLineText, defectsWorstFirst } from '../Lib/conversion'
 import { defectLineText, defectsWorstFirst } from '../Lib/conversion'
@@ -798,6 +799,15 @@ export async function createWorkOrderFromInspection(
             mileage: inspection.mileage,
             mileage: inspection.mileage,
           },
           },
         })
         })
+        // The job starts with the inspection's reading, which may be news to
+        // the vehicle: the rule is in vehicleReading.ts.
+        await applyJobReading(tx, {
+          organizationId,
+          vehicleId: inspection.vehicle.id,
+          jobId: draft.id,
+          jobDate: jobReadingDate(draft),
+          reading: inspection.mileage,
+        })
         // Hours start at zero: the workshop prices the job as it works. The
         // Hours start at zero: the workshop prices the job as it works. The
         // lines are labor, taxed or not as the workshop taxes labor.
         // lines are labor, taxed or not as the workshop taxes labor.
         const laborTaxable = (await loadTaxApplies(organizationId, tx)).labor
         const laborTaxable = (await loadTaxApplies(organizationId, tx)).labor
@@ -984,6 +994,9 @@ export async function linkWorkOrderToInspection(
           vehicleId: true,
           vehicleId: true,
           invoiceNumber: true,
           invoiceNumber: true,
           inspectionId: true,
           inspectionId: true,
+          mileage: true,
+          startDateTime: true,
+          serviceDate: true,
           laborItems: { select: { description: true } },
           laborItems: { select: { description: true } },
         },
         },
       })
       })
@@ -1007,6 +1020,18 @@ export async function linkWorkOrderToInspection(
           where: { id: job.id },
           where: { id: job.id },
           data: { inspectionId: inspection.id, mileage: inspection.mileage ?? undefined },
           data: { inspectionId: inspection.id, mileage: inspection.mileage ?? undefined },
         })
         })
+        // The inspection's reading is now the job's, and may be news to the
+        // vehicle: the rule is in vehicleReading.ts.
+        if (inspection.mileage != null) {
+          await applyJobReading(tx, {
+            organizationId,
+            vehicleId: inspection.vehicleId,
+            jobId: job.id,
+            jobDate: jobReadingDate(job),
+            reading: inspection.mileage,
+            previousReading: job.mileage,
+          })
+        }
         const lines = [
         const lines = [
           ...(hasInspectionLine ? [] : [inspection.template.name]),
           ...(hasInspectionLine ? [] : [inspection.template.name]),
           ...defects.map(defectLineText),
           ...defects.map(defectLineText),

+ 24 - 24
src/features/vehicles/Actions/serviceActions.ts

@@ -39,6 +39,7 @@ import { reconcileInventoryForParts } from '@/features/inventory/Lib/reconcileSt
 import { assertInvoiceEditable, getDocumentLockSettings } from '@/lib/document-lock.server'
 import { assertInvoiceEditable, getDocumentLockSettings } from '@/lib/document-lock.server'
 import { DocumentLockedError, invoiceLockState } from '@/lib/document-lock'
 import { DocumentLockedError, invoiceLockState } from '@/lib/document-lock'
 import { typeKeySearch } from '@/features/vehicles/Lib/typeKeySetting'
 import { typeKeySearch } from '@/features/vehicles/Lib/typeKeySetting'
+import { applyJobReading, jobReadingDate } from '@/features/vehicles/Lib/vehicleReading'
 import { ACTIVE_HELPERS } from '@/features/workboard/Lib/jobTeam'
 import { ACTIVE_HELPERS } from '@/features/workboard/Lib/jobTeam'
 import { FRESH_SHARE_LINK } from '@/lib/share-expiry'
 import { FRESH_SHARE_LINK } from '@/lib/share-expiry'
 
 
@@ -605,22 +606,19 @@ export async function createServiceRecord(input: unknown) {
         await onInventoryChanged(organizationId)
         await onInventoryChanged(organizationId)
       }
       }
 
 
-      // Update vehicle mileage if service mileage is higher, and reset maintenance dismissed
+      // A new job resets maintenance dismissed, and its reading may become the
+      // vehicle's: the rule is in vehicleReading.ts.
       if (vehicle) {
       if (vehicle) {
-        const vehicleUpdate: {
-          mileage?: number
-          maintenanceDismissed: boolean
-          maintenanceDismissedAt: null
-        } = {
-          maintenanceDismissed: false,
-          maintenanceDismissedAt: null,
-        }
-        if (data.mileage && data.mileage > vehicle.mileage) {
-          vehicleUpdate.mileage = data.mileage
-        }
         await db.vehicle.update({
         await db.vehicle.update({
           where: { id: vehicle.id },
           where: { id: vehicle.id },
-          data: vehicleUpdate,
+          data: { maintenanceDismissed: false, maintenanceDismissedAt: null },
+        })
+        await applyJobReading(db, {
+          organizationId,
+          vehicleId: vehicle.id,
+          jobId: record.id,
+          jobDate: jobReadingDate(record),
+          reading: data.mileage,
         })
         })
       }
       }
 
 
@@ -979,17 +977,19 @@ export async function updateServiceRecord(input: unknown) {
         return updated
         return updated
       })
       })
 
 
-      // Update vehicle mileage if this is the latest service record and mileage is higher
-      if (existing.vehicle && recordData.mileage && recordData.mileage > existing.vehicle.mileage) {
-        const latestRecord = await db.serviceRecord.findFirst({
-          where: { vehicleId: existing.vehicle.id },
-          orderBy: [{ startDateTime: { sort: 'desc', nulls: 'last' } }, { serviceDate: 'desc' }],
-          select: { id: true },
-        })
-        if (latestRecord?.id === id) {
-          await db.vehicle.update({
-            where: { id: existing.vehicle.id },
-            data: { mileage: recordData.mileage },
+      // 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, {
+            organizationId,
+            vehicleId: record.vehicleId,
+            jobId: id,
+            jobDate: jobReadingDate(record),
+            reading: record.mileage,
+            previousReading: sameVehicle ? existing.mileage : undefined,
           })
           })
         }
         }
       }
       }

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

@@ -0,0 +1,48 @@
+'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>
+  )
+}

+ 19 - 0
src/features/vehicles/Components/VehicleForm.tsx

@@ -51,6 +51,8 @@ import { PlateChip } from '@/components/plate-chip'
 import { StatusLamp, type LampTone } from '@/components/status-lamp'
 import { StatusLamp, type LampTone } from '@/components/status-lamp'
 import { cn } from '@/lib/utils'
 import { cn } from '@/lib/utils'
 import { PhotoHandoffButton } from './service-page/PhotoHandoffButton'
 import { PhotoHandoffButton } from './service-page/PhotoHandoffButton'
+import { LowerReadingNotice } from './LowerReadingNotice'
+import { isLowerReading } from '../Lib/vehicleReading'
 
 
 /**
 /**
  * How alike two names must read before the scanned keeper is offered as an
  * How alike two names must read before the scanned keeper is offered as an
@@ -893,6 +895,12 @@ export function VehicleForm({
                           </button>
                           </button>
                         )}
                         )}
                       </dd>
                       </dd>
+                      <LowerReadingNotice
+                        entered={mileageDraft}
+                        last={vehicle?.mileage}
+                        unit={unit}
+                        className="max-w-56"
+                      />
                     </div>
                     </div>
                     {!isMarine && (
                     {!isMarine && (
                       <div className="space-y-1">
                       <div className="space-y-1">
@@ -1237,6 +1245,11 @@ export function VehicleForm({
                           placeholder="0"
                           placeholder="0"
                           value={mileageDraft}
                           value={mileageDraft}
                           onChange={(e) => setMileageDraft(e.target.value)}
                           onChange={(e) => setMileageDraft(e.target.value)}
+                          aria-describedby={
+                            isLowerReading(mileageDraft, vehicle?.mileage)
+                              ? 'mileage-notice'
+                              : undefined
+                          }
                           // No spinner: it would sit on top of the unit, and
                           // No spinner: it would sit on top of the unit, and
                           // nobody steps an odometer reading one at a time.
                           // nobody steps an odometer reading one at a time.
                           className={cn(
                           className={cn(
@@ -1253,6 +1266,12 @@ export function VehicleForm({
                           </span>
                           </span>
                         )}
                         )}
                       </div>
                       </div>
+                      <LowerReadingNotice
+                        id="mileage-notice"
+                        entered={mileageDraft}
+                        last={vehicle?.mileage}
+                        unit={unit}
+                      />
                     </div>
                     </div>
                   </div>
                   </div>
                 </FormCard>
                 </FormCard>

+ 2 - 0
src/features/vehicles/Components/service-edit/form-types.ts

@@ -31,6 +31,8 @@ export interface InitialData {
   type: string
   type: string
   status: string
   status: string
   mileage: number | null
   mileage: number | null
+  /** The last known reading before this job's, for the notice beside the field. */
+  lastReading?: number | null
   serviceDate: string
   serviceDate: string
   startDateTime?: string | null
   startDateTime?: string | null
   endDateTime?: string | null
   endDateTime?: string | null

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

@@ -38,6 +38,7 @@ import { getServiceFindings } from '@/features/vehicles/Actions/findingActions'
 import { faultCodesConnected, seenBefore } from '@/features/fault-codes/Lib/service.server'
 import { faultCodesConnected, seenBefore } from '@/features/fault-codes/Lib/service.server'
 import { oemSourceFor } from '@/features/fault-codes/Lib/codes'
 import { oemSourceFor } from '@/features/fault-codes/Lib/codes'
 import { db } from '@/lib/db'
 import { db } from '@/lib/db'
+import { jobReadingDate, lastReadingBeforeJob } from '@/features/vehicles/Lib/vehicleReading'
 import {
 import {
   loadVehicleConditionMarks,
   loadVehicleConditionMarks,
   markTypeCatalogue,
   markTypeCatalogue,
@@ -249,6 +250,21 @@ export async function ServiceRecordPage({
   // The date inputs show the workshop's calendar day, not the server's.
   // The date inputs show the workshop's calendar day, not the server's.
   const timeZone = organizationId ? await workshopTimeZone(organizationId) : 'UTC'
   const timeZone = organizationId ? await workshopTimeZone(organizationId) : 'UTC'
 
 
+  // What the reading field warns against going below (vehicleReading.ts).
+  const lastReading =
+    record.vehicle && organizationId && isRenderable(record.serviceDate)
+      ? await lastReadingBeforeJob(db, {
+          organizationId,
+          vehicleId: record.vehicle.id,
+          jobId: record.id,
+          jobDate: jobReadingDate({
+            startDateTime: isRenderable(record.startDateTime) ? record.startDateTime : null,
+            serviceDate: record.serviceDate,
+          }),
+          vehicleReading: record.vehicle.mileage,
+        })
+      : null
+
   const initialData = {
   const initialData = {
     id: record.id,
     id: record.id,
     title: record.title,
     title: record.title,
@@ -256,6 +272,7 @@ export async function ServiceRecordPage({
     type: record.type,
     type: record.type,
     status: record.status,
     status: record.status,
     mileage: record.mileage,
     mileage: record.mileage,
+    lastReading,
     serviceDate: zonedDayKey(
     serviceDate: zonedDayKey(
       isRenderable(record.serviceDate) ? new Date(record.serviceDate) : new Date(),
       isRenderable(record.serviceDate) ? new Date(record.serviceDate) : new Date(),
       timeZone
       timeZone

+ 40 - 12
src/features/vehicles/Components/service-page/modern/JobFactsCard.tsx

@@ -19,6 +19,8 @@ import type { InitialData } from '../../service-edit/form-types'
 import { formatTypeKey } from '../../../Lib/typeKey'
 import { formatTypeKey } from '../../../Lib/typeKey'
 import { useTypeKeyEnabled } from '@/components/type-key-context'
 import { useTypeKeyEnabled } from '@/components/type-key-context'
 import { vehicleName as vehicleNameOf } from '@/lib/vehicle-name'
 import { vehicleName as vehicleNameOf } from '@/lib/vehicle-name'
+import { LowerReadingNotice } from '../../LowerReadingNotice'
+import { isLowerReading } from '../../../Lib/vehicleReading'
 
 
 interface JobFactsCardProps {
 interface JobFactsCardProps {
   record: ServiceDetail
   record: ServiceDetail
@@ -34,6 +36,8 @@ interface JobFactsCardProps {
   selectedVehicleId: string | null
   selectedVehicleId: string | null
   setSelectedVehicleId: (id: string) => void
   setSelectedVehicleId: (id: string) => void
   techName: string
   techName: string
+  /** "km" or "mi", for the notice under the reading. */
+  distanceUnit?: string
   initialVehicle?: {
   initialVehicle?: {
     id: string
     id: string
     make: string
     make: string
@@ -126,6 +130,7 @@ export function JobFactsCard({
   setSelectedVehicleId,
   setSelectedVehicleId,
   techName,
   techName,
   initialVehicle,
   initialVehicle,
+  distanceUnit,
 }: JobFactsCardProps) {
 }: JobFactsCardProps) {
   const t = useTranslations('service')
   const t = useTranslations('service')
   const tv = useTranslations('vehicles.form')
   const tv = useTranslations('vehicles.form')
@@ -137,6 +142,8 @@ export function JobFactsCard({
   const formatCurrency = useFormatCurrency()
   const formatCurrency = useFormatCurrency()
   const { timezone } = useDateSettings()
   const { timezone } = useDateSettings()
   const [changingVehicle, setChangingVehicle] = useState(false)
   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)
 
 
   // Closed on the server and on the first paint, then as this browser left it:
   // Closed on the server and on the first paint, then as this browser left it:
   // localStorage is not readable before hydration.
   // localStorage is not readable before hydration.
@@ -163,6 +170,10 @@ export function JobFactsCard({
   // The picker can point the job at another vehicle before the save; the facts
   // 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.
   // on this card describe the saved one, so say which is which while they differ.
   const vehicleChanged = Boolean(vehicle && selectedVehicleId && selectedVehicleId !== vehicle.id)
   const vehicleChanged = Boolean(vehicle && selectedVehicleId && selectedVehicleId !== vehicle.id)
+  const showReadingNotice =
+    readingTyped !== null &&
+    !vehicleChanged &&
+    isLowerReading(readingTyped, initialData.lastReading)
 
 
   return (
   return (
     <section
     <section
@@ -322,18 +333,35 @@ export function JobFactsCard({
             )}
             )}
 
 
             {selectedVehicleId && (
             {selectedVehicleId && (
-              <div className="flex items-center gap-2">
-                <Label htmlFor="mileage" className={factLabel}>
-                  {serviceType === 'marine' ? t('basicInfo.mileageMarine') : t('basicInfo.mileage')}
-                </Label>
-                <Input
-                  id="mileage"
-                  name="mileage"
-                  type="number"
-                  placeholder="50000"
-                  className="h-8 w-32"
-                  defaultValue={initialData.mileage ?? ''}
-                />
+              <div className="space-y-1">
+                <div className="flex items-center gap-2">
+                  <Label htmlFor="mileage" className={factLabel}>
+                    {serviceType === 'marine'
+                      ? t('basicInfo.mileageMarine')
+                      : t('basicInfo.mileage')}
+                  </Label>
+                  <Input
+                    id="mileage"
+                    name="mileage"
+                    type="number"
+                    placeholder="50000"
+                    className="h-8 w-32"
+                    defaultValue={initialData.mileage ?? ''}
+                    onChange={(e) => setReadingTyped(e.target.value)}
+                    aria-describedby={showReadingNotice ? 'mileage-notice' : undefined}
+                  />
+                </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. */}
+                {showReadingNotice && (
+                  <LowerReadingNotice
+                    id="mileage-notice"
+                    entered={readingTyped ?? ''}
+                    last={initialData.lastReading}
+                    unit={distanceUnit}
+                  />
+                )}
               </div>
               </div>
             )}
             )}
           </fieldset>
           </fieldset>

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

@@ -323,6 +323,7 @@ export function ModernDetails(props: ModernDetailsProps) {
                   setSelectedVehicleId={formState.dirtySetSelectedVehicleId}
                   setSelectedVehicleId={formState.dirtySetSelectedVehicleId}
                   techName={formState.techName}
                   techName={formState.techName}
                   initialVehicle={props.initialVehicle}
                   initialVehicle={props.initialVehicle}
+                  distanceUnit={unitSystem === 'metric' ? 'km' : 'mi'}
                 />
                 />
 
 
                 <Lockable locked={locked}>
                 <Lockable locked={locked}>

+ 158 - 0
src/features/vehicles/Lib/vehicleReading.ts

@@ -0,0 +1,158 @@
+import type { Prisma } from '@/generated/prisma/client'
+
+/**
+ * The vehicle's current reading (mileage, or engine hours on a boat) and the
+ * readings its jobs carry.
+ *
+ * THE RULE, for every writer of a job's reading (the work order page, a new
+ * job, the technician app's check-in, a job raised from an inspection, an
+ * imported history row):
+ *
+ *   A job's reading becomes the vehicle's current reading when
+ *     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.
+ *
+ * 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.
+ *
+ * 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).
+ */
+
+/**
+ * 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.
+ */
+export interface ReadingClient {
+  serviceRecord: {
+    findFirst(args: {
+      where: Prisma.ServiceRecordWhereInput
+      select: { id: true }
+    }): PromiseLike<{ id: string } | null>
+    aggregate(args: {
+      where: Prisma.ServiceRecordWhereInput
+      _max: { mileage: true }
+    }): PromiseLike<{ _max: { mileage: number | null } }>
+  }
+  vehicle: {
+    updateMany(args: {
+      where: Prisma.VehicleWhereInput
+      data: { mileage: number }
+    }): PromiseLike<{ count: number }>
+  }
+}
+
+export interface JobReading {
+  organizationId: string
+  vehicleId: string
+  /** The job the reading was written to. */
+  jobId: string
+  /** When the job starts, else its service date: see `jobReadingDate`. */
+  jobDate: Date
+  /** The reading as saved on the job. */
+  reading: number | null | undefined
+  /**
+   * What the job said before this save, when it had a say on this vehicle.
+   * Left out for a new job, or one that just moved to this vehicle.
+   */
+  previousReading?: number | null
+}
+
+/** The day a job's reading was taken, as far as the job knows. */
+export function jobReadingDate(job: { startDateTime?: Date | null; serviceDate: Date }): Date {
+  return job.startDateTime ?? job.serviceDate
+}
+
+/** Other jobs on the vehicle, dated after this one, that carry a reading. */
+function laterJobsWithReading(
+  job: Pick<JobReading, 'organizationId' | 'vehicleId' | 'jobId' | 'jobDate'>
+): Prisma.ServiceRecordWhereInput {
+  return {
+    organizationId: job.organizationId,
+    vehicleId: job.vehicleId,
+    id: { not: job.jobId },
+    // Zero counts: after a new odometer a later job may well read 0.
+    mileage: { not: null },
+    OR: [
+      { startDateTime: { gt: job.jobDate } },
+      { startDateTime: null, serviceDate: { gt: job.jobDate } },
+    ],
+  }
+}
+
+/**
+ * Applies the rule above after a job's reading was written. Answers whether
+ * the vehicle moved. Takes the transaction when the writer has one.
+ */
+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 later = await client.serviceRecord.findFirst({
+    where: laterJobsWithReading(job),
+    select: { id: true },
+  })
+  if (later) return false
+
+  // The comparison is the database's, so two saves at once cannot leave the
+  // lower of two readings behind.
+  const moved = await client.vehicle.updateMany({
+    where: { id: job.vehicleId, organizationId: job.organizationId, mileage: { lt: reading } },
+    data: { mileage: reading },
+  })
+  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.
+ */
+export async function lastReadingBeforeJob(
+  client: ReadingClient,
+  job: Pick<JobReading, 'organizationId' | 'vehicleId' | 'jobId' | 'jobDate'> & {
+    /** The vehicle's current reading, which the caller has already loaded. */
+    vehicleReading: number
+  }
+): Promise<number | null> {
+  const [later, earlier] = await Promise.all([
+    client.serviceRecord.findFirst({ where: laterJobsWithReading(job), select: { id: true } }),
+    client.serviceRecord.aggregate({
+      where: {
+        organizationId: job.organizationId,
+        vehicleId: job.vehicleId,
+        id: { not: job.jobId },
+        mileage: { gt: 0 },
+        OR: [
+          { startDateTime: { lt: job.jobDate } },
+          { startDateTime: null, serviceDate: { lt: job.jobDate } },
+        ],
+      },
+      _max: { mileage: true },
+    }),
+  ])
+  const last = Math.max(later ? 0 : job.vehicleReading, earlier._max.mileage ?? 0)
+  return last > 0 ? last : 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
+ * known yet".
+ */
+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
+}