Selaa lähdekoodia

Apply line limits to quotes, mark an absurd amount on the work order, and other follow-ups (#690)

* Apply line limits to quotes, mark an absurd amount on the work order, and other follow-ups

* Keep the totals labels readable beside an absurd amount

* Stop convert, PDF and send when a quote save is refused, and keep quote totals to the stored lines

* Await the quote save from the save shortcut
Bernt Christian Egeland 2 päivää sitten
vanhempi
sitoutus
0cd95d62c7
46 muutettua tiedostoa jossa 1854 lisäystä ja 236 poistoa
  1. 85 0
      e2e/specs/quotes/line-limits.spec.ts
  2. 17 0
      e2e/specs/work-orders/validation.spec.ts
  3. 1 1
      messages/bg/audit.json
  4. 1 1
      messages/de/audit.json
  5. 1 1
      messages/en/audit.json
  6. 1 1
      messages/es/audit.json
  7. 1 1
      messages/fr/audit.json
  8. 1 1
      messages/it/audit.json
  9. 1 1
      messages/lt/audit.json
  10. 1 1
      messages/nb/audit.json
  11. 1 1
      messages/nl/audit.json
  12. 1 1
      messages/pl/audit.json
  13. 1 1
      messages/pt-BR/audit.json
  14. 1 1
      messages/pt-PT/audit.json
  15. 1 1
      messages/ru/audit.json
  16. 1 1
      messages/tr/audit.json
  17. 111 0
      src/__tests__/features/payments/payment-audit-names-job.test.ts
  18. 254 0
      src/__tests__/features/quotes/quote-line-limits.test.tsx
  19. 278 0
      src/__tests__/features/quotes/quote-save-refused-follow-ups.test.tsx
  20. 85 0
      src/__tests__/features/tax/taxable-lines-save.test.ts
  21. 174 0
      src/__tests__/features/workorders/absurd-amount-marked.test.tsx
  22. 76 0
      src/__tests__/lib/settings-links-need-read.test.ts
  23. 11 7
      src/app/(authenticated)/audit-log/audit-log-client.tsx
  24. 2 2
      src/app/(authenticated)/tire-hotel/[id]/page.tsx
  25. 2 2
      src/app/(authenticated)/tire-hotel/storage/page.tsx
  26. 38 0
      src/components/field-errors.tsx
  27. 32 0
      src/features/audit/Lib/summaryParams.ts
  28. 2 2
      src/features/integrations/Actions/vehicleLookupActions.ts
  29. 9 3
      src/features/payments/Actions/paymentActions.ts
  30. 56 1
      src/features/quotes/Actions/quoteActions.ts
  31. 48 20
      src/features/quotes/Components/QuoteLaborEditor.tsx
  32. 6 5
      src/features/quotes/Components/QuotePageClient.tsx
  33. 61 29
      src/features/quotes/Components/QuotePartsEditor.tsx
  34. 85 18
      src/features/quotes/Components/useQuoteFormState.ts
  35. 25 2
      src/features/quotes/Lib/createQuoteRecord.ts
  36. 48 0
      src/features/quotes/Lib/validateQuoteLines.ts
  37. 79 44
      src/features/quotes/Schema/quoteSchema.ts
  38. 2 2
      src/features/vehicles/Actions/aiAnalyzeVehicleDocument.ts
  39. 5 3
      src/features/vehicles/Components/service-detail/PaymentsSection.tsx
  40. 45 19
      src/features/vehicles/Components/service-edit/LaborEditor.tsx
  41. 65 33
      src/features/vehicles/Components/service-edit/PartsEditor.tsx
  42. 15 6
      src/features/vehicles/Components/service-edit/TotalsSection.tsx
  43. 6 4
      src/features/vehicles/Components/service-page/ServiceRecordPage.tsx
  44. 34 18
      src/features/vehicles/Components/service-page/modern/MoneyBar.tsx
  45. 10 2
      src/features/vehicles/Components/service-page/useServiceActions.ts
  46. 74 0
      src/lib/input-limits.ts

+ 85 - 0
e2e/specs/quotes/line-limits.spec.ts

@@ -0,0 +1,85 @@
+import { expect, type Page, test } from '@playwright/test'
+import { ownerOrganizationId, plantQuote, quoteConversion, userIdFor } from '../../support/db'
+import { addQuotePart, newQuote } from '../../support/quote'
+import {
+  newOrderRadio,
+  openConvertDialog,
+  plantVehicle,
+  type PlantedVehicle,
+} from '../../support/quote-conversion'
+
+/**
+ * A quote's lines are held to the work order's rules.
+ *
+ * A quote took a priced part at a quantity of zero and a billion parts at a
+ * hundred million each, which a work order refuses. The figure is now
+ * marked under its field as it is typed and the save says why; a quote
+ * written before the rules still opens and converts as it is.
+ */
+
+test.describe.configure({ mode: 'serial' })
+
+const stamp = Date.now()
+const OWNER = 'demo@torqvoice.com'
+
+/** Clicks Save and expects it to be refused with one sentence. */
+async function expectRefused(page: Page, message: RegExp) {
+  await page.getByRole('button', { name: 'Save', exact: true }).click()
+  await expect(page.getByText(message).filter({ visible: true }).first()).toBeVisible()
+  await expect(page.getByText('Quote saved')).toHaveCount(0)
+}
+
+test.describe('a quote line the save would refuse', () => {
+  test('a priced part at a quantity of zero is marked and refused', async ({ page }) => {
+    await newQuote(page, `E2E quote zero quantity ${stamp}`)
+    await addQuotePart(page, { name: `E2E pads ${stamp}`, quantity: 0, unitPrice: 200 })
+
+    const quantity = page.getByRole('spinbutton', { description: 'Must be more than 0.' })
+    await expect(quantity).toBeVisible()
+    await expect(quantity).toHaveAttribute('aria-invalid', 'true')
+
+    await expectRefused(page, /needs a quantity above zero/i)
+    await expect(quantity).toBeFocused()
+  })
+
+  test('a billion parts at a hundred million each is marked and refused', async ({ page }) => {
+    await newQuote(page, `E2E quote absurd ${stamp}`)
+    await addQuotePart(page, {
+      name: `E2E discs ${stamp}`,
+      quantity: 1_000_000_000,
+      unitPrice: 99_999_999,
+    })
+
+    await expect(
+      page.getByRole('spinbutton', { description: 'Must be 100,000 or less.' })
+    ).toBeVisible()
+    await expect(page.getByText('Must be 1,000,000,000 or less.')).toBeVisible()
+    await expectRefused(page, /figure is too large/i)
+  })
+})
+
+test.describe('a quote saved before the limits', () => {
+  let vehicle: PlantedVehicle
+  let quoteId = ''
+
+  test.beforeAll(async () => {
+    vehicle = await plantVehicle(`Limits${String(stamp).slice(-6)}`)
+    quoteId = await plantQuote(await ownerOrganizationId(OWNER), await userIdFor(OWNER), {
+      vehicleId: vehicle.id,
+      title: `E2E quote from before the limits ${stamp}`,
+      parts: [{ name: `E2E old line ${stamp}`, quantity: 1_000_000_000, unitPrice: 99_999_999 }],
+    })
+  })
+
+  test('still opens and converts to a work order', async ({ page }) => {
+    await page.goto(`/quotes/${quoteId}`)
+    await expect(page.locator('#title')).toHaveValue(`E2E quote from before the limits ${stamp}`)
+
+    const dialog = await openConvertDialog(page)
+    await expect(newOrderRadio(dialog)).toBeChecked({ timeout: 15_000 })
+    await dialog.getByRole('button', { name: 'Convert', exact: true }).click()
+    await page.waitForURL(/\/(vehicles\/[^/]+\/service|sales)\/[^/]+$/, { timeout: 60_000 })
+
+    expect((await quoteConversion(quoteId)).status).toBe('converted')
+  })
+})

+ 17 - 0
e2e/specs/work-orders/validation.spec.ts

@@ -133,7 +133,24 @@ test.describe('a work order that cannot be saved says why', () => {
       await expect(quantity).toHaveValue('0', { timeout: 2_000 })
       await expect(quantity).toHaveValue('0', { timeout: 2_000 })
     }).toPass({ timeout: 30_000 })
     }).toPass({ timeout: 30_000 })
 
 
+    // Marked where it was typed, and where the refused save leaves the cursor.
+    await expect(quantity).toHaveAccessibleDescription('Must be more than 0.')
     await expectRefused(page, /needs a quantity above zero/i)
     await expectRefused(page, /needs a quantity above zero/i)
+    await expect(quantity).toBeFocused()
+  })
+
+  test('a billion parts at a hundred million each is marked under the field', async ({ page }) => {
+    await page.goto(jobUrl)
+    const row = partRowOf(partRows(page).first())
+    const quantity = row.locator('input[type="number"]').first()
+    await expect(async () => {
+      await quantity.fill('1000000000')
+      await expect(quantity).toHaveValue('1000000000', { timeout: 2_000 })
+    }).toPass({ timeout: 30_000 })
+
+    await expect(quantity).toHaveAccessibleDescription('Must be 100,000 or less.')
+    await expectRefused(page, /figure is too large/i)
+    await expect(quantity).toBeFocused()
   })
   })
 
 
   test('a negative reading is refused in words', async ({ page }) => {
   test('a negative reading is refused in words', async ({ page }) => {

+ 1 - 1
messages/bg/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "Изтрита бележка {id}",
     "note_delete": "Изтрита бележка {id}",
     "organization_create": "Създадена организация „{name}“",
     "organization_create": "Създадена организация „{name}“",
     "organization_sampleDataRemove": "Премахнати примерните данни за първоначално запознаване",
     "organization_sampleDataRemove": "Премахнати примерните данни за първоначално запознаване",
-    "payment_create": "Записано плащане {amount} за сервизен запис {serviceRecordId}",
+    "payment_create": "Записано плащане {amount} за сервизен запис {ref}",
     "payment_delete": "Изтрито плащане {id}",
     "payment_delete": "Изтрито плащане {id}",
     "quoteRequest_update": "Променен статус на заявката за оферта на {status, select, pending {изчакваща} approved {одобрена} rejected {отхвърлена} completed {завършена} other {{status}}}",
     "quoteRequest_update": "Променен статус на заявката за оферта на {status, select, pending {изчакваща} approved {одобрена} rejected {отхвърлена} completed {завършена} other {{status}}}",
     "quote_convert": "Преобразувана оферта {ref} в сервизен запис {serviceRecordId}",
     "quote_convert": "Преобразувана оферта {ref} в сервизен запис {serviceRecordId}",

+ 1 - 1
messages/de/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "Notiz {id} gelöscht",
     "note_delete": "Notiz {id} gelöscht",
     "organization_create": "Organisation „{name}“ angelegt",
     "organization_create": "Organisation „{name}“ angelegt",
     "organization_sampleDataRemove": "Beispieldaten aus der Einrichtung entfernt",
     "organization_sampleDataRemove": "Beispieldaten aus der Einrichtung entfernt",
-    "payment_create": "Zahlung {amount} zum Auftrag {serviceRecordId} erfasst",
+    "payment_create": "Zahlung {amount} zum Auftrag {ref} erfasst",
     "payment_delete": "Zahlung {id} gelöscht",
     "payment_delete": "Zahlung {id} gelöscht",
     "quoteRequest_update": "Status der Angebotsanfrage geändert auf {status, select, pending {offen} approved {genehmigt} rejected {abgelehnt} completed {abgeschlossen} other {{status}}}",
     "quoteRequest_update": "Status der Angebotsanfrage geändert auf {status, select, pending {offen} approved {genehmigt} rejected {abgelehnt} completed {abgeschlossen} other {{status}}}",
     "quote_convert": "Angebot {ref} in Auftrag {serviceRecordId} umgewandelt",
     "quote_convert": "Angebot {ref} in Auftrag {serviceRecordId} umgewandelt",

+ 1 - 1
messages/en/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "Deleted note {id}",
     "note_delete": "Deleted note {id}",
     "organization_create": "Created organization \"{name}\"",
     "organization_create": "Created organization \"{name}\"",
     "organization_sampleDataRemove": "Removed onboarding sample data",
     "organization_sampleDataRemove": "Removed onboarding sample data",
-    "payment_create": "Recorded payment {amount} for service {serviceRecordId}",
+    "payment_create": "Recorded payment {amount} for service {ref}",
     "payment_delete": "Deleted payment {id}",
     "payment_delete": "Deleted payment {id}",
     "quoteRequest_update": "Updated quote request status to {status, select, pending {pending} approved {approved} rejected {rejected} completed {completed} other {{status}}}",
     "quoteRequest_update": "Updated quote request status to {status, select, pending {pending} approved {approved} rejected {rejected} completed {completed} other {{status}}}",
     "quote_convert": "Converted quote {ref} to service record {serviceRecordId}",
     "quote_convert": "Converted quote {ref} to service record {serviceRecordId}",

+ 1 - 1
messages/es/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "Nota {id} eliminada",
     "note_delete": "Nota {id} eliminada",
     "organization_create": "Organización «{name}» creada",
     "organization_create": "Organización «{name}» creada",
     "organization_sampleDataRemove": "Datos de ejemplo de la puesta en marcha eliminados",
     "organization_sampleDataRemove": "Datos de ejemplo de la puesta en marcha eliminados",
-    "payment_create": "Pago {amount} registrado para el servicio {serviceRecordId}",
+    "payment_create": "Pago {amount} registrado para el servicio {ref}",
     "payment_delete": "Pago {id} eliminado",
     "payment_delete": "Pago {id} eliminado",
     "quoteRequest_update": "Estado de la solicitud de presupuesto cambiado a {status, select, pending {pendiente} approved {aprobada} rejected {rechazada} completed {completada} other {{status}}}",
     "quoteRequest_update": "Estado de la solicitud de presupuesto cambiado a {status, select, pending {pendiente} approved {aprobada} rejected {rechazada} completed {completada} other {{status}}}",
     "quote_convert": "Presupuesto {ref} convertido en servicio {serviceRecordId}",
     "quote_convert": "Presupuesto {ref} convertido en servicio {serviceRecordId}",

+ 1 - 1
messages/fr/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "Note {id} supprimée",
     "note_delete": "Note {id} supprimée",
     "organization_create": "Organisation « {name} » créée",
     "organization_create": "Organisation « {name} » créée",
     "organization_sampleDataRemove": "Données d'exemple de la mise en route supprimées",
     "organization_sampleDataRemove": "Données d'exemple de la mise en route supprimées",
-    "payment_create": "Paiement {amount} enregistré pour l'intervention {serviceRecordId}",
+    "payment_create": "Paiement {amount} enregistré pour l'intervention {ref}",
     "payment_delete": "Paiement {id} supprimé",
     "payment_delete": "Paiement {id} supprimé",
     "quoteRequest_update": "Statut de la demande de devis passé à {status, select, pending {en attente} approved {approuvée} rejected {refusée} completed {terminée} other {{status}}}",
     "quoteRequest_update": "Statut de la demande de devis passé à {status, select, pending {en attente} approved {approuvée} rejected {refusée} completed {terminée} other {{status}}}",
     "quote_convert": "Devis {ref} converti en intervention {serviceRecordId}",
     "quote_convert": "Devis {ref} converti en intervention {serviceRecordId}",

+ 1 - 1
messages/it/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "Nota {id} eliminata",
     "note_delete": "Nota {id} eliminata",
     "organization_create": "Organizzazione «{name}» creata",
     "organization_create": "Organizzazione «{name}» creata",
     "organization_sampleDataRemove": "Dati di esempio dell'avvio rimossi",
     "organization_sampleDataRemove": "Dati di esempio dell'avvio rimossi",
-    "payment_create": "Pagamento {amount} registrato per l'intervento {serviceRecordId}",
+    "payment_create": "Pagamento {amount} registrato per l'intervento {ref}",
     "payment_delete": "Pagamento {id} eliminato",
     "payment_delete": "Pagamento {id} eliminato",
     "quoteRequest_update": "Stato della richiesta di preventivo cambiato in {status, select, pending {in attesa} approved {approvata} rejected {rifiutata} completed {completata} other {{status}}}",
     "quoteRequest_update": "Stato della richiesta di preventivo cambiato in {status, select, pending {in attesa} approved {approvata} rejected {rifiutata} completed {completata} other {{status}}}",
     "quote_convert": "Preventivo {ref} convertito nell'intervento {serviceRecordId}",
     "quote_convert": "Preventivo {ref} convertito nell'intervento {serviceRecordId}",

+ 1 - 1
messages/lt/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "Ištrintas užrašas {id}",
     "note_delete": "Ištrintas užrašas {id}",
     "organization_create": "Sukurta organizacija „{name}“",
     "organization_create": "Sukurta organizacija „{name}“",
     "organization_sampleDataRemove": "Pašalinti pradinės sąrankos pavyzdiniai duomenys",
     "organization_sampleDataRemove": "Pašalinti pradinės sąrankos pavyzdiniai duomenys",
-    "payment_create": "Užregistruotas mokėjimas {amount} už darbą {serviceRecordId}",
+    "payment_create": "Užregistruotas mokėjimas {amount} už darbą {ref}",
     "payment_delete": "Ištrintas mokėjimas {id}",
     "payment_delete": "Ištrintas mokėjimas {id}",
     "quoteRequest_update": "Pasiūlymo užklausos būsena pakeista į „{status, select, pending {laukiama} approved {patvirtinta} rejected {atmesta} completed {užbaigta} other {{status}}}“",
     "quoteRequest_update": "Pasiūlymo užklausos būsena pakeista į „{status, select, pending {laukiama} approved {patvirtinta} rejected {atmesta} completed {užbaigta} other {{status}}}“",
     "quote_convert": "Pasiūlymas {ref} paverstas darbu {serviceRecordId}",
     "quote_convert": "Pasiūlymas {ref} paverstas darbu {serviceRecordId}",

+ 1 - 1
messages/nb/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "Slettet notat {id}",
     "note_delete": "Slettet notat {id}",
     "organization_create": "Opprettet organisasjon «{name}»",
     "organization_create": "Opprettet organisasjon «{name}»",
     "organization_sampleDataRemove": "Fjernet eksempeldata fra oppstarten",
     "organization_sampleDataRemove": "Fjernet eksempeldata fra oppstarten",
-    "payment_create": "Registrerte betaling {amount} for jobb {serviceRecordId}",
+    "payment_create": "Registrerte betaling {amount} for jobb {ref}",
     "payment_delete": "Slettet betaling {id}",
     "payment_delete": "Slettet betaling {id}",
     "quoteRequest_update": "Endret status på tilbudsforespørsel til {status, select, pending {venter} approved {godkjent} rejected {avslått} completed {fullført} other {{status}}}",
     "quoteRequest_update": "Endret status på tilbudsforespørsel til {status, select, pending {venter} approved {godkjent} rejected {avslått} completed {fullført} other {{status}}}",
     "quote_convert": "Gjorde tilbud {ref} om til jobb {serviceRecordId}",
     "quote_convert": "Gjorde tilbud {ref} om til jobb {serviceRecordId}",

+ 1 - 1
messages/nl/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "Notitie {id} verwijderd",
     "note_delete": "Notitie {id} verwijderd",
     "organization_create": "Organisatie \"{name}\" aangemaakt",
     "organization_create": "Organisatie \"{name}\" aangemaakt",
     "organization_sampleDataRemove": "Voorbeeldgegevens uit de installatie verwijderd",
     "organization_sampleDataRemove": "Voorbeeldgegevens uit de installatie verwijderd",
-    "payment_create": "Betaling {amount} geregistreerd voor opdracht {serviceRecordId}",
+    "payment_create": "Betaling {amount} geregistreerd voor opdracht {ref}",
     "payment_delete": "Betaling {id} verwijderd",
     "payment_delete": "Betaling {id} verwijderd",
     "quoteRequest_update": "Status van offerteaanvraag gewijzigd naar {status, select, pending {in behandeling} approved {goedgekeurd} rejected {afgewezen} completed {afgerond} other {{status}}}",
     "quoteRequest_update": "Status van offerteaanvraag gewijzigd naar {status, select, pending {in behandeling} approved {goedgekeurd} rejected {afgewezen} completed {afgerond} other {{status}}}",
     "quote_convert": "Offerte {ref} omgezet naar opdracht {serviceRecordId}",
     "quote_convert": "Offerte {ref} omgezet naar opdracht {serviceRecordId}",

+ 1 - 1
messages/pl/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "Usunięto notatkę {id}",
     "note_delete": "Usunięto notatkę {id}",
     "organization_create": "Utworzono organizację „{name}”",
     "organization_create": "Utworzono organizację „{name}”",
     "organization_sampleDataRemove": "Usunięto dane przykładowe z konfiguracji startowej",
     "organization_sampleDataRemove": "Usunięto dane przykładowe z konfiguracji startowej",
-    "payment_create": "Zarejestrowano płatność {amount} do zlecenia {serviceRecordId}",
+    "payment_create": "Zarejestrowano płatność {amount} do zlecenia {ref}",
     "payment_delete": "Usunięto płatność {id}",
     "payment_delete": "Usunięto płatność {id}",
     "quoteRequest_update": "Zmieniono status zapytania o wycenę na {status, select, pending {oczekujące} approved {zatwierdzone} rejected {odrzucone} completed {zakończone} other {{status}}}",
     "quoteRequest_update": "Zmieniono status zapytania o wycenę na {status, select, pending {oczekujące} approved {zatwierdzone} rejected {odrzucone} completed {zakończone} other {{status}}}",
     "quote_convert": "Przekształcono wycenę {ref} w zlecenie {serviceRecordId}",
     "quote_convert": "Przekształcono wycenę {ref} w zlecenie {serviceRecordId}",

+ 1 - 1
messages/pt-BR/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "Nota {id} excluída",
     "note_delete": "Nota {id} excluída",
     "organization_create": "Organização \"{name}\" criada",
     "organization_create": "Organização \"{name}\" criada",
     "organization_sampleDataRemove": "Dados de exemplo da configuração inicial removidos",
     "organization_sampleDataRemove": "Dados de exemplo da configuração inicial removidos",
-    "payment_create": "Pagamento {amount} registrado para o serviço {serviceRecordId}",
+    "payment_create": "Pagamento {amount} registrado para o serviço {ref}",
     "payment_delete": "Pagamento {id} excluído",
     "payment_delete": "Pagamento {id} excluído",
     "quoteRequest_update": "Status da solicitação de orçamento alterado para {status, select, pending {pendente} approved {aprovada} rejected {recusada} completed {concluída} other {{status}}}",
     "quoteRequest_update": "Status da solicitação de orçamento alterado para {status, select, pending {pendente} approved {aprovada} rejected {recusada} completed {concluída} other {{status}}}",
     "quote_convert": "Orçamento {ref} convertido no serviço {serviceRecordId}",
     "quote_convert": "Orçamento {ref} convertido no serviço {serviceRecordId}",

+ 1 - 1
messages/pt-PT/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "Nota {id} eliminada",
     "note_delete": "Nota {id} eliminada",
     "organization_create": "Organização \"{name}\" criada",
     "organization_create": "Organização \"{name}\" criada",
     "organization_sampleDataRemove": "Dados de exemplo da configuração inicial removidos",
     "organization_sampleDataRemove": "Dados de exemplo da configuração inicial removidos",
-    "payment_create": "Pagamento de {amount} registado no serviço {serviceRecordId}",
+    "payment_create": "Pagamento de {amount} registado no serviço {ref}",
     "payment_delete": "Pagamento {id} eliminado",
     "payment_delete": "Pagamento {id} eliminado",
     "quoteRequest_update": "Estado do pedido de orçamento alterado para {status, select, pending {pendente} approved {aprovado} rejected {recusado} completed {concluído} other {{status}}}",
     "quoteRequest_update": "Estado do pedido de orçamento alterado para {status, select, pending {pendente} approved {aprovado} rejected {recusado} completed {concluído} other {{status}}}",
     "quote_convert": "Orçamento {ref} convertido no registo de serviço {serviceRecordId}",
     "quote_convert": "Orçamento {ref} convertido no registo de serviço {serviceRecordId}",

+ 1 - 1
messages/ru/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "Удалена заметка {id}",
     "note_delete": "Удалена заметка {id}",
     "organization_create": "Создана организация «{name}»",
     "organization_create": "Создана организация «{name}»",
     "organization_sampleDataRemove": "Удалены demo-данные первичной настройки",
     "organization_sampleDataRemove": "Удалены demo-данные первичной настройки",
-    "payment_create": "Записан платёж {amount} по заказу {serviceRecordId}",
+    "payment_create": "Записан платёж {amount} по заказу {ref}",
     "payment_delete": "Удалён платёж {id}",
     "payment_delete": "Удалён платёж {id}",
     "quoteRequest_update": "Статус запроса на предложение изменён на «{status, select, pending {в ожидании} approved {одобрен} rejected {отклонён} completed {завершён} other {{status}}}»",
     "quoteRequest_update": "Статус запроса на предложение изменён на «{status, select, pending {в ожидании} approved {одобрен} rejected {отклонён} completed {завершён} other {{status}}}»",
     "quote_convert": "Предложение {ref} преобразовано в заказ {serviceRecordId}",
     "quote_convert": "Предложение {ref} преобразовано в заказ {serviceRecordId}",

+ 1 - 1
messages/tr/audit.json

@@ -276,7 +276,7 @@
     "note_delete": "{id} notu silindi",
     "note_delete": "{id} notu silindi",
     "organization_create": "\"{name}\" organizasyonu oluşturuldu",
     "organization_create": "\"{name}\" organizasyonu oluşturuldu",
     "organization_sampleDataRemove": "Kuruluma ait örnek veriler kaldırıldı",
     "organization_sampleDataRemove": "Kuruluma ait örnek veriler kaldırıldı",
-    "payment_create": "{serviceRecordId} işi için {amount} tutarında ödeme kaydedildi",
+    "payment_create": "{ref} işi için {amount} tutarında ödeme kaydedildi",
     "payment_delete": "{id} ödemesi silindi",
     "payment_delete": "{id} ödemesi silindi",
     "quoteRequest_update": "Teklif talebinin durumu {status, select, pending {beklemede} approved {onaylandı} rejected {reddedildi} completed {tamamlandı} other {{status}}} olarak değiştirildi",
     "quoteRequest_update": "Teklif talebinin durumu {status, select, pending {beklemede} approved {onaylandı} rejected {reddedildi} completed {tamamlandı} other {{status}}} olarak değiştirildi",
     "quote_convert": "{ref} teklifi {serviceRecordId} iş kaydına dönüştürüldü",
     "quote_convert": "{ref} teklifi {serviceRecordId} iş kaydına dönüştürüldü",

+ 111 - 0
src/__tests__/features/payments/payment-audit-names-job.test.ts

@@ -0,0 +1,111 @@
+/**
+ * The audit log names the job a payment was taken on as people know it.
+ *
+ * "Recorded payment 100 for service cmwv5zy…" gave the record's database id
+ * and a bare number. The row now carries the job's invoice number (or its
+ * title while it has none) and the workshop's currency, and the log reads
+ * "Recorded payment £100.00 for service INV-1001". Rows written before keep
+ * reading as they did, with the id.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { IntlMessageFormat } from 'intl-messageformat'
+import audit from '../../../../messages/en/audit.json'
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}))
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
+vi.mock('@/lib/audit', () => ({ logAudit: vi.fn() }))
+vi.mock('@/features/invoices/Lib/issueInvoice', () => ({
+  issueInvoice: vi.fn().mockResolvedValue(false),
+}))
+vi.mock('@/lib/workshop-timezone', () => ({
+  workshopTimeZone: vi.fn().mockResolvedValue('Pacific/Auckland'),
+}))
+
+const tx = {
+  $queryRaw: vi.fn(),
+  payment: { aggregate: vi.fn(), create: vi.fn() },
+}
+vi.mock('@/lib/db', () => ({
+  db: {
+    user: { findUnique: vi.fn() },
+    appSetting: { findMany: vi.fn() },
+    serviceRecord: { findFirst: vi.fn() },
+    $transaction: vi.fn(),
+  },
+}))
+
+import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
+import { db } from '@/lib/db'
+import { logAudit } from '@/lib/audit'
+import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
+import { createPayment } from '@/features/payments/Actions/paymentActions'
+import { auditSummaryParams } from '@/features/audit/Lib/summaryParams'
+import { formatCurrency } from '@/lib/format'
+
+function job(fields: { invoiceNumber: string | null; title: string }) {
+  vi.mocked(db.serviceRecord.findFirst).mockResolvedValue({
+    id: 'cmwv5zyjob',
+    vehicleId: 'v-1',
+    ...fields,
+  } as any)
+}
+
+const pay = () =>
+  createPayment({ serviceRecordId: 'cmwv5zyjob', amount: 100, date: '2026-11-24', method: 'card' })
+
+/** The audit row's sentence as the log reads it in English. */
+function sentence(params: Record<string, string | number> | undefined) {
+  const ready = auditSummaryParams(params, {
+    connectorName: () => null,
+    formatCurrency: (amount, code) => formatCurrency(amount, code),
+  })
+  return new IntlMessageFormat(audit.summary.payment_create, 'en').format(ready)
+}
+
+const loggedParams = () =>
+  (vi.mocked(logAudit).mock.calls[0][1] as { details: { params: Record<string, string | number> } })
+    .details.params
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  vi.mocked(getCachedSession).mockResolvedValue({ user: { id: 'user-1' } } as any)
+  vi.mocked(getCachedMembership).mockResolvedValue({
+    organizationId: 'org-1',
+    role: 'owner',
+    roleId: null,
+    customRole: null,
+  } as any)
+  vi.mocked(db.user.findUnique).mockResolvedValue({ isSuperAdmin: false } as any)
+  vi.mocked(db.appSetting.findMany).mockResolvedValue([
+    { key: SETTING_KEYS.CURRENCY_CODE, value: 'GBP' },
+  ] as any)
+  vi.mocked(db.$transaction).mockImplementation(async (cb: any) => cb(tx))
+  tx.$queryRaw.mockResolvedValue([{ totalAmount: 500, cost: 0 }])
+  tx.payment.aggregate.mockResolvedValue({ _sum: { amount: 0 } })
+  tx.payment.create.mockImplementation(async ({ data }: any) => ({ id: 'pay-1', ...data }))
+})
+
+describe('the audit row for a payment', () => {
+  it('names the job by its invoice number, with the amount in the workshop currency', async () => {
+    job({ invoiceNumber: 'INV-1001', title: 'Brake service' })
+    expect((await pay()).success).toBe(true)
+
+    expect(loggedParams()).toEqual({ amount: 100, currency: 'GBP', ref: 'INV-1001' })
+    expect(sentence(loggedParams())).toBe('Recorded payment £100.00 for service INV-1001')
+  })
+
+  it('names a job with no invoice number yet by its title', async () => {
+    job({ invoiceNumber: null, title: 'Brake service' })
+    await pay()
+    expect(loggedParams()).toMatchObject({ ref: 'Brake service' })
+  })
+
+  it('still reads, with the id, for a row written before', () => {
+    expect(sentence({ amount: 100, serviceRecordId: 'cmwv5zyjob' })).toBe(
+      'Recorded payment 100 for service cmwv5zyjob'
+    )
+  })
+})

+ 254 - 0
src/__tests__/features/quotes/quote-line-limits.test.tsx

@@ -0,0 +1,254 @@
+/**
+ * A quote's lines follow the work order's rules, since a quote becomes one.
+ *
+ * A quote took a quantity of a billion at a hundred million each, and a
+ * priced part at a quantity of zero, which a work order refuses. Now the
+ * quote's schema refuses them too, the editor marks the figure under its
+ * field as it is typed, and the save says why in the work order's words.
+ * What a work order allows stays allowed: a free part at zero, labour at
+ * zero hours. A quote saved before the rules still converts as it is.
+ */
+import { render, screen } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/features/inventory/Lib/reconcileStock', () => ({
+  reconcileInventoryForParts: vi.fn(),
+}))
+
+import { QuoteLaborEditor } from '@/features/quotes/Components/QuoteLaborEditor'
+import { QuotePartsEditor } from '@/features/quotes/Components/QuotePartsEditor'
+import type { QuoteLaborInput, QuotePartInput } from '@/features/quotes/Components/quote-page-types'
+import { copyQuoteLaborToJob, copyQuotePartsToJob } from '@/features/quotes/Lib/copyQuoteToJob'
+import { findQuoteLineProblem } from '@/features/quotes/Lib/validateQuoteLines'
+import {
+  quoteLaborSchema,
+  quotePartSchema,
+  updateQuoteSchema,
+} from '@/features/quotes/Schema/quoteSchema'
+import { fieldErrorsFromZod } from '@/lib/field-errors'
+
+const part = { name: 'Brake pads', quantity: 1, unitPrice: 100, total: 100 }
+const labor = { description: 'Fit pads', hours: 1, rate: 100, total: 100 }
+
+describe('a quote line on save', () => {
+  it('refuses a billion parts at a hundred million each', () => {
+    const result = quotePartSchema.safeParse({
+      ...part,
+      quantity: 1_000_000_000,
+      unitPrice: 99_999_999,
+      total: 99_999_999_000_000_000,
+    })
+    expect(result.success).toBe(false)
+    expect(quotePartSchema.safeParse({ ...part, quantity: 100_001 }).success).toBe(false)
+    expect(quotePartSchema.safeParse({ ...part, unitPrice: 10_000_001 }).success).toBe(false)
+    expect(quotePartSchema.safeParse({ ...part, unitCost: 10_000_001 }).success).toBe(false)
+    expect(
+      quotePartSchema.safeParse({ ...part, quantity: 100_000, unitPrice: 10, total: 1_000_000 })
+        .success
+    ).toBe(true)
+  })
+
+  it('refuses a line whose quantity times price passes the line limit, whatever total was sent', () => {
+    const result = quotePartSchema.safeParse({
+      ...part,
+      quantity: 100_000,
+      unitPrice: 10_001,
+      total: 1,
+    })
+    expect(result.success).toBe(false)
+    expect(result.error?.issues[0].path).toEqual(['total'])
+  })
+
+  it('refuses a priced part at a quantity of zero, and keeps a free one', () => {
+    const zero = updateQuoteSchema.safeParse({
+      id: 'q1',
+      partItems: [{ ...part, quantity: 0, total: 0 }],
+    })
+    expect(zero.success).toBe(false)
+    // Said under the field in the person's language, not in zod's English.
+    expect(fieldErrorsFromZod(zero.error!)).toEqual([
+      { field: 'partItems.0.quantity', issue: 'positive' },
+    ])
+    expect(
+      quotePartSchema.safeParse({ ...part, quantity: 0, unitPrice: 0, total: 0 }).success
+    ).toBe(true)
+  })
+
+  it('keeps labour at zero hours and refuses absurd hours or rates', () => {
+    expect(quoteLaborSchema.safeParse({ ...labor, hours: 0, total: 0 }).success).toBe(true)
+    expect(quoteLaborSchema.safeParse({ ...labor, hours: 100_001 }).success).toBe(false)
+    expect(quoteLaborSchema.safeParse({ ...labor, rate: 10_000_001 }).success).toBe(false)
+    expect(quoteLaborSchema.safeParse({ ...labor, hours: -1 }).success).toBe(false)
+  })
+
+  it('holds a line total to the cent', () => {
+    expect(
+      quotePartSchema.parse({ ...part, quantity: 3, unitPrice: 0.1, total: 0.30000000000000004 })
+        .total
+    ).toBe(0.3)
+    expect(
+      quoteLaborSchema.parse({ ...labor, hours: 2.5, rate: 19.99, total: 49.974999999999994 }).total
+    ).toBe(49.98)
+  })
+})
+
+describe('the quote editor before it saves', () => {
+  const parts = (over: Partial<QuotePartInput>) => [{ ...part, unitCost: 0, ...over }]
+
+  it('names the first problem in the order the work order checks', () => {
+    expect(findQuoteLineProblem(parts({ quantity: -1 }), [])).toBe('negative')
+    expect(findQuoteLineProblem(parts({ quantity: 1_000_000_000 }), [])).toBe('tooLarge')
+    expect(findQuoteLineProblem([], [{ ...labor, rate: 99_999_999, hours: 1000 }])).toBe('tooLarge')
+    expect(findQuoteLineProblem(parts({ quantity: 0 }), [])).toBe('zeroQuantity')
+    expect(findQuoteLineProblem(parts({ quantity: 0, unitPrice: 0 }), [])).toBeNull()
+    expect(findQuoteLineProblem([], [{ ...labor, hours: 0 }])).toBeNull()
+  })
+
+  it('leaves out the rows a save leaves out', () => {
+    // A row with no name is not sent, so it does not stop the save.
+    expect(findQuoteLineProblem(parts({ name: '', quantity: 1_000_000_000 }), [])).toBeNull()
+  })
+})
+
+const t = (key: string) => key
+
+const quotePart = (over: Partial<QuotePartInput>): QuotePartInput => ({
+  name: 'Brake pads',
+  partNumber: '',
+  quantity: 1,
+  unitCost: 0,
+  markupPercent: 0,
+  unitPrice: 100,
+  total: 100,
+  excluded: false,
+  ...over,
+})
+
+const quoteLabor = (over: Partial<QuoteLaborInput>): QuoteLaborInput => ({
+  description: 'Fit pads',
+  hours: 1,
+  rate: 100,
+  total: 100,
+  pricingType: 'hourly',
+  excluded: false,
+  ...over,
+})
+
+function renderParts(items: QuotePartInput[]) {
+  return render(
+    <QuotePartsEditor
+      partItems={items}
+      currencyCode="GBP"
+      partsSubtotal={0}
+      onUpdate={vi.fn()}
+      onDelete={vi.fn()}
+      onMove={vi.fn()}
+      onAdd={vi.fn()}
+      t={t}
+    />
+  )
+}
+
+describe('a quote line as it is typed', () => {
+  it('marks an absurd quantity and the line total under their fields', () => {
+    renderParts([
+      quotePart({ quantity: 1_000_000_000, unitPrice: 99_999_999, total: 99_999_999_000_000_000 }),
+    ])
+    const quantity = screen.getByDisplayValue('1000000000')
+    expect(quantity).toHaveAttribute('aria-invalid', 'true')
+    expect(quantity).toHaveAccessibleDescription('Must be 100,000 or less.')
+    expect(screen.getByDisplayValue('99999999')).toHaveAccessibleDescription(
+      'Must be 10,000,000 or less.'
+    )
+    expect(screen.getByText('Must be 1,000,000,000 or less.')).toBeInTheDocument()
+  })
+
+  it('marks a priced part at zero, and not a free one', () => {
+    const { unmount } = renderParts([quotePart({ quantity: 0, total: 0 })])
+    expect(screen.getByText('Must be more than 0.')).toBeInTheDocument()
+    unmount()
+    renderParts([quotePart({ quantity: 0, unitPrice: 0, total: 0 })])
+    expect(screen.queryByText('Must be more than 0.')).not.toBeInTheDocument()
+  })
+
+  it('marks absurd labour hours and leaves zero hours alone', () => {
+    const { unmount } = render(
+      <QuoteLaborEditor
+        laborItems={[quoteLabor({ hours: 1_000_000 })]}
+        currencyCode="GBP"
+        cs="£"
+        laborSubtotal={0}
+        onUpdate={vi.fn()}
+        onDelete={vi.fn()}
+        onMove={vi.fn()}
+        onAdd={vi.fn()}
+        onAddService={vi.fn()}
+        t={t}
+      />
+    )
+    expect(screen.getByDisplayValue('1000000')).toHaveAccessibleDescription(
+      'Must be 100,000 or less.'
+    )
+    unmount()
+    render(
+      <QuoteLaborEditor
+        laborItems={[quoteLabor({ hours: 0, total: 0 })]}
+        currencyCode="GBP"
+        cs="£"
+        laborSubtotal={0}
+        onUpdate={vi.fn()}
+        onDelete={vi.fn()}
+        onMove={vi.fn()}
+        onAdd={vi.fn()}
+        onAddService={vi.fn()}
+        t={t}
+      />
+    )
+    expect(screen.queryByText(/or less|more than 0/)).not.toBeInTheDocument()
+  })
+})
+
+describe('a quote saved before the limits', () => {
+  const tx = {
+    servicePart: { createMany: vi.fn() },
+    serviceLabor: { createMany: vi.fn() },
+  }
+  beforeEach(() => vi.clearAllMocks())
+
+  it('still converts, its lines copied onto the job as they are', async () => {
+    const stored = {
+      id: 'qp1',
+      quoteId: 'q1',
+      partNumber: null,
+      name: 'Brake pads',
+      quantity: 1_000_000_000,
+      unit: null,
+      category: null,
+      unitCost: 0,
+      markupPercent: 0,
+      unitPrice: 99_999_999,
+      total: 99_999_999_000_000_000,
+      excluded: false,
+      inventoryPartId: null,
+      taxable: true,
+      sortOrder: 0,
+    }
+    await copyQuotePartsToJob(tx as never, {
+      organizationId: 'org-1',
+      userId: 'user-1',
+      quote: { id: 'q1', quoteNumber: 'QT-1' },
+      partItems: [stored] as never,
+      target: { id: 'job-1', title: 'Brakes', invoiceNumber: 'INV-1' },
+    })
+    expect(tx.servicePart.createMany).toHaveBeenCalledWith({
+      data: [expect.objectContaining({ quantity: 1_000_000_000, unitPrice: 99_999_999 })],
+    })
+
+    await copyQuoteLaborToJob(tx as never, 'job-1', [
+      { description: 'Fit', hours: 1_000_000, rate: 100, total: 100_000_000 } as never,
+    ])
+    expect(tx.serviceLabor.createMany).toHaveBeenCalledWith({
+      data: [expect.objectContaining({ hours: 1_000_000 })],
+    })
+  })
+})

+ 278 - 0
src/__tests__/features/quotes/quote-save-refused-follow-ups.test.tsx

@@ -0,0 +1,278 @@
+/**
+ * Follow-ups to the quote line limits.
+ *
+ * - A save refused for a line past the limits stopped nothing: Convert went
+ *   on with what the database held before the edit (and the edit was lost),
+ *   and the PDF and sending went on too. A refused save now stops them, with
+ *   the refusal said; an unchanged quote, even one saved before the limits,
+ *   still converts.
+ * - The quote's taxed share was summed from unrounded lines while the
+ *   subtotal was summed from rounded ones (3 x 2.5 h at 19.99: 149.94
+ *   against 149.93), so 25% came to 37.48 instead of 37.49.
+ * - The work order's over-limit reading took the cursor on every autosave.
+ */
+import { act, cleanup, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const toastError = vi.fn()
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }),
+  usePathname: () => '/quotes/quote-1',
+}))
+vi.mock('sonner', () => ({
+  toast: { success: vi.fn(), info: vi.fn(), error: (m: string) => toastError(m) },
+}))
+vi.mock('@/components/glass-modal', () => ({ useGlassModal: () => ({ open: vi.fn() }) }))
+vi.mock('@/components/confirm-dialog', async (importOriginal) => ({
+  ...(await importOriginal<typeof import('@/components/confirm-dialog')>()),
+  useConfirm: () => vi.fn(async () => true),
+}))
+const updateQuote = vi.fn()
+const convertQuoteToServiceRecord = vi.fn()
+vi.mock('@/features/quotes/Actions/quoteActions', () => ({
+  updateQuote: (input: unknown) => updateQuote(input),
+  deleteQuote: vi.fn(),
+  convertQuoteToServiceRecord: (...args: unknown[]) => convertQuoteToServiceRecord(...args),
+  addQuoteToServiceRecord: vi.fn(),
+  getQuoteConversionConflicts: vi.fn(async () => ({ success: true, data: [] })),
+  getWorkOrdersForQuoteConversion: vi.fn(async () => ({ success: true, data: [] })),
+  updateQuoteStatus: vi.fn(),
+}))
+vi.mock('@/features/quotes/Actions/quoteResponseActions', () => ({
+  acknowledgeQuoteResponse: vi.fn(),
+}))
+const updateServiceRecord = vi.fn()
+vi.mock('@/features/vehicles/Actions/serviceActions', () => ({
+  updateServiceRecord: (input: unknown) => updateServiceRecord(input),
+  deleteServiceRecord: vi.fn(),
+  deleteServiceAttachment: vi.fn(),
+  toggleManuallyPaid: vi.fn(),
+}))
+vi.mock('@/features/payments/Actions/paymentActions', () => ({
+  createPayment: vi.fn(),
+  deletePayment: vi.fn(),
+}))
+vi.mock('@/features/sms/Actions/smsActions', () => ({ getSmsTemplates: vi.fn() }))
+
+import { useQuoteFormState } from '@/features/quotes/Components/useQuoteFormState'
+import { useServiceActions } from '@/features/vehicles/Components/service-page/useServiceActions'
+
+const part = (over: Record<string, unknown> = {}) => ({
+  partNumber: '',
+  name: 'ZZ Brake pads',
+  quantity: 1,
+  unitCost: 0,
+  markupPercent: 0,
+  unitPrice: 100,
+  total: 100,
+  excluded: false,
+  ...over,
+})
+
+const quote = (over: Record<string, unknown> = {}) =>
+  ({
+    id: 'quote-1',
+    status: 'draft',
+    customer: null,
+    vehicle: { id: 'v-1' },
+    partItems: [part()],
+    laborItems: [],
+    taxRate: 0,
+    taxInclusive: false,
+    discountType: 'none',
+    discountValue: 0,
+    description: '',
+    notes: '',
+    validUntil: null,
+    ...over,
+  }) as any
+
+/** The quote hook, with the form it submits through. */
+function quotePage(record: ReturnType<typeof quote>, taxRate = 0) {
+  const hook = renderHook(() =>
+    useQuoteFormState({
+      quote: record,
+      currencyCode: 'GBP',
+      defaultTaxRate: taxRate,
+      taxEnabled: true,
+      defaultLaborRate: 0,
+      t: (key: string) => key,
+    })
+  )
+  const form = document.createElement('form')
+  form.innerHTML = '<input name="title" value="ZZ Brakes" />'
+  form.requestSubmit = () => {
+    void hook.result.current.handleSubmit({
+      preventDefault: () => undefined,
+      currentTarget: form,
+    } as unknown as React.FormEvent<HTMLFormElement>)
+  }
+  document.body.appendChild(form)
+  ;(hook.result.current.formRef as { current: HTMLFormElement | null }).current = form
+  return hook
+}
+
+afterEach(() => {
+  cleanup()
+  document.body.innerHTML = ''
+})
+
+beforeEach(() => {
+  toastError.mockClear()
+  updateQuote.mockReset().mockResolvedValue({ success: true, data: {} })
+  convertQuoteToServiceRecord
+    .mockReset()
+    .mockResolvedValue({ success: true, data: { id: 'job-9' } })
+  updateServiceRecord.mockReset().mockResolvedValue({ success: true })
+})
+
+describe('a quote whose save is refused', () => {
+  it('is not converted, and says why', async () => {
+    const hook = quotePage(quote())
+    // A priced part typed down to a quantity of zero: the save refuses it.
+    act(() => hook.result.current.updatePart(0, 'quantity', 0))
+    await act(async () => {
+      await hook.result.current.handleConvert()
+    })
+    expect(updateQuote).not.toHaveBeenCalled()
+    expect(convertQuoteToServiceRecord).not.toHaveBeenCalled()
+    expect(toastError).toHaveBeenCalledWith('A priced part needs a quantity above zero.')
+  })
+
+  it('says so to whatever waits on the save', async () => {
+    const hook = quotePage(quote())
+    act(() => hook.result.current.updatePart(0, 'quantity', 1_000_000_000))
+    let saved = true
+    await act(async () => {
+      saved = await hook.result.current.saveNow()
+    })
+    expect(saved).toBe(false)
+  })
+
+  it('still converts once the edit saves', async () => {
+    const hook = quotePage(quote())
+    act(() => hook.result.current.updatePart(0, 'quantity', 2))
+    await act(async () => {
+      await hook.result.current.handleConvert()
+    })
+    expect(updateQuote).toHaveBeenCalledTimes(1)
+    expect(convertQuoteToServiceRecord).toHaveBeenCalledWith('quote-1', 'v-1')
+  })
+})
+
+describe('a quote saved before the limits, left as it is', () => {
+  it('converts without a save', async () => {
+    const hook = quotePage(
+      quote({
+        partItems: [part({ quantity: 1_000_000_000, unitPrice: 99_999_999, total: 9.9999999e16 })],
+      })
+    )
+    await act(async () => {
+      await hook.result.current.handleConvert()
+    })
+    expect(updateQuote).not.toHaveBeenCalled()
+    expect(convertQuoteToServiceRecord).toHaveBeenCalledWith('quote-1', 'v-1')
+  })
+})
+
+describe("a quote's tax", () => {
+  it('is charged on the lines as they are stored, each to the cent', () => {
+    // Three lines of 2.5 h at 19.99, each 49.975 before rounding.
+    const labor = {
+      description: 'Fit',
+      hours: 2.5,
+      rate: 19.99,
+      total: 49.974999999999994,
+      pricingType: 'hourly',
+      excluded: false,
+    }
+    const hook = quotePage(quote({ partItems: [], laborItems: [labor, labor, labor], taxRate: 25 }))
+    expect(hook.result.current.subtotal).toBe(149.94)
+    expect(hook.result.current.taxAmount).toBe(37.49)
+    // Every line taxed: nothing left out to show.
+    expect(hook.result.current.taxableShare).toBeNull()
+  })
+})
+
+describe("the work order's reading past the limit", () => {
+  function workOrder() {
+    const form = {
+      selectedVehicleId: 'v1',
+      type: 'repair',
+      status: 'in-progress',
+      concerns: [],
+      partItems: [],
+      laborItems: [],
+      partItemsForSave: [],
+      laborItemsForSave: [],
+      commitLaborAddedElsewhere: vi.fn(),
+      commitPartsAddedElsewhere: vi.fn(),
+      subtotal: 0,
+      taxRate: 0,
+      taxInclusive: false,
+      taxAmount: 0,
+      totalAmount: 0,
+      discountType: 'none',
+      discountValue: 0,
+      discountAmount: 0,
+      warranty: {},
+      isSavingRef: { current: false },
+      autosaveTimer: { current: null },
+      autosaveRunRef: { current: false },
+      leavingRef: { current: false },
+      lastSaveErrorRef: { current: null as string | null },
+      editRevisionRef: { current: 1 },
+      customFieldsSaveRef: { current: null },
+      setLoading: vi.fn(),
+      setHasUnsavedChanges: vi.fn(),
+      flashSaved: vi.fn(),
+      markSaved: vi.fn(),
+      markDirty: vi.fn(),
+      notesRef: { current: { description: '', diagnosticNotes: '', invoiceNotes: '' } },
+      initialData: { id: 'job1', mileage: null, lastReading: null },
+      confirmedReadingRef: { current: null },
+      acknowledgeSavedLines: vi.fn(),
+      sendingLinesRef: { current: null },
+    }
+    type Options = Parameters<typeof useServiceActions>[0]
+    const hook = renderHook(() =>
+      useServiceActions({
+        record: { id: 'job1' } as unknown as Options['record'],
+        vehicleId: 'v1',
+        currencyCode: 'GBP',
+        formState: form as unknown as Options['formState'],
+      })
+    )
+    const el = document.createElement('form')
+    el.innerHTML = `
+      <input name="title" value="ZZ Brakes" />
+      <input name="mileage" value="20000000" />
+      <textarea aria-label="Notes"></textarea>`
+    document.body.appendChild(el)
+    const save = (autosave: boolean) => {
+      form.autosaveRunRef.current = autosave
+      return act(() =>
+        hook.result.current.handleSubmit({
+          preventDefault: () => undefined,
+          currentTarget: el,
+        } as unknown as React.FormEvent<HTMLFormElement>)
+      )
+    }
+    return { el, save }
+  }
+
+  it('leaves the cursor where it is on an autosave', async () => {
+    const { el, save } = workOrder()
+    const notes = el.querySelector('textarea') as HTMLTextAreaElement
+    notes.focus()
+    await save(true)
+    expect(updateServiceRecord).not.toHaveBeenCalled()
+    expect(document.activeElement).toBe(notes)
+  })
+
+  it('takes the cursor to the reading on a save that was asked for', async () => {
+    const { el, save } = workOrder()
+    await save(false)
+    expect(document.activeElement).toBe(el.querySelector('input[name="mileage"]'))
+  })
+})

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

@@ -579,3 +579,88 @@ describe('saving an existing quote', () => {
     }
     }
   })
   })
 })
 })
+
+/**
+ * A quote tab opened before lines were held to the cent sends its own sum
+ * (2 x 2.5 h at 19.99 = 99.95) with lines stored as 49.98 each. The stored
+ * quote adds up to what its lines do: subtotal, discount, tax and total.
+ */
+describe('a quote whose page summed unrounded lines', () => {
+  // No part lines on these quotes, sent or stored.
+  beforeEach(() => vi.mocked(db.quotePart.findMany).mockResolvedValue([]))
+
+  const line = { description: 'Fit', hours: 2.5, rate: 19.99, total: 49.974999999999994 }
+  const stored = {
+    id: 'q-1',
+    organizationId: ORG,
+    status: 'draft',
+    subtotal: 0,
+    discountType: null,
+    discountValue: 0,
+    discountAmount: 0,
+    taxRate: 25,
+    taxAmount: 0,
+    taxInclusive: false,
+    taxComponents: null,
+    totalAmount: 0,
+    warrantyStatus: null,
+    warrantyMonths: null,
+    warrantyMileage: null,
+    warrantyNotes: null,
+  }
+
+  it('is stored with the subtotal its rounded lines add up to, discount and tax with it', async () => {
+    vi.mocked(db.quote.findFirst).mockResolvedValue(stored as never)
+    const tx = transaction()
+    const result = await updateQuote({
+      id: 'q-1',
+      title: 'Labour',
+      laborItems: [line, line],
+      subtotal: 99.95,
+      discountType: 'percentage',
+      discountValue: 10,
+      discountAmount: 9.995,
+      taxRate: 25,
+      taxAmount: 22.49,
+      totalAmount: 112.44,
+    })
+    expect(result.success).toBe(true)
+    expect(tx.labor().map((l) => (l as unknown as { total: number }).total)).toEqual([49.98, 49.98])
+    // 99.96 less 10% is 89.96; 25% of that is 22.49.
+    expect(tx.data()).toMatchObject({
+      subtotal: 99.96,
+      discountAmount: 10,
+      taxAmount: 22.49,
+      totalAmount: 112.45,
+    })
+  })
+
+  it('leaves a quote whose page summed the rounded lines as it was sent', async () => {
+    vi.mocked(db.quote.findFirst).mockResolvedValue({ ...stored, taxRate: 0 } as never)
+    const tx = transaction()
+    await updateQuote({
+      id: 'q-1',
+      title: 'Labour',
+      laborItems: [line, line],
+      subtotal: 99.96,
+      taxRate: 0,
+      taxAmount: 0,
+      totalAmount: 99.96,
+    })
+    expect(tx.data()).toMatchObject({ subtotal: 99.96, taxAmount: 0, totalAmount: 99.96 })
+  })
+
+  it('is created with the subtotal its rounded lines add up to', async () => {
+    const tx = transaction()
+    const result = await createQuote({
+      title: 'Labour',
+      laborItems: [line, line],
+      subtotal: 99.95,
+      taxRate: 25,
+      taxAmount: 24.99,
+      totalAmount: 124.94,
+    })
+    expect(result.success).toBe(true)
+    expect(tx.data()).toMatchObject({ subtotal: 99.96, taxAmount: 24.99, totalAmount: 124.95 })
+  })
+})

+ 174 - 0
src/__tests__/features/workorders/absurd-amount-marked.test.tsx

@@ -0,0 +1,174 @@
+/**
+ * An absurd amount on the work order is marked where it was typed.
+ *
+ * A quantity of 1,000,000,000 at £99,999,999 was refused only by a toast:
+ * the figure stayed in its box with nothing to say which, and the totals
+ * ran out of the side card and the bar along the bottom. Now the figure is
+ * red with the limit under it as it is typed, the save puts the cursor on
+ * it, and the totals stay inside their containers.
+ */
+import { fireEvent, render, screen } from '@testing-library/react'
+import { useCallback, useState } from 'react'
+import { describe, expect, it, vi } from 'vitest'
+import { LINE_ERROR_SELECTOR } from '@/components/field-errors'
+import { TooltipProvider } from '@/components/ui/tooltip'
+import { LaborEditor } from '@/features/vehicles/Components/service-edit/LaborEditor'
+import { PartsEditor } from '@/features/vehicles/Components/service-edit/PartsEditor'
+import { MoneyBar } from '@/features/vehicles/Components/service-page/modern/MoneyBar'
+import type { ServiceLaborInput, ServicePartInput } from '@/features/vehicles/Schema/serviceSchema'
+import { laborLineIssues, partLineIssues } from '@/lib/input-limits'
+
+vi.mock('@/components/line-drag-handle', () => ({ LineDragHandle: () => null }))
+
+const part = (over: Partial<ServicePartInput> = {}): ServicePartInput => ({
+  name: 'Brake pads',
+  partNumber: '',
+  quantity: 1,
+  unitPrice: 100,
+  total: 100,
+  unitCost: 0,
+  markupPercent: 0,
+  ...over,
+})
+
+function PartsHarness({ initial }: { initial: ServicePartInput[] }) {
+  const [items, setItems] = useState(initial)
+  const update = useCallback(
+    (index: number, field: keyof ServicePartInput, value: string | number) =>
+      setItems((prev) => prev.map((row, i) => (i === index ? { ...row, [field]: value } : row))),
+    []
+  )
+  return (
+    <TooltipProvider>
+      <form data-testid="work-order">
+        <PartsEditor
+          partItems={items}
+          setPartItems={setItems}
+          updatePart={update}
+          partsSubtotal={0}
+          currencyCode="GBP"
+          hasInventory={false}
+          onOpenInventory={vi.fn()}
+        />
+      </form>
+    </TooltipProvider>
+  )
+}
+
+describe('the figures a save would refuse', () => {
+  it('are found field by field, with the limit each passed', () => {
+    expect(
+      partLineIssues({ name: 'Pads', quantity: 1_000_000_000, unitPrice: 99_999_999 })
+    ).toEqual({
+      quantity: { issue: 'tooLarge', limit: 100_000 },
+      unitPrice: { issue: 'tooLarge', limit: 10_000_000 },
+      total: { issue: 'tooLarge', limit: 1_000_000_000 },
+    })
+    expect(partLineIssues({ name: 'Pads', quantity: 0, unitPrice: 10 })).toEqual({
+      quantity: { issue: 'positive' },
+    })
+    expect(partLineIssues({ name: 'Pads', quantity: 0, unitPrice: 0 })).toEqual({})
+    expect(partLineIssues({ name: 'Pads', quantity: -2, unitPrice: 10 })).toEqual({
+      quantity: { issue: 'negative' },
+    })
+    expect(laborLineIssues({ hours: 0, rate: 100 })).toEqual({})
+    expect(laborLineIssues({ hours: 100_000, rate: 10_001 })).toEqual({
+      total: { issue: 'tooLarge', limit: 1_000_000_000 },
+    })
+  })
+})
+
+describe('a part line on the work order', () => {
+  it('marks a billion parts at £99,999,999 under each field as it is typed', () => {
+    render(<PartsHarness initial={[part()]} />)
+    const quantity = screen.getByDisplayValue('1')
+    fireEvent.change(quantity, { target: { value: '1000000000' } })
+    fireEvent.change(screen.getByDisplayValue('100'), { target: { value: '99999999' } })
+
+    expect(quantity).toHaveAttribute('aria-invalid', 'true')
+    expect(quantity).toHaveAccessibleDescription('Must be 100,000 or less.')
+    expect(screen.getByDisplayValue('99999999')).toHaveAccessibleDescription(
+      'Must be 10,000,000 or less.'
+    )
+    expect(screen.getByText('Must be 1,000,000,000 or less.')).toBeInTheDocument()
+  })
+
+  it('is where the save puts the cursor', () => {
+    render(<PartsHarness initial={[part(), part({ name: 'Disc', quantity: 1_000_000 })]} />)
+    const form = screen.getByTestId('work-order') as HTMLFormElement
+    form.querySelector<HTMLElement>(LINE_ERROR_SELECTOR)?.focus()
+    expect(screen.getByDisplayValue('1000000')).toHaveFocus()
+  })
+
+  it('clears the mark once the figure is put right', () => {
+    render(<PartsHarness initial={[part({ quantity: 1_000_000 })]} />)
+    fireEvent.change(screen.getByDisplayValue('1000000'), { target: { value: '4' } })
+    expect(screen.getByDisplayValue('4')).not.toHaveAttribute('aria-invalid')
+    expect(screen.queryByText(/or less/)).not.toBeInTheDocument()
+  })
+
+  it('marks a priced part at zero and leaves a free one alone', () => {
+    const { unmount } = render(<PartsHarness initial={[part({ quantity: 0, total: 0 })]} />)
+    expect(screen.getByText('Must be more than 0.')).toBeInTheDocument()
+    unmount()
+    render(<PartsHarness initial={[part({ quantity: 0, unitPrice: 0, total: 0 })]} />)
+    expect(screen.queryByText('Must be more than 0.')).not.toBeInTheDocument()
+  })
+})
+
+describe('a labour line on the work order', () => {
+  const labor = (over: Partial<ServiceLaborInput>): ServiceLaborInput => ({
+    description: 'Diagnose',
+    hours: 1,
+    rate: 100,
+    total: 100,
+    pricingType: 'hourly',
+    ...over,
+  })
+  const renderLabor = (line: ServiceLaborInput) =>
+    render(
+      <TooltipProvider>
+        <LaborEditor
+          laborItems={[line]}
+          setLaborItems={vi.fn()}
+          updateLabor={vi.fn()}
+          laborSubtotal={0}
+          currencyCode="GBP"
+          defaultLaborRate={100}
+        />
+      </TooltipProvider>
+    )
+
+  it('marks absurd hours', () => {
+    renderLabor(labor({ hours: 2_000_000 }))
+    expect(screen.getByDisplayValue('2000000')).toHaveAccessibleDescription(
+      'Must be 100,000 or less.'
+    )
+  })
+
+  it('keeps a line with no hours yet unmarked', () => {
+    renderLabor(labor({ hours: 0, total: 0 }))
+    expect(screen.queryByText(/or less|more than 0/)).not.toBeInTheDocument()
+  })
+})
+
+describe('the bar along the bottom', () => {
+  it('keeps an absurd balance whole on hover while it is cut short on the bar', () => {
+    render(
+      <MoneyBar
+        total={119_999_998_800_000_000}
+        paid={0}
+        balance={119_999_998_800_000_000}
+        currencyCode="GBP"
+        onTakePayment={vi.fn()}
+        onPreview={vi.fn()}
+        onSend={vi.fn()}
+      />
+    )
+    const balance = screen.getByTestId('money-balance')
+    expect(balance).toHaveClass('truncate')
+    expect(balance.getAttribute('title')).toBe(balance.textContent)
+    // The buttons stay on the bar.
+    expect(screen.getByRole('button', { name: /take payment/i })).toBeInTheDocument()
+  })
+})

+ 76 - 0
src/__tests__/lib/settings-links-need-read.test.ts

@@ -0,0 +1,76 @@
+/**
+ * A link into settings is offered only to somebody the settings pages open
+ * for.
+ *
+ * The settings layout sends anyone without READ on settings to the
+ * dashboard. The work order's "add a status" link, the tyre hotel's price
+ * and capacity links and the "switch it on in settings" lines under the
+ * plate lookup and the document scan were offered on UPDATE alone, so a
+ * role holding UPDATE without READ followed a link that turned them away.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { getCachedMembership } = vi.hoisted(() => ({ getCachedMembership: vi.fn() }))
+vi.mock('@/lib/cached-session', () => ({ getCachedMembership, getCachedSession: vi.fn() }))
+vi.mock('@/lib/with-auth', () => ({
+  withAuth: async (
+    fn: (ctx: { organizationId: string; userId: string; role: string }) => unknown
+  ) => ({
+    success: true,
+    data: await fn({ organizationId: 'org-1', userId: 'u1', role: 'member' }),
+  }),
+}))
+vi.mock('@/lib/features', () => ({
+  getFeatures: vi.fn().mockResolvedValue({ integrations: true }),
+}))
+vi.mock('@/features/integrations/Lib/vehicle-lookup', () => ({
+  askRegistry: vi.fn(),
+  findLookupConnection: vi.fn().mockResolvedValue(null),
+  lookupKeys: vi.fn(),
+  withinLookupBudget: vi.fn(),
+}))
+vi.mock('@/features/integrations/Lib/inspection-sync', () => ({ recordRegistryAnswer: vi.fn() }))
+
+import { getVehicleLookupAvailability } from '@/features/integrations/Actions/vehicleLookupActions'
+import { PermissionAction, PermissionSubject } from '@/lib/permissions'
+import { canOpenAndEditSettings } from '@/lib/settings-access'
+
+const READ = { action: PermissionAction.READ, subject: PermissionSubject.SETTINGS }
+const UPDATE = { action: PermissionAction.UPDATE, subject: PermissionSubject.SETTINGS }
+
+function role(permissions: { action: string; subject: string }[]) {
+  getCachedMembership.mockResolvedValue({ roleId: 'r1', customRole: { permissions } })
+}
+
+beforeEach(() => getCachedMembership.mockReset())
+
+describe('whether a link into settings is offered', () => {
+  it('is not, to a role that may change settings but not open them', async () => {
+    role([UPDATE])
+    expect(await canOpenAndEditSettings('u1', 'member')).toBe(false)
+  })
+
+  it('is not, to a role that may only look at them', async () => {
+    role([READ])
+    expect(await canOpenAndEditSettings('u1', 'member')).toBe(false)
+  })
+
+  it('is, to a role with both, to owners and admins, and to a member with no role', async () => {
+    role([READ, UPDATE])
+    expect(await canOpenAndEditSettings('u1', 'member')).toBe(true)
+    expect(await canOpenAndEditSettings('u1', 'owner')).toBe(true)
+    expect(await canOpenAndEditSettings('u1', 'admin')).toBe(true)
+    getCachedMembership.mockResolvedValue({ roleId: null })
+    expect(await canOpenAndEditSettings('u1', 'member')).toBe(true)
+  })
+
+  it('leaves the plate lookup saying "ask an admin" rather than linking a page that turns them away', async () => {
+    role([UPDATE])
+    const result = await getVehicleLookupAvailability()
+    expect(result.data).toMatchObject({ reason: 'notConnected', canEditSettings: false })
+
+    role([READ, UPDATE])
+    const allowed = await getVehicleLookupAvailability()
+    expect(allowed.data).toMatchObject({ canEditSettings: true })
+  })
+})

+ 11 - 7
src/app/(authenticated)/audit-log/audit-log-client.tsx

@@ -32,6 +32,8 @@ import {
 import { DataTablePagination } from '@/components/data-table-pagination'
 import { DataTablePagination } from '@/components/data-table-pagination'
 import { TableContextMenuHint } from '@/components/table-context-menu-hint'
 import { TableContextMenuHint } from '@/components/table-context-menu-hint'
 import { useFormatDate } from '@/lib/use-format-date'
 import { useFormatDate } from '@/lib/use-format-date'
+import { useFormatCurrency } from '@/components/currency-settings-context'
+import { auditSummaryParams } from '@/features/audit/Lib/summaryParams'
 import { cn } from '@/lib/utils'
 import { cn } from '@/lib/utils'
 import { ExternalLink, Search, Loader2 } from 'lucide-react'
 import { ExternalLink, Search, Loader2 } from 'lucide-react'
 
 
@@ -89,6 +91,7 @@ export function AuditLogClient({
   const tableNav = useTableKeyboardNav()
   const tableNav = useTableKeyboardNav()
   const [selectedLog, setSelectedLog] = useState<AuditLogData['logs'][number] | null>(null)
   const [selectedLog, setSelectedLog] = useState<AuditLogData['logs'][number] | null>(null)
   const { formatDateTime } = useFormatDate()
   const { formatDateTime } = useFormatDate()
+  const formatCurrency = useFormatCurrency()
   const t = useTranslations('audit')
   const t = useTranslations('audit')
   const ti = useTranslations('integrations')
   const ti = useTranslations('integrations')
 
 
@@ -114,13 +117,14 @@ export function AuditLogClient({
       | undefined
       | undefined
     if (details?.key) {
     if (details?.key) {
       const key = `summary.${details.key}`
       const key = `summary.${details.key}`
-      // An integration named by id gets the reader's name for it; the
-      // English name the row was written with stands in for the vendors.
-      const params = { ...details.params }
-      const connectorId = params.connectorId
-      if (typeof connectorId === 'string' && ti.has(`connectors.${connectorId}.name`)) {
-        params.name = ti(`connectors.${connectorId}.name`)
-      }
+      // An integration named by id gets the reader's name for it (the
+      // English name the row was written with stands in for the vendors),
+      // and an amount stored with its currency reads as money.
+      const params = auditSummaryParams(details.params, {
+        connectorName: (id) =>
+          ti.has(`connectors.${id}.name`) ? ti(`connectors.${id}.name`) : null,
+        formatCurrency,
+      })
       if (t.has(key)) return t(key, params)
       if (t.has(key)) return t(key, params)
     }
     }
     return log.message
     return log.message

+ 2 - 2
src/app/(authenticated)/tire-hotel/[id]/page.tsx

@@ -2,7 +2,7 @@ import { resolveCurrencyCode } from '@/lib/currencies'
 import { notFound } from 'next/navigation'
 import { notFound } from 'next/navigation'
 import { db } from '@/lib/db'
 import { db } from '@/lib/db'
 import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
 import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
-import { canEditSettings } from '@/lib/settings-access'
+import { canOpenAndEditSettings } from '@/lib/settings-access'
 import { getTireHotelSettings } from '@/features/tire-hotel/Lib/tireHotelSettings'
 import { getTireHotelSettings } from '@/features/tire-hotel/Lib/tireHotelSettings'
 import { getTireSet } from '@/features/tire-hotel/Actions/tireSetActions'
 import { getTireSet } from '@/features/tire-hotel/Actions/tireSetActions'
 import { getLocationOptions } from '@/features/tire-hotel/Actions/storageActions'
 import { getLocationOptions } from '@/features/tire-hotel/Actions/storageActions'
@@ -28,7 +28,7 @@ export default async function TireSetPage({ params }: { params: Promise<{ id: st
 
 
   // Decides whether the prices and limits on this page offer a way to change
   // Decides whether the prices and limits on this page offer a way to change
   // them. Someone who cannot is better off not seeing the link at all.
   // them. Someone who cannot is better off not seeing the link at all.
-  const canChangeSettings = await canEditSettings(session?.user?.id ?? '', membership?.role)
+  const canChangeSettings = await canOpenAndEditSettings(session?.user?.id ?? '', membership?.role)
 
 
   const { id } = await params
   const { id } = await params
 
 

+ 2 - 2
src/app/(authenticated)/tire-hotel/storage/page.tsx

@@ -1,6 +1,6 @@
 import { notFound } from 'next/navigation'
 import { notFound } from 'next/navigation'
 import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
 import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
-import { canEditSettings } from '@/lib/settings-access'
+import { canOpenAndEditSettings } from '@/lib/settings-access'
 import { getTireHotelSettings } from '@/features/tire-hotel/Lib/tireHotelSettings'
 import { getTireHotelSettings } from '@/features/tire-hotel/Lib/tireHotelSettings'
 import { getStorageOverview } from '@/features/tire-hotel/Actions/storageActions'
 import { getStorageOverview } from '@/features/tire-hotel/Actions/storageActions'
 import { PageHeader } from '@/components/page-header'
 import { PageHeader } from '@/components/page-header'
@@ -21,7 +21,7 @@ export default async function TireStoragePage() {
   const config = await getTireHotelSettings(organizationId)
   const config = await getTireHotelSettings(organizationId)
   if (!config.enabled) notFound()
   if (!config.enabled) notFound()
 
 
-  const canChangeSettings = await canEditSettings(session?.user?.id ?? '', membership?.role)
+  const canChangeSettings = await canOpenAndEditSettings(session?.user?.id ?? '', membership?.role)
   const result = await getStorageOverview()
   const result = await getStorageOverview()
   const warehouses = result.success && result.data ? result.data : []
   const warehouses = result.success && result.data ? result.data : []
 
 

+ 38 - 0
src/components/field-errors.tsx

@@ -121,3 +121,41 @@ export function useFieldErrors() {
 
 
   return { errors, report, clear, reset, invalidProps, message, text }
   return { errors, report, clear, reset, invalidProps, message, text }
 }
 }
+
+/**
+ * The line under one figure of a part or labour line that the save would
+ * refuse ("Must be 100,000 or less."), with the id its field points at
+ * through aria-describedby. Nothing when the figure is fine.
+ */
+export function LineFieldError({
+  id,
+  error,
+}: {
+  id: string
+  error: Pick<FieldError, 'issue' | 'limit'> | undefined
+}) {
+  const text = useFieldErrorText()
+  if (!error) return null
+  return (
+    <p id={id} className="text-xs text-destructive">
+      {text(error)}
+    </p>
+  )
+}
+
+/** The first of a form's line figures the save would refuse, for the save to focus. */
+export const LINE_ERROR_SELECTOR = '[data-line-error], [data-line-total-error]'
+
+/**
+ * The attributes that mark a line's figure as refused: red, announced, and
+ * findable by the save that wants to put the cursor on it.
+ */
+export function lineFieldInvalidProps(id: string, error: unknown) {
+  return error
+    ? {
+        'aria-invalid': true as const,
+        'aria-describedby': id,
+        'data-line-error': '',
+      }
+    : {}
+}

+ 32 - 0
src/features/audit/Lib/summaryParams.ts

@@ -0,0 +1,32 @@
+/**
+ * The values an audit sentence is written with, made ready for the reader.
+ *
+ * A row keeps what it was given when it was written, so this is where a
+ * value becomes what a person reads: an integration named by id gets the
+ * reader's name for it, an amount stored with its currency reads as money
+ * the way the workshop prints it ("£100.00", not "100"), and a payment
+ * logged before it named the job by invoice number or title still shows the
+ * job's id.
+ */
+export function auditSummaryParams(
+  stored: Record<string, string | number> | undefined,
+  read: {
+    /** The reader's name for a connector, or null when there is none. */
+    connectorName: (connectorId: string) => string | null
+    formatCurrency: (amount: number, currencyCode: string) => string
+  }
+): Record<string, string | number> {
+  const params = { ...stored }
+  const { connectorId, amount, currency } = params
+  if (typeof connectorId === 'string') {
+    const name = read.connectorName(connectorId)
+    if (name) params.name = name
+  }
+  if (typeof amount === 'number' && typeof currency === 'string') {
+    params.amount = read.formatCurrency(amount, currency)
+  }
+  if (params.ref === undefined && params.serviceRecordId !== undefined) {
+    params.ref = params.serviceRecordId
+  }
+  return params
+}

+ 2 - 2
src/features/integrations/Actions/vehicleLookupActions.ts

@@ -3,7 +3,7 @@
 import { db } from '@/lib/db'
 import { db } from '@/lib/db'
 import { getFeatures } from '@/lib/features'
 import { getFeatures } from '@/lib/features'
 import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { PermissionAction, PermissionSubject } from '@/lib/permissions'
-import { canEditSettings } from '@/lib/settings-access'
+import { canOpenAndEditSettings } from '@/lib/settings-access'
 import { withAuth } from '@/lib/with-auth'
 import { withAuth } from '@/lib/with-auth'
 import { lookupAppliesTo } from '@/features/vehicles/Lib/registryLookup'
 import { lookupAppliesTo } from '@/features/vehicles/Lib/registryLookup'
 import { recordRegistryAnswer } from '../Lib/inspection-sync'
 import { recordRegistryAnswer } from '../Lib/inspection-sync'
@@ -72,7 +72,7 @@ export async function getVehicleLookupAvailability() {
   return withAuth(
   return withAuth(
     async ({ organizationId, userId, role }): Promise<VehicleLookupAvailability> => {
     async ({ organizationId, userId, role }): Promise<VehicleLookupAvailability> => {
       const features = await getFeatures(organizationId)
       const features = await getFeatures(organizationId)
-      const editor = await canEditSettings(userId, role)
+      const editor = await canOpenAndEditSettings(userId, role)
       if (!features.integrations)
       if (!features.integrations)
         return { plate: false, vin: false, reason: 'notInPlan', canEditSettings: editor }
         return { plate: false, vin: false, reason: 'notInPlan', canEditSettings: editor }
       const [plate, vin] = await Promise.all([
       const [plate, vin] = await Promise.all([

+ 9 - 3
src/features/payments/Actions/paymentActions.ts

@@ -10,7 +10,7 @@ import { createPaymentSchema } from '../Schema/paymentSchema'
 import { revalidatePath } from 'next/cache'
 import { revalidatePath } from 'next/cache'
 import { getTranslations } from 'next-intl/server'
 import { getTranslations } from 'next-intl/server'
 import { roundMoney } from '@/lib/money'
 import { roundMoney } from '@/lib/money'
-import { workshopMoneyFormatter } from '@/lib/workshop-currency'
+import { workshopCurrencySettings, workshopMoneyFormatter } from '@/lib/workshop-currency'
 import { paymentBalanceDue } from '../Lib/balanceDue'
 import { paymentBalanceDue } from '../Lib/balanceDue'
 import { getDocumentLockSettings } from '@/lib/document-lock.server'
 import { getDocumentLockSettings } from '@/lib/document-lock.server'
 import { DocumentLockedError, invoiceLockState } from '@/lib/document-lock'
 import { DocumentLockedError, invoiceLockState } from '@/lib/document-lock'
@@ -25,7 +25,8 @@ export async function createPayment(input: unknown) {
       // Verify ownership: serviceRecord -> vehicle -> organizationId
       // Verify ownership: serviceRecord -> vehicle -> organizationId
       const serviceRecord = await db.serviceRecord.findFirst({
       const serviceRecord = await db.serviceRecord.findFirst({
         where: { id: data.serviceRecordId, organizationId },
         where: { id: data.serviceRecordId, organizationId },
-        select: { id: true, vehicleId: true, status: true },
+        // The invoice number or the title name the job in the audit log.
+        select: { id: true, vehicleId: true, status: true, invoiceNumber: true, title: true },
       })
       })
       if (!serviceRecord) throw new Error('Service record not found')
       if (!serviceRecord) throw new Error('Service record not found')
       // Nothing is owed on a cancelled invoice; a refund is booked as it is cancelled.
       // Nothing is owed on a cancelled invoice; a refund is booked as it is cancelled.
@@ -85,11 +86,16 @@ export async function createPayment(input: unknown) {
           ? `/vehicles/${serviceRecord.vehicleId}/service/${data.serviceRecordId}`
           ? `/vehicles/${serviceRecord.vehicleId}/service/${data.serviceRecordId}`
           : `/sales/${data.serviceRecordId}`
           : `/sales/${data.serviceRecordId}`
       )
       )
+      // The log names the job as people know it, and the amount in the
+      // workshop's currency, as service_update does with its ref.
+      const { currencyCode } = await workshopCurrencySettings(organizationId)
       return {
       return {
         ...payment,
         ...payment,
         serviceRecordId: data.serviceRecordId,
         serviceRecordId: data.serviceRecordId,
         amount,
         amount,
         method: data.method,
         method: data.method,
+        jobRef: serviceRecord.invoiceNumber || serviceRecord.title || serviceRecord.id,
+        currencyCode,
       }
       }
     },
     },
     {
     {
@@ -102,7 +108,7 @@ export async function createPayment(input: unknown) {
         entityId: result.id,
         entityId: result.id,
         details: {
         details: {
           key: 'payment_create',
           key: 'payment_create',
-          params: { amount: result.amount, serviceRecordId: result.serviceRecordId },
+          params: { amount: result.amount, currency: result.currencyCode, ref: result.jobRef },
         },
         },
         metadata: {
         metadata: {
           paymentId: result.id,
           paymentId: result.id,

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

@@ -19,7 +19,12 @@ import { db } from '@/lib/db'
 import { assertOwnedCustomer, assertOwnedVehicle } from '@/lib/owned-records'
 import { assertOwnedCustomer, assertOwnedVehicle } from '@/lib/owned-records'
 import { Prisma } from '@/generated/prisma/client'
 import { Prisma } from '@/generated/prisma/client'
 import { parseTaxComponentDefinitions } from '@/lib/tax-components'
 import { parseTaxComponentDefinitions } from '@/lib/tax-components'
-import { savedDocumentTax, taxComponentsForCopy } from '@/features/settings/Lib/workshopTax'
+import {
+  documentTotals,
+  savedDocumentTax,
+  taxComponentsForCopy,
+} from '@/features/settings/Lib/workshopTax'
+import { restatedSubtotal, subtotalFromLines } from '@/features/vehicles/Lib/subtotalFromLines'
 import { loadTaxApplies } from '@/features/settings/Lib/loadTaxApplies'
 import { loadTaxApplies } from '@/features/settings/Lib/loadTaxApplies'
 import { withTaxableLabor, withTaxableParts } from '@/lib/taxable-lines'
 import { withTaxableLabor, withTaxableParts } from '@/lib/taxable-lines'
 import { parseSentFields, sentId } from '@/lib/parse-sent-fields'
 import { parseSentFields, sentId } from '@/lib/parse-sent-fields'
@@ -321,6 +326,43 @@ export async function updateQuote(input: unknown) {
         laborItems !== undefined && taxApplies
         laborItems !== undefined && taxApplies
           ? withTaxableLabor(laborItems, taxApplies)
           ? withTaxableLabor(laborItems, taxApplies)
           : undefined
           : undefined
+      // Lines are stored to the cent (quoteSchema). The subtotal the page sent
+      // was added up from its own figures, and a tab opened before the lines
+      // were rounded sends 99.95 for lines stored as 99.96, so it is restated
+      // from the lines as stored, the discount and tax with it, as on a work
+      // order. Lines left out of the customer's total do not count.
+      let fromLines: ReturnType<typeof restatedSubtotal> = null
+      if (linesSent && quoteData.subtotal !== undefined) {
+        const counted = <T extends { excluded?: boolean | null }>(lines: T[]) =>
+          lines.filter((line) => !line.excluded)
+        fromLines = restatedSubtotal({
+          sentSubtotal: quoteData.subtotal,
+          linesSubtotal: subtotalFromLines(
+            counted(
+              partItems ??
+                (await db.quotePart.findMany({
+                  where: { quoteId: id },
+                  select: { total: true, excluded: true },
+                }))
+            ),
+            counted(
+              laborItems ??
+                (await db.quoteLabor.findMany({
+                  where: { quoteId: id },
+                  select: { total: true, excluded: true },
+                }))
+            )
+          ),
+          discountType: quoteData.discountType ?? existing.discountType,
+          discountValue: quoteData.discountValue ?? existing.discountValue,
+        })
+        if (fromLines) {
+          quoteData.subtotal = fromLines.subtotal
+          if (fromLines.discountAmount !== undefined) {
+            quoteData.discountAmount = fromLines.discountAmount
+          }
+        }
+      }
       const moneyTouched =
       const moneyTouched =
         linesSent ||
         linesSent ||
         quoteData.subtotal !== undefined ||
         quoteData.subtotal !== undefined ||
@@ -358,6 +400,19 @@ export async function updateQuote(input: unknown) {
         if (restated.taxComponents) quoteData.taxRate = existing.taxRate
         if (restated.taxComponents) quoteData.taxRate = existing.taxRate
         quoteData.taxAmount = restated.taxAmount
         quoteData.taxAmount = restated.taxAmount
         quoteData.totalAmount = restated.totalAmount
         quoteData.totalAmount = restated.totalAmount
+      } else if (fromLines) {
+        // A plain quote, every line taxed at one rate: its tax and total
+        // follow the restated subtotal too.
+        const totals = documentTotals({
+          subtotal: fromLines.subtotal,
+          discountAmount: quoteData.discountAmount ?? existing.discountAmount,
+          taxRate: quoteData.taxRate ?? existing.taxRate,
+          taxInclusive: quoteData.taxInclusive ?? existing.taxInclusive,
+          taxComponents: existing.taxComponents,
+          taxableSubtotal: null,
+        })
+        quoteData.taxAmount = totals.taxAmount
+        quoteData.totalAmount = totals.totalAmount
       }
       }
 
 
       const quote = await db.$transaction(async (tx) => {
       const quote = await db.$transaction(async (tx) => {

+ 48 - 20
src/features/quotes/Components/QuoteLaborEditor.tsx

@@ -1,6 +1,6 @@
 'use client'
 'use client'
 
 
-import { memo } from 'react'
+import { memo, useId } from 'react'
 import { Button } from '@/components/ui/button'
 import { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import { Input } from '@/components/ui/input'
 import { Textarea } from '@/components/ui/textarea'
 import { Textarea } from '@/components/ui/textarea'
@@ -14,6 +14,9 @@ import { ShopFeeTag, useShopFeeLocked } from '@/features/settings/Components/Sho
 import { LineTaxToggle } from '@/features/settings/Components/LineTaxToggle'
 import { LineTaxToggle } from '@/features/settings/Components/LineTaxToggle'
 import { useLineTax } from '@/features/settings/Components/LineTaxContext'
 import { useLineTax } from '@/features/settings/Components/LineTaxContext'
 import { laborTaxable } from '@/lib/taxable-lines'
 import { laborTaxable } from '@/lib/taxable-lines'
+import { laborLineIssues } from '@/lib/input-limits'
+import { cn } from '@/lib/utils'
+import { LineFieldError, lineFieldInvalidProps } from '@/components/field-errors'
 import { LaborGuideButton } from '@/features/vehicles/Components/labor-guide/LaborGuideButton'
 import { LaborGuideButton } from '@/features/vehicles/Components/labor-guide/LaborGuideButton'
 import type { LaborGuideJob } from '@/features/vehicles/Components/labor-guide/LaborGuideDialog'
 import type { LaborGuideJob } from '@/features/vehicles/Components/labor-guide/LaborGuideDialog'
 import type { LaborGuideStock } from '@/features/vehicles/Components/labor-guide/FluidPartButton'
 import type { LaborGuideStock } from '@/features/vehicles/Components/labor-guide/FluidPartButton'
@@ -56,6 +59,10 @@ const QuoteLaborRow = memo(function QuoteLaborRow({
   const feeLocked = useShopFeeLocked()
   const feeLocked = useShopFeeLocked()
   const formatCurrency = useFormatCurrency()
   const formatCurrency = useFormatCurrency()
   const { applies } = useLineTax()
   const { applies } = useLineTax()
+  // Hours, a rate or a line total the save would refuse, said under the field.
+  const issues = laborLineIssues(labor)
+  const rowId = useId()
+  const errorId = (field: string) => `${rowId}-${field}-error`
   return (
   return (
     <div
     <div
       className={`grid grid-cols-2 gap-2 sm:grid-cols-[2fr_1fr_1fr_1fr_auto] ${labor.excluded ? 'line-through opacity-50' : ''}`}
       className={`grid grid-cols-2 gap-2 sm:grid-cols-[2fr_1fr_1fr_1fr_auto] ${labor.excluded ? 'line-through opacity-50' : ''}`}
@@ -85,25 +92,46 @@ const QuoteLaborRow = memo(function QuoteLaborRow({
           </button>
           </button>
         )}
         )}
       </div>
       </div>
-      <Input
-        type="number"
-        min="0"
-        step={isService || isFee ? '1' : '0.1'}
-        placeholder={isService || isFee ? tQty : tHours}
-        value={labor.hours}
-        disabled={isFee}
-        onChange={(e) => onUpdate(index, 'hours', e.target.value)}
-      />
-      <Input
-        type="number"
-        min="0"
-        step="0.01"
-        value={labor.rate}
-        disabled={isFee && feeLocked}
-        onChange={(e) => onUpdate(index, 'rate', e.target.value)}
-      />
-      <div className="flex items-center rounded-md bg-muted/50 px-3 text-sm font-medium">
-        {formatCurrency(labor.total, currencyCode)}
+      <div className="flex min-w-0 flex-col gap-1">
+        <Input
+          type="number"
+          min="0"
+          step={isService || isFee ? '1' : '0.1'}
+          placeholder={isService || isFee ? tQty : tHours}
+          value={labor.hours}
+          disabled={isFee}
+          onChange={(e) => onUpdate(index, 'hours', e.target.value)}
+          {...lineFieldInvalidProps(errorId('hours'), issues.hours)}
+          // A line total past the limit has no box of its own to put the cursor in.
+          data-line-total-error={issues.total ? '' : undefined}
+        />
+        <LineFieldError id={errorId('hours')} error={issues.hours} />
+      </div>
+      <div className="flex min-w-0 flex-col gap-1">
+        <Input
+          type="number"
+          min="0"
+          step="0.01"
+          value={labor.rate}
+          disabled={isFee && feeLocked}
+          onChange={(e) => onUpdate(index, 'rate', e.target.value)}
+          {...lineFieldInvalidProps(errorId('rate'), issues.rate)}
+        />
+        <LineFieldError id={errorId('rate')} error={issues.rate} />
+      </div>
+      <div className="flex min-w-0 flex-col gap-1">
+        {/* Kept inside its cell however long the figure, in full on hover. */}
+        <div
+          className={cn(
+            'flex h-9 min-w-0 items-center rounded-md bg-muted/50 px-3 text-sm font-medium',
+            issues.total && 'text-destructive ring-1 ring-destructive'
+          )}
+          title={formatCurrency(labor.total, currencyCode)}
+          aria-describedby={issues.total ? errorId('total') : undefined}
+        >
+          <span className="truncate">{formatCurrency(labor.total, currencyCode)}</span>
+        </div>
+        <LineFieldError id={errorId('total')} error={issues.total} />
       </div>
       </div>
       <div className="flex items-center gap-1">
       <div className="flex items-center gap-1">
         <LineTaxToggle
         <LineTaxToggle

+ 6 - 5
src/features/quotes/Components/QuotePageClient.tsx

@@ -162,8 +162,9 @@ export function QuotePageClient({
   // the next autosave to be refused.
   // the next autosave to be refused.
   const handleQuoteSent = useCallback(() => router.refresh(), [router])
   const handleQuoteSent = useCallback(() => router.refresh(), [router])
 
 
-  useSaveShortcut(() => {
-    if (state.hasUnsavedChanges) return state.saveNow()
+  useSaveShortcut(async () => {
+    // The shortcut only saves; a refusal is already said on the page.
+    if (state.hasUnsavedChanges) await state.saveNow()
   })
   })
 
 
   const [showPresetPicker, setShowPresetPicker] = useState(false)
   const [showPresetPicker, setShowPresetPicker] = useState(false)
@@ -401,7 +402,7 @@ export function QuotePageClient({
                       disabled={state.saving}
                       disabled={state.saving}
                       onClick={async () => {
                       onClick={async () => {
                         if (state.saving) return
                         if (state.saving) return
-                        if (state.hasUnsavedChanges) await state.saveNow()
+                        if (state.hasUnsavedChanges && !(await state.saveNow())) return
                         setShowPdfPreview(true)
                         setShowPdfPreview(true)
                       }}
                       }}
                     >
                     >
@@ -427,7 +428,7 @@ export function QuotePageClient({
                       disabled={state.saving}
                       disabled={state.saving}
                       onClick={async () => {
                       onClick={async () => {
                         if (state.saving) return
                         if (state.saving) return
-                        if (state.hasUnsavedChanges) await state.saveNow()
+                        if (state.hasUnsavedChanges && !(await state.saveNow())) return
                         state.setShowEmailDialog(true)
                         state.setShowEmailDialog(true)
                       }}
                       }}
                     >
                     >
@@ -444,7 +445,7 @@ export function QuotePageClient({
                       disabled={state.saving}
                       disabled={state.saving}
                       onClick={async () => {
                       onClick={async () => {
                         if (state.saving) return
                         if (state.saving) return
-                        if (state.hasUnsavedChanges) await state.saveNow()
+                        if (state.hasUnsavedChanges && !(await state.saveNow())) return
                         state.setShowShareDialog(true)
                         state.setShowShareDialog(true)
                       }}
                       }}
                     >
                     >

+ 61 - 29
src/features/quotes/Components/QuotePartsEditor.tsx

@@ -9,6 +9,8 @@ import { useFormatCurrency } from '@/components/currency-settings-context'
 import { LineTaxToggle } from '@/features/settings/Components/LineTaxToggle'
 import { LineTaxToggle } from '@/features/settings/Components/LineTaxToggle'
 import { useLineTax } from '@/features/settings/Components/LineTaxContext'
 import { useLineTax } from '@/features/settings/Components/LineTaxContext'
 import { partTaxable } from '@/lib/taxable-lines'
 import { partTaxable } from '@/lib/taxable-lines'
+import { partLineIssues } from '@/lib/input-limits'
+import { LineFieldError, lineFieldInvalidProps } from '@/components/field-errors'
 import { cn } from '@/lib/utils'
 import { cn } from '@/lib/utils'
 import { InventoryPickerDialog } from '@/features/vehicles/Components/service-edit/InventoryPickerDialog'
 import { InventoryPickerDialog } from '@/features/vehicles/Components/service-edit/InventoryPickerDialog'
 import type { InventoryPartOption } from '@/features/vehicles/Components/service-edit/form-types'
 import type { InventoryPartOption } from '@/features/vehicles/Components/service-edit/form-types'
@@ -73,6 +75,11 @@ const QuotePartRow = memo(function QuotePartRow({
       Number(part.unitPrice) > 0 ||
       Number(part.unitPrice) > 0 ||
       Number(part.total) > 0
       Number(part.total) > 0
     )
     )
+  // The figures the save would refuse, marked and said under their field as
+  // they are typed: the same rules as a work order's lines.
+  const issues = partLineIssues(part)
+  const rowId = useId()
+  const errorId = (field: string) => `${rowId}-${field}-error`
   return (
   return (
     <div
     <div
       className={`grid grid-cols-2 gap-2 sm:grid-cols-[1fr_2fr_0.6fr_0.9fr_0.7fr_0.9fr_0.9fr_auto] ${part.excluded ? 'line-through opacity-50' : ''}`}
       className={`grid grid-cols-2 gap-2 sm:grid-cols-[1fr_2fr_0.6fr_0.9fr_0.7fr_0.9fr_0.9fr_auto] ${part.excluded ? 'line-through opacity-50' : ''}`}
@@ -118,31 +125,41 @@ const QuotePartRow = memo(function QuotePartRow({
         />
         />
       </div>
       </div>
       {/* The unit rides along from the stocked part; shown, not edited. */}
       {/* The unit rides along from the stocked part; shown, not edited. */}
-      <div className="relative">
+      <div className="flex min-w-0 flex-col gap-1">
+        <div className="relative">
+          <Input
+            type="number"
+            min="0"
+            step="any"
+            value={part.quantity}
+            onChange={(e) => onUpdate(index, 'quantity', e.target.value)}
+            className={cn(part.unit && 'pr-9')}
+            {...lineFieldInvalidProps(errorId('quantity'), issues.quantity)}
+            // A line total past the limit has no box of its own to put the cursor in.
+            data-line-total-error={issues.total ? '' : undefined}
+          />
+          {part.unit && (
+            <span className="pointer-events-none absolute right-2 top-1/2 max-w-8 -translate-y-1/2 truncate text-xs text-muted-foreground">
+              {part.unit}
+            </span>
+          )}
+        </div>
+        <LineFieldError id={errorId('quantity')} error={issues.quantity} />
+      </div>
+      <div className="flex min-w-0 flex-col gap-1">
         <Input
         <Input
           type="number"
           type="number"
           min="0"
           min="0"
-          step="any"
-          value={part.quantity}
-          onChange={(e) => onUpdate(index, 'quantity', e.target.value)}
-          className={cn(part.unit && 'pr-9')}
+          step="0.01"
+          value={part.unitCost}
+          onChange={(e) => onUpdate(index, 'unitCost', e.target.value)}
+          // The margin is restated here rather than on each keystroke: a cost
+          // still being typed is not a cost anyone meant.
+          onBlur={(e) => onUpdate(index, 'unitCost', e.target.value, { commit: true })}
+          {...lineFieldInvalidProps(errorId('unitCost'), issues.unitCost)}
         />
         />
-        {part.unit && (
-          <span className="pointer-events-none absolute right-2 top-1/2 max-w-8 -translate-y-1/2 truncate text-xs text-muted-foreground">
-            {part.unit}
-          </span>
-        )}
+        <LineFieldError id={errorId('unitCost')} error={issues.unitCost} />
       </div>
       </div>
-      <Input
-        type="number"
-        min="0"
-        step="0.01"
-        value={part.unitCost}
-        onChange={(e) => onUpdate(index, 'unitCost', e.target.value)}
-        // The margin is restated here rather than on each keystroke: a cost
-        // still being typed is not a cost anyone meant.
-        onBlur={(e) => onUpdate(index, 'unitCost', e.target.value, { commit: true })}
-      />
       <Input
       <Input
         type="number"
         type="number"
         min="0"
         min="0"
@@ -150,15 +167,30 @@ const QuotePartRow = memo(function QuotePartRow({
         value={part.markupPercent}
         value={part.markupPercent}
         onChange={(e) => onUpdate(index, 'markupPercent', e.target.value)}
         onChange={(e) => onUpdate(index, 'markupPercent', e.target.value)}
       />
       />
-      <Input
-        type="number"
-        min="0"
-        step="0.01"
-        value={part.unitPrice}
-        onChange={(e) => onUpdate(index, 'unitPrice', e.target.value)}
-      />
-      <div className="flex items-center rounded-md bg-muted/50 px-3 text-sm font-medium">
-        {formatCurrency(part.total, currencyCode)}
+      <div className="flex min-w-0 flex-col gap-1">
+        <Input
+          type="number"
+          min="0"
+          step="0.01"
+          value={part.unitPrice}
+          onChange={(e) => onUpdate(index, 'unitPrice', e.target.value)}
+          {...lineFieldInvalidProps(errorId('unitPrice'), issues.unitPrice)}
+        />
+        <LineFieldError id={errorId('unitPrice')} error={issues.unitPrice} />
+      </div>
+      <div className="flex min-w-0 flex-col gap-1">
+        {/* Kept inside its cell however long the figure, in full on hover. */}
+        <div
+          className={cn(
+            'flex h-9 min-w-0 items-center rounded-md bg-muted/50 px-3 text-sm font-medium',
+            issues.total && 'text-destructive ring-1 ring-destructive'
+          )}
+          title={formatCurrency(part.total, currencyCode)}
+          aria-describedby={issues.total ? errorId('total') : undefined}
+        >
+          <span className="truncate">{formatCurrency(part.total, currencyCode)}</span>
+        </div>
+        <LineFieldError id={errorId('total')} error={issues.total} />
       </div>
       </div>
       <div className="flex items-center gap-1">
       <div className="flex items-center gap-1">
         <LineTaxToggle
         <LineTaxToggle

+ 85 - 18
src/features/quotes/Components/useQuoteFormState.ts

@@ -5,6 +5,11 @@ import { useState, useCallback, useEffect, useRef, useMemo } from 'react'
 import { useRouter } from 'next/navigation'
 import { useRouter } from 'next/navigation'
 import { arrayMove } from '@dnd-kit/sortable'
 import { arrayMove } from '@dnd-kit/sortable'
 import { toast } from 'sonner'
 import { toast } from 'sonner'
+import { useFormatter, useTranslations } from 'next-intl'
+import { roundMoney } from '@/lib/money'
+import { LINE_TOTAL_MAX, QUANTITY_MAX, READING_MAX, UNIT_PRICE_MAX } from '@/lib/input-limits'
+import { LINE_ERROR_SELECTOR, useFieldErrorText } from '@/components/field-errors'
+import { findQuoteLineProblem } from '@/features/quotes/Lib/validateQuoteLines'
 import { useSaveBeforeLeaving } from '@/hooks/use-save-before-leaving'
 import { useSaveBeforeLeaving } from '@/hooks/use-save-before-leaving'
 import { useGlassModal } from '@/components/glass-modal'
 import { useGlassModal } from '@/components/glass-modal'
 import { useConfirm } from '@/components/confirm-dialog'
 import { useConfirm } from '@/components/confirm-dialog'
@@ -96,6 +101,11 @@ export function useQuoteFormState({
   const router = useRouter()
   const router = useRouter()
   const modal = useGlassModal()
   const modal = useGlassModal()
   const confirm = useConfirm()
   const confirm = useConfirm()
+  // A line's figures are refused in the work order's own words.
+  const tService = useTranslations('service')
+  const { number: formatNumber } = useFormatter()
+  const tCommon = useTranslations('common')
+  const fieldErrorText = useFieldErrorText()
 
 
   // Tab state
   // Tab state
   const [activeTab, setActiveTab] = useState<'details' | 'images' | 'documents'>('details')
   const [activeTab, setActiveTab] = useState<'details' | 'images' | 'documents'>('details')
@@ -326,12 +336,16 @@ export function useQuoteFormState({
   }, [hasUnsavedChanges])
   }, [hasUnsavedChanges])
 
 
   // Calculations
   // Calculations
+  // Each line to the cent first, as the save stores it (quoteSchema), so the
+  // subtotal is what the stored lines add up to, as on a work order.
   const partsSubtotal = useMemo(
   const partsSubtotal = useMemo(
-    () => partItems.reduce((sum, p) => (p.excluded ? sum : sum + p.total), 0),
+    () =>
+      roundMoney(partItems.reduce((sum, p) => (p.excluded ? sum : sum + roundMoney(p.total)), 0)),
     [partItems]
     [partItems]
   )
   )
   const laborSubtotal = useMemo(
   const laborSubtotal = useMemo(
-    () => laborItems.reduce((sum, l) => (l.excluded ? sum : sum + l.total), 0),
+    () =>
+      roundMoney(laborItems.reduce((sum, l) => (l.excluded ? sum : sum + roundMoney(l.total)), 0)),
     [laborItems]
     [laborItems]
   )
   )
   // A percentage shop fee follows the lines the customer is being quoted for.
   // A percentage shop fee follows the lines the customer is being quoted for.
@@ -344,17 +358,19 @@ export function useQuoteFormState({
     markDirty()
     markDirty()
   }, [laborItems, partsSubtotal, shopFee, locked, markDirty])
   }, [laborItems, partsSubtotal, shopFee, locked, markDirty])
 
 
-  const subtotal = partsSubtotal + laborSubtotal
+  const subtotal = roundMoney(partsSubtotal + laborSubtotal)
   const discountAmount = discountAmountFor(subtotal, discountType, discountValue)
   const discountAmount = discountAmountFor(subtotal, discountType, discountValue)
   // The tax is charged on the taxable lines the customer kept. A line says
   // The tax is charged on the taxable lines the customer kept. A line says
   // whether it is taxed, and one that has not been asked follows the
   // whether it is taxed, and one that has not been asked follows the
   // workshop's rule for its kind; the server settles it the same way.
   // workshop's rule for its kind; the server settles it the same way.
+  // Each line to the cent here too, or the taxed share is summed from other
+  // figures than the subtotal (3 x 2.5 h at 19.99: 149.94 against 149.93).
   const taxableParts = taxablePartsTotal(
   const taxableParts = taxablePartsTotal(
-    partItems.filter((p) => !p.excluded),
+    partItems.filter((p) => !p.excluded).map((p) => ({ ...p, total: roundMoney(p.total) })),
     taxApplies
     taxApplies
   )
   )
   const taxableLabor = taxableLaborTotal(
   const taxableLabor = taxableLaborTotal(
-    laborItems.filter((l) => !l.excluded),
+    laborItems.filter((l) => !l.excluded).map((l) => ({ ...l, total: roundMoney(l.total) })),
     taxApplies
     taxApplies
   )
   )
   const taxableSubtotal = storedTaxableSubtotal(subtotal, taxableParts + taxableLabor)
   const taxableSubtotal = storedTaxableSubtotal(subtotal, taxableParts + taxableLabor)
@@ -434,7 +450,7 @@ export function useQuoteFormState({
         const updated = [...prev]
         const updated = [...prev]
         const labor = { ...updated[index], [field]: value }
         const labor = { ...updated[index], [field]: value }
         if (field === 'hours' || field === 'rate')
         if (field === 'hours' || field === 'rate')
-          labor.total = Number(labor.hours) * Number(labor.rate)
+          labor.total = roundMoney(Number(labor.hours) * Number(labor.rate))
         updated[index] = labor
         updated[index] = labor
         return updated
         return updated
       })
       })
@@ -518,6 +534,8 @@ export function useQuoteFormState({
     autosaveRunRef.current = false
     autosaveRunRef.current = false
     if (isSavingRef.current) return
     if (isSavingRef.current) return
     if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
     if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
+    // This save's answer, not an earlier one's (see saveNow).
+    lastSaveErrorRef.current = null
     // Saving from here on, the custom fields included: whoever waits for this
     // Saving from here on, the custom fields included: whoever waits for this
     // save (a link held back, the PDF) must not take that first step for the end.
     // save (a link held back, the PDF) must not take that first step for the end.
     isSavingRef.current = true
     isSavingRef.current = true
@@ -560,6 +578,23 @@ export function useQuoteFormState({
       }
       }
     }
     }
 
 
+    // A figure the server would refuse is said now, in the work order's words,
+    // and the cursor put on the first marked field (see partLineIssues),
+    // unless this is an autosave and the person is typing somewhere.
+    const lineProblem = locked ? null : findQuoteLineProblem(partItems, laborItems)
+    if (lineProblem) {
+      isSavingRef.current = false
+      const message = tService(`page.problems.${lineProblem}`, {
+        quantity: formatNumber(QUANTITY_MAX),
+        price: formatNumber(UNIT_PRICE_MAX),
+        total: formatNumber(LINE_TOTAL_MAX),
+        reading: formatNumber(READING_MAX),
+      })
+      failed(message, () => toast.error(message))
+      if (!autosave) form.querySelector<HTMLElement>(LINE_ERROR_SELECTOR)?.focus()
+      return
+    }
+
     setSaving(true)
     setSaving(true)
     try {
     try {
       const formData = new FormData(form)
       const formData = new FormData(form)
@@ -603,7 +638,23 @@ export function useQuoteFormState({
         savedTimerRef.current = setTimeout(() => setShowSaved(false), 2000)
         savedTimerRef.current = setTimeout(() => setShowSaved(false), 2000)
         router.refresh()
         router.refresh()
       } else {
       } else {
-        const message = result.error || t('page.failedSave')
+        // What the schema refused, in the person's language and named by the
+        // section it is in ("Parts: Must be 100,000 or less."), not zod's English.
+        const message = result.fieldErrors?.length
+          ? result.fieldErrors
+              .map((error) => {
+                const problem = fieldErrorText(error)
+                const [head] = error.field.split('.')
+                const label =
+                  head === 'partItems'
+                    ? tService('parts.title')
+                    : head === 'laborItems'
+                      ? tService('labor.title')
+                      : null
+                return label ? tCommon('fieldErrors.withLabel', { label, problem }) : problem
+              })
+              .join(' ')
+          : result.error || t('page.failedSave')
         failed(message, () => modal.open('error', 'Error', message))
         failed(message, () => modal.open('error', 'Error', message))
       }
       }
     } catch (err) {
     } catch (err) {
@@ -635,17 +686,31 @@ export function useQuoteFormState({
     }
     }
   }
   }
 
 
-  const saveNow = async () => {
-    if (!formRef.current || isSavingRef.current) return
+  /**
+   * Saves now and says whether it went through. A save refused (a line past
+   * the limits, a custom field missing, the server saying no) has already
+   * said why; whatever waited on it (convert, the PDF, sending) stops there
+   * rather than going on with what the database held before the edit.
+   */
+  const saveNow = async (): Promise<boolean> => {
+    if (!formRef.current) return false
+    const settled = () =>
+      new Promise<void>((resolve) => {
+        const check = () => {
+          if (!isSavingRef.current) return resolve()
+          setTimeout(check, 50)
+        }
+        setTimeout(check, 50)
+      })
+    // An autosave already under way is the save; its answer is the answer.
+    if (isSavingRef.current) {
+      await settled()
+      return lastSaveErrorRef.current === null
+    }
     if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
     if (autosaveTimer.current) clearTimeout(autosaveTimer.current)
     formRef.current.requestSubmit()
     formRef.current.requestSubmit()
-    await new Promise<void>((resolve) => {
-      const check = () => {
-        if (!isSavingRef.current) return resolve()
-        setTimeout(check, 50)
-      }
-      setTimeout(check, 50)
-    })
+    await settled()
+    return lastSaveErrorRef.current === null
   }
   }
 
 
   // Leaving by a link, a shortcut or the search palette saves first. The
   // Leaving by a link, a shortcut or the search palette saves first. The
@@ -671,7 +736,7 @@ export function useQuoteFormState({
   })
   })
 
 
   const handleDownloadPDF = async () => {
   const handleDownloadPDF = async () => {
-    if (hasUnsavedChanges) await saveNow()
+    if (hasUnsavedChanges && !(await saveNow())) return
     setDownloading(true)
     setDownloading(true)
     try {
     try {
       const res = await fetch(`/api/protected/quotes/${quote.id}/pdf`)
       const res = await fetch(`/api/protected/quotes/${quote.id}/pdf`)
@@ -740,7 +805,9 @@ export function useQuoteFormState({
   const convertConflictsUnresolved = convertConflicts.some((c) => !convertResolutions[c.kind])
   const convertConflictsUnresolved = convertConflicts.some((c) => !convertResolutions[c.kind])
 
 
   const handleConvert = async () => {
   const handleConvert = async () => {
-    if (hasUnsavedChanges) await saveNow()
+    // A refused save stops the conversion: going on would convert what the
+    // database held, and the edit on screen would be lost with no word.
+    if (hasUnsavedChanges && !(await saveNow())) return
     if (!convertVehicleId) {
     if (!convertVehicleId) {
       modal.open('error', 'Error', t('page.selectVehicle'))
       modal.open('error', 'Error', t('page.selectVehicle'))
       return
       return

+ 25 - 2
src/features/quotes/Lib/createQuoteRecord.ts

@@ -1,4 +1,5 @@
 import { discountAmountFor } from '@/lib/tax'
 import { discountAmountFor } from '@/lib/tax'
+import { restatedSubtotal, subtotalFromLines } from '@/features/vehicles/Lib/subtotalFromLines'
 import 'server-only'
 import 'server-only'
 
 
 import { db } from '@/lib/db'
 import { db } from '@/lib/db'
@@ -79,6 +80,27 @@ export async function createQuoteRecord(
     if (!inspection) throw new Error('Inspection not found')
     if (!inspection) throw new Error('Inspection not found')
   }
   }
 
 
+  // The lines are stored to the cent (quoteSchema), so the subtotal is what
+  // they add up to as stored, not the page's own sum: a tab opened before the
+  // lines were rounded sends 99.95 for two lines stored as 49.98 each. The
+  // discount follows, and the tax and total are recomputed below.
+  const sentLines = (data.partItems?.length ?? 0) + (data.laborItems?.length ?? 0) > 0
+  const fromLines = sentLines
+    ? restatedSubtotal({
+        sentSubtotal: data.subtotal,
+        linesSubtotal: subtotalFromLines(
+          (data.partItems ?? []).filter((p) => !p.excluded),
+          (data.laborItems ?? []).filter((l) => !l.excluded)
+        ),
+        discountType: data.discountType,
+        discountValue: data.discountValue,
+      })
+    : null
+  if (fromLines) {
+    data.subtotal = fromLines.subtotal
+    if (fromLines.discountAmount !== undefined) data.discountAmount = fromLines.discountAmount
+  }
+
   // The workshop's shop fee, priced for the lines the quote starts with. A
   // The workshop's shop fee, priced for the lines the quote starts with. A
   // caller that already carries one (a copied quote) keeps its own. Most
   // caller that already carries one (a copied quote) keeps its own. Most
   // quotes start empty, so a percentage fee starts at nothing; the line is
   // quotes start empty, so a percentage fee starts at nothing; the line is
@@ -139,8 +161,9 @@ export async function createQuoteRecord(
   const counted = <T extends { excluded?: boolean }>(lines: T[]) =>
   const counted = <T extends { excluded?: boolean }>(lines: T[]) =>
     lines.filter((line) => !line.excluded)
     lines.filter((line) => !line.excluded)
   const taxableSubtotal = taxableSubtotalOf(counted(taxedParts), counted(taxedLabor))
   const taxableSubtotal = taxableSubtotalOf(counted(taxedParts), counted(taxedLabor))
-  // The fee moved the subtotal, so the caller's tax and total are recomputed.
-  if (feeAdded) {
+  // The fee or the stored lines moved the subtotal, so the caller's tax and
+  // total are recomputed.
+  if (feeAdded || fromLines) {
     const totals = documentTotals({
     const totals = documentTotals({
       subtotal: data.subtotal,
       subtotal: data.subtotal,
       discountAmount: data.discountAmount,
       discountAmount: data.discountAmount,

+ 48 - 0
src/features/quotes/Lib/validateQuoteLines.ts

@@ -0,0 +1,48 @@
+import {
+  type LaborLineIssues,
+  laborLineIssues,
+  type PartLineIssues,
+  partLineIssues,
+} from '@/lib/input-limits'
+
+/**
+ * Why a quote's lines cannot be saved, in the words the work order uses for
+ * the same thing (service.page.problems), checked in the browser before the
+ * save so the person is told at once and the field is marked where it is.
+ * The server's schema (quoteSchema) holds the same rules.
+ */
+export type QuoteLineProblem = 'negative' | 'tooLarge' | 'zeroQuantity'
+
+interface QuotePartLine {
+  name: string
+  quantity: unknown
+  unitPrice: unknown
+  unitCost?: unknown
+}
+
+interface QuoteLaborLine {
+  description: string
+  hours: unknown
+  rate: unknown
+}
+
+/**
+ * The first problem with the lines a save would send: parts with a name and
+ * labour with a description, since the save leaves out the rest. Negatives
+ * first, then figures past the limits, then a priced part at zero, the order
+ * the work order checks them in.
+ */
+export function findQuoteLineProblem(
+  parts: readonly QuotePartLine[],
+  labor: readonly QuoteLaborLine[]
+): QuoteLineProblem | null {
+  const issues: (PartLineIssues | LaborLineIssues)[] = [
+    ...parts.filter((p) => p.name).map(partLineIssues),
+    ...labor.filter((l) => l.description).map(laborLineIssues),
+  ]
+  const all = issues.flatMap((line) => Object.values(line))
+  if (all.some((i) => i?.issue === 'negative')) return 'negative'
+  if (all.some((i) => i?.issue === 'tooLarge')) return 'tooLarge'
+  if (all.some((i) => i?.issue === 'positive')) return 'zeroQuantity'
+  return null
+}

+ 79 - 44
src/features/quotes/Schema/quoteSchema.ts

@@ -1,51 +1,86 @@
 import { z } from 'zod'
 import { z } from 'zod'
+import { roundMoney } from '@/lib/money'
+import {
+  checkLineAmounts,
+  LABOR_HOURS_MAX,
+  LINE_TOTAL_MAX,
+  QUANTITY_MAX,
+  UNIT_PRICE_MAX,
+} from '@/lib/input-limits'
 import { uploadUrlSchema } from '@/lib/upload-url'
 import { uploadUrlSchema } from '@/lib/upload-url'
 
 
-export const quotePartSchema = z.object({
-  partNumber: z.string().optional(),
-  name: z.string().min(1, 'Part name is required'),
-  quantity: z.coerce.number().min(0).default(1),
-  /** Unit of measure snapshotted from the picked inventory part. */
-  unit: z.string().nullish(),
-  category: z.string().nullish(),
-  unitCost: z.coerce.number().min(0).default(0),
-  /**
-   * Selling below cost is a real decision (a goodwill line, matching a price),
-   * and the markup has to be able to say so. Floored at -100, which is giving
-   * the part away: anything lower would imply a negative price, which
-   * unitPrice already refuses.
-   */
-  markupPercent: z.coerce.number().min(-100).default(0),
-  unitPrice: z.coerce.number().min(0).default(0),
-  total: z.coerce.number().min(0).default(0),
-  excluded: z.boolean().optional().default(false),
-  /**
-   * Set when the line was picked from stock. Carried through to ServicePart on
-   * conversion so the resulting job deducts this exact inventory item.
-   */
-  inventoryPartId: z.string().nullish(),
-  /**
-   * Whether the document's tax is charged on this line. Left out by a caller
-   * that does not choose, and the server then takes the workshop's answer
-   * for this kind of line (Settings, Tax).
-   */
-  taxable: z.boolean().optional(),
-})
+/**
+ * A quote's lines follow the work order's rules (serviceSchema), since a
+ * quote becomes one: no negatives, nothing past lib/input-limits.ts, no
+ * priced part at a quantity of zero, and each total held to the cent.
+ * Checked on a save only: a quote saved before these rules still opens and
+ * converts, its lines copied as they are.
+ */
+export const quotePartSchema = z
+  .object({
+    partNumber: z.string().optional(),
+    name: z.string().min(1, 'Part name is required'),
+    quantity: z.coerce.number().min(0).max(QUANTITY_MAX).default(1),
+    /** Unit of measure snapshotted from the picked inventory part. */
+    unit: z.string().nullish(),
+    category: z.string().nullish(),
+    unitCost: z.coerce.number().min(0).max(UNIT_PRICE_MAX).default(0),
+    /**
+     * Selling below cost is a real decision (a goodwill line, matching a price),
+     * and the markup has to be able to say so. Floored at -100, which is giving
+     * the part away: anything lower would imply a negative price, which
+     * unitPrice already refuses.
+     */
+    markupPercent: z.coerce.number().min(-100).default(0),
+    unitPrice: z.coerce.number().min(0).max(UNIT_PRICE_MAX).default(0),
+    /** Held to the cent on save, whatever the page worked it out as. */
+    total: z.coerce.number().min(0).max(LINE_TOTAL_MAX).default(0).transform(roundMoney),
+    excluded: z.boolean().optional().default(false),
+    /**
+     * Set when the line was picked from stock. Carried through to ServicePart on
+     * conversion so the resulting job deducts this exact inventory item.
+     */
+    inventoryPartId: z.string().nullish(),
+    /**
+     * Whether the document's tax is charged on this line. Left out by a caller
+     * that does not choose, and the server then takes the workshop's answer
+     * for this kind of line (Settings, Tax).
+     */
+    taxable: z.boolean().optional(),
+  })
+  // A free part may still be listed at zero; a priced one may not.
+  .superRefine((part, ctx) =>
+    checkLineAmounts(
+      { count: part.quantity, price: part.unitPrice },
+      ctx,
+      { count: 'quantity', total: 'total' },
+      { pricedNeedsCount: true }
+    )
+  )
 
 
-export const quoteLaborSchema = z.object({
-  description: z.string().min(1, 'Description is required'),
-  hours: z.coerce.number().min(0).default(0),
-  rate: z.coerce.number().min(0).default(0),
-  total: z.coerce.number().min(0).default(0),
-  pricingType: z.enum(['hourly', 'service', 'shopFee']).default('hourly'),
-  excluded: z.boolean().optional().default(false),
-  /**
-   * Whether the document's tax is charged on this line. Left out by a caller
-   * that does not choose, and the server then takes the workshop's answer
-   * for this kind of line (Settings, Tax).
-   */
-  taxable: z.boolean().optional(),
-})
+/** Hours may be zero, as on a work order: only negatives and absurd figures are refused. */
+export const quoteLaborSchema = z
+  .object({
+    description: z.string().min(1, 'Description is required'),
+    hours: z.coerce.number().min(0).max(LABOR_HOURS_MAX).default(0),
+    rate: z.coerce.number().min(0).max(UNIT_PRICE_MAX).default(0),
+    /** Held to the cent on save, whatever the page worked it out as. */
+    total: z.coerce.number().min(0).max(LINE_TOTAL_MAX).default(0).transform(roundMoney),
+    pricingType: z.enum(['hourly', 'service', 'shopFee']).default('hourly'),
+    excluded: z.boolean().optional().default(false),
+    /**
+     * Whether the document's tax is charged on this line. Left out by a caller
+     * that does not choose, and the server then takes the workshop's answer
+     * for this kind of line (Settings, Tax).
+     */
+    taxable: z.boolean().optional(),
+  })
+  .superRefine((labor, ctx) =>
+    checkLineAmounts({ count: labor.hours, price: labor.rate }, ctx, {
+      count: 'hours',
+      total: 'total',
+    })
+  )
 
 
 export const quoteAttachmentSchema = z.object({
 export const quoteAttachmentSchema = z.object({
   fileName: z.string(),
   fileName: z.string(),

+ 2 - 2
src/features/vehicles/Actions/aiAnalyzeVehicleDocument.ts

@@ -2,7 +2,7 @@
 
 
 import { withAuth } from '@/lib/with-auth'
 import { withAuth } from '@/lib/with-auth'
 import { getFeatures } from '@/lib/features'
 import { getFeatures } from '@/lib/features'
-import { canEditSettings } from '@/lib/settings-access'
+import { canOpenAndEditSettings } from '@/lib/settings-access'
 import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { PermissionAction, PermissionSubject } from '@/lib/permissions'
 import { isAiConfigured } from '@/features/integrations/Lib/ai'
 import { isAiConfigured } from '@/features/integrations/Lib/ai'
 import { visionCompletion } from '@/lib/ai'
 import { visionCompletion } from '@/lib/ai'
@@ -63,7 +63,7 @@ export interface VehicleScanAvailability {
 export async function getVehicleScanAvailability() {
 export async function getVehicleScanAvailability() {
   return withAuth(
   return withAuth(
     async ({ organizationId, userId, role }): Promise<VehicleScanAvailability> => {
     async ({ organizationId, userId, role }): Promise<VehicleScanAvailability> => {
-      const editor = await canEditSettings(userId, role)
+      const editor = await canOpenAndEditSettings(userId, role)
       if (await isAiConfigured(organizationId))
       if (await isAiConfigured(organizationId))
         return { available: true, reason: null, canEditSettings: editor }
         return { available: true, reason: null, canEditSettings: editor }
       // A provider can only be connected on a plan with AI, so without one
       // A provider can only be connected on a plan with AI, so without one

+ 5 - 3
src/features/vehicles/Components/service-detail/PaymentsSection.tsx

@@ -329,12 +329,14 @@ export function PaymentsSection({
             {t('cancelledNotice')}
             {t('cancelledNotice')}
           </p>
           </p>
         ) : (
         ) : (
-          <div className="flex items-baseline justify-between rounded-lg bg-foreground px-4 py-4 text-background">
-            <span className="text-xs font-medium uppercase tracking-wider opacity-70">
+          // The figure wraps inside the card when it is absurd (a billion parts
+          // at a hundred million) rather than running over the label and out.
+          <div className="flex items-baseline justify-between gap-3 rounded-lg bg-foreground px-4 py-4 text-background">
+            <span className="shrink-0 text-xs font-medium uppercase tracking-wider opacity-70">
               {t('balanceDue')}
               {t('balanceDue')}
             </span>
             </span>
             <span
             <span
-              className="order-number text-3xl font-bold leading-none tabular-nums"
+              className="order-number min-w-0 text-right text-3xl font-bold leading-none tabular-nums [overflow-wrap:anywhere]"
               data-testid="balance-due"
               data-testid="balance-due"
             >
             >
               {formatCurrency(balanceDue, currencyCode)}
               {formatCurrency(balanceDue, currencyCode)}

+ 45 - 19
src/features/vehicles/Components/service-edit/LaborEditor.tsx

@@ -24,6 +24,8 @@ import {
 } from '@/components/ui/dropdown-menu'
 } from '@/components/ui/dropdown-menu'
 import { getCurrencySymbol } from '@/lib/format'
 import { getCurrencySymbol } from '@/lib/format'
 import { laborRowHasContent } from '@/features/vehicles/Lib/validateServiceForm'
 import { laborRowHasContent } from '@/features/vehicles/Lib/validateServiceForm'
+import { laborLineIssues } from '@/lib/input-limits'
+import { LineFieldError, lineFieldInvalidProps } from '@/components/field-errors'
 import { useFormatCurrency, useCurrencySettings } from '@/components/currency-settings-context'
 import { useFormatCurrency, useCurrencySettings } from '@/components/currency-settings-context'
 import { useTranslations } from 'next-intl'
 import { useTranslations } from 'next-intl'
 import type { ServiceLaborInput } from '@/features/vehicles/Schema/serviceSchema'
 import type { ServiceLaborInput } from '@/features/vehicles/Schema/serviceSchema'
@@ -117,6 +119,9 @@ const SortableLaborRow = memo(function SortableLaborRow({
   // Hours or a rate with nothing said about them: the row is meant, and until
   // Hours or a rate with nothing said about them: the row is meant, and until
   // it is described the job cannot be saved.
   // it is described the job cannot be saved.
   const descriptionMissing = laborRowHasContent(labor) && !labor.description.trim()
   const descriptionMissing = laborRowHasContent(labor) && !labor.description.trim()
+  // Hours, a rate or a line total the save would refuse, said under the field.
+  const issues = laborLineIssues(labor)
+  const errorId = (field: string) => `${id}-${field}-error`
 
 
   const style = dragEnabled
   const style = dragEnabled
     ? {
     ? {
@@ -180,32 +185,53 @@ const SortableLaborRow = memo(function SortableLaborRow({
           />
           />
         </div>
         </div>
         <FieldRow label={isService || isFee ? t('qty') : t('hours')}>
         <FieldRow label={isService || isFee ? t('qty') : t('hours')}>
-          <Input
-            type="number"
-            min="0"
-            step={isService || isFee ? '1' : 'any'}
-            placeholder={isService || isFee ? t('qty') : t('hours')}
-            value={labor.hours}
-            disabled={isFee}
-            onChange={(e) => updateLabor(index, 'hours', e.target.value)}
-          />
+          <div className="flex w-full min-w-0 flex-col gap-1 self-start">
+            <Input
+              type="number"
+              min="0"
+              step={isService || isFee ? '1' : 'any'}
+              placeholder={isService || isFee ? t('qty') : t('hours')}
+              value={labor.hours}
+              disabled={isFee}
+              onChange={(e) => updateLabor(index, 'hours', e.target.value)}
+              {...lineFieldInvalidProps(errorId('hours'), issues.hours)}
+              // A line total past the limit has no box of its own to put the cursor in.
+              data-line-total-error={issues.total ? '' : undefined}
+            />
+            <LineFieldError id={errorId('hours')} error={issues.hours} />
+          </div>
         </FieldRow>
         </FieldRow>
         <FieldRow label={rateLabel}>
         <FieldRow label={rateLabel}>
-          <Input
-            type="number"
-            min="0"
-            step="0.01"
-            value={labor.rate}
-            disabled={isFee && feeLocked}
-            onChange={(e) => updateLabor(index, 'rate', e.target.value)}
-          />
+          <div className="flex w-full min-w-0 flex-col gap-1 self-start">
+            <Input
+              type="number"
+              min="0"
+              step="0.01"
+              value={labor.rate}
+              disabled={isFee && feeLocked}
+              onChange={(e) => updateLabor(index, 'rate', e.target.value)}
+              {...lineFieldInvalidProps(errorId('rate'), issues.rate)}
+            />
+            <LineFieldError id={errorId('rate')} error={issues.rate} />
+          </div>
         </FieldRow>
         </FieldRow>
         <div className="flex items-center gap-2 @2xl:contents">
         <div className="flex items-center gap-2 @2xl:contents">
           <span className="w-24 shrink-0 text-xs text-muted-foreground @2xl:hidden">
           <span className="w-24 shrink-0 text-xs text-muted-foreground @2xl:hidden">
             {t('total')}
             {t('total')}
           </span>
           </span>
-          <div className="flex h-9 flex-1 items-center rounded-md bg-muted/50 px-3 text-sm font-medium">
-            {formatCurrency(labor.total, currencyCode)}
+          <div className="flex min-w-0 flex-1 flex-col gap-1 self-start">
+            {/* Kept inside its cell however long the figure, in full on hover. */}
+            <div
+              className={cn(
+                'flex h-9 min-w-0 items-center rounded-md bg-muted/50 px-3 text-sm font-medium',
+                issues.total && 'text-destructive ring-1 ring-destructive'
+              )}
+              title={formatCurrency(labor.total, currencyCode)}
+              aria-describedby={issues.total ? errorId('total') : undefined}
+            >
+              <span className="truncate">{formatCurrency(labor.total, currencyCode)}</span>
+            </div>
+            <LineFieldError id={errorId('total')} error={issues.total} />
           </div>
           </div>
           <Button
           <Button
             type="button"
             type="button"

+ 65 - 33
src/features/vehicles/Components/service-edit/PartsEditor.tsx

@@ -15,6 +15,8 @@ import { useFormatCurrency } from '@/components/currency-settings-context'
 import { useTranslations } from 'next-intl'
 import { useTranslations } from 'next-intl'
 import type { ServicePartInput } from '@/features/vehicles/Schema/serviceSchema'
 import type { ServicePartInput } from '@/features/vehicles/Schema/serviceSchema'
 import { partRowHasContent } from '@/features/vehicles/Lib/validateServiceForm'
 import { partRowHasContent } from '@/features/vehicles/Lib/validateServiceForm'
+import { partLineIssues } from '@/lib/input-limits'
+import { LineFieldError, lineFieldInvalidProps } from '@/components/field-errors'
 import { emptyPart } from './form-types'
 import { emptyPart } from './form-types'
 import { LineTaxToggle } from '@/features/settings/Components/LineTaxToggle'
 import { LineTaxToggle } from '@/features/settings/Components/LineTaxToggle'
 import { useLineTax } from '@/features/settings/Components/LineTaxContext'
 import { useLineTax } from '@/features/settings/Components/LineTaxContext'
@@ -136,6 +138,10 @@ const SortablePartRow = memo(function SortablePartRow({
   // Same rule the save refuses on, so the red border and the refusal can
   // Same rule the save refuses on, so the red border and the refusal can
   // never disagree about which rows are a problem.
   // never disagree about which rows are a problem.
   const nameMissing = partRowHasContent(part) && !part.name.trim()
   const nameMissing = partRowHasContent(part) && !part.name.trim()
+  // The figures the save would refuse (a quantity of a billion, a priced part
+  // at zero), each marked and said under its own field as it is typed.
+  const issues = partLineIssues(part)
+  const errorId = (field: string) => `${id}-${field}-error`
   const { applies } = useLineTax()
   const { applies } = useLineTax()
 
 
   return (
   return (
@@ -207,36 +213,46 @@ const SortablePartRow = memo(function SortablePartRow({
         <FieldRow label={t('qty')}>
         <FieldRow label={t('qty')}>
           {/* The unit is a property of the stocked part, snapshotted at pick
           {/* The unit is a property of the stocked part, snapshotted at pick
               time, so it renders as a suffix rather than an editable field. */}
               time, so it renders as a suffix rather than an editable field. */}
-          <div className="relative w-full self-start">
+          <div className="flex w-full min-w-0 flex-col gap-1 self-start">
+            <div className="relative w-full">
+              <Input
+                type="number"
+                min="0"
+                step="any"
+                value={part.quantity}
+                onChange={(e) => updatePart(index, 'quantity', e.target.value)}
+                className={cn(part.unit && 'pr-9')}
+                {...lineFieldInvalidProps(errorId('quantity'), issues.quantity)}
+                // A line total past the limit has no box of its own to put the cursor in.
+                data-line-total-error={issues.total ? '' : undefined}
+              />
+              {part.unit && (
+                <span className="pointer-events-none absolute right-2 top-1/2 max-w-8 -translate-y-1/2 truncate text-xs text-muted-foreground">
+                  {part.unit}
+                </span>
+              )}
+            </div>
+            <LineFieldError id={errorId('quantity')} error={issues.quantity} />
+          </div>
+        </FieldRow>
+        <FieldRow label={t('unitCost')} hint={t('unitCostHint')}>
+          <div className="flex w-full min-w-0 flex-col gap-1 self-start">
             <Input
             <Input
               type="number"
               type="number"
               min="0"
               min="0"
-              step="any"
-              value={part.quantity}
-              onChange={(e) => updatePart(index, 'quantity', e.target.value)}
-              className={cn(part.unit && 'pr-9')}
+              step="0.01"
+              placeholder={t('unitCost')}
+              title={t('unitCostHint')}
+              value={part.unitCost ?? 0}
+              onChange={(e) => updatePart(index, 'unitCost', e.target.value)}
+              // The margin is restated here rather than on each keystroke: a
+              // cost still being typed is not a cost anyone meant.
+              onBlur={(e) => updatePart(index, 'unitCost', e.target.value, { commit: true })}
+              {...lineFieldInvalidProps(errorId('unitCost'), issues.unitCost)}
             />
             />
-            {part.unit && (
-              <span className="pointer-events-none absolute right-2 top-1/2 max-w-8 -translate-y-1/2 truncate text-xs text-muted-foreground">
-                {part.unit}
-              </span>
-            )}
+            <LineFieldError id={errorId('unitCost')} error={issues.unitCost} />
           </div>
           </div>
         </FieldRow>
         </FieldRow>
-        <FieldRow label={t('unitCost')} hint={t('unitCostHint')}>
-          <Input
-            type="number"
-            min="0"
-            step="0.01"
-            placeholder={t('unitCost')}
-            title={t('unitCostHint')}
-            value={part.unitCost ?? 0}
-            onChange={(e) => updatePart(index, 'unitCost', e.target.value)}
-            // The margin is restated here rather than on each keystroke: a
-            // cost still being typed is not a cost anyone meant.
-            onBlur={(e) => updatePart(index, 'unitCost', e.target.value, { commit: true })}
-          />
-        </FieldRow>
         <FieldRow label={t('markupPercent')} hint={t('markupPercentHint')}>
         <FieldRow label={t('markupPercent')} hint={t('markupPercentHint')}>
           <div className="relative w-full self-start">
           <div className="relative w-full self-start">
             <Input
             <Input
@@ -255,20 +271,36 @@ const SortablePartRow = memo(function SortablePartRow({
           </div>
           </div>
         </FieldRow>
         </FieldRow>
         <FieldRow label={t('unitPrice')}>
         <FieldRow label={t('unitPrice')}>
-          <Input
-            type="number"
-            min="0"
-            step="0.01"
-            value={part.unitPrice}
-            onChange={(e) => updatePart(index, 'unitPrice', e.target.value)}
-          />
+          <div className="flex w-full min-w-0 flex-col gap-1 self-start">
+            <Input
+              type="number"
+              min="0"
+              step="0.01"
+              value={part.unitPrice}
+              onChange={(e) => updatePart(index, 'unitPrice', e.target.value)}
+              {...lineFieldInvalidProps(errorId('unitPrice'), issues.unitPrice)}
+            />
+            <LineFieldError id={errorId('unitPrice')} error={issues.unitPrice} />
+          </div>
         </FieldRow>
         </FieldRow>
         <div className="flex items-center gap-2 @2xl:contents">
         <div className="flex items-center gap-2 @2xl:contents">
           <span className="w-24 shrink-0 text-xs text-muted-foreground @2xl:hidden">
           <span className="w-24 shrink-0 text-xs text-muted-foreground @2xl:hidden">
             {t('total')}
             {t('total')}
           </span>
           </span>
-          <div className="flex h-9 flex-1 items-center rounded-md bg-muted/50 px-3 text-sm font-medium">
-            {formatCurrency(part.total, currencyCode)}
+          <div className="flex min-w-0 flex-1 flex-col gap-1 self-start">
+            {/* A figure past every limit is still drawn in full on hover,
+                but kept inside its cell rather than across the next one. */}
+            <div
+              className={cn(
+                'flex h-9 min-w-0 items-center rounded-md bg-muted/50 px-3 text-sm font-medium',
+                issues.total && 'text-destructive ring-1 ring-destructive'
+              )}
+              title={formatCurrency(part.total, currencyCode)}
+              aria-describedby={issues.total ? errorId('total') : undefined}
+            >
+              <span className="truncate">{formatCurrency(part.total, currencyCode)}</span>
+            </div>
+            <LineFieldError id={errorId('total')} error={issues.total} />
           </div>
           </div>
           <Button
           <Button
             type="button"
             type="button"

+ 15 - 6
src/features/vehicles/Components/service-edit/TotalsSection.tsx

@@ -91,7 +91,7 @@ function Row({
       {control && (
       {control && (
         <span
         <span
           className={cn(
           className={cn(
-            'flex items-center justify-end gap-1.5',
+            'flex min-w-0 flex-wrap items-center justify-end gap-1.5',
             stackControl &&
             stackControl &&
               'col-span-3 row-start-2 @[22rem]:col-span-1 @[22rem]:col-start-2 @[22rem]:row-start-1'
               'col-span-3 row-start-2 @[22rem]:col-span-1 @[22rem]:col-start-2 @[22rem]:row-start-1'
           )}
           )}
@@ -99,7 +99,14 @@ function Row({
           {control}
           {control}
         </span>
         </span>
       )}
       )}
-      <span className={cn('text-right tabular-nums', stackControl && 'col-start-3 row-start-1')}>
+      {/* An absurd figure (a billion parts at a hundred million) wraps inside
+          the card instead of running out of it. */}
+      <span
+        className={cn(
+          'min-w-0 text-right tabular-nums [overflow-wrap:anywhere]',
+          stackControl && 'col-start-3 row-start-1'
+        )}
+      >
         {amount}
         {amount}
       </span>
       </span>
     </div>
     </div>
@@ -184,7 +191,7 @@ export function TotalsSection({
 
 
   const rows = (
   const rows = (
     <div className="space-y-2" data-testid="totals">
     <div className="space-y-2" data-testid="totals">
-      <div className="@container grid grid-cols-[minmax(0,1fr)_auto_auto] gap-x-3 gap-y-2">
+      <div className="@container grid grid-cols-[minmax(min-content,1fr)_minmax(0,auto)_minmax(0,auto)] gap-x-3 gap-y-2">
         <Row label={t('parts')} amount={formatCurrency(displayPartsSubtotal, currencyCode)} />
         <Row label={t('parts')} amount={formatCurrency(displayPartsSubtotal, currencyCode)} />
         {partsCostSubtotal > 0 && (
         {partsCostSubtotal > 0 && (
           <Row
           <Row
@@ -290,10 +297,12 @@ export function TotalsSection({
 
 
       <div
       <div
         data-totals-row
         data-totals-row
-        className="flex items-center justify-between border-t pt-2 text-lg font-bold tabular-nums"
+        className="flex items-center justify-between gap-3 border-t pt-2 text-lg font-bold tabular-nums"
       >
       >
-        <span>{t('total')}</span>
-        <span>{formatCurrency(totalAmount, currencyCode)}</span>
+        <span className="shrink-0">{t('total')}</span>
+        <span className="min-w-0 text-right [overflow-wrap:anywhere]">
+          {formatCurrency(totalAmount, currencyCode)}
+        </span>
       </div>
       </div>
       {taxInclusive && (
       {taxInclusive && (
         <p className="text-xs text-muted-foreground italic">{t('inclusiveModeHint')}</p>
         <p className="text-xs text-muted-foreground italic">{t('inclusiveModeHint')}</p>

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

@@ -47,7 +47,7 @@ import {
 } from '@/features/condition-map/Lib/loadMarks.server'
 } from '@/features/condition-map/Lib/loadMarks.server'
 import { invoiceDesignPrintsConditionMap } from '@/features/invoices/Lib/assembleInvoicePrint'
 import { invoiceDesignPrintsConditionMap } from '@/features/invoices/Lib/assembleInvoicePrint'
 import { getCachedSession, getCachedMembership } from '@/lib/cached-session'
 import { getCachedSession, getCachedMembership } from '@/lib/cached-session'
-import { canEditSettings, canOpenAndEditSettings } from '@/lib/settings-access'
+import { canOpenAndEditSettings } from '@/lib/settings-access'
 import { canEditVehicles } from '@/lib/vehicle-access'
 import { canEditVehicles } from '@/lib/vehicle-access'
 import { canTakePayments } from '@/lib/billing-access'
 import { canTakePayments } from '@/lib/billing-access'
 import { ServicePageClient } from '@/features/vehicles/Components/service-page/ServicePageClient'
 import { ServicePageClient } from '@/features/vehicles/Components/service-page/ServicePageClient'
@@ -205,11 +205,13 @@ export async function ServiceRecordPage({
   const membership = session?.user?.id ? await getCachedMembership(session.user.id) : null
   const membership = session?.user?.id ? await getCachedMembership(session.user.id) : null
   const orgId = membership?.organizationId
   const orgId = membership?.organizationId
   // Whether the status menus offer the way to add a status. Somebody who
   // Whether the status menus offer the way to add a status. Somebody who
-  // cannot change settings is better off not seeing a link that turns them away.
-  const canAddStatus = await canEditSettings(session?.user?.id ?? '', membership?.role)
+  // cannot change settings is better off not seeing a link that turns them
+  // away, and so is somebody who may change them but not open the page (the
+  // settings layout needs READ as well as UPDATE).
+  const canAddStatus = await canOpenAndEditSettings(session?.user?.id ?? '', membership?.role)
   // Whether the invoice's "Set payment terms" link may be offered: the
   // Whether the invoice's "Set payment terms" link may be offered: the
   // settings page has to open for them (READ) as well as save (UPDATE).
   // settings page has to open for them (READ) as well as save (UPDATE).
-  const canSetPaymentTerms = await canOpenAndEditSettings(session?.user?.id ?? '', membership?.role)
+  const canSetPaymentTerms = canAddStatus
   // Whether a job whose vehicle has no owner offers to add one.
   // Whether a job whose vehicle has no owner offers to add one.
   const canSetCustomer = await canEditVehicles(authContext)
   const canSetCustomer = await canEditVehicles(authContext)
   // Whether the header's "Unpaid" opens the payment form.
   // Whether the header's "Unpaid" opens the payment form.

+ 34 - 18
src/features/vehicles/Components/service-page/modern/MoneyBar.tsx

@@ -57,16 +57,27 @@ export function MoneyBar({
       className="hidden shrink-0 border-t bg-background/95 backdrop-blur lg:block"
       className="hidden shrink-0 border-t bg-background/95 backdrop-blur lg:block"
     >
     >
       <div className="mx-auto flex w-full max-w-[1800px] flex-wrap items-center gap-x-6 gap-y-2 px-4 py-2">
       <div className="mx-auto flex w-full max-w-[1800px] flex-wrap items-center gap-x-6 gap-y-2 px-4 py-2">
+        {/* Each figure keeps to its share of the bar: an absurd total is cut
+            short (in full on hover) rather than pushing the buttons off. */}
         <dl className="flex min-w-0 flex-1 items-baseline gap-x-5 gap-y-1">
         <dl className="flex min-w-0 flex-1 items-baseline gap-x-5 gap-y-1">
-          <div className="hidden items-baseline gap-1.5 sm:flex">
-            <dt className="text-xs text-muted-foreground">{t('total')}</dt>
-            <dd className="font-mono text-sm tabular-nums" data-testid="money-total">
+          <div className="hidden min-w-0 items-baseline gap-1.5 sm:flex">
+            <dt className="shrink-0 text-xs text-muted-foreground">{t('total')}</dt>
+            <dd
+              className="min-w-0 truncate font-mono text-sm tabular-nums"
+              data-testid="money-total"
+              title={formatCurrency(total, currencyCode)}
+            >
               {formatCurrency(total, currencyCode)}
               {formatCurrency(total, currencyCode)}
             </dd>
             </dd>
           </div>
           </div>
-          <div className="hidden items-baseline gap-1.5 sm:flex">
-            <dt className="text-xs text-muted-foreground">{t('paid')}</dt>
-            <dd className="font-mono text-sm tabular-nums" data-testid="money-paid">
+          {/* Gives way last: what was paid is never more than the total. */}
+          <div className="hidden shrink-0 items-baseline gap-1.5 sm:flex">
+            <dt className="shrink-0 text-xs text-muted-foreground">{t('paid')}</dt>
+            <dd
+              className="min-w-0 truncate font-mono text-sm tabular-nums"
+              data-testid="money-paid"
+              title={formatCurrency(paid, currencyCode)}
+            >
               {formatCurrency(paid, currencyCode)}
               {formatCurrency(paid, currencyCode)}
             </dd>
             </dd>
           </div>
           </div>
@@ -78,14 +89,15 @@ export function MoneyBar({
               <dd className="text-sm text-muted-foreground">{t('nothingOwed')}</dd>
               <dd className="text-sm text-muted-foreground">{t('nothingOwed')}</dd>
             </div>
             </div>
           ) : (
           ) : (
-            <div className="flex items-baseline gap-2">
-              <dt className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
+            <div className="flex min-w-0 items-baseline gap-2">
+              <dt className="shrink-0 text-xs font-medium uppercase tracking-wider text-muted-foreground">
                 {settled ? t('settled') : t('balance')}
                 {settled ? t('settled') : t('balance')}
               </dt>
               </dt>
               <dd
               <dd
                 data-testid="money-balance"
                 data-testid="money-balance"
+                title={formatCurrency(balance, currencyCode)}
                 className={cn(
                 className={cn(
-                  'order-number text-xl font-bold leading-none tabular-nums',
+                  'order-number min-w-0 truncate text-xl font-bold leading-none tabular-nums',
                   settled && 'text-emerald-600 dark:text-emerald-400'
                   settled && 'text-emerald-600 dark:text-emerald-400'
                 )}
                 )}
               >
               >
@@ -149,23 +161,27 @@ export function MoneyLine({
       data-testid="money-line"
       data-testid="money-line"
       className="flex flex-wrap items-baseline justify-end gap-x-5 gap-y-1 rounded-lg border border-card-edge bg-card px-5 py-3 lg:hidden"
       className="flex flex-wrap items-baseline justify-end gap-x-5 gap-y-1 rounded-lg border border-card-edge bg-card px-5 py-3 lg:hidden"
     >
     >
-      <div className="flex items-baseline gap-1.5">
-        <dt className="text-xs text-muted-foreground">{t('total')}</dt>
-        <dd className="font-mono text-sm tabular-nums">{formatCurrency(total, currencyCode)}</dd>
+      <div className="flex min-w-0 items-baseline gap-1.5">
+        <dt className="shrink-0 text-xs text-muted-foreground">{t('total')}</dt>
+        <dd className="min-w-0 font-mono text-sm tabular-nums [overflow-wrap:anywhere]">
+          {formatCurrency(total, currencyCode)}
+        </dd>
       </div>
       </div>
       {paid > 0 && (
       {paid > 0 && (
-        <div className="flex items-baseline gap-1.5">
-          <dt className="text-xs text-muted-foreground">{t('paid')}</dt>
-          <dd className="font-mono text-sm tabular-nums">{formatCurrency(paid, currencyCode)}</dd>
+        <div className="flex min-w-0 items-baseline gap-1.5">
+          <dt className="shrink-0 text-xs text-muted-foreground">{t('paid')}</dt>
+          <dd className="min-w-0 font-mono text-sm tabular-nums [overflow-wrap:anywhere]">
+            {formatCurrency(paid, currencyCode)}
+          </dd>
         </div>
         </div>
       )}
       )}
-      <div className="flex items-baseline gap-2">
-        <dt className="text-xs font-medium uppercase tracking-wider text-muted-foreground">
+      <div className="flex min-w-0 items-baseline gap-2">
+        <dt className="shrink-0 text-xs font-medium uppercase tracking-wider text-muted-foreground">
           {settled ? t('settled') : t('balance')}
           {settled ? t('settled') : t('balance')}
         </dt>
         </dt>
         <dd
         <dd
           className={cn(
           className={cn(
-            'order-number text-lg font-bold leading-none tabular-nums',
+            'order-number min-w-0 text-lg font-bold leading-none tabular-nums [overflow-wrap:anywhere]',
             settled && 'text-emerald-600 dark:text-emerald-400'
             settled && 'text-emerald-600 dark:text-emerald-400'
           )}
           )}
         >
         >

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

@@ -19,7 +19,7 @@ import { formatCurrency } from '@/lib/format'
 import { findServiceFormProblem } from '@/features/vehicles/Lib/validateServiceForm'
 import { findServiceFormProblem } from '@/features/vehicles/Lib/validateServiceForm'
 import { LINE_TOTAL_MAX, QUANTITY_MAX, READING_MAX, UNIT_PRICE_MAX } from '@/lib/input-limits'
 import { LINE_TOTAL_MAX, QUANTITY_MAX, READING_MAX, UNIT_PRICE_MAX } from '@/lib/input-limits'
 import { useServiceType } from '@/components/service-type-context'
 import { useServiceType } from '@/components/service-type-context'
-import { useFieldErrorText } from '@/components/field-errors'
+import { LINE_ERROR_SELECTOR, useFieldErrorText } from '@/components/field-errors'
 import type { FieldError } from '@/lib/field-errors'
 import type { FieldError } from '@/lib/field-errors'
 import { readingNeedsAnswer } from '@/features/vehicles/Lib/vehicleReading'
 import { readingNeedsAnswer } from '@/features/vehicles/Lib/vehicleReading'
 import { revealRequiredMeters } from '@/features/meters/Lib/requiredMetersReveal'
 import { revealRequiredMeters } from '@/features/meters/Lib/requiredMetersReveal'
@@ -215,8 +215,16 @@ export function useServiceActions({
           reading: formatNumber(READING_MAX),
           reading: formatNumber(READING_MAX),
         })
         })
       )
       )
-      if (problem === 'negativeReading')
+      // The cursor goes to the figure at fault: the reading, or the first
+      // line figure the editors have marked (see partLineIssues). Not on an
+      // autosave, which would pull the cursor out of whatever is being typed.
+      const lineField = form.querySelector<HTMLElement>(LINE_ERROR_SELECTOR)
+      if (autosave) {
+        // Said, and the cursor left where it is.
+      } else if (problem === 'negativeReading' || (problem === 'tooLarge' && !lineField))
         form.querySelector<HTMLInputElement>('input[name="mileage"]')?.focus()
         form.querySelector<HTMLInputElement>('input[name="mileage"]')?.focus()
+      else if (problem === 'negative' || problem === 'tooLarge' || problem === 'zeroQuantity')
+        lineField?.focus()
       return
       return
     }
     }
 
 

+ 74 - 0
src/lib/input-limits.ts

@@ -64,6 +64,80 @@ export function checkLineAmounts(
   }
   }
 }
 }
 
 
+/**
+ * What is wrong with one figure on a line, in the terms of
+ * src/lib/field-errors.ts, so a line editor can say it under the field.
+ */
+export interface LineFigureIssue {
+  issue: 'negative' | 'positive' | 'tooLarge'
+  limit?: number
+}
+
+/** A figure as typed: an empty box or letters count as nothing, as the save reads them. */
+function figure(value: unknown): number {
+  const parsed = Number(value ?? 0)
+  return Number.isFinite(parsed) ? parsed : 0
+}
+
+function bounded(value: number, max: number): LineFigureIssue | undefined {
+  if (value < 0) return { issue: 'negative' }
+  if (value > max) return { issue: 'tooLarge', limit: max }
+  return undefined
+}
+
+export type PartLineIssues = Partial<
+  Record<'quantity' | 'unitPrice' | 'unitCost' | 'total', LineFigureIssue>
+>
+export type LaborLineIssues = Partial<Record<'hours' | 'rate' | 'total', LineFigureIssue>>
+
+/**
+ * The figures on a part line the save would refuse, by field: the rules of
+ * servicePartSchema and quotePartSchema, worked out as the line is typed so
+ * the field is marked before anybody presses Save. The line's quantity times
+ * its price is reported as "total", said under the line's total.
+ */
+export function partLineIssues(part: {
+  name?: string | null
+  quantity: unknown
+  unitPrice: unknown
+  unitCost?: unknown
+}): PartLineIssues {
+  const quantity = figure(part.quantity)
+  const unitPrice = figure(part.unitPrice)
+  const issues: PartLineIssues = {}
+  const quantityIssue = bounded(quantity, QUANTITY_MAX)
+  if (quantityIssue) issues.quantity = quantityIssue
+  // Priced and billed nothing. A free part may sit at zero as a note of what
+  // was used, and a row with no name yet is still being typed.
+  else if (part.name?.trim() && unitPrice > 0 && quantity <= 0) {
+    issues.quantity = { issue: 'positive' }
+  }
+  const priceIssue = bounded(unitPrice, UNIT_PRICE_MAX)
+  if (priceIssue) issues.unitPrice = priceIssue
+  const costIssue = bounded(figure(part.unitCost), UNIT_PRICE_MAX)
+  if (costIssue) issues.unitCost = costIssue
+  if (quantity * unitPrice > LINE_TOTAL_MAX) {
+    issues.total = { issue: 'tooLarge', limit: LINE_TOTAL_MAX }
+  }
+  return issues
+}
+
+/**
+ * The figures on a labour line the save would refuse, by field. Hours may be
+ * zero: a line started and not yet clocked, or work done for nothing.
+ */
+export function laborLineIssues(labor: { hours: unknown; rate: unknown }): LaborLineIssues {
+  const hours = figure(labor.hours)
+  const rate = figure(labor.rate)
+  const issues: LaborLineIssues = {}
+  const hoursIssue = bounded(hours, LABOR_HOURS_MAX)
+  if (hoursIssue) issues.hours = hoursIssue
+  const rateIssue = bounded(rate, UNIT_PRICE_MAX)
+  if (rateIssue) issues.rate = rateIssue
+  if (hours * rate > LINE_TOTAL_MAX) issues.total = { issue: 'tooLarge', limit: LINE_TOTAL_MAX }
+  return issues
+}
+
 /** A person's or a company's name, a make, a model. */
 /** A person's or a company's name, a make, a model. */
 export const NAME_MAX_LENGTH = 200
 export const NAME_MAX_LENGTH = 200
 /** A postal address, street to country. */
 /** A postal address, street to country. */