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

Save only the fields edited in this tab (#688)

* Save only the fields edited in this tab

* Keep edits made while a save runs, and a refused rename, through a refresh

* Tell a job's own screens about a conditional update that names it

* Revert "Tell a job's own screens about a conditional update that names it"

This reverts commit d818ece9e7868d8f32cf87eaf6f7ba54420afa26.
Bernt Christian Egeland 2 дней назад
Родитель
Сommit
e8faf18943
43 измененных файлов с 2751 добавлено и 641 удалено
  1. 93 0
      e2e/specs/work-orders/two-tabs.spec.ts
  2. 14 0
      e2e/support/db.ts
  3. 24 0
      messages/bg/service.json
  4. 24 0
      messages/de/service.json
  5. 24 0
      messages/en/service.json
  6. 24 0
      messages/es/service.json
  7. 24 0
      messages/fr/service.json
  8. 24 0
      messages/it/service.json
  9. 24 0
      messages/lt/service.json
  10. 24 0
      messages/nb/service.json
  11. 24 0
      messages/nl/service.json
  12. 24 0
      messages/pl/service.json
  13. 24 0
      messages/pt-BR/service.json
  14. 24 0
      messages/pt-PT/service.json
  15. 24 0
      messages/ru/service.json
  16. 24 0
      messages/tr/service.json
  17. 8 6
      src/__tests__/features/custom-fields/missing-required-page-save.test.tsx
  18. 1 0
      src/__tests__/features/equipment/equipment-gates.test.ts
  19. 5 2
      src/__tests__/features/meters/meters-gates.test.ts
  20. 2 1
      src/__tests__/features/service-concerns.test.ts
  21. 4 0
      src/__tests__/features/vehicles/add-observations-to-work-order.test.tsx
  22. 11 6
      src/__tests__/features/vehicles/edit-then-preset.test.tsx
  23. 4 0
      src/__tests__/features/vehicles/expired-dates-workshop-today.test.tsx
  24. 5 1
      src/__tests__/features/vehicles/live-parts.test.tsx
  25. 291 0
      src/__tests__/features/vehicles/save-service-record-changes.test.ts
  26. 352 0
      src/__tests__/features/vehicles/two-tabs-save.test.tsx
  27. 4 0
      src/__tests__/features/vehicles/work-order-header-pills.test.tsx
  28. 47 7
      src/__tests__/features/vehicles/work-order-reading-question.test.tsx
  29. 44 5
      src/__tests__/features/vehicles/work-order-required-meters-save.test.tsx
  30. 250 0
      src/__tests__/features/vehicles/work-order-title-refresh.test.tsx
  31. 50 0
      src/features/vehicles/Actions/saveServiceRecordChanges.ts
  32. 7 478
      src/features/vehicles/Actions/serviceActions.ts
  33. 15 4
      src/features/vehicles/Components/service-edit/InvoiceDetailsSection.tsx
  34. 19 1
      src/features/vehicles/Components/service-edit/NotesSection.tsx
  35. 65 0
      src/features/vehicles/Components/service-page/ChangedElsewhereBanner.tsx
  36. 17 5
      src/features/vehicles/Components/service-page/ServicePageClient.tsx
  37. 2 0
      src/features/vehicles/Components/service-page/modern/ModernDetails.tsx
  38. 68 97
      src/features/vehicles/Components/service-page/useServiceActions.ts
  39. 271 27
      src/features/vehicles/Components/service-page/useServiceFormState.ts
  40. 2 1
      src/features/vehicles/Lib/lineSums.ts
  41. 213 0
      src/features/vehicles/Lib/workOrderFields.ts
  42. 530 0
      src/features/vehicles/Lib/writeServiceRecordUpdate.server.ts
  43. 21 0
      src/features/vehicles/Schema/serviceSchema.ts

+ 93 - 0
e2e/specs/work-orders/two-tabs.spec.ts

@@ -0,0 +1,93 @@
+import { expect, type Locator, type Page, test } from '@playwright/test'
+import { highestReadingForJob, jobNotesAndReading } from '../../support/db'
+import { fillSettled, settle } from '../../support/hydration'
+import { jobIdOf, newWorkOrder, saveWorkOrder, seededVehicleUrl } from '../../support/work-order'
+
+/**
+ * The same work order open in two tabs of one browser.
+ *
+ * The page used to save its whole form, so the tab opened earlier wrote back
+ * every field as it had first read it: a note saved in the other tab was gone
+ * the moment this one saved its mileage. Each save now sends only the fields
+ * its tab changed. When both tabs change the same field the later save wins,
+ * and the tab that lost is told so on its own screen.
+ */
+
+// Two work order pages at once, which is more than the default budget on a cold server.
+test.describe.configure({ mode: 'serial', timeout: 120_000 })
+
+const stamp = Date.now()
+
+async function openJob(page: Page, url: string): Promise<void> {
+  await page.goto(url)
+  await settle(page)
+  await expect(page.getByTestId('service-layout-modern')).toBeVisible()
+}
+
+/** Types at the end of a notes box, as modern-page.spec.ts does. */
+async function typeInNotes(page: Page, card: Locator, text: string): Promise<void> {
+  const area = card.getByTestId('rich-text-area')
+  const editor = card.locator('.ProseMirror')
+  await expect(async () => {
+    const box = await area.boundingBox()
+    if (!box) throw new Error('notes box not on screen')
+    await area.click({ position: { x: box.width / 2, y: box.height - 12 } })
+    await expect(editor).toBeFocused({ timeout: 2_000 })
+  }).toPass({ timeout: 30_000 })
+  await page.keyboard.press('End')
+  await page.keyboard.type(text)
+  await expect(editor).toContainText(text)
+}
+
+test('a note saved in one tab survives a mileage saved in the other', async ({ page }) => {
+  const url = await newWorkOrder(page, await seededVehicleUrl(page), `E2E two tabs ${stamp}`)
+  const jobId = jobIdOf(url)
+  const tabA = page
+  const tabB = await page.context().newPage()
+  await openJob(tabB, url)
+
+  const note = `Customer hears a rattle ${stamp}`
+  await typeInNotes(tabB, tabB.getByTestId('notes-internal'), note)
+  await saveWorkOrder(tabB)
+  await expect.poll(async () => (await jobNotesAndReading(jobId)).diagnosticNotes).toContain(note)
+
+  // Tab A was opened before the note was written.
+  const reading = (await highestReadingForJob(jobId)) + 25
+  await fillSettled(tabA.locator('input[name="mileage"]'), String(reading))
+  await saveWorkOrder(tabA)
+
+  await expect.poll(async () => (await jobNotesAndReading(jobId)).mileage).toBe(reading)
+  expect((await jobNotesAndReading(jobId)).diagnosticNotes).toContain(note)
+
+  await tabA.reload()
+  await settle(tabA)
+  await expect(tabA.getByTestId('notes-internal').locator('.ProseMirror')).toContainText(note)
+  await expect(tabA.locator('input[name="mileage"]')).toHaveValue(String(reading))
+  await tabB.close()
+})
+
+test('the later save of the same note wins, and the other tab is told', async ({ page }) => {
+  const url = await newWorkOrder(page, await seededVehicleUrl(page), `E2E two tabs same ${stamp}`)
+  const jobId = jobIdOf(url)
+  const tabA = page
+  const tabB = await page.context().newPage()
+  await openJob(tabB, url)
+
+  const first = `Tab B thinks it is the caliper ${stamp}`
+  await typeInNotes(tabB, tabB.getByTestId('notes-internal'), first)
+  await saveWorkOrder(tabB)
+  await expect.poll(async () => (await jobNotesAndReading(jobId)).diagnosticNotes).toContain(first)
+
+  const later = `Tab A found a seized slide pin ${stamp}`
+  await typeInNotes(tabA, tabA.getByTestId('notes-internal'), later)
+  await saveWorkOrder(tabA)
+  await expect.poll(async () => (await jobNotesAndReading(jobId)).diagnosticNotes).toContain(later)
+
+  // Tab B hears of the save, shows the newer note, and says its own was replaced.
+  const banner = tabB.getByTestId('changed-elsewhere-banner')
+  await expect(banner).toContainText('Changed elsewhere: Internal notes.', { timeout: 30_000 })
+  await expect(tabB.getByTestId('notes-internal').locator('.ProseMirror')).toContainText(later)
+  await banner.getByRole('button', { name: 'OK' }).click()
+  await expect(banner).toHaveCount(0)
+  await tabB.close()
+})

+ 14 - 0
e2e/support/db.ts

@@ -2390,3 +2390,17 @@ export async function removeSharedDocuments(planted: PlantedSharedDocuments): Pr
     await db.query('delete from vehicles where id = $1', [planted.vehicleId])
   })
 }
+
+/** What a job has stored of the fields two tabs on it save. */
+export async function jobNotesAndReading(
+  serviceRecordId: string
+): Promise<{ diagnosticNotes: string | null; mileage: number | null }> {
+  return withDb(async (db) => {
+    const result = await db.query<{ diagnosticNotes: string | null; mileage: number | null }>(
+      `select "diagnosticNotes", mileage from service_records where id = $1`,
+      [serviceRecordId]
+    )
+    if (!result.rows[0]) throw new Error(`no job ${serviceRecordId}`)
+    return result.rows[0]
+  })
+}

+ 24 - 0
messages/bg/service.json

@@ -275,6 +275,30 @@
     "body": "Не се показва в списъка, докато редактирате. При следващото запазване ще бъде включено независимо от избора ви.",
     "show": "Покажи го"
   },
+  "changedElsewhere": {
+    "keptTitle": "Променено другаде, докато редактирахте: {fields}.",
+    "keptBody": "Тази страница ще запише вашата версия върху нея.",
+    "replacedTitle": "Променено другаде: {fields}.",
+    "replacedBody": "По-късно записване замени вашата промяна. Страницата вече показва по-новата версия.",
+    "dismiss": "OK",
+    "fields": {
+      "title": "Заглавие",
+      "type": "Тип",
+      "status": "Статус",
+      "mileage": "Пробег",
+      "mileageMarine": "Моточасове",
+      "description": "Описание",
+      "diagnosticNotes": "Вътрешни бележки",
+      "invoiceNotes": "Бележки за клиента",
+      "invoiceNumber": "Номер на фактура",
+      "invoiceDate": "Дата на фактура",
+      "invoiceDueDate": "Падеж",
+      "taxRate": "Данъчна ставка",
+      "discount": "Отстъпка",
+      "warranty": "Гаранция",
+      "concerns": "Оплаквания"
+    }
+  },
   "totals": {
     "title": "Общи суми",
     "parts": "Резервни части",

+ 24 - 0
messages/de/service.json

@@ -275,6 +275,30 @@
     "body": "Sie bleibt beim Bearbeiten aus der Liste. Beim nächsten Speichern wird sie ohnehin übernommen.",
     "show": "Anzeigen"
   },
+  "changedElsewhere": {
+    "keptTitle": "Woanders geändert, während Sie bearbeitet haben: {fields}.",
+    "keptBody": "Diese Seite speichert Ihre Version darüber.",
+    "replacedTitle": "Woanders geändert: {fields}.",
+    "replacedBody": "Eine spätere Speicherung hat Ihre Änderung ersetzt. Diese Seite zeigt jetzt die neuere Version.",
+    "dismiss": "OK",
+    "fields": {
+      "title": "Titel",
+      "type": "Typ",
+      "status": "Status",
+      "mileage": "Kilometerstand",
+      "mileageMarine": "Motorstunden",
+      "description": "Beschreibung",
+      "diagnosticNotes": "Interne Notizen",
+      "invoiceNotes": "Kundennotizen",
+      "invoiceNumber": "Rechnungsnummer",
+      "invoiceDate": "Rechnungsdatum",
+      "invoiceDueDate": "Fälligkeitsdatum",
+      "taxRate": "Steuersatz",
+      "discount": "Rabatt",
+      "warranty": "Garantie",
+      "concerns": "Anliegen"
+    }
+  },
   "totals": {
     "title": "Summen",
     "parts": "Teile",

+ 24 - 0
messages/en/service.json

@@ -275,6 +275,30 @@
     "body": "It stays out of the list while you are editing. Your next save includes it either way.",
     "show": "Show it"
   },
+  "changedElsewhere": {
+    "keptTitle": "Changed elsewhere while you were editing: {fields}.",
+    "keptBody": "This page saves your version over it.",
+    "replacedTitle": "Changed elsewhere: {fields}.",
+    "replacedBody": "A later save replaced your change. This page now shows the newer version.",
+    "dismiss": "OK",
+    "fields": {
+      "title": "Title",
+      "type": "Type",
+      "status": "Status",
+      "mileage": "Mileage",
+      "mileageMarine": "Engine hours",
+      "description": "Description",
+      "diagnosticNotes": "Internal notes",
+      "invoiceNotes": "Customer notes",
+      "invoiceNumber": "Invoice number",
+      "invoiceDate": "Invoice date",
+      "invoiceDueDate": "Due date",
+      "taxRate": "Tax rate",
+      "discount": "Discount",
+      "warranty": "Warranty",
+      "concerns": "Concerns"
+    }
+  },
   "totals": {
     "title": "Totals",
     "parts": "Parts",

+ 24 - 0
messages/es/service.json

@@ -275,6 +275,30 @@
     "body": "Se mantiene fuera de la lista mientras editas. Se guardará de todos modos al guardar.",
     "show": "Mostrar"
   },
+  "changedElsewhere": {
+    "keptTitle": "Cambiado en otro lugar mientras editabas: {fields}.",
+    "keptBody": "Esta página guarda tu versión encima.",
+    "replacedTitle": "Cambiado en otro lugar: {fields}.",
+    "replacedBody": "Un guardado posterior reemplazó tu cambio. Esta página muestra ahora la versión más reciente.",
+    "dismiss": "Aceptar",
+    "fields": {
+      "title": "Título",
+      "type": "Tipo",
+      "status": "Estado",
+      "mileage": "Kilometraje",
+      "mileageMarine": "Horas de motor",
+      "description": "Descripción",
+      "diagnosticNotes": "Notas internas",
+      "invoiceNotes": "Notas para el cliente",
+      "invoiceNumber": "Número de factura",
+      "invoiceDate": "Fecha de factura",
+      "invoiceDueDate": "Fecha de vencimiento",
+      "taxRate": "Tipo de impuesto",
+      "discount": "Descuento",
+      "warranty": "Garantía",
+      "concerns": "Problemas"
+    }
+  },
   "totals": {
     "title": "Totales",
     "parts": "Piezas",

+ 24 - 0
messages/fr/service.json

@@ -275,6 +275,30 @@
     "body": "Elle reste hors de la liste pendant votre saisie. Votre prochain enregistrement l’inclura de toute façon.",
     "show": "Afficher"
   },
+  "changedElsewhere": {
+    "keptTitle": "Modifié ailleurs pendant votre saisie : {fields}.",
+    "keptBody": "Cette page enregistre votre version par-dessus.",
+    "replacedTitle": "Modifié ailleurs : {fields}.",
+    "replacedBody": "Un enregistrement plus récent a remplacé votre modification. Cette page affiche maintenant la version la plus récente.",
+    "dismiss": "OK",
+    "fields": {
+      "title": "Titre",
+      "type": "Type",
+      "status": "Statut",
+      "mileage": "Kilométrage",
+      "mileageMarine": "Heures moteur",
+      "description": "Description",
+      "diagnosticNotes": "Notes internes",
+      "invoiceNotes": "Notes client",
+      "invoiceNumber": "Numéro de facture",
+      "invoiceDate": "Date de facture",
+      "invoiceDueDate": "Date d'échéance",
+      "taxRate": "Taux de taxe",
+      "discount": "Remise",
+      "warranty": "Garantie",
+      "concerns": "Problèmes"
+    }
+  },
   "totals": {
     "title": "Totaux",
     "parts": "Pièces",

+ 24 - 0
messages/it/service.json

@@ -275,6 +275,30 @@
     "body": "Resta fuori dall’elenco mentre modifichi. Verrà salvata comunque al prossimo salvataggio.",
     "show": "Mostra"
   },
+  "changedElsewhere": {
+    "keptTitle": "Modificato altrove mentre stavi modificando: {fields}.",
+    "keptBody": "Questa pagina salva la tua versione sopra.",
+    "replacedTitle": "Modificato altrove: {fields}.",
+    "replacedBody": "Un salvataggio successivo ha sostituito la tua modifica. Questa pagina mostra ora la versione più recente.",
+    "dismiss": "OK",
+    "fields": {
+      "title": "Titolo",
+      "type": "Tipo",
+      "status": "Stato",
+      "mileage": "Chilometraggio",
+      "mileageMarine": "Ore motore",
+      "description": "Descrizione",
+      "diagnosticNotes": "Note interne",
+      "invoiceNotes": "Note per il cliente",
+      "invoiceNumber": "Numero fattura",
+      "invoiceDate": "Data fattura",
+      "invoiceDueDate": "Data di scadenza",
+      "taxRate": "Aliquota fiscale",
+      "discount": "Sconto",
+      "warranty": "Garanzia",
+      "concerns": "Problemi"
+    }
+  },
   "totals": {
     "title": "Totali",
     "parts": "Pezzi",

+ 24 - 0
messages/lt/service.json

@@ -275,6 +275,30 @@
     "body": "Kol redaguojate, ji nerodoma sąraše. Kitą kartą išsaugant ji bus įtraukta.",
     "show": "Rodyti"
   },
+  "changedElsewhere": {
+    "keptTitle": "Pakeista kitur, kol redagavote: {fields}.",
+    "keptBody": "Šis puslapis išsaugos jūsų versiją vietoj jos.",
+    "replacedTitle": "Pakeista kitur: {fields}.",
+    "replacedBody": "Vėlesnis išsaugojimas pakeitė jūsų pakeitimą. Puslapyje dabar rodoma naujesnė versija.",
+    "dismiss": "Gerai",
+    "fields": {
+      "title": "Pavadinimas",
+      "type": "Tipas",
+      "status": "Būsena",
+      "mileage": "Rida",
+      "mileageMarine": "Variklio valandos",
+      "description": "Aprašymas",
+      "diagnosticNotes": "Vidinės pastabos",
+      "invoiceNotes": "Pastabos klientui",
+      "invoiceNumber": "Sąskaitos numeris",
+      "invoiceDate": "Sąskaitos data",
+      "invoiceDueDate": "Mokėjimo terminas",
+      "taxRate": "Mokesčio tarifas",
+      "discount": "Nuolaida",
+      "warranty": "Garantija",
+      "concerns": "Nusiskundimai"
+    }
+  },
   "totals": {
     "title": "Sumos",
     "parts": "Dalys",

+ 24 - 0
messages/nb/service.json

@@ -275,6 +275,30 @@
     "body": "Den holdes utenfor listen mens du redigerer. Den blir lagret uansett neste gang du lagrer.",
     "show": "Vis den"
   },
+  "changedElsewhere": {
+    "keptTitle": "Endret et annet sted mens du redigerte: {fields}.",
+    "keptBody": "Denne siden lagrer din versjon over den.",
+    "replacedTitle": "Endret et annet sted: {fields}.",
+    "replacedBody": "En senere lagring erstattet endringen din. Siden viser nå den nyeste versjonen.",
+    "dismiss": "OK",
+    "fields": {
+      "title": "Tittel",
+      "type": "Type",
+      "status": "Status",
+      "mileage": "Kilometerstand",
+      "mileageMarine": "Motortimer",
+      "description": "Beskrivelse",
+      "diagnosticNotes": "Interne notater",
+      "invoiceNotes": "Kundenotater",
+      "invoiceNumber": "Fakturanummer",
+      "invoiceDate": "Fakturadato",
+      "invoiceDueDate": "Forfallsdato",
+      "taxRate": "Mva-sats",
+      "discount": "Rabatt",
+      "warranty": "Garanti",
+      "concerns": "Problemer"
+    }
+  },
   "totals": {
     "title": "Totalt",
     "parts": "Deler",

+ 24 - 0
messages/nl/service.json

@@ -275,6 +275,30 @@
     "body": "Die blijft buiten de lijst terwijl je bewerkt. Bij je volgende keer opslaan gaat die sowieso mee.",
     "show": "Tonen"
   },
+  "changedElsewhere": {
+    "keptTitle": "Elders gewijzigd terwijl je aan het bewerken was: {fields}.",
+    "keptBody": "Deze pagina slaat jouw versie eroverheen op.",
+    "replacedTitle": "Elders gewijzigd: {fields}.",
+    "replacedBody": "Een latere opslag heeft je wijziging vervangen. Deze pagina toont nu de nieuwste versie.",
+    "dismiss": "OK",
+    "fields": {
+      "title": "Titel",
+      "type": "Type",
+      "status": "Status",
+      "mileage": "Kilometerstand",
+      "mileageMarine": "Motoruren",
+      "description": "Omschrijving",
+      "diagnosticNotes": "Interne notities",
+      "invoiceNotes": "Klantnotities",
+      "invoiceNumber": "Factuurnummer",
+      "invoiceDate": "Factuurdatum",
+      "invoiceDueDate": "Vervaldatum",
+      "taxRate": "Btw-tarief",
+      "discount": "Korting",
+      "warranty": "Garantie",
+      "concerns": "Klachten"
+    }
+  },
   "totals": {
     "title": "Totalen",
     "parts": "Onderdelen",

+ 24 - 0
messages/pl/service.json

@@ -275,6 +275,30 @@
     "body": "Pozostaje poza listą podczas edycji. Następny zapis i tak ją uwzględni.",
     "show": "Pokaż"
   },
+  "changedElsewhere": {
+    "keptTitle": "Zmieniono gdzie indziej podczas Twojej edycji: {fields}.",
+    "keptBody": "Ta strona zapisze Twoją wersję w jej miejsce.",
+    "replacedTitle": "Zmieniono gdzie indziej: {fields}.",
+    "replacedBody": "Późniejszy zapis zastąpił Twoją zmianę. Ta strona pokazuje teraz nowszą wersję.",
+    "dismiss": "OK",
+    "fields": {
+      "title": "Tytuł",
+      "type": "Typ",
+      "status": "Status",
+      "mileage": "Przebieg",
+      "mileageMarine": "Motogodziny",
+      "description": "Opis",
+      "diagnosticNotes": "Notatki wewnętrzne",
+      "invoiceNotes": "Notatki dla klienta",
+      "invoiceNumber": "Numer faktury",
+      "invoiceDate": "Data faktury",
+      "invoiceDueDate": "Termin płatności",
+      "taxRate": "Stawka podatku",
+      "discount": "Rabat",
+      "warranty": "Gwarancja",
+      "concerns": "Usterki"
+    }
+  },
   "totals": {
     "title": "Razem",
     "parts": "Części",

+ 24 - 0
messages/pt-BR/service.json

@@ -275,6 +275,30 @@
     "body": "Ela fica fora da lista enquanto você edita. O próximo salvamento a inclui de qualquer forma.",
     "show": "Mostrar"
   },
+  "changedElsewhere": {
+    "keptTitle": "Alterado em outro lugar enquanto você editava: {fields}.",
+    "keptBody": "Esta página salva sua versão por cima.",
+    "replacedTitle": "Alterado em outro lugar: {fields}.",
+    "replacedBody": "Um salvamento posterior substituiu sua alteração. Esta página agora mostra a versão mais recente.",
+    "dismiss": "OK",
+    "fields": {
+      "title": "Título",
+      "type": "Tipo",
+      "status": "Status",
+      "mileage": "Quilometragem",
+      "mileageMarine": "Horas do motor",
+      "description": "Descrição",
+      "diagnosticNotes": "Notas internas",
+      "invoiceNotes": "Notas para o cliente",
+      "invoiceNumber": "Número da fatura",
+      "invoiceDate": "Data da fatura",
+      "invoiceDueDate": "Data de vencimento",
+      "taxRate": "Alíquota de imposto",
+      "discount": "Desconto",
+      "warranty": "Garantia",
+      "concerns": "Problemas"
+    }
+  },
   "totals": {
     "title": "Totais",
     "parts": "Peças",

+ 24 - 0
messages/pt-PT/service.json

@@ -275,6 +275,30 @@
     "body": "Fica fora da lista enquanto edita. A próxima gravação inclui-a de qualquer forma.",
     "show": "Mostrar"
   },
+  "changedElsewhere": {
+    "keptTitle": "Alterado noutro local enquanto editava: {fields}.",
+    "keptBody": "Esta página guarda a sua versão por cima.",
+    "replacedTitle": "Alterado noutro local: {fields}.",
+    "replacedBody": "Uma gravação posterior substituiu a sua alteração. Esta página mostra agora a versão mais recente.",
+    "dismiss": "OK",
+    "fields": {
+      "title": "Título",
+      "type": "Tipo",
+      "status": "Estado",
+      "mileage": "Quilometragem",
+      "mileageMarine": "Horas de motor",
+      "description": "Descrição",
+      "diagnosticNotes": "Notas internas",
+      "invoiceNotes": "Notas para o cliente",
+      "invoiceNumber": "Número da fatura",
+      "invoiceDate": "Data da fatura",
+      "invoiceDueDate": "Data de vencimento",
+      "taxRate": "Taxa de imposto",
+      "discount": "Desconto",
+      "warranty": "Garantia",
+      "concerns": "Problemas"
+    }
+  },
   "totals": {
     "title": "Totais",
     "parts": "Peças",

+ 24 - 0
messages/ru/service.json

@@ -275,6 +275,30 @@
     "body": "Пока вы редактируете, она не попадает в список. При следующем сохранении она сохранится в любом случае.",
     "show": "Показать"
   },
+  "changedElsewhere": {
+    "keptTitle": "Изменено в другом месте, пока вы редактировали: {fields}.",
+    "keptBody": "Эта страница сохранит вашу версию поверх.",
+    "replacedTitle": "Изменено в другом месте: {fields}.",
+    "replacedBody": "Более позднее сохранение заменило ваше изменение. Сейчас на странице новая версия.",
+    "dismiss": "ОК",
+    "fields": {
+      "title": "Название",
+      "type": "Тип",
+      "status": "Статус",
+      "mileage": "Пробег",
+      "mileageMarine": "Моточасы",
+      "description": "Описание",
+      "diagnosticNotes": "Внутренние заметки",
+      "invoiceNotes": "Заметки для клиента",
+      "invoiceNumber": "Номер счёта",
+      "invoiceDate": "Дата счёта",
+      "invoiceDueDate": "Срок оплаты",
+      "taxRate": "Ставка налога",
+      "discount": "Скидка",
+      "warranty": "Гарантия",
+      "concerns": "Жалобы"
+    }
+  },
   "totals": {
     "title": "Итоги",
     "parts": "Запчасти",

+ 24 - 0
messages/tr/service.json

@@ -275,6 +275,30 @@
     "body": "Siz düzenlerken listeye eklenmez. Bir sonraki kaydetmede yine de kaydedilir.",
     "show": "Göster"
   },
+  "changedElsewhere": {
+    "keptTitle": "Siz düzenlerken başka bir yerde değiştirildi: {fields}.",
+    "keptBody": "Bu sayfa sizin sürümünüzü onun üzerine kaydeder.",
+    "replacedTitle": "Başka bir yerde değiştirildi: {fields}.",
+    "replacedBody": "Daha sonraki bir kayıt değişikliğinizin yerini aldı. Bu sayfa artık daha yeni sürümü gösteriyor.",
+    "dismiss": "Tamam",
+    "fields": {
+      "title": "Başlık",
+      "type": "Tür",
+      "status": "Durum",
+      "mileage": "Kilometre",
+      "mileageMarine": "Motor saati",
+      "description": "Açıklama",
+      "diagnosticNotes": "Dahili notlar",
+      "invoiceNotes": "Müşteri notları",
+      "invoiceNumber": "Fatura numarası",
+      "invoiceDate": "Fatura tarihi",
+      "invoiceDueDate": "Vade tarihi",
+      "taxRate": "Vergi oranı",
+      "discount": "İndirim",
+      "warranty": "Garanti",
+      "concerns": "Şikayetler"
+    }
+  },
   "totals": {
     "title": "Toplamlar",
     "parts": "Parçalar",

+ 8 - 6
src/__tests__/features/custom-fields/missing-required-page-save.test.tsx

@@ -30,9 +30,11 @@ vi.mock('@/features/quotes/Actions/quoteActions', () => ({
 vi.mock('@/features/quotes/Actions/quoteResponseActions', () => ({
   acknowledgeQuoteResponse: vi.fn(),
 }))
-const updateServiceRecord = vi.fn()
+const saveServiceRecordChanges = vi.fn()
+vi.mock('@/features/vehicles/Actions/saveServiceRecordChanges', () => ({
+  saveServiceRecordChanges: (input: unknown) => saveServiceRecordChanges(input),
+}))
 vi.mock('@/features/vehicles/Actions/serviceActions', () => ({
-  updateServiceRecord: (input: unknown) => updateServiceRecord(input),
   deleteServiceRecord: vi.fn(),
   deleteServiceAttachment: vi.fn(),
   toggleManuallyPaid: vi.fn(),
@@ -66,7 +68,7 @@ afterEach(() => {
 beforeEach(() => {
   toastError.mockClear()
   updateQuote.mockReset().mockResolvedValue({ success: true })
-  updateServiceRecord.mockReset().mockResolvedValue({ success: true })
+  saveServiceRecordChanges.mockReset().mockResolvedValue({ success: true })
 })
 
 describe('the words', () => {
@@ -118,7 +120,7 @@ describe('a work order', () => {
     await save()
 
     expect(toastError).toHaveBeenCalledWith('Not saved. Fill in: Fleet contact')
-    expect(updateServiceRecord).not.toHaveBeenCalled()
+    expect(saveServiceRecordChanges).not.toHaveBeenCalled()
     // Saving is free again, and the page was not marked saved.
     expect(form.isSavingRef.current).toBe(false)
     expect(form.setHasUnsavedChanges).not.toHaveBeenCalled()
@@ -132,7 +134,7 @@ describe('a work order', () => {
     await save()
 
     expect(toastError).toHaveBeenCalledWith('Not saved. Fill in: Fleet contact, Cost centre')
-    expect(updateServiceRecord).not.toHaveBeenCalled()
+    expect(saveServiceRecordChanges).not.toHaveBeenCalled()
   })
 
   it('a value that does not fit is named too, in its own words', async () => {
@@ -166,7 +168,7 @@ describe('a work order', () => {
 
     expect(form.lastSaveErrorRef.current).toBe('Not saved. Fill in: Fleet contact, Cost centre')
     expect(toastError).not.toHaveBeenCalled()
-    expect(updateServiceRecord).not.toHaveBeenCalled()
+    expect(saveServiceRecordChanges).not.toHaveBeenCalled()
   })
 })
 

+ 1 - 0
src/__tests__/features/equipment/equipment-gates.test.ts

@@ -25,6 +25,7 @@ const ALLOWED = [
   'src/lib/backup/',
   // A job moved to another vehicle stops working on the old one's equipment.
   'src/features/vehicles/Actions/serviceActions.ts',
+  'src/features/vehicles/Lib/writeServiceRecordUpdate.server.ts',
   // And so does a quote.
   'src/features/quotes/Actions/quoteActions.ts',
   // Deletes that must find an item's report file before the rows go.

+ 5 - 2
src/__tests__/features/meters/meters-gates.test.ts

@@ -80,9 +80,12 @@ describe('the meter tables', () => {
   })
 
   it('are no longer a job’s when the job moves to another vehicle, in the same save', () => {
-    const source = readFileSync('src/features/vehicles/Actions/serviceActions.ts', 'utf8')
+    const source = readFileSync(
+      'src/features/vehicles/Lib/writeServiceRecordUpdate.server.ts',
+      'utf8'
+    )
     const move = source.slice(source.indexOf('if (!sameVehicle && vehicleBefore) {'))
-    expect(move.slice(0, move.indexOf('\n        }\n'))).toContain(
+    expect(move.slice(0, move.indexOf('\n    }\n'))).toContain(
       'unlinkJobMeterReadingsFromOtherVehicles(tx'
     )
   })

+ 2 - 1
src/__tests__/features/service-concerns.test.ts

@@ -46,7 +46,8 @@ describe('service concerns', () => {
   })
 
   it('reconciles concerns by id on update instead of replacing them', () => {
-    const actions = read('src/features/vehicles/Actions/serviceActions.ts')
+    // The work order's update, which both save actions write through.
+    const actions = read('src/features/vehicles/Lib/writeServiceRecordUpdate.server.ts')
     // The guard rail for the bug above: if this ever becomes a deleteMany over
     // the whole job again, findings lose their concern on the next autosave.
     expect(actions).not.toMatch(/serviceConcern\.deleteMany\(\{\s*where:\s*\{\s*serviceRecordId/)

+ 4 - 0
src/__tests__/features/vehicles/add-observations-to-work-order.test.tsx

@@ -154,6 +154,10 @@ vi.mock('@/features/vehicles/Components/service-page/useServiceFormState', () =>
       blockedLeave: null,
       laborAddedElsewhere: [],
       partsAddedElsewhere: [],
+      changedElsewhere: { kept: [], replaced: [] },
+      dismissChangedElsewhere: vi.fn(),
+      adoptedFields: {},
+      acknowledgeSavedFields: vi.fn(),
       imageAttachments: [],
       showPresetPicker: false,
       showInventoryPicker: false,

+ 11 - 6
src/__tests__/features/vehicles/edit-then-preset.test.tsx

@@ -27,9 +27,11 @@ vi.mock('@/components/confirm-dialog', async (importOriginal) => ({
   ...(await importOriginal<typeof import('@/components/confirm-dialog')>()),
   useConfirm: () => vi.fn(async () => true),
 }))
-const updateServiceRecord = vi.fn()
+const saveServiceRecordChanges = vi.fn()
+vi.mock('@/features/vehicles/Actions/saveServiceRecordChanges', () => ({
+  saveServiceRecordChanges: (input: unknown) => saveServiceRecordChanges(input),
+}))
 vi.mock('@/features/vehicles/Actions/serviceActions', () => ({
-  updateServiceRecord: (input: unknown) => updateServiceRecord(input),
   deleteServiceRecord: vi.fn(),
   deleteServiceAttachment: vi.fn(),
   toggleManuallyPaid: vi.fn(),
@@ -121,7 +123,7 @@ function openPage() {
 /** The save the server is running, held open until the test lets it finish. */
 function heldSave() {
   let finish: () => void = () => undefined
-  updateServiceRecord.mockImplementationOnce(
+  saveServiceRecordChanges.mockImplementationOnce(
     () =>
       new Promise((resolve) => {
         finish = () => resolve({ success: true })
@@ -131,7 +133,7 @@ function heldSave() {
 }
 
 const sent = (call = -1) =>
-  updateServiceRecord.mock.calls.at(call)?.[0] as {
+  saveServiceRecordChanges.mock.calls.at(call)?.[0] as {
     laborItems: ServiceLaborInput[]
     partItems: ServicePartInput[]
   }
@@ -143,7 +145,7 @@ const applyPreset = (page: ReturnType<typeof openPage>['page']) =>
   })
 
 beforeEach(() => {
-  updateServiceRecord.mockReset().mockResolvedValue({ success: true })
+  saveServiceRecordChanges.mockReset().mockResolvedValue({ success: true })
 })
 
 afterEach(() => {
@@ -315,6 +317,9 @@ describe('saved lines compared as the server returns them', () => {
     expect(page().partsAddedElsewhere).toEqual([])
     await act(() => submit())
     expect(sent().laborItems.map((l) => l.description)).toEqual(['ZZ Repro B', 'ZZ Oil service'])
-    expect(sent().partItems.map((p) => p.name)).toEqual(['ZZ Oil filter', 'ZZ Brake cleaner'])
+    // The parts went with the first save and have not changed since, so the
+    // second leaves them as they are stored; on screen each shows once.
+    expect(sent().partItems).toBeUndefined()
+    expect(page().partItems.map((p) => p.name)).toEqual(['ZZ Oil filter', 'ZZ Brake cleaner'])
   })
 })

+ 4 - 0
src/__tests__/features/vehicles/expired-dates-workshop-today.test.tsx

@@ -140,6 +140,10 @@ vi.mock('@/features/vehicles/Components/service-page/useServiceFormState', () =>
       blockedLeave: null,
       laborAddedElsewhere: [],
       partsAddedElsewhere: [],
+      changedElsewhere: { kept: [], replaced: [] },
+      dismissChangedElsewhere: vi.fn(),
+      adoptedFields: {},
+      acknowledgeSavedFields: vi.fn(),
       imageAttachments: [],
       showPresetPicker: false,
       showInventoryPicker: false,

+ 5 - 1
src/__tests__/features/vehicles/live-parts.test.tsx

@@ -149,7 +149,11 @@ describe('saving with lines still waiting', () => {
       pricingType: 'hourly',
     }
 
-    act(() => result.current.dirtySetPartItems([DESK]))
+    // The desk is editing its lines, labour among them.
+    act(() => {
+      result.current.dirtySetPartItems([DESK])
+      result.current.dirtySetLaborItems([])
+    })
     rerender(props([], [billed]))
     expect(result.current.laborAddedElsewhere).toEqual([billed])
     expect(result.current.subtotal).toBe(DESK.total + 125)

+ 291 - 0
src/__tests__/features/vehicles/save-service-record-changes.test.ts

@@ -0,0 +1,291 @@
+/**
+ * The two ways a work order's form reaches the server.
+ *
+ * saveServiceRecordChanges takes only what one tab changed, and none of the
+ * money: a tab holding an old copy of the lines would otherwise write totals
+ * that belong to them. The totals are worked out on the server from the lines,
+ * the discount and the tax as stored once the save is written.
+ *
+ * updateServiceRecord keeps taking the whole form, money and all: a tab opened
+ * before the deploy still calls it that way, and must still save.
+ *
+ * The job lives in memory here, and both actions write to it through the
+ * same transaction calls Prisma would see.
+ */
+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('server-only', () => ({}))
+vi.mock('@/lib/workshop-timezone', async (importOriginal) => ({
+  ...(await importOriginal<typeof import('@/lib/workshop-timezone')>()),
+  workshopTimeZone: async () => 'UTC',
+}))
+vi.mock('@/lib/features', () => ({
+  getFeatures: vi.fn().mockResolvedValue({}),
+  requireFeature: vi.fn().mockResolvedValue(undefined),
+  FeatureGatedError: class FeatureGatedError extends Error {},
+}))
+vi.mock('@/lib/notification-bus', () => ({ notificationBus: { emit: vi.fn() } }))
+vi.mock('@/lib/document-lock.server', () => ({
+  assertInvoiceEditable: vi.fn(),
+  getDocumentLockSettings: vi.fn().mockResolvedValue({}),
+}))
+vi.mock('@/features/inventory/Lib/reconcileStock', () => ({
+  reconcileInventoryForParts: vi.fn().mockResolvedValue(undefined),
+}))
+vi.mock('@/features/inventory/Lib/onInventoryChanged', () => ({
+  onInventoryChanged: vi.fn().mockResolvedValue(undefined),
+}))
+vi.mock('@/lib/files/manager', () => ({ releaseFiles: vi.fn().mockResolvedValue(undefined) }))
+vi.mock('@/lib/db', () => ({
+  db: {
+    $queryRaw: async () => [],
+    user: { findUnique: vi.fn() },
+    appSetting: { findMany: vi.fn() },
+    organization: { findUnique: vi.fn() },
+    serviceRecord: { findFirst: vi.fn() },
+    servicePart: { findMany: vi.fn() },
+    serviceLabor: { findMany: vi.fn() },
+    $transaction: vi.fn(),
+  },
+}))
+
+import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
+import { db } from '@/lib/db'
+import { assertInvoiceEditable } from '@/lib/document-lock.server'
+import { saveServiceRecordChanges } from '@/features/vehicles/Actions/saveServiceRecordChanges'
+import { updateServiceRecord } from '@/features/vehicles/Actions/serviceActions'
+
+type Line = { total: number; taxable: boolean; [key: string]: unknown }
+
+let job: Record<string, unknown>
+let parts: Line[]
+let labor: Line[]
+
+const sum = (rows: Line[], where: { taxable?: boolean }) => ({
+  _sum: {
+    total: rows
+      .filter((row) => where.taxable === undefined || row.taxable === where.taxable)
+      .reduce((total, row) => total + row.total, 0),
+  },
+})
+
+/** Writes what Prisma would be told to, leaving out what the update leaves alone. */
+function write(data: Record<string, unknown>) {
+  for (const [key, value] of Object.entries(data)) {
+    if (value !== undefined) job[key] = value
+  }
+  return { ...job }
+}
+
+const tx = {
+  $queryRaw: async () => [],
+  serviceRecord: {
+    update: vi.fn(async ({ data }: { data: Record<string, unknown> }) => write(data)),
+    findUnique: async () => ({ ...job }),
+    findUniqueOrThrow: async () => ({ ...job }),
+  },
+  servicePart: {
+    findMany: async () => parts,
+    deleteMany: async () => {
+      parts = []
+    },
+    createMany: async ({ data }: { data: Line[] }) => {
+      parts = data
+    },
+    aggregate: vi.fn(async ({ where }: { where: { taxable?: boolean } }) => sum(parts, where)),
+  },
+  serviceLabor: {
+    findMany: async () => labor,
+    deleteMany: async () => {
+      labor = []
+    },
+    createMany: async ({ data }: { data: Line[] }) => {
+      labor = data
+    },
+    aggregate: async ({ where }: { where: { taxable?: boolean } }) => sum(labor, where),
+  },
+  serviceConcern: { findMany: async () => [] },
+  serviceRecordEquipment: { deleteMany: async () => ({ count: 0 }) },
+}
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  vi.mocked(getCachedSession).mockResolvedValue({
+    user: { id: 'user-1', email: 'a@example.com' },
+  } as never)
+  vi.mocked(getCachedMembership).mockResolvedValue({
+    organizationId: 'org-1',
+    role: 'owner',
+    roleId: null,
+    customRole: null,
+  } as never)
+  vi.mocked(db.user.findUnique).mockResolvedValue({ isSuperAdmin: false } as never)
+  vi.mocked(db.appSetting.findMany).mockResolvedValue([])
+  vi.mocked(assertInvoiceEditable).mockResolvedValue(undefined as never)
+  // A counter sale, so no vehicle reading moves with these saves.
+  job = {
+    id: 'rec-1',
+    organizationId: 'org-1',
+    vehicleId: null,
+    title: 'ZZ Brakes',
+    status: 'in-progress',
+    mileage: null,
+    diagnosticNotes: '<p>Pads worn</p>',
+    invoiceNumber: 'ZZ-1001',
+    subtotal: 500,
+    discountType: 'none',
+    discountValue: 0,
+    discountAmount: 0,
+    taxRate: 10,
+    taxInclusive: false,
+    taxComponents: null,
+    taxAmount: 50,
+    totalAmount: 550,
+    cost: 550,
+    warrantyStatus: null,
+    warrantyMonths: null,
+    warrantyMileage: null,
+    warrantyNotes: null,
+    serviceDate: new Date('2026-11-20T12:00:00Z'),
+  }
+  parts = [{ name: 'ZZ Pads', quantity: 1, unitPrice: 200, total: 200, taxable: true }]
+  labor = [{ description: 'ZZ Fit pads', hours: 3, rate: 100, total: 300, taxable: true }]
+  vi.mocked(db.serviceRecord.findFirst).mockImplementation((async () => ({
+    ...job,
+    attachments: [],
+    vehicle: null,
+  })) as never)
+  vi.mocked(db.$transaction).mockImplementation((async (fn: (client: typeof tx) => unknown) =>
+    fn(tx)) as never)
+})
+
+describe('saveServiceRecordChanges', () => {
+  it('writes the one field sent and leaves every other as stored', async () => {
+    const result = await saveServiceRecordChanges({
+      id: 'rec-1',
+      diagnosticNotes: '<p>Pads worn</p><p>Rattle on the left</p>',
+    })
+    expect(result.success).toBe(true)
+    expect(assertInvoiceEditable).toHaveBeenCalledWith('rec-1', 'org-1')
+    expect(job).toMatchObject({
+      diagnosticNotes: '<p>Pads worn</p><p>Rattle on the left</p>',
+      title: 'ZZ Brakes',
+      status: 'in-progress',
+      invoiceNumber: 'ZZ-1001',
+      totalAmount: 550,
+    })
+    // Nothing the money is made of moved, so the money is not reckoned again.
+    expect(tx.servicePart.aggregate).not.toHaveBeenCalled()
+  })
+
+  it('takes no money from the page, and totals a new discount from the stored lines', async () => {
+    const result = await saveServiceRecordChanges({
+      id: 'rec-1',
+      discountType: 'fixed',
+      discountValue: 50,
+      // What a tab holding an old copy of the lines would have worked out.
+      subtotal: 300,
+      discountAmount: 50,
+      taxAmount: 25,
+      totalAmount: 275,
+      cost: 275,
+    })
+    expect(result.success).toBe(true)
+    // 500 of lines, 50 off, 10% on the 450: 45, and 495 in all.
+    expect(job).toMatchObject({
+      discountType: 'fixed',
+      discountValue: 50,
+      subtotal: 500,
+      discountAmount: 50,
+      taxAmount: 45,
+      totalAmount: 495,
+      cost: 495,
+    })
+  })
+
+  it('totals the lines it was sent as they are stored', async () => {
+    await saveServiceRecordChanges({
+      id: 'rec-1',
+      partItems: [{ name: 'ZZ Pads', quantity: 2, unitPrice: 200, total: 400 }],
+    })
+    expect(job).toMatchObject({ subtotal: 700, taxAmount: 70, totalAmount: 770, cost: 770 })
+  })
+
+  it('stores each line to the cent and totals the job from the stored lines', async () => {
+    await saveServiceRecordChanges({
+      id: 'rec-1',
+      // 2.5 h at 19.99, twice: 49.975 each as typed.
+      laborItems: [
+        { description: 'ZZ Front', hours: 2.5, rate: 19.99, total: 49.975, pricingType: 'hourly' },
+        { description: 'ZZ Rear', hours: 2.5, rate: 19.99, total: 49.975, pricingType: 'hourly' },
+      ],
+    })
+    expect(labor.map((line) => line.total)).toEqual([49.98, 49.98])
+    // 200 of parts and 99.96 of labour; 10% tax.
+    expect(job).toMatchObject({ subtotal: 299.96, taxAmount: 30, totalAmount: 329.96 })
+  })
+
+  it('is refused on a cancelled job before anything is written', async () => {
+    vi.mocked(assertInvoiceEditable).mockRejectedValue(new Error('This invoice is cancelled.'))
+    const result = await saveServiceRecordChanges({ id: 'rec-1', title: 'ZZ Renamed' })
+    expect(result.success).toBe(false)
+    expect(job.title).toBe('ZZ Brakes')
+  })
+
+  it('is refused on a locked invoice before anything is written', async () => {
+    vi.mocked(assertInvoiceEditable).mockRejectedValue(new Error('This invoice is locked.'))
+    const result = await saveServiceRecordChanges({ id: 'rec-1', diagnosticNotes: 'x' })
+    expect(result.success).toBe(false)
+    expect(job.diagnosticNotes).toBe('<p>Pads worn</p>')
+  })
+})
+
+describe('updateServiceRecord, as a tab opened before the deploy calls it', () => {
+  it('still saves the whole form, with the money the page worked out', async () => {
+    const result = await updateServiceRecord({
+      id: 'rec-1',
+      vehicleId: null,
+      title: 'ZZ Brakes and discs',
+      type: 'repair',
+      status: 'in-progress',
+      cost: 660,
+      mileage: null,
+      serviceDate: '2026-11-20',
+      diagnosticNotes: '<p>Pads worn</p>',
+      invoiceNotes: '',
+      invoiceNumber: 'ZZ-1001',
+      concerns: [],
+      partItems: [{ name: 'ZZ Pads', quantity: 1, unitPrice: 200, total: 200 }],
+      laborItems: [
+        { description: 'ZZ Fit pads', hours: 3, rate: 100, total: 300, pricingType: 'hourly' },
+        { description: 'ZZ Discs', hours: 1, rate: 100, total: 100, pricingType: 'hourly' },
+      ],
+      subtotal: 600,
+      taxRate: 10,
+      taxInclusive: false,
+      taxAmount: 60,
+      totalAmount: 660,
+      discountType: 'none',
+      discountValue: 0,
+      discountAmount: 0,
+      warrantyStatus: 'none',
+      warrantyMonths: 0,
+      warrantyMileage: 0,
+      warrantyNotes: '',
+    })
+    expect(result.success).toBe(true)
+    expect(job).toMatchObject({
+      title: 'ZZ Brakes and discs',
+      subtotal: 600,
+      taxAmount: 60,
+      totalAmount: 660,
+      cost: 660,
+    })
+    expect(labor.map((line) => line.description)).toEqual(['ZZ Fit pads', 'ZZ Discs'])
+  })
+})

+ 352 - 0
src/__tests__/features/vehicles/two-tabs-save.test.tsx

@@ -0,0 +1,352 @@
+/**
+ * The same work order open in two tabs.
+ *
+ * The page used to save its whole form. Tab B added a line to the internal
+ * notes and saved; tab A, opened earlier, then changed the mileage and saved
+ * its whole form, notes included, as it had read them: B's note was gone.
+ *
+ * Now each save sends only the fields that tab changed. A field saved in both
+ * goes to the later save, and the tab whose value lost is told. A tab with
+ * edits of its own takes, from the job as the server has it, every field it
+ * has not touched.
+ *
+ * Both tabs are the real form state and the real save, as ServicePageClient
+ * wires them, against one stored job; only the server action is a stand-in
+ * that writes what it is sent, field by field, as the real one does.
+ */
+import { act, cleanup, render, renderHook, screen } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { ServiceLaborInput } from '@/features/vehicles/Schema/serviceSchema'
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }),
+  usePathname: () => '/vehicles/veh-1/service/rec-1',
+}))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/hooks/use-deferred-commit', () => ({
+  useDeferredCommit: () => ({ schedule: vi.fn(), cancel: vi.fn() }),
+}))
+vi.mock('@/components/confirm-dialog', async (importOriginal) => ({
+  ...(await importOriginal<typeof import('@/components/confirm-dialog')>()),
+  useConfirm: () => vi.fn(async () => true),
+}))
+const saveServiceRecordChanges = vi.fn()
+vi.mock('@/features/vehicles/Actions/saveServiceRecordChanges', () => ({
+  saveServiceRecordChanges: (input: unknown) => saveServiceRecordChanges(input),
+}))
+vi.mock('@/features/vehicles/Actions/serviceActions', () => ({
+  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 { ChangedElsewhereBanner } from '@/features/vehicles/Components/service-page/ChangedElsewhereBanner'
+import { useServiceActions } from '@/features/vehicles/Components/service-page/useServiceActions'
+import { useServiceFormState } from '@/features/vehicles/Components/service-page/useServiceFormState'
+
+const DIAGNOSIS: ServiceLaborInput = {
+  description: 'ZZ Diagnosis',
+  hours: 1,
+  rate: 100,
+  total: 100,
+  pricingType: 'hourly',
+}
+
+/** The job as the server stores it. */
+let stored: Record<string, unknown>
+
+function freshJob() {
+  return {
+    id: 'rec-1',
+    title: 'ZZ Brake inspection',
+    type: 'repair',
+    status: 'in-progress',
+    mileage: 88000,
+    description: '',
+    diagnosticNotes: '<p>Pads worn</p>',
+    invoiceNotes: '',
+    invoiceNumber: 'ZZ-1001',
+    invoiceDate: '',
+    invoiceDueDate: '',
+    concerns: [],
+    partItems: [],
+    laborItems: [DIAGNOSIS],
+    taxRate: 25,
+    taxInclusive: false,
+    discountType: 'none',
+    discountValue: 0,
+    warrantyStatus: null,
+    warrantyMonths: null,
+    warrantyMileage: null,
+    warrantyNotes: null,
+  }
+}
+
+/** What a tab's next read of the job brings: the stored job, copied. */
+function props() {
+  return {
+    vehicleId: 'veh-1',
+    defaultTaxRate: 25,
+    currentUserName: 'Desk',
+    record: { id: 'rec-1', attachments: [], payments: [] } as never,
+    initialData: structuredClone(stored) as never,
+  }
+}
+
+/** One browser tab on the work order: its form state, its save and its form. */
+function openTab() {
+  const hook = renderHook(
+    (p: ReturnType<typeof props>) => {
+      const formState = useServiceFormState(p)
+      const actions = useServiceActions({
+        record: p.record,
+        vehicleId: 'veh-1',
+        currencyCode: 'GBP',
+        formState,
+      })
+      return { formState, actions }
+    },
+    { initialProps: props() }
+  )
+  const form = document.createElement('form')
+  form.innerHTML = `
+    <input type="hidden" name="title" value="${stored.title}" />
+    <input name="mileage" value="${stored.mileage ?? ''}" />
+    <input name="invoiceNumber" value="${stored.invoiceNumber}" />`
+  document.body.appendChild(form)
+  hook.result.current.formState.formRef.current = form
+  const page = () => hook.result.current.formState
+  const input = (name: string) =>
+    form.querySelector<HTMLInputElement>(`input[name="${name}"]`) as HTMLInputElement
+  return {
+    page,
+    input,
+    /** A field typed into, the way the form's onInput marks the page unsaved. */
+    type: (name: string, value: string) =>
+      act(() => {
+        input(name).value = value
+        page().markDirty()
+      }),
+    writeNote: (field: 'diagnosticNotes' | 'invoiceNotes', html: string) =>
+      act(() => page().handleNotesChange(field, html)),
+    save: () =>
+      act(() =>
+        hook.result.current.actions.handleSubmit({
+          preventDefault: () => undefined,
+          currentTarget: form,
+        } as unknown as React.FormEvent<HTMLFormElement>)
+      ),
+    /** The job changed somewhere else; the page reads it again (useLiveRecord). */
+    refresh: () => hook.rerender(props()),
+  }
+}
+
+const sent = (call = -1) =>
+  saveServiceRecordChanges.mock.calls.at(call)?.[0] as Record<string, unknown>
+
+beforeEach(() => {
+  vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+  stored = freshJob()
+  // The server writes each field it is sent and leaves the rest as stored.
+  saveServiceRecordChanges
+    .mockReset()
+    .mockImplementation(async (input: Record<string, unknown>) => {
+      const { id: _id, ...fields } = input
+      stored = { ...stored, ...structuredClone(fields) }
+      return { success: true, data: { id: 'rec-1' } }
+    })
+})
+
+afterEach(() => {
+  cleanup()
+  document.body.innerHTML = ''
+  vi.useRealTimers()
+})
+
+describe('the same work order in two tabs', () => {
+  it('keeps a note saved in one tab when the other, opened earlier, saves the mileage', async () => {
+    const a = openTab()
+    const b = openTab()
+
+    b.writeNote('diagnosticNotes', '<p>Pads worn</p><p>Customer hears a rattle</p>')
+    await b.save()
+    // Tab A never heard about it: it saves the mileage from its old copy.
+    a.type('mileage', '88450')
+    await a.save()
+
+    expect(sent()).toEqual({ id: 'rec-1', mileage: 88450 })
+    expect(stored.diagnosticNotes).toBe('<p>Pads worn</p><p>Customer hears a rattle</p>')
+    expect(stored.mileage).toBe(88450)
+  })
+
+  it('sends no money: the server totals the job from what it stores', async () => {
+    const a = openTab()
+    act(() => a.page().dirtySetDiscountType('percentage'))
+    act(() => a.page().dirtySetDiscountValue(10))
+    await a.save()
+
+    expect(sent()).toEqual({ id: 'rec-1', discountType: 'percentage', discountValue: 10 })
+    for (const money of ['subtotal', 'taxAmount', 'totalAmount', 'discountAmount', 'cost']) {
+      expect(sent()).not.toHaveProperty(money)
+    }
+  })
+
+  it('gives a field saved in both tabs to the later save, and tells the other tab', async () => {
+    const a = openTab()
+    const b = openTab()
+
+    b.writeNote('diagnosticNotes', '<p>From tab B</p>')
+    await b.save()
+    // Tab A is typing in the same note when B's save reaches it.
+    a.writeNote('diagnosticNotes', '<p>From tab A</p>')
+    a.refresh()
+    // A keeps what is being typed, and is told its save will replace B's.
+    expect(a.page().notesRef.current.diagnosticNotes).toBe('<p>From tab A</p>')
+    expect(a.page().changedElsewhere).toEqual({ kept: ['diagnosticNotes'], replaced: [] })
+
+    await a.save()
+    expect(stored.diagnosticNotes).toBe('<p>From tab A</p>')
+    // Said and done: the notice goes once A's save is through.
+    expect(a.page().changedElsewhere).toEqual({ kept: [], replaced: [] })
+
+    // B hears of A's save: it shows A's note, and is told its own was replaced.
+    b.refresh()
+    expect(b.page().notesRef.current.diagnosticNotes).toBe('<p>From tab A</p>')
+    expect(b.page().adoptedFields.diagnosticNotes).toEqual({ value: '<p>From tab A</p>' })
+    expect(b.page().changedElsewhere).toEqual({ kept: [], replaced: ['diagnosticNotes'] })
+
+    render(
+      <ChangedElsewhereBanner
+        kept={b.page().changedElsewhere.kept}
+        replaced={b.page().changedElsewhere.replaced}
+        onDismiss={() => b.page().dismissChangedElsewhere()}
+      />
+    )
+    expect(screen.getByRole('status')).toHaveTextContent('Changed elsewhere: Internal notes.')
+    expect(screen.getByRole('status')).toHaveTextContent(
+      'A later save replaced your change. This page now shows the newer version.'
+    )
+  })
+
+  it('takes every field it has not touched from the job as saved elsewhere, mid-edit', async () => {
+    const a = openTab()
+    const b = openTab()
+
+    // A is part-way through the mileage, not yet saved.
+    a.type('mileage', '91000')
+    // B saves the stage, a discount, the notes and the invoice number.
+    act(() => {
+      b.page().dirtySetStatus('waiting-parts')
+      b.page().dirtySetDiscountType('fixed')
+      b.page().dirtySetDiscountValue(50)
+    })
+    b.writeNote('invoiceNotes', '<p>Parts ordered</p>')
+    b.type('invoiceNumber', 'ZZ-2002')
+    await b.save()
+
+    a.refresh()
+    const page = a.page()
+    expect(page.status).toBe('waiting-parts')
+    expect(page.discountType).toBe('fixed')
+    expect(page.discountValue).toBe(50)
+    expect(page.notesRef.current.invoiceNotes).toBe('<p>Parts ordered</p>')
+    expect(page.adoptedFields.invoiceNotes).toEqual({ value: '<p>Parts ordered</p>' })
+    expect(a.input('invoiceNumber').value).toBe('ZZ-2002')
+    // What A is typing stays, still unsaved, and nothing was taken from it.
+    expect(a.input('mileage').value).toBe('91000')
+    expect(page.hasUnsavedChanges).toBe(true)
+    expect(page.changedElsewhere).toEqual({ kept: [], replaced: [] })
+
+    await a.save()
+    expect(sent()).toEqual({ id: 'rec-1', mileage: 91000 })
+    expect(stored).toMatchObject({
+      status: 'waiting-parts',
+      discountType: 'fixed',
+      discountValue: 50,
+      invoiceNotes: '<p>Parts ordered</p>',
+      invoiceNumber: 'ZZ-2002',
+      mileage: 91000,
+    })
+  })
+
+  it('takes a line added elsewhere into a list it has not touched, and does not send the lines', async () => {
+    const a = openTab()
+    a.writeNote('diagnosticNotes', '<p>Checked the rotors</p>')
+    const fromTheBay = { ...DIAGNOSIS, description: 'ZZ Replaced pads', total: 150, hours: 1.5 }
+    stored = { ...stored, laborItems: [DIAGNOSIS, fromTheBay] }
+    a.refresh()
+
+    expect(a.page().laborItems).toEqual([DIAGNOSIS, fromTheBay])
+    expect(a.page().laborAddedElsewhere).toEqual([])
+    await a.save()
+    expect(sent()).toEqual({ id: 'rec-1', diagnosticNotes: '<p>Checked the rotors</p>' })
+    expect(stored.laborItems).toEqual([DIAGNOSIS, fromTheBay])
+  })
+
+  it('sends its lines when it changed them, with a line added elsewhere among them', async () => {
+    const a = openTab()
+    const road = { ...DIAGNOSIS, description: 'ZZ Road test' }
+    act(() => a.page().dirtySetLaborItems((prev) => [...prev, road]))
+    const fromTheBay = { ...DIAGNOSIS, description: 'ZZ Replaced pads' }
+    stored = { ...stored, laborItems: [DIAGNOSIS, fromTheBay] }
+    a.refresh()
+    expect(a.page().laborAddedElsewhere).toEqual([fromTheBay])
+
+    await a.save()
+    expect(sent().laborItems).toEqual([DIAGNOSIS, road, fromTheBay])
+    expect(sent()).not.toHaveProperty('partItems')
+  })
+
+  it('takes a cancel made elsewhere even when this tab has picked another stage', async () => {
+    const a = openTab()
+    act(() => a.page().dirtySetStatus('completed'))
+    a.writeNote('diagnosticNotes', '<p>Unsaved note</p>')
+    // The invoice is cancelled in another tab.
+    stored = { ...stored, status: 'cancelled' }
+    a.refresh()
+
+    expect(a.page().status).toBe('cancelled')
+    expect(a.page().changedElsewhere.kept).not.toContain('status')
+    // The rest of what is typed stays on screen.
+    expect(a.page().notesRef.current.diagnosticNotes).toBe('<p>Unsaved note</p>')
+  })
+
+  it('keeps an edit made while its save runs, when a refresh shows that save first', async () => {
+    const a = openTab()
+    // The save of note B is held on its way; the server has already written it.
+    let answer: (value: unknown) => void = () => undefined
+    saveServiceRecordChanges.mockImplementationOnce(async (input: Record<string, unknown>) => {
+      const { id: _id, ...fields } = input
+      stored = { ...stored, ...structuredClone(fields) }
+      return new Promise((resolve) => {
+        answer = resolve
+      })
+    })
+    a.writeNote('diagnosticNotes', '<p>Note B</p>')
+    let saving: Promise<void> = Promise.resolve()
+    act(() => {
+      saving = a.save()
+    })
+    // Put back as it was before, while the save runs.
+    a.writeNote('diagnosticNotes', '<p>Pads worn</p>')
+    // The refresh shows the save before its answer arrives.
+    a.refresh()
+    expect(a.page().notesRef.current.diagnosticNotes).toBe('<p>Pads worn</p>')
+    expect(a.page().adoptedFields.diagnosticNotes).toBeUndefined()
+    expect(a.page().changedElsewhere).toEqual({ kept: [], replaced: [] })
+
+    await act(async () => {
+      answer({ success: true, data: { id: 'rec-1' } })
+      await saving
+    })
+    // The newer edit is still this page's, and the next save sends it.
+    await a.save()
+    expect(sent()).toEqual({ id: 'rec-1', diagnosticNotes: '<p>Pads worn</p>' })
+    expect(stored.diagnosticNotes).toBe('<p>Pads worn</p>')
+  })
+})

+ 4 - 0
src/__tests__/features/vehicles/work-order-header-pills.test.tsx

@@ -137,6 +137,10 @@ vi.mock('@/features/vehicles/Components/service-page/useServiceFormState', () =>
       blockedLeave: null,
       laborAddedElsewhere: [],
       partsAddedElsewhere: [],
+      changedElsewhere: { kept: [], replaced: [] },
+      dismissChangedElsewhere: vi.fn(),
+      adoptedFields: {},
+      acknowledgeSavedFields: vi.fn(),
       imageAttachments: [],
       showPresetPicker: false,
       showInventoryPicker: false,

+ 47 - 7
src/__tests__/features/vehicles/work-order-reading-question.test.tsx

@@ -20,9 +20,11 @@ vi.mock('@/components/confirm-dialog', async (importOriginal) => ({
   ...(await importOriginal<typeof import('@/components/confirm-dialog')>()),
   useConfirm: () => vi.fn(async () => true),
 }))
-const updateServiceRecord = vi.fn()
+const saveServiceRecordChanges = vi.fn()
+vi.mock('@/features/vehicles/Actions/saveServiceRecordChanges', () => ({
+  saveServiceRecordChanges: (input: unknown) => saveServiceRecordChanges(input),
+}))
 vi.mock('@/features/vehicles/Actions/serviceActions', () => ({
-  updateServiceRecord: (input: unknown) => updateServiceRecord(input),
   deleteServiceRecord: vi.fn(),
   deleteServiceAttachment: vi.fn(),
   toggleManuallyPaid: vi.fn(),
@@ -34,9 +36,34 @@ vi.mock('@/features/payments/Actions/paymentActions', () => ({
 vi.mock('@/features/sms/Actions/smsActions', () => ({ getSmsTemplates: vi.fn() }))
 
 import { useServiceActions } from '@/features/vehicles/Components/service-page/useServiceActions'
+import {
+  changedWorkOrderFields,
+  savedWorkOrderFields,
+  type WorkOrderFieldValues,
+} from '@/features/vehicles/Lib/workOrderFields'
 
 type Options = Parameters<typeof useServiceActions>[0]
 
+/**
+ * What the page changed, worked out as the real form state does it
+ * (workOrderFields): the form's title and reading, and the stage, against the
+ * job as saved.
+ */
+function fieldChanges(form: { status: string; initialData: object }) {
+  const value = (name: string) =>
+    document.querySelector<HTMLInputElement>(`form input[name="${name}"]`)?.value
+  const current: Partial<WorkOrderFieldValues> = { status: form.status }
+  const title = value('title')
+  if (title !== undefined) current.title = title
+  const mileage = value('mileage')
+  if (mileage !== undefined) current.mileage = mileage === '' ? null : Number(mileage)
+  const saved = savedWorkOrderFields(
+    form.initialData as Parameters<typeof savedWorkOrderFields>[0],
+    0
+  )
+  return { current, changed: changedWorkOrderFields(saved, current) }
+}
+
 const WAITING = 'The reading is not saved yet. Answer the question under it first.'
 
 afterEach(() => {
@@ -45,7 +72,7 @@ afterEach(() => {
 })
 
 beforeEach(() => {
-  updateServiceRecord.mockReset().mockResolvedValue({ success: true })
+  saveServiceRecordChanges.mockReset().mockResolvedValue({ success: true })
 })
 
 /** The work order as the page holds it: last reading 148,000, nothing saved on the job yet. */
@@ -87,6 +114,18 @@ function page(over: { confirmed?: number | null; saved?: number | null } = {}) {
     confirmedReadingRef: { current: over.confirmed ?? null },
     acknowledgeSavedLines: vi.fn(),
     sendingLinesRef: { current: null },
+    partsAddedElsewhere: [],
+    laborAddedElsewhere: [],
+    fieldChanges: () => fieldChanges(form),
+    acknowledgeSavedFields: vi.fn(),
+    beginFieldSave: vi.fn(),
+    lineEditsForSave: () => ({
+      parts: true,
+      labor: true,
+      partsRevision: 0,
+      laborRevision: 0,
+    }),
+    settleLineEdits: vi.fn(),
   }
   const hook = renderHook(() =>
     useServiceActions({
@@ -120,13 +159,13 @@ function page(over: { confirmed?: number | null; saved?: number | null } = {}) {
   return { form, save, reading }
 }
 
-const sent = () => updateServiceRecord.mock.calls.at(-1)?.[0] as Record<string, unknown>
+const sent = () => saveServiceRecordChanges.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(saveServiceRecordChanges).toHaveBeenCalledTimes(1)
     expect(sent()).toMatchObject({ id: 'job1', title: 'ZZ Brakes' })
     // Left out, the job keeps the reading it had.
     expect(sent().mileage).toBeUndefined()
@@ -171,7 +210,7 @@ describe('a reading far above the last one, not yet answered', () => {
     expect(form.markDirty).not.toHaveBeenCalled()
 
     // An edit made while the save ran is newer and gets a save of its own.
-    updateServiceRecord.mockImplementationOnce(async () => {
+    saveServiceRecordChanges.mockImplementationOnce(async () => {
       form.editRevisionRef.current += 1
       return { success: true }
     })
@@ -207,7 +246,8 @@ describe('once answered, or when nothing needs asking', () => {
   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)
+    // Not changed on this page, so not sent: the job keeps it as it is.
+    expect(sent().mileage).toBeUndefined()
     expect(form.markSaved).toHaveBeenCalled()
   })
 })

+ 44 - 5
src/__tests__/features/vehicles/work-order-required-meters-save.test.tsx

@@ -19,9 +19,11 @@ vi.mock('@/components/confirm-dialog', async (importOriginal) => ({
   ...(await importOriginal<typeof import('@/components/confirm-dialog')>()),
   useConfirm: () => vi.fn(async () => true),
 }))
-const updateServiceRecord = vi.fn()
+const saveServiceRecordChanges = vi.fn()
+vi.mock('@/features/vehicles/Actions/saveServiceRecordChanges', () => ({
+  saveServiceRecordChanges: (input: unknown) => saveServiceRecordChanges(input),
+}))
 vi.mock('@/features/vehicles/Actions/serviceActions', () => ({
-  updateServiceRecord: (input: unknown) => updateServiceRecord(input),
   deleteServiceRecord: vi.fn(),
   deleteServiceAttachment: vi.fn(),
   toggleManuallyPaid: vi.fn(),
@@ -33,6 +35,11 @@ vi.mock('@/features/payments/Actions/paymentActions', () => ({
 vi.mock('@/features/sms/Actions/smsActions', () => ({ getSmsTemplates: vi.fn() }))
 
 import { useServiceActions } from '@/features/vehicles/Components/service-page/useServiceActions'
+import {
+  changedWorkOrderFields,
+  savedWorkOrderFields,
+  type WorkOrderFieldValues,
+} from '@/features/vehicles/Lib/workOrderFields'
 import {
   onRevealRequiredMeters,
   type RevealOptions,
@@ -40,6 +47,26 @@ import {
 
 type Options = Parameters<typeof useServiceActions>[0]
 
+/**
+ * What the page changed, worked out as the real form state does it
+ * (workOrderFields): the form's title and reading, and the stage, against the
+ * job as saved.
+ */
+function fieldChanges(form: { status: string; initialData: object }) {
+  const value = (name: string) =>
+    document.querySelector<HTMLInputElement>(`form input[name="${name}"]`)?.value
+  const current: Partial<WorkOrderFieldValues> = { status: form.status }
+  const title = value('title')
+  if (title !== undefined) current.title = title
+  const mileage = value('mileage')
+  if (mileage !== undefined) current.mileage = mileage === '' ? null : Number(mileage)
+  const saved = savedWorkOrderFields(
+    form.initialData as Parameters<typeof savedWorkOrderFields>[0],
+    0
+  )
+  return { current, changed: changedWorkOrderFields(saved, current) }
+}
+
 const PTO = { vehicleMeterId: 'vm-pto', meterTypeId: 't-pto', name: 'PTO hours', item: null }
 const REFUSED = {
   success: false,
@@ -59,7 +86,7 @@ afterEach(() => {
 beforeEach(() => {
   reveals.length = 0
   stopListening = onRevealRequiredMeters('job1', (ids, options) => reveals.push({ ids, options }))
-  updateServiceRecord.mockReset().mockResolvedValue(REFUSED)
+  saveServiceRecordChanges.mockReset().mockResolvedValue(REFUSED)
 })
 
 /** The page with a stage picked: `status` sent, `saved` the stage the job is at. */
@@ -106,6 +133,18 @@ function page(status: string, saved: string) {
     confirmedReadingRef: { current: null },
     acknowledgeSavedLines: vi.fn(),
     sendingLinesRef: { current: null },
+    partsAddedElsewhere: [],
+    laborAddedElsewhere: [],
+    fieldChanges: () => fieldChanges(form),
+    acknowledgeSavedFields: vi.fn(),
+    beginFieldSave: vi.fn(),
+    lineEditsForSave: () => ({
+      parts: false,
+      labor: false,
+      partsRevision: 0,
+      laborRevision: 0,
+    }),
+    settleLineEdits: vi.fn(),
   }
   const hook = renderHook(() =>
     useServiceActions({
@@ -143,7 +182,7 @@ describe('a completion refused for readings', () => {
 
   it('keeps a stage picked while the save was on its way', async () => {
     const { form, save, stage } = page('completed', 'in-progress')
-    updateServiceRecord.mockImplementationOnce(async () => {
+    saveServiceRecordChanges.mockImplementationOnce(async () => {
       // The person picks "Waiting for parts" while the save runs.
       stage.current = 'waiting-parts'
       form.editRevisionRef.current += 1
@@ -174,7 +213,7 @@ describe('a completion refused for readings', () => {
 
 describe('a completed job moved to a vehicle whose readings are missing', () => {
   it('is refused without queueing a save that could only be refused again', async () => {
-    updateServiceRecord.mockResolvedValue({ ...REFUSED, error: 'Not moved.' })
+    saveServiceRecordChanges.mockResolvedValue({ ...REFUSED, error: 'Not moved.' })
     const { form, save, stage } = page('completed', 'completed')
     await save({ autosave: true })
     expect(stage.current).toBe('completed')

+ 250 - 0
src/__tests__/features/vehicles/work-order-title-refresh.test.tsx

@@ -0,0 +1,250 @@
+/**
+ * The title, edited in the work order's header, when the job is renamed in
+ * another tab.
+ *
+ * The header saves a rename on its own the moment the field is left. A rename
+ * the server refuses stays on the page, unsaved, for the form's save to try
+ * again. The page used to put the record's title back over the header and the
+ * form's hidden copy whenever it was read again, so a rename in another tab
+ * quietly threw away the one waiting here. The header now follows a title
+ * saved elsewhere only when this page has none of its own waiting.
+ *
+ * The page, its form state and its save are the real ones; the details below
+ * the header are cut down to the form and its hidden title, wired as
+ * ModernDetails wires them.
+ */
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/lib/cached-session', () => ({ getCachedMembership: async () => null }))
+vi.mock('@/features/inspections/Components/NewInspectionDialog', () => ({
+  NewInspectionDialog: () => null,
+}))
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ push: vi.fn(), refresh: vi.fn(), replace: vi.fn() }),
+  usePathname: () => '/vehicles/v1/service/job1',
+}))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/features/vehicles/Actions/findingActions', () => ({ deleteFinding: vi.fn() }))
+const updateServiceRecordTitle = vi.fn()
+vi.mock('@/features/vehicles/Actions/serviceActions', () => ({
+  updateServiceRecordTitle: (id: string, title: string) => updateServiceRecordTitle(id, title),
+  updateServiceStatus: vi.fn(),
+  updateServiceRecord: vi.fn(),
+  deleteServiceRecord: vi.fn(),
+  deleteServiceAttachment: vi.fn(),
+  toggleManuallyPaid: vi.fn(),
+}))
+const saveServiceRecordChanges = vi.fn()
+vi.mock('@/features/vehicles/Actions/saveServiceRecordChanges', () => ({
+  saveServiceRecordChanges: (input: unknown) => saveServiceRecordChanges(input),
+}))
+vi.mock('@/features/payments/Actions/paymentActions', () => ({
+  createPayment: vi.fn(),
+  deletePayment: vi.fn(),
+}))
+vi.mock('@/features/email/Actions/emailActions', () => ({ sendInvoiceEmail: vi.fn() }))
+vi.mock('@/features/settings/Actions/documentLockActions', () => ({
+  setInvoiceEditUnlocked: vi.fn(),
+}))
+vi.mock('@/features/inventory/Actions/lookupPartByBarcode', () => ({
+  lookupPartByBarcode: vi.fn(),
+}))
+vi.mock('@/features/sms/Actions/smsActions', () => ({ getSmsTemplates: vi.fn() }))
+vi.mock('@/lib/analytics', () => ({ track: vi.fn() }))
+vi.mock('@/components/confirm-dialog', () => ({ useConfirm: () => vi.fn() }))
+vi.mock('@/hooks/use-hardware-scanner', () => ({ useHardwareScanner: () => undefined }))
+vi.mock('@/hooks/use-save-shortcut', () => ({ useSaveShortcut: () => undefined }))
+vi.mock('@/hooks/use-deferred-commit', () => ({
+  useDeferredCommit: () => ({ schedule: vi.fn(), cancel: vi.fn() }),
+}))
+vi.mock('@/features/realtime/hooks', () => ({ useLiveRecord: () => undefined }))
+
+const { passThrough } = vi.hoisted(() => ({
+  passThrough: ({ children }: { children?: React.ReactNode }) => children,
+}))
+vi.mock('@/features/settings/Components/ShopFeeContext', () => ({ ShopFeeProvider: passThrough }))
+vi.mock('@/features/settings/Components/LineTaxContext', () => ({ LineTaxProvider: passThrough }))
+vi.mock('@/features/settings/Components/WorkshopTaxOffer', () => ({
+  useTaxOfferValue: () => null,
+  WorkshopTaxOfferProvider: passThrough,
+}))
+vi.mock('@/features/fault-codes/Components/FaultCodesOnJob', () => ({
+  FaultCodesJobProvider: passThrough,
+}))
+vi.mock('@/components/document-lock-banner', () => ({ DocumentLockBanner: () => null }))
+vi.mock('@/features/vehicles/Components/service-page/InvoiceDesignMenu', () => ({
+  InvoiceDesignMenu: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-page/PayCodeButton', () => ({
+  PayCodeButton: () => null,
+}))
+vi.mock('@/features/messaging/Components/SendDocumentDialog', () => ({
+  SendDocumentDialog: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-detail/ImageCarousel', () => ({
+  ImageCarousel: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-detail/ShareDialog', () => ({
+  ShareDialog: () => null,
+}))
+vi.mock('@/components/notify-customer-dialog', () => ({ NotifyCustomerDialog: () => null }))
+vi.mock('@/components/pdf-preview-dialog', () => ({ PdfPreviewDialog: () => null }))
+vi.mock('@/features/vehicles/Components/service-edit/InventoryPickerDialog', () => ({
+  InventoryPickerDialog: () => null,
+}))
+vi.mock('@/components/barcode-scanner-dialog', () => ({ BarcodeScannerDialog: () => null }))
+vi.mock('@/features/labor-presets/Components/LaborPresetPickerDialog', () => ({
+  LaborPresetPickerDialog: () => null,
+}))
+vi.mock('@/features/status-reports/Components/StatusReportList', () => ({
+  StatusReportList: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-page/ServiceHeaderActions', () => ({
+  ServiceHeaderActions: () => null,
+}))
+vi.mock('@/features/vehicles/Components/service-page/LeaveUnsavedDialog', () => ({
+  LeaveUnsavedDialog: () => null,
+}))
+vi.mock('@/features/realtime/Components/PresenceChips', () => ({ PresenceChips: () => null }))
+vi.mock('@/features/vehicles/Components/service-page/ObservationsManager', () => ({
+  ObservationsManager: () => null,
+}))
+
+/** The form and its hidden title, as ModernDetails draws them. */
+vi.mock('@/features/vehicles/Components/service-page/modern/ModernDetails', () => ({
+  ModernDetails: ({
+    form,
+    title,
+  }: {
+    form: React.FormHTMLAttributes<HTMLFormElement> & { ref: React.Ref<HTMLFormElement> }
+    title: string
+  }) => (
+    <form {...form} data-testid="service-form" noValidate>
+      <input type="hidden" name="title" value={title} />
+    </form>
+  ),
+}))
+
+import { ServicePageClient } from '@/features/vehicles/Components/service-page/ServicePageClient'
+
+/** The page's props, read with the job titled `title`. */
+function props(title: string) {
+  return {
+    record: {
+      id: 'job1',
+      title,
+      invoiceNumber: 'WO-1001',
+      customer: null,
+      vehicle: { id: 'v1', year: 2019, make: 'Volvo', model: 'V70', customer: null },
+      publicToken: null,
+      payments: [],
+      attachments: [],
+      manuallyPaid: false,
+      cost: 0,
+    },
+    vehicleId: 'v1',
+    organizationId: 'org1',
+    lockState: { locked: false, unlockedAt: null },
+    canUnlock: false,
+    canTakePayment: false,
+    currencyCode: 'GBP',
+    unitSystem: 'metric',
+    defaultTaxRate: 20,
+    initialData: {
+      id: 'job1',
+      title,
+      type: 'repair',
+      status: 'in-progress',
+      mileage: null,
+      invoiceDate: '',
+      invoiceDueDate: '',
+      concerns: [],
+      partItems: [],
+      laborItems: [],
+      taxRate: 20,
+      taxInclusive: false,
+      discountValue: 0,
+    },
+    openObservations: [],
+  } as unknown as Parameters<typeof ServicePageClient>[0]
+}
+
+const hiddenTitle = () =>
+  (screen.getByTestId('service-form').querySelector('input[name="title"]') as HTMLInputElement)
+    .value
+const headerTitle = () => screen.getAllByTestId('service-title')[0].textContent
+
+async function renameInHeader(next: string) {
+  await act(async () => {
+    fireEvent.click(screen.getByTestId('edit-title'))
+  })
+  const field = screen.getByTestId('title-input')
+  fireEvent.change(field, { target: { value: next } })
+  await act(async () => {
+    fireEvent.keyDown(field, { key: 'Enter' })
+  })
+}
+
+beforeEach(() => {
+  vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
+  updateServiceRecordTitle.mockReset()
+  saveServiceRecordChanges.mockReset().mockResolvedValue({ success: true })
+})
+
+afterEach(() => {
+  cleanup()
+  vi.useRealTimers()
+})
+
+describe('the header title when the job is renamed in another tab', () => {
+  it('keeps a rename the server refused, says so, and saves it with the form', async () => {
+    updateServiceRecordTitle.mockResolvedValue({ success: false, error: 'Try again.' })
+    const page = render(<ServicePageClient {...props('ZZ Annual service')} />)
+
+    await renameInHeader('ZZ Annual service and brakes')
+    expect(updateServiceRecordTitle).toHaveBeenCalledWith('job1', 'ZZ Annual service and brakes')
+
+    // Another tab renames the job; this page reads it again.
+    page.rerender(<ServicePageClient {...props('ZZ Renamed in the other tab')} />)
+
+    expect(headerTitle()).toContain('ZZ Annual service and brakes')
+    expect(hiddenTitle()).toBe('ZZ Annual service and brakes')
+    expect(screen.getByTestId('changed-elsewhere-banner')).toHaveTextContent(
+      'Changed elsewhere while you were editing: Title.'
+    )
+
+    // The form's save tries the rename again, and it is the later one.
+    await act(async () => {
+      fireEvent.submit(screen.getByTestId('service-form'))
+    })
+    expect(saveServiceRecordChanges).toHaveBeenCalledWith({
+      id: 'job1',
+      title: 'ZZ Annual service and brakes',
+    })
+  })
+
+  it('follows a rename made elsewhere when this page has none waiting', async () => {
+    const page = render(<ServicePageClient {...props('ZZ Annual service')} />)
+    page.rerender(<ServicePageClient {...props('ZZ Renamed in the other tab')} />)
+
+    expect(headerTitle()).toContain('ZZ Renamed in the other tab')
+    expect(hiddenTitle()).toBe('ZZ Renamed in the other tab')
+    expect(screen.queryByTestId('changed-elsewhere-banner')).toBeNull()
+  })
+
+  it('takes a later rename elsewhere over one it saved, and says so', async () => {
+    updateServiceRecordTitle.mockResolvedValue({ success: true })
+    const page = render(<ServicePageClient {...props('ZZ Annual service')} />)
+
+    await renameInHeader('ZZ Annual service and brakes')
+    page.rerender(<ServicePageClient {...props('ZZ Annual service and brakes')} />)
+    page.rerender(<ServicePageClient {...props('ZZ Renamed in the other tab')} />)
+
+    expect(headerTitle()).toContain('ZZ Renamed in the other tab')
+    expect(hiddenTitle()).toBe('ZZ Renamed in the other tab')
+    expect(screen.getByTestId('changed-elsewhere-banner')).toHaveTextContent(
+      'Changed elsewhere: Title.'
+    )
+  })
+})

+ 50 - 0
src/features/vehicles/Actions/saveServiceRecordChanges.ts

@@ -0,0 +1,50 @@
+'use server'
+
+import { assertInvoiceEditable } from '@/lib/document-lock.server'
+import { parseSentFields, sentId } from '@/lib/parse-sent-fields'
+import { PermissionAction, PermissionSubject } from '@/lib/permissions'
+import { withAuth } from '@/lib/with-auth'
+import { writeServiceRecordUpdate } from '@/features/vehicles/Lib/writeServiceRecordUpdate.server'
+import { saveServiceChangesSchema } from '../Schema/serviceSchema'
+
+/**
+ * Saves what one tab of a work order changed, and nothing else.
+ *
+ * The page used to send its whole form (updateServiceRecord). With the same
+ * job open in two tabs, the one opened earlier sent back every field as it
+ * had first read it, and a note saved in the other tab was gone the moment
+ * this one saved its mileage. Now each field the page did not change is left
+ * out, and left as it is stored; when both tabs changed the same field the
+ * later save wins, and the page that lost hears about it (see
+ * changedElsewhere in useServiceFormState).
+ *
+ * No money is taken from the page: its totals are reckoned from the lines it
+ * holds, which may not be the lines stored. They are worked out here from what
+ * is stored once this save is written.
+ *
+ * A new name rather than a new meaning for updateServiceRecord: a tab opened
+ * before the deploy still calls that one with its whole form.
+ */
+export async function saveServiceRecordChanges(input: unknown) {
+  return withAuth(
+    async ({ userId, organizationId }) => {
+      // The lock first, before the input is read, as for the whole-form save.
+      const recordId = sentId(input)
+      if (recordId) await assertInvoiceEditable(recordId, organizationId)
+      const data = parseSentFields(saveServiceChangesSchema, input)
+      return writeServiceRecordUpdate({ userId, organizationId }, data, { retotal: true })
+    },
+    {
+      requiredPermissions: [
+        { action: PermissionAction.UPDATE, subject: PermissionSubject.SERVICES },
+      ],
+      audit: ({ result }) => ({
+        action: 'service.update',
+        entity: 'ServiceRecord',
+        entityId: result.id,
+        details: { key: 'service_update', params: { ref: result.invoiceNumber || result.id } },
+        metadata: { serviceRecordId: result.id },
+      }),
+    }
+  )
+}

+ 7 - 478
src/features/vehicles/Actions/serviceActions.ts

@@ -1,9 +1,6 @@
 'use server'
 
-import {
-  unlinkJobMeterReadingsFromOtherVehicles,
-  unlinkMeterReadingsOfDeletedJobs,
-} from '@/features/meters/Lib/jobMeterReading.server'
+import { unlinkMeterReadingsOfDeletedJobs } from '@/features/meters/Lib/jobMeterReading.server'
 import { gateFleetNumber, isFleetNumberEnabled } from '@/features/vehicles/Lib/fleetNumberSetting'
 import { assertInvoiceHasRequiredReference } from '@/features/customer-reference/Lib/invoiceGuard.server'
 import {
@@ -24,7 +21,6 @@ import {
   taxFieldsForNewDocument,
   WORKSHOP_TAX_SETTING_KEYS,
 } from '@/features/settings/Lib/workshopTax'
-import { loadTaxApplies } from '@/features/settings/Lib/loadTaxApplies'
 import { withTaxableLabor, withTaxableParts } from '@/lib/taxable-lines'
 import {
   readWarrantyDefaults,
@@ -33,7 +29,6 @@ import {
   warrantyFieldsForNewDocument,
 } from '@/features/settings/Lib/warrantyDefaults'
 import { EMPTY_WARRANTY, normalizeWarranty } from '@/lib/warranty'
-import { parseTaxComponentDefinitions } from '@/lib/tax-components'
 import { restatedSubtotal, subtotalFromLines } from '@/features/vehicles/Lib/subtotalFromLines'
 import { documentTotals } from '@/features/settings/Lib/workshopTax'
 import { issueInvoice } from '@/features/invoices/Lib/issueInvoice'
@@ -70,12 +65,8 @@ 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,
-  forgetJobReading,
-  jobReadingDate,
-  lockJobReading,
-} from '@/features/vehicles/Lib/vehicleReading'
+import { applyJobReading, jobReadingDate } from '@/features/vehicles/Lib/vehicleReading'
+import { writeServiceRecordUpdate } from '@/features/vehicles/Lib/writeServiceRecordUpdate.server'
 import { ACTIVE_HELPERS } from '@/features/workboard/Lib/jobTeam'
 import { FRESH_SHARE_LINK } from '@/lib/share-expiry'
 
@@ -744,472 +735,10 @@ export async function updateServiceRecord(input: unknown) {
       if (recordId) await assertInvoiceEditable(recordId, organizationId)
       // Only what was sent: see parseSentFields for what the defaults did.
       const data = parseSentFields(updateServiceSchema, input)
-      const timeZone = await workshopTimeZone(organizationId)
-      const existing = await db.serviceRecord.findFirst({
-        where: { id: data.id, organizationId },
-        include: {
-          attachments: { select: { fileUrl: true, category: true } },
-          vehicle: {
-            select: {
-              id: true,
-              mileage: true,
-              make: true,
-              model: true,
-              year: true,
-              licensePlate: true,
-            },
-          },
-        },
-      })
-      if (!existing) throw new Error('Service record not found')
-      // A save that leaves the job completed asks for its required meters
-      // first, on the vehicle it will be on, when it completes the job or
-      // moves a completed one to another vehicle; nothing of the save is
-      // written without them. Any other save is never asked.
-      const vehicleAfter = data.vehicleId !== undefined ? data.vehicleId : existing.vehicleId
-      const statusAfter = data.status ?? existing.status
-      if (
-        statusAfter === 'completed' &&
-        (existing.status !== 'completed' || vehicleAfter !== existing.vehicleId)
-      ) {
-        await assertRequiredMetersRead(
-          organizationId,
-          existing.id,
-          existing.status === 'completed' ? 'move' : 'complete',
-          { vehicleId: vehicleAfter }
-        )
-      }
-
-      const {
-        id,
-        partItems,
-        laborItems,
-        concerns,
-        attachments,
-        customerId: _cid,
-        serviceDate: _sd,
-        invoiceDate: _id,
-        invoiceDueDate: _idd,
-        warrantyStatus: _ws,
-        warrantyMonths: _wm,
-        warrantyMileage: _wmil,
-        warrantyNotes: _wn,
-        ...recordData
-      } = data
-
-      // The four warranty columns move together. A save that names any of them
-      // restates the whole warranty, with the row filling in what was left
-      // out, so they can never be left contradicting each other; and the
-      // expiry follows the service date even when only the date was changed.
-      const warrantyTouched =
-        data.warrantyStatus !== undefined ||
-        data.warrantyMonths !== undefined ||
-        data.warrantyMileage !== undefined ||
-        data.warrantyNotes !== undefined
-      const warranty = warrantyTouched
-        ? normalizeWarranty({
-            warrantyStatus: data.warrantyStatus ?? existing.warrantyStatus,
-            warrantyMonths: data.warrantyMonths ?? existing.warrantyMonths,
-            warrantyMileage: data.warrantyMileage ?? existing.warrantyMileage,
-            warrantyNotes: data.warrantyNotes ?? existing.warrantyNotes,
-          })
-        : null
-      const movedServiceDate =
-        data.serviceDate !== undefined ? toSafeWorkshopDate(data.serviceDate, timeZone) : undefined
-      const warrantyExpiresAt =
-        warranty || movedServiceDate
-          ? warrantyExpiryFor(
-              warranty ?? normalizeWarranty(existing),
-              movedServiceDate ?? existing.serviceDate,
-              timeZone
-            )
-          : undefined
-
-      // A job totalled with tax components keeps its split in step with the
-      // lines the client sent: the amounts are recomputed here from the
-      // components on the row, because the editor only knows the combined
-      // rate and must not leave the printed GST and QST lines stale.
-      //
-      // The same goes for a job with a line left out of the tax: what the
-      // tax is charged on comes from the lines as they are about to be
-      // stored, so it is worked out here and never taken from the caller.
-      // Lines the caller did not send are the ones already on the job.
-      const linesSent = partItems !== undefined || laborItems !== undefined
-      const taxApplies = linesSent ? await loadTaxApplies(organizationId) : null
-      const taxedParts =
-        partItems !== undefined && taxApplies ? withTaxableParts(partItems, taxApplies) : undefined
-      const taxedLabor =
-        laborItems !== undefined && taxApplies
-          ? withTaxableLabor(laborItems, taxApplies)
-          : undefined
-      // Lines are stored to the cent (serviceSchema). The subtotal the page
-      // sent was added up from its own figures, so it is restated from the
-      // lines as stored, and the discount and tax with it, or the invoice's
-      // lines would not add up to its subtotal.
-      let fromLines: ReturnType<typeof restatedSubtotal> = null
-      if (linesSent && recordData.subtotal !== undefined) {
-        const linesSubtotal = subtotalFromLines(
-          partItems ??
-            (await db.servicePart.findMany({
-              where: { serviceRecordId: id },
-              select: { total: true },
-            })),
-          laborItems ??
-            (await db.serviceLabor.findMany({
-              where: { serviceRecordId: id },
-              select: { total: true },
-            }))
-        )
-        fromLines = restatedSubtotal({
-          sentSubtotal: recordData.subtotal,
-          linesSubtotal,
-          discountType: recordData.discountType ?? existing.discountType,
-          discountValue: recordData.discountValue ?? existing.discountValue,
-        })
-        if (fromLines) {
-          recordData.subtotal = fromLines.subtotal
-          if (fromLines.discountAmount !== undefined) {
-            recordData.discountAmount = fromLines.discountAmount
-          }
-        }
-      }
-      const moneyTouched =
-        linesSent ||
-        recordData.subtotal !== undefined ||
-        recordData.discountAmount !== undefined ||
-        recordData.taxRate !== undefined
-      const savedTax = moneyTouched
-        ? savedDocumentTax({
-            subtotal: recordData.subtotal ?? existing.subtotal,
-            discountAmount: recordData.discountAmount ?? existing.discountAmount,
-            // A job with components keeps the rate they add up to.
-            taxRate: parseTaxComponentDefinitions(existing.taxComponents)
-              ? existing.taxRate
-              : (recordData.taxRate ?? existing.taxRate),
-            taxInclusive: recordData.taxInclusive ?? existing.taxInclusive,
-            taxComponents: existing.taxComponents,
-            parts:
-              taxedParts ??
-              (await db.servicePart.findMany({
-                where: { serviceRecordId: id },
-                select: { total: true, taxable: true },
-              })),
-            labor:
-              taxedLabor ??
-              (await db.serviceLabor.findMany({
-                where: { serviceRecordId: id },
-                select: { total: true, taxable: true, pricingType: true },
-              })),
-          })
-        : null
-      // The split is restated only by a save that restates the subtotal, as
-      // before; a job with untaxed lines is restated by any save that touches
-      // its money, since any of them moves what the tax is charged on.
-      const restated =
-        savedTax?.totals && (recordData.subtotal !== undefined || savedTax.taxableSubtotal !== null)
-          ? savedTax.totals
-          : null
-      if (restated) {
-        if (restated.taxComponents) recordData.taxRate = existing.taxRate
-        recordData.taxAmount = restated.taxAmount
-        recordData.totalAmount = restated.totalAmount
-      } else if (fromLines) {
-        // A plain job, every line taxed at one rate: its tax and total follow
-        // the restated subtotal too.
-        const totals = documentTotals({
-          subtotal: fromLines.subtotal,
-          discountAmount: recordData.discountAmount ?? existing.discountAmount,
-          taxRate: recordData.taxRate ?? existing.taxRate,
-          taxInclusive: recordData.taxInclusive ?? existing.taxInclusive,
-          taxComponents: existing.taxComponents,
-          taxableSubtotal: null,
-        })
-        recordData.taxAmount = totals.taxAmount
-        recordData.totalAmount = totals.totalAmount
-      }
-      if (fromLines && recordData.cost !== undefined && recordData.totalAmount !== undefined) {
-        // The page sends the job's cost as its total.
-        recordData.cost = recordData.totalAmount
-      }
-
-      // A null vehicleId from the client means "no vehicle" (counter sale) —
-      // treat it as no-change rather than detaching an existing vehicle.
-      if (recordData.vehicleId == null) {
-        delete recordData.vehicleId
-      } else if (recordData.vehicleId !== existing.vehicleId) {
-        // Moving the record to another vehicle: it must belong to this org, and
-        // the record's customer then follows the vehicle again.
-        const targetVehicle = await db.vehicle.findFirst({
-          where: { id: recordData.vehicleId, organizationId },
-          select: { id: true },
-        })
-        if (!targetVehicle) throw new Error('Vehicle not found')
-      }
-
-      // Determine which categories are being replaced and which files were removed
-      let removedFileUrls: string[] = []
-      let categoriesToReplace: string[] = []
-      if (attachments !== undefined) {
-        categoriesToReplace = [...new Set(attachments.map((a) => a.category || 'diagnostic'))]
-        const existingInCategories = existing.attachments.filter((a) =>
-          categoriesToReplace.includes(a.category)
-        )
-        const newFileUrls = new Set(attachments.map((a) => a.fileUrl))
-        removedFileUrls = existingInCategories
-          .map((a) => a.fileUrl)
-          .filter((url) => !newFileUrls.has(url))
-      }
-
-      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: {
-            ...recordData,
-            // The form carries the stage, not the workshop's own status, which
-            // is chosen and saved on its own. So a save that moves the stage
-            // drops a status that belonged to the old one, and a save that
-            // leaves the stage alone leaves the status alone.
-            ...(recordData.status !== undefined && recordData.status !== existing.status
-              ? { customStatusId: null, customStatusSince: null }
-              : {}),
-            // Completed by this save: booked time still ahead is let go.
-            ...(recordData.status !== undefined
-              ? slotOnCompletion(existing, recordData.status)
-              : {}),
-            taxComponents: restated?.taxComponents,
-            ...(savedTax ? { taxableSubtotal: savedTax.taxableSubtotal } : {}),
-            // Attaching a vehicle to a counter sale: the direct customer link is
-            // cleared so the invoice follows the vehicle's customer again.
-            customerId:
-              recordData.vehicleId &&
-              recordData.vehicleId !== existing.vehicleId &&
-              existing.customerId
-                ? null
-                : undefined,
-            description:
-              recordData.description !== undefined ? recordData.description || null : undefined,
-            techName: recordData.techName !== undefined ? recordData.techName || null : undefined,
-            diagnosticNotes:
-              recordData.diagnosticNotes !== undefined
-                ? recordData.diagnosticNotes || null
-                : undefined,
-            invoiceNotes:
-              recordData.invoiceNotes !== undefined ? recordData.invoiceNotes || null : undefined,
-            invoiceNumber:
-              recordData.invoiceNumber !== undefined ? recordData.invoiceNumber || null : undefined,
-            mileage: recordData.mileage !== undefined ? (recordData.mileage ?? null) : undefined,
-            serviceDate: toSafeWorkshopDate(data.serviceDate, timeZone),
-            // An emptied date clears it; the invoice then falls back to the
-            // scheduled start or the service date, as it did before one was set.
-            invoiceDate:
-              data.invoiceDate !== undefined
-                ? (toSafeWorkshopDate(data.invoiceDate, timeZone) ?? null)
-                : undefined,
-            invoiceDueDate:
-              data.invoiceDueDate !== undefined
-                ? (toSafeWorkshopDate(data.invoiceDueDate, timeZone) ?? null)
-                : undefined,
-            ...(warranty ?? {}),
-            warrantyExpiresAt,
-          },
-        })
-
-        // Replace parts if provided
-        if (partItems !== undefined) {
-          // Snapshot the parts being replaced BEFORE deleting them, so inventory
-          // can be reconciled by the delta between the old and new linked parts
-          // (this is what keeps stock correct when parts are added, edited,
-          // reduced or removed on an existing work order).
-          const previousParts = await tx.servicePart.findMany({
-            where: { serviceRecordId: id },
-            select: { inventoryPartId: true, quantity: true },
-          })
-
-          await tx.servicePart.deleteMany({ where: { serviceRecordId: id } })
-          if (taxedParts && taxedParts.length > 0) {
-            await tx.servicePart.createMany({
-              data: taxedParts.map((p) => ({
-                partNumber: p.partNumber,
-                name: p.name,
-                quantity: p.quantity,
-                unit: p.unit ?? null,
-                category: p.category ?? null,
-                unitPrice: p.unitPrice,
-                total: p.total,
-                unitCost: p.unitCost ?? 0,
-                markupPercent: p.markupPercent ?? 0,
-                inventoryPartId: p.inventoryPartId || null,
-                taxable: p.taxable,
-                serviceRecordId: id,
-              })),
-            })
-          }
-
-          await reconcileInventoryForParts(tx, organizationId, previousParts, partItems, {
-            reason: 'service_record',
-            userId,
-            serviceRecordId: id,
-            serviceRecordLabel: existing.invoiceNumber || existing.title,
-          })
-        }
-
-        /**
-         * Reconcile concerns by id, rather than replacing them like the rows
-         * above.
-         *
-         * Parts and labour can be deleted and rewritten on every save because
-         * nothing points at them. Findings point at concerns, and the relation
-         * is SetNull, so deleting the whole list on an autosave would silently
-         * cut every diagnosis loose from the question it answered. The rows
-         * that survive an edit have to keep their ids.
-         */
-        if (concerns !== undefined) {
-          const existingConcerns = await tx.serviceConcern.findMany({
-            where: { serviceRecordId: id },
-            select: { id: true, confirmedAt: true, confirmedById: true },
-          })
-          const existingById = new Map(existingConcerns.map((concern) => [concern.id, concern]))
-          const now = new Date()
-          const keptIds = new Set(
-            concerns.map((concern) => concern.id).filter((cid): cid is string => Boolean(cid))
-          )
-
-          const removedIds = existingConcerns
-            .map((concern) => concern.id)
-            .filter((cid) => !keptIds.has(cid))
-          if (removedIds.length > 0) {
-            await tx.serviceConcern.deleteMany({ where: { id: { in: removedIds } } })
-          }
-
-          for (const [index, concern] of concerns.entries()) {
-            const sortOrder = concern.sortOrder ?? index
-            // An id the client sent that is not on this job is not ours to
-            // trust: fall through to a create rather than updating by id.
-            if (concern.id && keptIds.has(concern.id)) {
-              const { count } = await tx.serviceConcern.updateMany({
-                where: { id: concern.id, serviceRecordId: id },
-                data: {
-                  description: concern.description,
-                  sortOrder,
-                  ...concernStoryData(concern, existingById.get(concern.id) ?? null, userId, now),
-                },
-              })
-              if (count > 0) continue
-            }
-            await tx.serviceConcern.create({
-              data: {
-                description: concern.description,
-                sortOrder,
-                serviceRecordId: id,
-                ...concernStoryData(concern, null, userId, now),
-              },
-            })
-          }
-        }
-
-        // Replace labor if provided
-        if (laborItems !== undefined) {
-          await tx.serviceLabor.deleteMany({ where: { serviceRecordId: id } })
-          if (taxedLabor && taxedLabor.length > 0) {
-            await tx.serviceLabor.createMany({
-              data: taxedLabor.map((l) => ({
-                ...l,
-                serviceRecordId: id,
-              })),
-            })
-          }
-        }
-
-        // Replace attachments if provided (only for the categories included in the payload)
-        if (attachments !== undefined) {
-          if (categoriesToReplace.length > 0) {
-            await tx.serviceAttachment.deleteMany({
-              where: { serviceRecordId: id, category: { in: categoriesToReplace } },
-            })
-          }
-          if (attachments.length > 0) {
-            await tx.serviceAttachment.createMany({
-              data: attachments.map((a) => ({
-                ...a,
-                serviceRecordId: id,
-              })),
-            })
-          }
-        }
-
-        // 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 })
-          // Its meter readings stay in the old vehicle's history, no longer the job's.
-          await unlinkJobMeterReadingsFromOtherVehicles(tx, {
-            organizationId,
-            jobId: id,
-            vehicleId: updated.vehicleId,
-          })
-          // And it no longer works on the old vehicle's equipment.
-          await tx.serviceRecordEquipment.deleteMany({
-            where: {
-              organizationId,
-              serviceRecordId: id,
-              ...(updated.vehicleId ? { item: { vehicleId: { not: updated.vehicleId } } } : {}),
-            },
-          })
-        }
-        if (updated.vehicleId && (recordData.mileage !== undefined || !sameVehicle)) {
-          await applyJobReading(tx, {
-            organizationId,
-            vehicleId: updated.vehicleId,
-            jobId: id,
-            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, {
-        organizationId,
-        reason: 'work order attachments replaced',
-      })
-
-      // Notify workboard if status changed
-      if (record.status !== existing.status) {
-        notificationBus.emit('workboard', {
-          type: 'job_status_changed',
-          organizationId,
-          serviceRecordId: id,
-          status: record.status,
-          serviceRecord: {
-            id: existing.id,
-            title: record.title || existing.title,
-            status: record.status,
-            vehicle: existing.vehicle,
-          },
-        })
-      }
-
-      revalidatePath('/')
-      if (existing.vehicleId) {
-        revalidatePath(`/vehicles/${existing.vehicleId}`)
-        revalidatePath(`/vehicles/${existing.vehicleId}/service/${id}`)
-      } else {
-        revalidatePath(`/sales/${id}`)
-      }
-      revalidatePath('/services')
-      // Parts may have been added, changed or removed on this record.
-      await onInventoryChanged(organizationId)
-      return record
+      // The whole form, money and all, as a page sends it that was opened
+      // before saveServiceRecordChanges existed. The page now sends only what
+      // it edited, to that action.
+      return writeServiceRecordUpdate({ userId, organizationId }, data)
     },
     {
       requiredPermissions: [

+ 15 - 4
src/features/vehicles/Components/service-edit/InvoiceDetailsSection.tsx

@@ -35,6 +35,11 @@ const FOLLOW_DEFAULT = '__default__'
 
 interface InvoiceDetailsSectionProps {
   initialData: InitialData
+  /** Dates saved elsewhere that the page has taken; see useServiceFormState. */
+  adopted?: {
+    invoiceDate?: { value: unknown }
+    invoiceDueDate?: { value: unknown }
+  }
   type: string
   setType: (type: string) => void
   /** Counter sales (no vehicle) have no meaningful service type; hide the field. */
@@ -70,6 +75,7 @@ interface InvoiceDetailsSectionProps {
 
 export function InvoiceDetailsSection({
   initialData,
+  adopted,
   type,
   setType,
   showType = true,
@@ -117,13 +123,18 @@ export function InvoiceDetailsSection({
   const [invoiceDate, setInvoiceDate] = useState(initialData.invoiceDate || '')
   const [invoiceDueDate, setInvoiceDueDate] = useState(initialData.invoiceDueDate || '')
 
+  // A date saved elsewhere, taken when nothing was typed in it here (see
+  // useServiceFormState). Following every saved date instead put the other
+  // tab's date over one being typed, and the next save sent it back.
+  const adoptedDate = adopted?.invoiceDate
+  const adoptedDueDate = adopted?.invoiceDueDate
   useEffect(() => {
-    setInvoiceDate(initialData.invoiceDate || '')
-  }, [initialData.invoiceDate])
+    if (adoptedDate) setInvoiceDate(String(adoptedDate.value ?? ''))
+  }, [adoptedDate])
 
   useEffect(() => {
-    setInvoiceDueDate(initialData.invoiceDueDate || '')
-  }, [initialData.invoiceDueDate])
+    if (adoptedDueDate) setInvoiceDueDate(String(adoptedDueDate.value ?? ''))
+  }, [adoptedDueDate])
 
   // A draft's empty invoice date is filled the day it is sent; the hint says
   // so while nobody has typed a date of their own.

+ 19 - 1
src/features/vehicles/Components/service-edit/NotesSection.tsx

@@ -1,6 +1,6 @@
 'use client'
 
-import { useState } from 'react'
+import { useEffect, useState } from 'react'
 import { useTranslations } from 'next-intl'
 import { toast } from 'sonner'
 import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
@@ -31,6 +31,14 @@ interface NotesSectionProps {
   publicLocked?: boolean
   /** Only when the internal notes have no save of their own on a locked invoice. */
   internalLocked?: boolean
+  /**
+   * Notes saved elsewhere that the page has taken, because nothing was typed
+   * in them here; see useServiceFormState. A note being typed is never in it.
+   */
+  adopted?: {
+    invoiceNotes?: { value: unknown }
+    diagnosticNotes?: { value: unknown }
+  }
 }
 
 function hasContent(html: string): boolean {
@@ -45,6 +53,7 @@ export function NotesSection({
   aiEnabled,
   publicLocked = false,
   internalLocked = false,
+  adopted,
 }: NotesSectionProps) {
   const t = useTranslations('service.notes')
   const modern = useModernWorkOrder()
@@ -55,6 +64,15 @@ export function NotesSection({
   const [showDialog, setShowDialog] = useState(false)
   const [dontShowAgain, setDontShowAgain] = useState(false)
 
+  const adoptedPublic = adopted?.invoiceNotes
+  const adoptedInternal = adopted?.diagnosticNotes
+  useEffect(() => {
+    if (adoptedPublic) setPublicNotes(String(adoptedPublic.value ?? ''))
+  }, [adoptedPublic])
+  useEffect(() => {
+    if (adoptedInternal) setInternalNotes(String(adoptedInternal.value ?? ''))
+  }, [adoptedInternal])
+
   const handlePublicChange = (html: string) => {
     setPublicNotes(html)
     onNotesChange('invoiceNotes', html)

+ 65 - 0
src/features/vehicles/Components/service-page/ChangedElsewhereBanner.tsx

@@ -0,0 +1,65 @@
+'use client'
+
+import { useTranslations } from 'next-intl'
+import { RefreshCw } from 'lucide-react'
+import { Button } from '@/components/ui/button'
+import { useServiceType } from '@/components/service-type-context'
+import type { WorkOrderField } from '@/features/vehicles/Lib/workOrderFields'
+
+/**
+ * A field this page had changed was saved somewhere else too: the same job in
+ * another tab, or a colleague's screen. Each save sends only the fields it
+ * changed, so the later one wins, and this says which page that was.
+ *
+ * - `kept`: still being edited here. This page's version is the later one,
+ *   and its save replaces the other.
+ * - `replaced`: this page had saved it, and a later save elsewhere replaced
+ *   that. The page now shows the newer version.
+ *
+ * Drawn like the banner for lines added elsewhere (LaborAddedBanner).
+ */
+export function ChangedElsewhereBanner({
+  kept,
+  replaced,
+  onDismiss,
+}: {
+  kept: WorkOrderField[]
+  replaced: WorkOrderField[]
+  onDismiss: () => void
+}) {
+  const t = useTranslations('service.changedElsewhere')
+  const marine = useServiceType() === 'marine'
+  if (kept.length === 0 && replaced.length === 0) return null
+
+  const names = (fields: WorkOrderField[]) =>
+    fields
+      .map((field) => t(`fields.${field === 'mileage' && marine ? 'mileageMarine' : field}`))
+      .join(', ')
+
+  return (
+    <div
+      data-testid="changed-elsewhere-banner"
+      role="status"
+      className="flex shrink-0 flex-wrap items-center gap-x-3 gap-y-2 border-b border-primary/20 bg-primary/10 px-4 py-2"
+    >
+      <RefreshCw className="h-4 w-4 shrink-0 text-primary" aria-hidden="true" />
+      <div className="min-w-0 flex-1 space-y-0.5 text-sm">
+        {replaced.length > 0 && (
+          <p>
+            <span className="font-medium">{t('replacedTitle', { fields: names(replaced) })}</span>{' '}
+            <span className="text-muted-foreground">{t('replacedBody')}</span>
+          </p>
+        )}
+        {kept.length > 0 && (
+          <p>
+            <span className="font-medium">{t('keptTitle', { fields: names(kept) })}</span>{' '}
+            <span className="text-muted-foreground">{t('keptBody')}</span>
+          </p>
+        )}
+      </div>
+      <Button type="button" size="sm" variant="outline" className="h-8" onClick={onDismiss}>
+        {t('dismiss')}
+      </Button>
+    </div>
+  )
+}

+ 17 - 5
src/features/vehicles/Components/service-page/ServicePageClient.tsx

@@ -70,6 +70,7 @@ import type { ServicePageClientProps, ServiceTab } from './service-page-types'
 import { WorkOrderLayoutProvider } from '@/components/work-order-layout-context'
 import { track } from '@/lib/analytics'
 import { LaborAddedBanner } from './LaborAddedBanner'
+import { ChangedElsewhereBanner } from './ChangedElsewhereBanner'
 import { LeaveUnsavedDialog } from './LeaveUnsavedDialog'
 import { useLiveRecord } from '@/features/realtime/hooks'
 import { PresenceChips } from '@/features/realtime/Components/PresenceChips'
@@ -213,16 +214,14 @@ export function ServicePageClient({
   const [requestedTab, setRequestedTab] = useState<ServiceTab>(resolvedInitialTab)
 
   // The overhauled page edits the title in its header, outside the form, so
-  // the page holds it and the form carries it as a hidden field. It follows
-  // the record again after every save.
+  // the page holds it and the form carries it as a hidden field. It follows a
+  // title saved elsewhere only when the form state takes it (adoptedFields):
+  // a rename the server refused is still this page's, waiting to be saved.
   const [title, setTitle] = useState(record.title)
   // Bumped by "Take payment" in the money bar and by "Unpaid" in the header:
   // the payments form opens and scrolls into view.
   const [paymentSignal, setPaymentSignal] = useState(0)
   const takePayment = useCallback(() => setPaymentSignal((n) => n + 1), [])
-  useEffect(() => {
-    setTitle(record.title)
-  }, [record.title])
 
   // One view per work order opened.
   useEffect(() => {
@@ -279,6 +278,11 @@ export function ServicePageClient({
     taxApplies: lineTax.applies,
   })
 
+  const adoptedTitle = formState.adoptedFields.title
+  useEffect(() => {
+    if (adoptedTitle) setTitle(String(adoptedTitle.value ?? ''))
+  }, [adoptedTitle])
+
   // Anything that happens to this job somewhere else: a technician billing
   // their time from the app, marking it complete in the bay, or the person at
   // the next desk saving it. Every write reaches here, because every write
@@ -700,6 +704,8 @@ export function ServicePageClient({
     // marks the form dirty, so the ordinary path can try again.
     void updateServiceRecordTitle(record.id, next).then((result) => {
       if (result.success) {
+        // The server's title now: a later rename elsewhere replaces it.
+        formState.acknowledgeSavedFields({ title: next })
         formState.flashSaved()
       } else {
         toast.error(result.error || t('page.failedUpdate'))
@@ -862,6 +868,12 @@ export function ServicePageClient({
               }}
             />
 
+            <ChangedElsewhereBanner
+              kept={formState.changedElsewhere.kept}
+              replaced={formState.changedElsewhere.replaced}
+              onDismiss={formState.dismissChangedElsewhere}
+            />
+
             <CancelInvoiceDialog
               open={showCancelDialog}
               onOpenChange={setShowCancelDialog}

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

@@ -540,6 +540,7 @@ export function ModernDetails(props: ModernDetailsProps) {
                   serviceRecordId={record.id}
                   aiEnabled={props.aiEnabled}
                   publicLocked={locked}
+                  adopted={formState.adoptedFields}
                 />
               </div>
 
@@ -594,6 +595,7 @@ export function ModernDetails(props: ModernDetailsProps) {
                       <InvoiceDetailsSection
                         part="invoice"
                         initialData={formState.initialData}
+                        adopted={formState.adoptedFields}
                         type={formState.type}
                         setType={formState.dirtySetType}
                         status={formState.status}

+ 68 - 97
src/features/vehicles/Components/service-page/useServiceActions.ts

@@ -5,8 +5,8 @@ import { toast } from 'sonner'
 import { useGlassModal } from '@/components/glass-modal'
 import { useConfirm } from '@/components/confirm-dialog'
 import { useFormatter, useTranslations } from 'next-intl'
+import { saveServiceRecordChanges } from '@/features/vehicles/Actions/saveServiceRecordChanges'
 import {
-  updateServiceRecord,
   deleteServiceRecord,
   deleteServiceAttachment,
   toggleManuallyPaid,
@@ -18,13 +18,13 @@ import { SMS_TEMPLATE_DEFAULTS, interpolateSmsTemplate } from '@/lib/sms-templat
 import { formatCurrency } from '@/lib/format'
 import { findServiceFormProblem } from '@/features/vehicles/Lib/validateServiceForm'
 import { LINE_TOTAL_MAX, QUANTITY_MAX, READING_MAX, UNIT_PRICE_MAX } from '@/lib/input-limits'
-import { WARRANTY_NONE } from '@/lib/warranty'
 import { useServiceType } from '@/components/service-type-context'
 import { useFieldErrorText } from '@/components/field-errors'
 import type { FieldError } from '@/lib/field-errors'
 import { readingNeedsAnswer } from '@/features/vehicles/Lib/vehicleReading'
 import { revealRequiredMeters } from '@/features/meters/Lib/requiredMetersReveal'
 import type { ServiceDetail } from '../service-detail/types'
+import type { WorkOrderFieldValues } from '@/features/vehicles/Lib/workOrderFields'
 import type { useServiceFormState } from './useServiceFormState'
 
 type FormState = ReturnType<typeof useServiceFormState>
@@ -98,24 +98,16 @@ export function useServiceActions({
     partItems,
     laborItems,
     laborItemsForSave,
+    laborAddedElsewhere,
     commitLaborAddedElsewhere,
     partItemsForSave,
+    partsAddedElsewhere,
     commitPartsAddedElsewhere,
-    subtotal,
-    taxRate,
-    taxInclusive,
-    taxAmount,
-    totalAmount,
-    discountType,
-    discountValue,
-    discountAmount,
-    warranty,
     isSavingRef,
     autosaveTimer,
     setLoading,
     setHasUnsavedChanges,
     flashSaved,
-    notesRef,
     initialData,
     customFieldsSaveRef,
     lastSaveErrorRef,
@@ -127,6 +119,11 @@ export function useServiceActions({
     confirmedReadingRef,
     acknowledgeSavedLines,
     sendingLinesRef,
+    fieldChanges,
+    beginFieldSave,
+    acknowledgeSavedFields,
+    lineEditsForSave,
+    settleLineEdits,
   } = formState
 
   /**
@@ -225,17 +222,11 @@ export function useServiceActions({
 
     setLoading(true)
 
-    // A field the layout does not render at all is left alone; an emptied one
-    // is sent so the update action clears it ('' for text, null for mileage).
-    const optionalText = (name: string): string | undefined => getVisible(name) ?? undefined
-    const rawMileage = getVisible('mileage') as string | null | undefined
-    const mileageNumber = rawMileage == null ? undefined : Number(rawMileage)
-    const parsedMileage =
-      rawMileage == null || Number.isNaN(mileageNumber)
-        ? undefined
-        : rawMileage.trim() === ''
-          ? null
-          : mileageNumber
+    // Only the fields this page changed (fieldChanges): a field it did not
+    // touch may have been saved in another tab since this one read it, and
+    // sending this page's old copy back would throw that away. An emptied
+    // field is a change, and is sent so the action clears it.
+    const { current, changed } = fieldChanges()
     // 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
@@ -243,84 +234,57 @@ export function useServiceActions({
     // one is not asked about.
     const holdReading =
       selectedVehicleId === vehicleId &&
+      changed.includes('mileage') &&
       readingNeedsAnswer({
-        value: parsedMileage,
+        value: current.mileage,
         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)
-
+    const sentFields: Partial<WorkOrderFieldValues> = {}
+    for (const field of changed) {
+      // Left out, the job keeps the reading it has.
+      if (field === 'mileage' && holdReading) continue
+      Object.assign(sentFields, { [field]: current[field] })
+    }
+    const { discount, warranty, ...plainFields } = sentFields
+    // Parts and labour only when this page changed them, and then the whole
+    // list: lines a technician added while this page was open go with it
+    // even if the offer to show them was never taken, since the save
+    // replaces every line and one left out of it is deleted.
+    const lines = lineEditsForSave({
+      parts: partsAddedElsewhere.length,
+      labor: laborAddedElsewhere.length,
+    })
     const payload = {
       id: initialData.id,
-      vehicleId: selectedVehicleId,
-      title: getVisible('title'),
-      description: richText(notesRef.current.description),
-      // What the customer said at drop-off. Typed at intake beside the vehicle,
-      // not in the notes section, so it is read from the form rather than from
-      // the notes state.
-      type,
-      status,
-      cost: totalAmount,
-      // 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
-      // the form-state value here would clobber a tech change made via the
-      // Schedule card with a stale name from initial load.
-      diagnosticNotes: richText(notesRef.current.diagnosticNotes),
-      invoiceNotes: richText(notesRef.current.invoiceNotes),
-      invoiceNumber: optionalText('invoiceNumber'),
-      invoiceDate: optionalText('invoiceDate'),
-      invoiceDueDate: optionalText('invoiceDueDate'),
-      // Blank rows are somebody halfway through typing, not a concern.
-      // Only the saved fields: the stamp of who confirmed is the server's.
-      concerns: concerns
-        .filter((c) => c.description.trim())
-        .map((c, index) => ({
-          id: c.id,
-          description: c.description.trim(),
-          sortOrder: index,
-          cause: c.cause ?? null,
-          correction: c.correction ?? null,
-          confirmation: c.confirmation ?? null,
-          confirmed: c.confirmed ?? false,
-        })),
-      // Parts and labour a technician added while this page was open go with
-      // the save even if the offer to show them was never taken: this action
-      // replaces every line, so one left out of the payload is deleted.
-      partItems: partItemsForSave.filter((p) => p.name),
-      // A line a technician added while this page was open goes with the save
-      // even if the offer to show it was never taken: this action replaces
-      // every labour line, so one left out of the payload is deleted.
-      laborItems: laborItemsForSave.filter((l) => l.description),
-      subtotal,
-      taxRate,
-      taxInclusive,
-      taxAmount,
-      totalAmount,
-      discountType: discountType === 'none' ? 'none' : discountType,
-      discountValue: discountType === 'none' ? 0 : discountValue,
-      discountAmount: discountType === 'none' ? 0 : discountAmount,
-      // Cleared fields go as 'none', 0 and '' so the action clears them;
-      // undefined would leave the old value in place.
-      warrantyStatus: warranty.warrantyStatus ?? WARRANTY_NONE,
-      warrantyMonths: warranty.warrantyMonths ?? 0,
-      warrantyMileage: warranty.warrantyMileage ?? 0,
-      warrantyNotes: warranty.warrantyNotes ?? '',
+      // Moving the job to another vehicle; null (a counter sale) is no change.
+      ...(selectedVehicleId && selectedVehicleId !== vehicleId
+        ? { vehicleId: selectedVehicleId }
+        : {}),
+      ...plainFields,
+      ...(discount ?? {}),
+      ...(warranty ?? {}),
+      ...(lines.parts ? { partItems: partItemsForSave.filter((p) => p.name) } : {}),
+      ...(lines.labor ? { laborItems: laborItemsForSave.filter((l) => l.description) } : {}),
+      // No money: the server totals the job from what it stores.
     }
 
-    let result: Awaited<ReturnType<typeof updateServiceRecord>>
+    let result: Awaited<ReturnType<typeof saveServiceRecordChanges>>
     // A refresh that lands while this runs must not take these lines, the
     // page's own, for ones added elsewhere.
-    sendingLinesRef.current = { parts: payload.partItems, labor: payload.laborItems }
+    const sentLines = {
+      parts: payload.partItems ?? partItemsForSave,
+      labor: payload.laborItems ?? laborItemsForSave,
+    }
+    sendingLinesRef.current = sentLines
+    beginFieldSave(sentFields)
     try {
-      result = await updateServiceRecord(payload)
+      result = await saveServiceRecordChanges(payload)
     } catch (err) {
       sendingLinesRef.current = null
+      beginFieldSave(null)
       // The request never came back (the connection dropped). Saving has to
       // end here, or the next save, and a link waiting on this one, waits
       // forever.
@@ -330,10 +294,19 @@ export function useServiceActions({
     }
     sendingLinesRef.current = null
 
+    if (result.success) acknowledgeSavedFields(sentFields)
+    beginFieldSave(null)
+    if (result.success) {
+      settleLineEdits(lines)
+      if (lines.labor) commitLaborAddedElsewhere()
+      if (lines.parts) commitPartsAddedElsewhere()
+      // The same on every save: a preset or an edit made while it ran, or
+      // before the refresh after it comes back, leaves the page unsaved when
+      // the saved lines arrive, and they must not read as added elsewhere.
+      if (lines.parts || lines.labor) acknowledgeSavedLines(sentLines)
+    }
+
     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.
@@ -346,12 +319,6 @@ export function useServiceActions({
         question?.querySelector<HTMLButtonElement>('[data-reading-confirm]')?.focus()
       }
     } else if (result.success) {
-      commitLaborAddedElsewhere()
-      commitPartsAddedElsewhere()
-      // The same on every save: a preset or an edit made while it ran, or
-      // before the refresh below comes back, leaves the page unsaved when the
-      // saved lines arrive, and they must not read as added elsewhere.
-      acknowledgeSavedLines({ parts: payload.partItems, labor: payload.laborItems })
       markSaved(revision)
       flashSaved()
       if (selectedVehicleId && selectedVehicleId !== vehicleId) {
@@ -366,12 +333,16 @@ export function useServiceActions({
       // whose boxes are marked. Only if the stage is still the one this save
       // sent: one picked while it ran is newer, and is what the next save
       // sends.
-      setStatus((current) => (current === payload.status ? initialData.status : current))
+      setStatus((now) => (now === payload.status ? initialData.status : now))
       // The next save is queued only when it can go through: with the stage
       // put back. A completed job moved to another vehicle stays refused
       // until the person moves it back or reopens it, and a save every five
       // seconds would only say so again.
-      if (editRevisionRef.current === revision && payload.status !== initialData.status) {
+      if (
+        editRevisionRef.current === revision &&
+        payload.status !== undefined &&
+        payload.status !== initialData.status
+      ) {
         markDirty()
       }
       refuse(result.error || t('page.failedUpdate'))

+ 271 - 27
src/features/vehicles/Components/service-page/useServiceFormState.ts

@@ -1,4 +1,4 @@
-import { useState, useCallback, useRef, useEffect } from 'react'
+import { useState, useCallback, useRef, useEffect, useLayoutEffect } from 'react'
 import { roundMoney } from '@/lib/money'
 import { calculateTotals, discountAmountFor, storedTaxableSubtotal } from '@/lib/tax'
 import {
@@ -15,6 +15,18 @@ import { lineTotal, repricePartRow } from '@/features/inventory/Lib/partPricing'
 import { reconcileConcernRows } from '@/features/vehicles/Lib/concernStory'
 import { addedLaborLines, savedLaborShape } from '@/features/vehicles/Lib/laborLines'
 import { addedPartLines, savedPartShape } from '@/features/vehicles/Lib/partLines'
+import {
+  concernsForSave,
+  changedWorkOrderFields,
+  discountForSave,
+  mergeWorkOrderFields,
+  richText,
+  sameFieldValue,
+  savedWorkOrderFields,
+  warrantyForSave,
+  type WorkOrderField,
+  type WorkOrderFieldValues,
+} from '@/features/vehicles/Lib/workOrderFields'
 import {
   recalculateShopFeeLines,
   shopFeeLinesLast,
@@ -155,9 +167,14 @@ export function useServiceFormState({
   // save, was taken for a new one, and the saved row was deleted with every
   // finding that pointed at it.
   const savedConcernsKey = JSON.stringify(initialData.concerns ?? [])
+  // Set by the merge below when the concerns changed elsewhere and not here:
+  // the server's list is taken then, whatever else is being edited.
+  const adoptConcernsRef = useRef(false)
   useEffect(() => {
     const saved: ConcernRow[] = JSON.parse(savedConcernsKey)
-    setConcerns((current) => reconcileConcernRows(current, saved, hasUnsavedChangesRef.current))
+    const keepRows = hasUnsavedChangesRef.current && !adoptConcernsRef.current
+    adoptConcernsRef.current = false
+    setConcerns((current) => reconcileConcernRows(current, saved, keepRows))
   }, [savedConcernsKey])
 
   /**
@@ -173,24 +190,6 @@ export function useServiceFormState({
    * the page offers them (see the banner on the work order) and the save adds
    * them whether or not the offer was taken.
    */
-  /**
-   * The status as the server now has it. A technician marking the job
-   * complete in the bay has to move the bar on the desk's screen, and the
-   * page refreshes on that event, so the saved status arrives here.
-   *
-   * Not while the desk is editing: the status is part of what a save writes,
-   * and replacing a choice someone has just made in the dropdown would send
-   * back the wrong one. Their save wins, and the bar follows it.
-   */
-  const savedStatus = initialData.status
-  useEffect(() => {
-    if (!savedStatus) return
-    // A cancelled invoice is final, and no save can change it back, so it
-    // is taken whatever is being edited.
-    if (hasUnsavedChangesRef.current && savedStatus !== 'cancelled') return
-    setStatus(savedStatus)
-  }, [savedStatus])
-
   /**
    * The lines of the save on its way to the server, if one is. A refresh can
    * be read either side of its write; see addedLaborLines.
@@ -200,6 +199,27 @@ export function useServiceFormState({
     labor: ServiceLaborInput[]
   } | null>(null)
 
+  /**
+   * Whether this page has changed its parts, or its labour, since its last
+   * save. A save sends a list only then (it replaces every line of it), and
+   * only then does a list keep what is typed and hold lines from elsewhere
+   * behind the banner: a page editing the notes takes the technician's new
+   * line straight into its list, as a page editing nothing does. The
+   * revision says whether a save covered every edit of the list.
+   */
+  const partsEditedRef = useRef(false)
+  const laborEditedRef = useRef(false)
+  const partsRevisionRef = useRef(0)
+  const laborRevisionRef = useRef(0)
+  const markPartsEdited = useCallback(() => {
+    partsEditedRef.current = true
+    partsRevisionRef.current += 1
+  }, [])
+  const markLaborEdited = useCallback(() => {
+    laborEditedRef.current = true
+    laborRevisionRef.current += 1
+  }, [])
+
   const [laborAddedElsewhere, setLaborAddedElsewhere] = useState<ServiceLaborInput[]>([])
   const savedLaborKey = JSON.stringify(initialData.laborItems ?? [])
   const syncedLaborRef = useRef<ServiceLaborInput[]>(initialData.laborItems ?? [])
@@ -207,7 +227,7 @@ export function useServiceFormState({
     const saved: ServiceLaborInput[] = JSON.parse(savedLaborKey)
     const previous = syncedLaborRef.current
     syncedLaborRef.current = saved
-    if (!hasUnsavedChangesRef.current) {
+    if (!laborEditedRef.current) {
       setLaborItems(saved)
       setLaborAddedElsewhere([])
       return
@@ -227,7 +247,7 @@ export function useServiceFormState({
     const saved: ServicePartInput[] = JSON.parse(savedPartsKey)
     const previous = syncedPartsRef.current
     syncedPartsRef.current = saved
-    if (!hasUnsavedChangesRef.current) {
+    if (!partsEditedRef.current) {
       setPartItems(saved)
       setPartsAddedElsewhere([])
       return
@@ -386,6 +406,214 @@ export function useServiceFormState({
     [markDirty]
   )
 
+  /**
+   * The job's own fields as the server last told this page (workOrderFields).
+   * A save sends the ones the page holds differently, and no others: with the
+   * job open in a second tab, a field this one never touched is the other
+   * tab's to change, and sending back this page's old copy of it threw away
+   * what was saved there.
+   */
+  const serverFieldsKey = JSON.stringify(savedWorkOrderFields(initialData, defaultTaxRate))
+  const syncedFieldsRef = useRef<WorkOrderFieldValues>(JSON.parse(serverFieldsKey))
+  /** The fields this page has saved, so it can be told when a later save replaces one. */
+  const savedHereRef = useRef(new Set<WorkOrderField>())
+  /**
+   * The values a save on its way to the server sent, as they were when it
+   * left. A refresh can show that save before its answer arrives; the field
+   * then compares against what was sent, not what is on screen, so an edit
+   * made after the save left is still this page's (even one that puts the
+   * field back as it was before).
+   */
+  const sendingFieldsRef = useRef<Partial<WorkOrderFieldValues> | null>(null)
+  /**
+   * Values taken from the server for fields drawn by sections that hold
+   * their own copy (the notes editors, the invoice dates). A new object each
+   * time, so a section follows even when the same value comes back.
+   */
+  const [adoptedFields, setAdoptedFields] = useState<
+    Partial<Record<WorkOrderField, { value: unknown }>>
+  >({})
+  /**
+   * Fields saved somewhere else that this page had changed too. `kept`: this
+   * page is still editing it, and its save replaces the other one. `replaced`:
+   * this page had saved it, and a later save elsewhere replaced that.
+   */
+  const [changedElsewhere, setChangedElsewhere] = useState<{
+    kept: WorkOrderField[]
+    replaced: WorkOrderField[]
+  }>({ kept: [], replaced: [] })
+  const dismissChangedElsewhere = useCallback(
+    () => setChangedElsewhere({ kept: [], replaced: [] }),
+    []
+  )
+
+  /**
+   * The fields as the page holds them now. Most are state; the title, the
+   * reading and the invoice number and dates are read from the form, and a
+   * field the page does not draw is left out.
+   */
+  const readCurrentFields = (): Partial<WorkOrderFieldValues> => {
+    const current: Partial<WorkOrderFieldValues> = {
+      type,
+      status,
+      taxRate,
+      discount: discountForSave(discountType, discountValue),
+      warranty: warrantyForSave(warranty),
+      concerns: concernsForSave(concerns),
+      description: richText(notesRef.current.description),
+      diagnosticNotes: richText(notesRef.current.diagnosticNotes),
+      invoiceNotes: richText(notesRef.current.invoiceNotes),
+    }
+    const form = formRef.current
+    const read = (name: string) =>
+      form?.querySelector<HTMLInputElement | HTMLTextAreaElement>(
+        `input[name="${name}"], textarea[name="${name}"]`
+      )?.value
+    const title = read('title')
+    if (title !== undefined) current.title = title
+    const mileage = read('mileage')
+    if (mileage !== undefined) {
+      if (mileage.trim() === '') current.mileage = null
+      else if (!Number.isNaN(Number(mileage))) current.mileage = Number(mileage)
+    }
+    for (const name of ['invoiceNumber', 'invoiceDate', 'invoiceDueDate'] as const) {
+      const value = read(name)
+      if (value !== undefined) current[name] = value
+    }
+    return current
+  }
+  const readCurrentFieldsRef = useRef(readCurrentFields)
+  readCurrentFieldsRef.current = readCurrentFields
+
+  /**
+   * The job as the server has it now, after a save here or anywhere else:
+   * each field this page has not changed takes the server's value, each one
+   * it has keeps what is typed (mergeWorkOrderFields). Before the sections'
+   * own effects run, so what they hold is still what this page had.
+   */
+  useLayoutEffect(() => {
+    const server: WorkOrderFieldValues = JSON.parse(serverFieldsKey)
+    // This page's own save, shown by the refresh before its answer is back:
+    // what it sent is what this page last knew of those fields.
+    let synced = syncedFieldsRef.current
+    const sending = sendingFieldsRef.current
+    if (sending) {
+      for (const field of Object.keys(sending) as WorkOrderField[]) {
+        if (!sameFieldValue(field, server[field], sending[field])) continue
+        synced = { ...synced, [field]: sending[field] }
+        delete sending[field]
+        savedHereRef.current.add(field)
+      }
+    }
+    const merged = mergeWorkOrderFields({
+      synced,
+      current: readCurrentFieldsRef.current(),
+      server,
+      savedHere: savedHereRef.current,
+    })
+    const { adopt, replaced } = merged
+    let { kept } = merged
+    // A cancelled invoice is final, and no save can change it back, so the
+    // cancel is taken whatever stage this page had picked.
+    if (server.status === 'cancelled' && kept.includes('status')) {
+      kept = kept.filter((field) => field !== 'status')
+      adopt.push('status')
+    }
+    syncedFieldsRef.current = server
+    for (const field of replaced) savedHereRef.current.delete(field)
+    const setInput = (name: string, value: string) => {
+      const input = formRef.current?.querySelector<HTMLInputElement>(`input[name="${name}"]`)
+      if (input) input.value = value
+    }
+    for (const field of adopt) {
+      if (field === 'type') setType(server.type)
+      else if (field === 'status') setStatus(server.status)
+      else if (field === 'taxRate') setTaxRate(server.taxRate)
+      else if (field === 'discount') {
+        setDiscountType(server.discount.discountType)
+        setDiscountValue(server.discount.discountValue)
+      } else if (field === 'warranty') setWarranty(normalizeWarranty(server.warranty))
+      else if (field === 'concerns') adoptConcernsRef.current = true
+      else if (field === 'mileage') setInput('mileage', String(server.mileage ?? ''))
+      else if (field === 'invoiceNumber') setInput('invoiceNumber', server.invoiceNumber)
+      else if (field === 'description' || field === 'diagnosticNotes' || field === 'invoiceNotes') {
+        notesRef.current[field] = server[field]
+      }
+    }
+    if (adopt.length > 0) {
+      setAdoptedFields((previous) => {
+        const next = { ...previous }
+        for (const field of adopt) next[field] = { value: server[field] }
+        return next
+      })
+    }
+    if (kept.length > 0 || replaced.length > 0) {
+      const union = (a: WorkOrderField[], b: WorkOrderField[]) => [...new Set([...a, ...b])]
+      setChangedElsewhere((previous) => ({
+        kept: union(previous.kept, kept),
+        replaced: union(previous.replaced, replaced),
+      }))
+    }
+  }, [serverFieldsKey])
+
+  /**
+   * What a save sends of the job's own fields: those this page changed,
+   * as the page holds them.
+   */
+  const fieldChanges = useCallback(() => {
+    const current = readCurrentFieldsRef.current()
+    return { current, changed: changedWorkOrderFields(syncedFieldsRef.current, current) }
+  }, [])
+
+  /** A save leaves with these values (see sendingFieldsRef); null when it is over. */
+  const beginFieldSave = useCallback((sent: Partial<WorkOrderFieldValues> | null) => {
+    sendingFieldsRef.current = sent ? { ...sent } : null
+  }, [])
+
+  /** A save went through: these values are the server's now, and this page's. */
+  const acknowledgeSavedFields = useCallback((sent: Partial<WorkOrderFieldValues>) => {
+    const fields = Object.keys(sent) as WorkOrderField[]
+    // A field a refresh already showed this save for is settled there, and
+    // may have moved on since; only the rest are taken as sent.
+    const sending = sendingFieldsRef.current
+    if (fields.length === 0) return
+    const unseen = sending
+      ? Object.fromEntries(fields.filter((f) => f in sending).map((f) => [f, sent[f]]))
+      : sent
+    syncedFieldsRef.current = { ...syncedFieldsRef.current, ...unseen }
+    for (const field of fields) savedHereRef.current.add(field)
+    setChangedElsewhere((previous) => {
+      const kept = previous.kept.filter((field) => !fields.includes(field))
+      const replaced = previous.replaced.filter((field) => !fields.includes(field))
+      return kept.length === previous.kept.length && replaced.length === previous.replaced.length
+        ? previous
+        : { kept, replaced }
+    })
+  }, [])
+
+  /**
+   * Which lists a save is about to send, and the edits it covers; handed back
+   * to settleLineEdits once it went through.
+   */
+  const lineEditsForSave = useCallback(
+    (pending: { parts: number; labor: number }) => ({
+      parts: partsEditedRef.current || pending.parts > 0,
+      labor: laborEditedRef.current || pending.labor > 0,
+      partsRevision: partsRevisionRef.current,
+      laborRevision: laborRevisionRef.current,
+    }),
+    []
+  )
+  /** The lists a save wrote are the server's again, unless edited while it ran. */
+  const settleLineEdits = useCallback((sent: ReturnType<typeof lineEditsForSave>) => {
+    if (sent.parts && partsRevisionRef.current === sent.partsRevision) {
+      partsEditedRef.current = false
+    }
+    if (sent.labor && laborRevisionRef.current === sent.laborRevision) {
+      laborEditedRef.current = false
+    }
+  }, [])
+
   /**
    * What a save has to write: the lists on screen plus anything added
    * elsewhere that has not been shown yet. A save replaces every part and
@@ -417,8 +645,9 @@ export function useServiceFormState({
     const next = recalculateShopFeeLines(laborItems, partsSubtotal, shopFee)
     if (next === laborItems) return
     setLaborItems(next)
+    markLaborEdited()
     markDirty()
-  }, [laborItems, partsSubtotal, shopFee, locked, markDirty])
+  }, [laborItems, partsSubtotal, shopFee, locked, markDirty, markLaborEdited])
 
   // Internal-only: what the parts cost the workshop before markup. Shown in
   // the totals card for the mechanic, never on the PDF or share views.
@@ -524,9 +753,10 @@ export function useServiceFormState({
         )
       }
 
+      markPartsEdited()
       markDirty()
     },
-    [markDirty, cancelCommit, scheduleCommit]
+    [markDirty, markPartsEdited, cancelCommit, scheduleCommit]
   )
 
   const updateLabor = useCallback(
@@ -540,26 +770,29 @@ export function useServiceFormState({
         updated[index] = labor
         return updated
       })
+      markLaborEdited()
       markDirty()
     },
-    [markDirty]
+    [markDirty, markLaborEdited]
   )
 
   // Wrapped setters that trigger autosave
   const dirtySetPartItems: typeof setPartItems = useCallback(
     (action) => {
       setPartItems(action)
+      markPartsEdited()
       markDirty()
     },
-    [markDirty]
+    [markDirty, markPartsEdited]
   )
 
   const dirtySetLaborItems: typeof setLaborItems = useCallback(
     (action) => {
       setLaborItems(action)
+      markLaborEdited()
       markDirty()
     },
-    [markDirty]
+    [markDirty, markLaborEdited]
   )
 
   const applyLaborAddedElsewhere = useCallback(() => {
@@ -690,6 +923,17 @@ export function useServiceFormState({
     confirmReading,
     acknowledgeSavedLines,
     sendingLinesRef,
+    /** The job's fields this page changed, for a save to send (see workOrderFields). */
+    fieldChanges,
+    beginFieldSave,
+    acknowledgeSavedFields,
+    lineEditsForSave,
+    settleLineEdits,
+    /** Server values for the sections that keep their own copy of a field. */
+    adoptedFields,
+    /** Fields this page changed that were saved elsewhere too; see the banner. */
+    changedElsewhere,
+    dismissChangedElsewhere,
     /**
      * 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

+ 2 - 1
src/features/vehicles/Lib/lineSums.ts

@@ -25,7 +25,8 @@ export async function serviceRecordLineSums(
     }),
   ])
   return {
-    subtotal: (parts._sum.total || 0) + (labor._sum.total || 0),
+    // Each stored line is to the cent; the sum is held there too (subtotalFromLines).
+    subtotal: roundMoney((parts._sum.total || 0) + (labor._sum.total || 0)),
     taxableSubtotal: roundMoney((taxableParts._sum.total || 0) + (taxableLabor._sum.total || 0)),
   }
 }

+ 213 - 0
src/features/vehicles/Lib/workOrderFields.ts

@@ -0,0 +1,213 @@
+import { normalizeWarranty, WARRANTY_NONE } from '@/lib/warranty'
+import type { ConcernRowLike } from './concernStory'
+
+/**
+ * The fields of a work order a save writes one by one, as the page sends them.
+ *
+ * With the same job open in two tabs, each tab sends only the fields it
+ * changed (saveServiceRecordChanges): a field is changed when what the page
+ * holds differs from what the server last told this page, so a note saved in
+ * the other tab is never written back over by a copy read before it. Lines of
+ * parts and labour are not here: they have their own reconciliation (see the
+ * line lists in useServiceFormState).
+ *
+ * The discount's type and value, and the warranty's four columns, move
+ * together, so each is one field here.
+ */
+export const WORK_ORDER_FIELDS = [
+  'title',
+  'type',
+  'status',
+  'mileage',
+  'description',
+  'diagnosticNotes',
+  'invoiceNotes',
+  'invoiceNumber',
+  'invoiceDate',
+  'invoiceDueDate',
+  'taxRate',
+  'discount',
+  'warranty',
+  'concerns',
+] as const
+
+export type WorkOrderField = (typeof WORK_ORDER_FIELDS)[number]
+
+export interface ConcernForSave {
+  id?: string
+  description: string
+  sortOrder: number
+  cause: string | null
+  correction: string | null
+  confirmation: string | null
+  confirmed: boolean
+}
+
+export interface WorkOrderFieldValues {
+  title: string
+  type: string
+  status: string
+  mileage: number | null
+  description: string
+  diagnosticNotes: string
+  invoiceNotes: string
+  invoiceNumber: string
+  invoiceDate: string
+  invoiceDueDate: string
+  taxRate: number
+  discount: { discountType: string; discountValue: number }
+  warranty: {
+    warrantyStatus: string
+    warrantyMonths: number
+    warrantyMileage: number
+    warrantyNotes: string
+  }
+  concerns: ConcernForSave[]
+}
+
+/** The editor reports an emptied box as one empty paragraph. */
+export function richText(html: string): string {
+  return html === '<p></p>' ? '' : html
+}
+
+/** Blank rows are somebody halfway through typing, not a concern. */
+export function concernsForSave(rows: readonly ConcernRowLike[]): ConcernForSave[] {
+  return rows
+    .filter((c) => c.description.trim())
+    .map((c, index) => ({
+      id: c.id,
+      description: c.description.trim(),
+      sortOrder: index,
+      cause: c.cause ?? null,
+      correction: c.correction ?? null,
+      confirmation: c.confirmation ?? null,
+      confirmed: c.confirmed ?? false,
+    }))
+}
+
+export function discountForSave(type: string | null | undefined, value: number | null | undefined) {
+  const discountType = type || 'none'
+  return { discountType, discountValue: discountType === 'none' ? 0 : (value ?? 0) }
+}
+
+/** Cleared fields go as 'none', 0 and '' so the action clears them. */
+export function warrantyForSave(input: {
+  warrantyStatus?: string | null
+  warrantyMonths?: number | null
+  warrantyMileage?: number | null
+  warrantyNotes?: string | null
+}) {
+  return {
+    warrantyStatus: input.warrantyStatus ?? WARRANTY_NONE,
+    warrantyMonths: input.warrantyMonths ?? 0,
+    warrantyMileage: input.warrantyMileage ?? 0,
+    warrantyNotes: input.warrantyNotes ?? '',
+  }
+}
+
+/** What the server holds, in the shape the page sends it back. */
+export function savedWorkOrderFields(
+  saved: {
+    title: string
+    type?: string | null
+    status?: string | null
+    mileage?: number | null
+    description?: string | null
+    diagnosticNotes?: string | null
+    invoiceNotes?: string | null
+    invoiceNumber?: string | null
+    invoiceDate?: string | null
+    invoiceDueDate?: string | null
+    taxRate?: number | null
+    discountType?: string | null
+    discountValue?: number | null
+    warrantyStatus?: string | null
+    warrantyMonths?: number | null
+    warrantyMileage?: number | null
+    warrantyNotes?: string | null
+    concerns?: readonly ConcernRowLike[] | null
+  },
+  defaultTaxRate: number
+): WorkOrderFieldValues {
+  return {
+    title: saved.title ?? '',
+    type: saved.type || 'maintenance',
+    status: saved.status || 'completed',
+    mileage: saved.mileage ?? null,
+    description: richText(saved.description || ''),
+    diagnosticNotes: richText(saved.diagnosticNotes || ''),
+    invoiceNotes: richText(saved.invoiceNotes || ''),
+    invoiceNumber: saved.invoiceNumber || '',
+    invoiceDate: saved.invoiceDate || '',
+    invoiceDueDate: saved.invoiceDueDate || '',
+    taxRate: saved.taxRate ?? defaultTaxRate,
+    discount: discountForSave(saved.discountType, saved.discountValue),
+    warranty: warrantyForSave(normalizeWarranty(saved)),
+    concerns: concernsForSave(saved.concerns ?? []),
+  }
+}
+
+/**
+ * Two values of a field compared as the server would store them. A concern is
+ * compared without its id: the save that creates one gives it its id, and the
+ * concern is the same one before and after.
+ */
+export function sameFieldValue(field: WorkOrderField, a: unknown, b: unknown): boolean {
+  if (field === 'concerns') {
+    const strip = (list: unknown) =>
+      JSON.stringify(((list as ConcernForSave[]) ?? []).map(({ id: _id, ...rest }) => rest))
+    return strip(a) === strip(b)
+  }
+  return JSON.stringify(a ?? null) === JSON.stringify(b ?? null)
+}
+
+/**
+ * The fields the page holds differently from what the server last told it:
+ * the ones this tab changed. A field the page does not draw (absent from
+ * `current`) is not one of them.
+ */
+export function changedWorkOrderFields(
+  synced: WorkOrderFieldValues,
+  current: Partial<WorkOrderFieldValues>
+): WorkOrderField[] {
+  return WORK_ORDER_FIELDS.filter(
+    (field) => field in current && !sameFieldValue(field, current[field], synced[field])
+  )
+}
+
+/**
+ * What a page does with the job as the server now has it (a refresh after a
+ * save somewhere else), field by field, against what it last knew (`synced`)
+ * and what it holds now (`current`):
+ *
+ * - not changed anywhere: nothing;
+ * - changed elsewhere, not here: the page takes the new value (`adopt`); and
+ *   when this page had saved that field itself, its change was replaced by a
+ *   later one, which it is told (`replaced`);
+ * - changed here and elsewhere to different values: the page keeps its own,
+ *   which is saved later and so wins, and is told (`kept`);
+ * - changed here and elsewhere to the same value: nothing left to do.
+ */
+export function mergeWorkOrderFields(args: {
+  synced: WorkOrderFieldValues
+  current: Partial<WorkOrderFieldValues>
+  server: WorkOrderFieldValues
+  savedHere: ReadonlySet<WorkOrderField>
+}): { adopt: WorkOrderField[]; kept: WorkOrderField[]; replaced: WorkOrderField[] } {
+  const { synced, current, server, savedHere } = args
+  const adopt: WorkOrderField[] = []
+  const kept: WorkOrderField[] = []
+  const replaced: WorkOrderField[] = []
+  for (const field of WORK_ORDER_FIELDS) {
+    if (sameFieldValue(field, server[field], synced[field])) continue
+    const mine = field in current ? current[field] : synced[field]
+    if (sameFieldValue(field, mine, server[field])) continue
+    if (sameFieldValue(field, mine, synced[field])) {
+      adopt.push(field)
+      if (savedHere.has(field)) replaced.push(field)
+    } else {
+      kept.push(field)
+    }
+  }
+  return { adopt, kept, replaced }
+}

+ 530 - 0
src/features/vehicles/Lib/writeServiceRecordUpdate.server.ts

@@ -0,0 +1,530 @@
+import { unlinkJobMeterReadingsFromOtherVehicles } from '@/features/meters/Lib/jobMeterReading.server'
+import { assertRequiredMetersRead } from '@/features/meters/Lib/requiredMeters.server'
+import { db } from '@/lib/db'
+import { concernStoryData } from '@/features/vehicles/Lib/concernStory'
+import { documentTotals, savedDocumentTax } from '@/features/settings/Lib/workshopTax'
+import { restatedSubtotal, subtotalFromLines } from '@/features/vehicles/Lib/subtotalFromLines'
+import { loadTaxApplies } from '@/features/settings/Lib/loadTaxApplies'
+import { withTaxableLabor, withTaxableParts } from '@/lib/taxable-lines'
+import { warrantyExpiryFor } from '@/features/settings/Lib/warrantyDefaults'
+import { normalizeWarranty } from '@/lib/warranty'
+import { parseTaxComponentDefinitions } from '@/lib/tax-components'
+import { revalidatePath } from 'next/cache'
+import { onInventoryChanged } from '@/features/inventory/Lib/onInventoryChanged'
+import { releaseFiles } from '@/lib/files/manager'
+import { workshopTimeZone } from '@/lib/workshop-timezone'
+import { toSafeWorkshopDate } from '@/lib/workshop-datetime'
+import { notificationBus } from '@/lib/notification-bus'
+import { reconcileInventoryForParts } from '@/features/inventory/Lib/reconcileStock'
+import {
+  applyJobReading,
+  forgetJobReading,
+  jobReadingDate,
+  lockJobReading,
+} from '@/features/vehicles/Lib/vehicleReading'
+import { slotOnCompletion } from '@/features/work-order-statuses/Lib/stages'
+import { retotalServiceRecord } from '@/features/vehicles/Lib/retotalServiceRecord'
+import type { UpdateServiceInput } from '../Schema/serviceSchema'
+
+/**
+ * Writes an update of a work order: the fields in `data`, and only those.
+ * The caller has checked the lock and parsed the input (parseSentFields), so
+ * a field left out of `data` is a field left as it is.
+ *
+ * Two callers. updateServiceRecord takes the page's whole form, money and all,
+ * as it always has: a tab opened before a deploy still sends that. And
+ * saveServiceRecordChanges takes only what one tab edited, with no money at
+ * all: `retotal` then works the totals out here from the lines and the
+ * discount and tax as they are stored once this save is written, because a
+ * tab that changed only the discount cannot know the lines another tab saved.
+ */
+export async function writeServiceRecordUpdate(
+  { userId, organizationId }: { userId: string; organizationId: string },
+  data: UpdateServiceInput,
+  options: { retotal?: boolean } = {}
+) {
+  const timeZone = await workshopTimeZone(organizationId)
+  const existing = await db.serviceRecord.findFirst({
+    where: { id: data.id, organizationId },
+    include: {
+      attachments: { select: { fileUrl: true, category: true } },
+      vehicle: {
+        select: {
+          id: true,
+          mileage: true,
+          make: true,
+          model: true,
+          year: true,
+          licensePlate: true,
+        },
+      },
+    },
+  })
+  if (!existing) throw new Error('Service record not found')
+  // A save that leaves the job completed asks for its required meters
+  // first, on the vehicle it will be on, when it completes the job or
+  // moves a completed one to another vehicle; nothing of the save is
+  // written without them. Any other save is never asked.
+  const vehicleAfter = data.vehicleId !== undefined ? data.vehicleId : existing.vehicleId
+  const statusAfter = data.status ?? existing.status
+  if (
+    statusAfter === 'completed' &&
+    (existing.status !== 'completed' || vehicleAfter !== existing.vehicleId)
+  ) {
+    await assertRequiredMetersRead(
+      organizationId,
+      existing.id,
+      existing.status === 'completed' ? 'move' : 'complete',
+      { vehicleId: vehicleAfter }
+    )
+  }
+
+  const {
+    id,
+    partItems,
+    laborItems,
+    concerns,
+    attachments,
+    customerId: _cid,
+    serviceDate: _sd,
+    invoiceDate: _id,
+    invoiceDueDate: _idd,
+    warrantyStatus: _ws,
+    warrantyMonths: _wm,
+    warrantyMileage: _wmil,
+    warrantyNotes: _wn,
+    ...recordData
+  } = data
+
+  // The four warranty columns move together. A save that names any of them
+  // restates the whole warranty, with the row filling in what was left
+  // out, so they can never be left contradicting each other; and the
+  // expiry follows the service date even when only the date was changed.
+  const warrantyTouched =
+    data.warrantyStatus !== undefined ||
+    data.warrantyMonths !== undefined ||
+    data.warrantyMileage !== undefined ||
+    data.warrantyNotes !== undefined
+  const warranty = warrantyTouched
+    ? normalizeWarranty({
+        warrantyStatus: data.warrantyStatus ?? existing.warrantyStatus,
+        warrantyMonths: data.warrantyMonths ?? existing.warrantyMonths,
+        warrantyMileage: data.warrantyMileage ?? existing.warrantyMileage,
+        warrantyNotes: data.warrantyNotes ?? existing.warrantyNotes,
+      })
+    : null
+  const movedServiceDate =
+    data.serviceDate !== undefined ? toSafeWorkshopDate(data.serviceDate, timeZone) : undefined
+  const warrantyExpiresAt =
+    warranty || movedServiceDate
+      ? warrantyExpiryFor(
+          warranty ?? normalizeWarranty(existing),
+          movedServiceDate ?? existing.serviceDate,
+          timeZone
+        )
+      : undefined
+
+  // A job totalled with tax components keeps its split in step with the
+  // lines the client sent: the amounts are recomputed here from the
+  // components on the row, because the editor only knows the combined
+  // rate and must not leave the printed GST and QST lines stale.
+  //
+  // The same goes for a job with a line left out of the tax: what the
+  // tax is charged on comes from the lines as they are about to be
+  // stored, so it is worked out here and never taken from the caller.
+  // Lines the caller did not send are the ones already on the job.
+  const linesSent = partItems !== undefined || laborItems !== undefined
+  const taxApplies = linesSent ? await loadTaxApplies(organizationId) : null
+  const taxedParts =
+    partItems !== undefined && taxApplies ? withTaxableParts(partItems, taxApplies) : undefined
+  const taxedLabor =
+    laborItems !== undefined && taxApplies ? withTaxableLabor(laborItems, taxApplies) : undefined
+  // Lines are stored to the cent (serviceSchema). The subtotal the page
+  // sent was added up from its own figures, so it is restated from the
+  // lines as stored, and the discount and tax with it, or the invoice's
+  // lines would not add up to its subtotal. Only a save that sends money:
+  // one re-totalled from what is stored (below) never takes the page's.
+  let fromLines: ReturnType<typeof restatedSubtotal> = null
+  if (linesSent && recordData.subtotal !== undefined) {
+    const linesSubtotal = subtotalFromLines(
+      partItems ??
+        (await db.servicePart.findMany({
+          where: { serviceRecordId: id },
+          select: { total: true },
+        })),
+      laborItems ??
+        (await db.serviceLabor.findMany({
+          where: { serviceRecordId: id },
+          select: { total: true },
+        }))
+    )
+    fromLines = restatedSubtotal({
+      sentSubtotal: recordData.subtotal,
+      linesSubtotal,
+      discountType: recordData.discountType ?? existing.discountType,
+      discountValue: recordData.discountValue ?? existing.discountValue,
+    })
+    if (fromLines) {
+      recordData.subtotal = fromLines.subtotal
+      if (fromLines.discountAmount !== undefined) {
+        recordData.discountAmount = fromLines.discountAmount
+      }
+    }
+  }
+  const moneyTouched =
+    linesSent ||
+    recordData.subtotal !== undefined ||
+    recordData.discountAmount !== undefined ||
+    recordData.taxRate !== undefined
+  // A save that is re-totalled from what is stored works its money out once
+  // everything is written, below; this reckons from the caller's subtotal.
+  const savedTax =
+    moneyTouched && !options.retotal
+      ? savedDocumentTax({
+          subtotal: recordData.subtotal ?? existing.subtotal,
+          discountAmount: recordData.discountAmount ?? existing.discountAmount,
+          // A job with components keeps the rate they add up to.
+          taxRate: parseTaxComponentDefinitions(existing.taxComponents)
+            ? existing.taxRate
+            : (recordData.taxRate ?? existing.taxRate),
+          taxInclusive: recordData.taxInclusive ?? existing.taxInclusive,
+          taxComponents: existing.taxComponents,
+          parts:
+            taxedParts ??
+            (await db.servicePart.findMany({
+              where: { serviceRecordId: id },
+              select: { total: true, taxable: true },
+            })),
+          labor:
+            taxedLabor ??
+            (await db.serviceLabor.findMany({
+              where: { serviceRecordId: id },
+              select: { total: true, taxable: true, pricingType: true },
+            })),
+        })
+      : null
+  // The split is restated only by a save that restates the subtotal, as
+  // before; a job with untaxed lines is restated by any save that touches
+  // its money, since any of them moves what the tax is charged on.
+  const restated =
+    savedTax?.totals && (recordData.subtotal !== undefined || savedTax.taxableSubtotal !== null)
+      ? savedTax.totals
+      : null
+  if (restated) {
+    if (restated.taxComponents) recordData.taxRate = existing.taxRate
+    recordData.taxAmount = restated.taxAmount
+    recordData.totalAmount = restated.totalAmount
+  } else if (fromLines) {
+    // A plain job, every line taxed at one rate: its tax and total follow
+    // the restated subtotal too.
+    const totals = documentTotals({
+      subtotal: fromLines.subtotal,
+      discountAmount: recordData.discountAmount ?? existing.discountAmount,
+      taxRate: recordData.taxRate ?? existing.taxRate,
+      taxInclusive: recordData.taxInclusive ?? existing.taxInclusive,
+      taxComponents: existing.taxComponents,
+      taxableSubtotal: null,
+    })
+    recordData.taxAmount = totals.taxAmount
+    recordData.totalAmount = totals.totalAmount
+  }
+  if (fromLines && recordData.cost !== undefined && recordData.totalAmount !== undefined) {
+    // The page sends the job's cost as its total.
+    recordData.cost = recordData.totalAmount
+  }
+  // A job with components keeps the rate they add up to, here too.
+  if (options.retotal && parseTaxComponentDefinitions(existing.taxComponents)) {
+    delete recordData.taxRate
+  }
+
+  // A null vehicleId from the client means "no vehicle" (counter sale) —
+  // treat it as no-change rather than detaching an existing vehicle.
+  if (recordData.vehicleId == null) {
+    delete recordData.vehicleId
+  } else if (recordData.vehicleId !== existing.vehicleId) {
+    // Moving the record to another vehicle: it must belong to this org, and
+    // the record's customer then follows the vehicle again.
+    const targetVehicle = await db.vehicle.findFirst({
+      where: { id: recordData.vehicleId, organizationId },
+      select: { id: true },
+    })
+    if (!targetVehicle) throw new Error('Vehicle not found')
+  }
+
+  // Determine which categories are being replaced and which files were removed
+  let removedFileUrls: string[] = []
+  let categoriesToReplace: string[] = []
+  if (attachments !== undefined) {
+    categoriesToReplace = [...new Set(attachments.map((a) => a.category || 'diagnostic'))]
+    const existingInCategories = existing.attachments.filter((a) =>
+      categoriesToReplace.includes(a.category)
+    )
+    const newFileUrls = new Set(attachments.map((a) => a.fileUrl))
+    removedFileUrls = existingInCategories
+      .map((a) => a.fileUrl)
+      .filter((url) => !newFileUrls.has(url))
+  }
+
+  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: {
+        ...recordData,
+        // The form carries the stage, not the workshop's own status, which
+        // is chosen and saved on its own. So a save that moves the stage
+        // drops a status that belonged to the old one, and a save that
+        // leaves the stage alone leaves the status alone.
+        ...(recordData.status !== undefined && recordData.status !== existing.status
+          ? { customStatusId: null, customStatusSince: null }
+          : {}),
+        // Completed by this save: booked time still ahead is let go.
+        ...(recordData.status !== undefined ? slotOnCompletion(existing, recordData.status) : {}),
+        taxComponents: restated?.taxComponents,
+        ...(savedTax ? { taxableSubtotal: savedTax.taxableSubtotal } : {}),
+        // Attaching a vehicle to a counter sale: the direct customer link is
+        // cleared so the invoice follows the vehicle's customer again.
+        customerId:
+          recordData.vehicleId && recordData.vehicleId !== existing.vehicleId && existing.customerId
+            ? null
+            : undefined,
+        description:
+          recordData.description !== undefined ? recordData.description || null : undefined,
+        techName: recordData.techName !== undefined ? recordData.techName || null : undefined,
+        diagnosticNotes:
+          recordData.diagnosticNotes !== undefined ? recordData.diagnosticNotes || null : undefined,
+        invoiceNotes:
+          recordData.invoiceNotes !== undefined ? recordData.invoiceNotes || null : undefined,
+        invoiceNumber:
+          recordData.invoiceNumber !== undefined ? recordData.invoiceNumber || null : undefined,
+        mileage: recordData.mileage !== undefined ? (recordData.mileage ?? null) : undefined,
+        serviceDate: toSafeWorkshopDate(data.serviceDate, timeZone),
+        // An emptied date clears it; the invoice then falls back to the
+        // scheduled start or the service date, as it did before one was set.
+        invoiceDate:
+          data.invoiceDate !== undefined
+            ? (toSafeWorkshopDate(data.invoiceDate, timeZone) ?? null)
+            : undefined,
+        invoiceDueDate:
+          data.invoiceDueDate !== undefined
+            ? (toSafeWorkshopDate(data.invoiceDueDate, timeZone) ?? null)
+            : undefined,
+        ...(warranty ?? {}),
+        warrantyExpiresAt,
+      },
+    })
+
+    // Replace parts if provided
+    if (partItems !== undefined) {
+      // Snapshot the parts being replaced BEFORE deleting them, so inventory
+      // can be reconciled by the delta between the old and new linked parts
+      // (this is what keeps stock correct when parts are added, edited,
+      // reduced or removed on an existing work order).
+      const previousParts = await tx.servicePart.findMany({
+        where: { serviceRecordId: id },
+        select: { inventoryPartId: true, quantity: true },
+      })
+
+      await tx.servicePart.deleteMany({ where: { serviceRecordId: id } })
+      if (taxedParts && taxedParts.length > 0) {
+        await tx.servicePart.createMany({
+          data: taxedParts.map((p) => ({
+            partNumber: p.partNumber,
+            name: p.name,
+            quantity: p.quantity,
+            unit: p.unit ?? null,
+            category: p.category ?? null,
+            unitPrice: p.unitPrice,
+            total: p.total,
+            unitCost: p.unitCost ?? 0,
+            markupPercent: p.markupPercent ?? 0,
+            inventoryPartId: p.inventoryPartId || null,
+            taxable: p.taxable,
+            serviceRecordId: id,
+          })),
+        })
+      }
+
+      await reconcileInventoryForParts(tx, organizationId, previousParts, partItems, {
+        reason: 'service_record',
+        userId,
+        serviceRecordId: id,
+        serviceRecordLabel: existing.invoiceNumber || existing.title,
+      })
+    }
+
+    /**
+     * Reconcile concerns by id, rather than replacing them like the rows
+     * above.
+     *
+     * Parts and labour can be deleted and rewritten on every save because
+     * nothing points at them. Findings point at concerns, and the relation
+     * is SetNull, so deleting the whole list on an autosave would silently
+     * cut every diagnosis loose from the question it answered. The rows
+     * that survive an edit have to keep their ids.
+     */
+    if (concerns !== undefined) {
+      const existingConcerns = await tx.serviceConcern.findMany({
+        where: { serviceRecordId: id },
+        select: { id: true, confirmedAt: true, confirmedById: true },
+      })
+      const existingById = new Map(existingConcerns.map((concern) => [concern.id, concern]))
+      const now = new Date()
+      const keptIds = new Set(
+        concerns.map((concern) => concern.id).filter((cid): cid is string => Boolean(cid))
+      )
+
+      const removedIds = existingConcerns
+        .map((concern) => concern.id)
+        .filter((cid) => !keptIds.has(cid))
+      if (removedIds.length > 0) {
+        await tx.serviceConcern.deleteMany({ where: { id: { in: removedIds } } })
+      }
+
+      for (const [index, concern] of concerns.entries()) {
+        const sortOrder = concern.sortOrder ?? index
+        // An id the client sent that is not on this job is not ours to
+        // trust: fall through to a create rather than updating by id.
+        if (concern.id && keptIds.has(concern.id)) {
+          const { count } = await tx.serviceConcern.updateMany({
+            where: { id: concern.id, serviceRecordId: id },
+            data: {
+              description: concern.description,
+              sortOrder,
+              ...concernStoryData(concern, existingById.get(concern.id) ?? null, userId, now),
+            },
+          })
+          if (count > 0) continue
+        }
+        await tx.serviceConcern.create({
+          data: {
+            description: concern.description,
+            sortOrder,
+            serviceRecordId: id,
+            ...concernStoryData(concern, null, userId, now),
+          },
+        })
+      }
+    }
+
+    // Replace labor if provided
+    if (laborItems !== undefined) {
+      await tx.serviceLabor.deleteMany({ where: { serviceRecordId: id } })
+      if (taxedLabor && taxedLabor.length > 0) {
+        await tx.serviceLabor.createMany({
+          data: taxedLabor.map((l) => ({
+            ...l,
+            serviceRecordId: id,
+          })),
+        })
+      }
+    }
+
+    // Replace attachments if provided (only for the categories included in the payload)
+    if (attachments !== undefined) {
+      if (categoriesToReplace.length > 0) {
+        await tx.serviceAttachment.deleteMany({
+          where: { serviceRecordId: id, category: { in: categoriesToReplace } },
+        })
+      }
+      if (attachments.length > 0) {
+        await tx.serviceAttachment.createMany({
+          data: attachments.map((a) => ({
+            ...a,
+            serviceRecordId: id,
+          })),
+        })
+      }
+    }
+
+    // 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 })
+      // Its meter readings stay in the old vehicle's history, no longer the job's.
+      await unlinkJobMeterReadingsFromOtherVehicles(tx, {
+        organizationId,
+        jobId: id,
+        vehicleId: updated.vehicleId,
+      })
+      // And it no longer works on the old vehicle's equipment.
+      await tx.serviceRecordEquipment.deleteMany({
+        where: {
+          organizationId,
+          serviceRecordId: id,
+          ...(updated.vehicleId ? { item: { vehicleId: { not: updated.vehicleId } } } : {}),
+        },
+      })
+    }
+    if (updated.vehicleId && (recordData.mileage !== undefined || !sameVehicle)) {
+      await applyJobReading(tx, {
+        organizationId,
+        vehicleId: updated.vehicleId,
+        jobId: id,
+        jobDate: jobReadingDate(updated),
+        reading: updated.mileage,
+        previousReading: sameVehicle ? (before ? before.mileage : existing.mileage) : undefined,
+      })
+    }
+
+    // The money of a save that sent none: worked out from the lines, the
+    // discount and the tax as they are stored now, whoever wrote each of
+    // them. Only when this save moved something the money is made of.
+    if (
+      options.retotal &&
+      (linesSent ||
+        data.discountType !== undefined ||
+        data.discountValue !== undefined ||
+        data.taxRate !== undefined)
+    ) {
+      await retotalServiceRecord(id, tx)
+      const totals = await tx.serviceRecord.findUniqueOrThrow({
+        where: { id },
+        select: { totalAmount: true },
+      })
+      return tx.serviceRecord.update({ where: { id }, data: { cost: totals.totalAmount } })
+    }
+
+    return updated
+  })
+
+  // Files of removed attachments, let go after the transaction committed.
+  await releaseFiles(removedFileUrls, {
+    organizationId,
+    reason: 'work order attachments replaced',
+  })
+
+  // Notify workboard if status changed
+  if (record.status !== existing.status) {
+    notificationBus.emit('workboard', {
+      type: 'job_status_changed',
+      organizationId,
+      serviceRecordId: id,
+      status: record.status,
+      serviceRecord: {
+        id: existing.id,
+        title: record.title || existing.title,
+        status: record.status,
+        vehicle: existing.vehicle,
+      },
+    })
+  }
+
+  revalidatePath('/')
+  if (existing.vehicleId) {
+    revalidatePath(`/vehicles/${existing.vehicleId}`)
+    revalidatePath(`/vehicles/${existing.vehicleId}/service/${id}`)
+  } else {
+    revalidatePath(`/sales/${id}`)
+  }
+  revalidatePath('/services')
+  // Parts may have been added, changed or removed on this record.
+  await onInventoryChanged(organizationId)
+  return record
+}

+ 21 - 0
src/features/vehicles/Schema/serviceSchema.ts

@@ -165,6 +165,27 @@ export const updateServiceSchema = createServiceSchema.partial().extend({
   id: z.string(),
 })
 
+/**
+ * What one tab of a work order changed (saveServiceRecordChanges). The money
+ * is not among it: the server reckons the totals from what is stored, so a
+ * tab holding an old copy of the lines cannot write totals that belong to
+ * them. Nor the fields the page has no control for.
+ */
+export const saveServiceChangesSchema = updateServiceSchema.omit({
+  customerId: true,
+  cost: true,
+  shopName: true,
+  techName: true,
+  parts: true,
+  laborHours: true,
+  attachments: true,
+  subtotal: true,
+  taxAmount: true,
+  taxInclusive: true,
+  totalAmount: true,
+  discountAmount: true,
+})
+
 export type ServiceAttachmentInput = z.infer<typeof serviceAttachmentSchema>
 export type ServiceConcernInput = z.infer<typeof serviceConcernSchema>
 /**