Răsfoiți Sursa

Refuse negative readings, zero quantities and absurd amounts (#683)

* Refuse negative readings, zero quantities and absurd amounts

* Hold line totals to the cent everywhere lines are compared, summed or added
Bernt Christian Egeland 3 zile în urmă
părinte
comite
5cfdc3c76d
55 a modificat fișierele cu 927 adăugiri și 127 ștergeri
  1. 24 0
      e2e/specs/work-orders/validation.spec.ts
  2. 2 1
      messages/bg/common.json
  3. 4 1
      messages/bg/service.json
  4. 2 1
      messages/de/common.json
  5. 4 1
      messages/de/service.json
  6. 2 1
      messages/en/common.json
  7. 4 1
      messages/en/service.json
  8. 2 1
      messages/es/common.json
  9. 4 1
      messages/es/service.json
  10. 2 1
      messages/fr/common.json
  11. 4 1
      messages/fr/service.json
  12. 2 1
      messages/it/common.json
  13. 4 1
      messages/it/service.json
  14. 2 1
      messages/lt/common.json
  15. 4 1
      messages/lt/service.json
  16. 2 1
      messages/nb/common.json
  17. 4 1
      messages/nb/service.json
  18. 2 1
      messages/nl/common.json
  19. 4 1
      messages/nl/service.json
  20. 2 1
      messages/pl/common.json
  21. 4 1
      messages/pl/service.json
  22. 2 1
      messages/pt-BR/common.json
  23. 4 1
      messages/pt-BR/service.json
  24. 2 1
      messages/pt-PT/common.json
  25. 4 1
      messages/pt-PT/service.json
  26. 2 1
      messages/ru/common.json
  27. 4 1
      messages/ru/service.json
  28. 2 1
      messages/tr/common.json
  29. 4 1
      messages/tr/service.json
  30. 23 0
      src/__tests__/features/tax/taxable-lines-retotal.test.ts
  31. 25 0
      src/__tests__/features/tax/taxable-lines-save.test.ts
  32. 121 0
      src/__tests__/features/workorders/impossible-values.test.ts
  33. 118 0
      src/__tests__/features/workorders/rounded-lines.test.ts
  34. 40 0
      src/__tests__/features/workorders/validate-service-form.test.ts
  35. 14 10
      src/app/(authenticated)/customers/[id]/customer-detail-client.tsx
  36. 14 0
      src/features/customers/Components/CustomerForm.tsx
  37. 14 7
      src/features/customers/Schema/customerSchema.ts
  38. 3 2
      src/features/inspections/Schema/inspectionSchema.ts
  39. 5 0
      src/features/labor-presets/Components/LaborPresetForm.tsx
  40. 35 18
      src/features/labor-presets/Schema/laborPresetSchema.ts
  41. 78 0
      src/features/vehicles/Actions/serviceActions.ts
  42. 8 0
      src/features/vehicles/Components/VehicleForm.tsx
  43. 3 0
      src/features/vehicles/Components/service-page/modern/JobFactsCard.tsx
  44. 14 2
      src/features/vehicles/Components/service-page/useServiceActions.ts
  45. 14 6
      src/features/vehicles/Components/service-page/useServiceFormState.ts
  46. 26 1
      src/features/vehicles/Lib/addPart.ts
  47. 4 1
      src/features/vehicles/Lib/laborLines.ts
  48. 4 1
      src/features/vehicles/Lib/partLines.ts
  49. 43 0
      src/features/vehicles/Lib/subtotalFromLines.ts
  50. 44 0
      src/features/vehicles/Lib/validateServiceForm.ts
  51. 2 1
      src/features/vehicles/Schema/fuelSchema.ts
  52. 76 39
      src/features/vehicles/Schema/serviceSchema.ts
  53. 12 11
      src/features/vehicles/Schema/vehicleSchema.ts
  54. 3 0
      src/lib/field-errors.ts
  55. 76 0
      src/lib/input-limits.ts

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

@@ -123,6 +123,30 @@ test.describe('a work order that cannot be saved says why', () => {
     await expectRefused(page, /cannot be negative/i)
     await expectRefused(page, /cannot be negative/i)
   })
   })
 
 
+  test('a priced part with a quantity of zero is refused, not billed as nothing', async ({
+    page,
+  }) => {
+    await page.goto(jobUrl)
+    const quantity = partRowOf(partRows(page).first()).locator('input[type="number"]').first()
+    await expect(async () => {
+      await quantity.fill('0')
+      await expect(quantity).toHaveValue('0', { timeout: 2_000 })
+    }).toPass({ timeout: 30_000 })
+
+    await expectRefused(page, /needs a quantity above zero/i)
+  })
+
+  test('a negative reading is refused in words', async ({ page }) => {
+    await page.goto(jobUrl)
+    const reading = page.locator('input[name="mileage"]').filter({ visible: true })
+    await expect(async () => {
+      await reading.fill('-5')
+      await expect(reading).toHaveValue('-5', { timeout: 2_000 })
+    }).toPass({ timeout: 30_000 })
+
+    await expectRefused(page, /reading can't be negative/i)
+  })
+
   test('the job is left as it was found, saved and correct', async ({ page }) => {
   test('the job is left as it was found, saved and correct', async ({ page }) => {
     await page.goto(jobUrl)
     await page.goto(jobUrl)
     await expect(totalsRow(page, 'Parts')).toContainText('$1,100.00')
     await expect(totalsRow(page, 'Parts')).toContainText('$1,100.00')

+ 2 - 1
messages/bg/common.json

@@ -341,6 +341,7 @@
     "wholeNumber": "Въведете цяло число.",
     "wholeNumber": "Въведете цяло число.",
     "invalid": "Тази стойност е невалидна.",
     "invalid": "Тази стойност е невалидна.",
     "notSaved": "Не е запазено. Проверете отбелязаните полета.",
     "notSaved": "Не е запазено. Проверете отбелязаните полета.",
-    "withLabel": "{label}: {problem}"
+    "withLabel": "{label}: {problem}",
+    "positive": "Трябва да е повече от 0."
   }
   }
 }
 }

+ 4 - 1
messages/bg/service.json

@@ -23,7 +23,10 @@
       "negative": "Количествата, часовете, цените и разходите не могат да бъдат отрицателни.",
       "negative": "Количествата, часовете, цените и разходите не могат да бъдат отрицателни.",
       "partName": "Всяка резервна част с цена трябва да има име.",
       "partName": "Всяка резервна част с цена трябва да има име.",
       "laborDescription": "Всяка позиция за труд с часове или ставка трябва да има описание.",
       "laborDescription": "Всяка позиция за труд с часове или ставка трябва да има описание.",
-      "concernCondition": "Проблем, за който са попълнени причина, корекция или потвърждение, трябва да има и попълнено състояние."
+      "concernCondition": "Проблем, за който са попълнени причина, корекция или потвърждение, трябва да има и попълнено състояние.",
+      "negativeReading": "Показанието не може да е отрицателно.",
+      "tooLarge": "Стойност е твърде голяма. Количеството може да е най-много {quantity}, цената {price}, сумата на ред {total}, а показанието {reading}.",
+      "zeroQuantity": "Част с цена трябва да има количество над нула."
     }
     }
   },
   },
   "header": {
   "header": {

+ 2 - 1
messages/de/common.json

@@ -341,6 +341,7 @@
     "wholeNumber": "Geben Sie eine ganze Zahl ein.",
     "wholeNumber": "Geben Sie eine ganze Zahl ein.",
     "invalid": "Dieser Wert ist ungültig.",
     "invalid": "Dieser Wert ist ungültig.",
     "notSaved": "Nicht gespeichert. Prüfen Sie die markierten Felder.",
     "notSaved": "Nicht gespeichert. Prüfen Sie die markierten Felder.",
-    "withLabel": "{label}: {problem}"
+    "withLabel": "{label}: {problem}",
+    "positive": "Muss größer als 0 sein."
   }
   }
 }
 }

+ 4 - 1
messages/de/service.json

@@ -23,7 +23,10 @@
       "negative": "Mengen, Stunden, Preise und Kosten dürfen nicht negativ sein.",
       "negative": "Mengen, Stunden, Preise und Kosten dürfen nicht negativ sein.",
       "partName": "Jedes Teil mit Preis braucht einen Namen.",
       "partName": "Jedes Teil mit Preis braucht einen Namen.",
       "laborDescription": "Jede Arbeitszeile mit Stunden oder Satz braucht eine Beschreibung.",
       "laborDescription": "Jede Arbeitszeile mit Stunden oder Satz braucht eine Beschreibung.",
-      "concernCondition": "Ein Anliegen mit Ursache, Behebung oder Kontrolle braucht eine ausgefüllte Beanstandung."
+      "concernCondition": "Ein Anliegen mit Ursache, Behebung oder Kontrolle braucht eine ausgefüllte Beanstandung.",
+      "negativeReading": "Der Zählerstand darf nicht negativ sein.",
+      "tooLarge": "Ein Wert ist zu groß. Eine Menge darf höchstens {quantity} sein, ein Preis {price}, eine Zeilensumme {total} und ein Zählerstand {reading}.",
+      "zeroQuantity": "Ein Teil mit Preis braucht eine Menge über null."
     }
     }
   },
   },
   "header": {
   "header": {

+ 2 - 1
messages/en/common.json

@@ -341,6 +341,7 @@
     "wholeNumber": "Enter a whole number.",
     "wholeNumber": "Enter a whole number.",
     "invalid": "This value isn't valid.",
     "invalid": "This value isn't valid.",
     "notSaved": "Not saved. Check the marked fields.",
     "notSaved": "Not saved. Check the marked fields.",
-    "withLabel": "{label}: {problem}"
+    "withLabel": "{label}: {problem}",
+    "positive": "Must be more than 0."
   }
   }
 }
 }

+ 4 - 1
messages/en/service.json

@@ -23,7 +23,10 @@
       "negative": "Quantities, hours, prices and costs cannot be negative.",
       "negative": "Quantities, hours, prices and costs cannot be negative.",
       "partName": "Every priced part needs a name.",
       "partName": "Every priced part needs a name.",
       "laborDescription": "Every labor line with hours or a rate needs a description.",
       "laborDescription": "Every labor line with hours or a rate needs a description.",
-      "concernCondition": "A concern with a cause, correction or confirmation needs its condition filled in."
+      "concernCondition": "A concern with a cause, correction or confirmation needs its condition filled in.",
+      "negativeReading": "The reading can't be negative.",
+      "tooLarge": "A figure is too large. A quantity can be at most {quantity}, a price {price}, a line total {total} and a reading {reading}.",
+      "zeroQuantity": "A priced part needs a quantity above zero."
     }
     }
   },
   },
   "header": {
   "header": {

+ 2 - 1
messages/es/common.json

@@ -341,6 +341,7 @@
     "wholeNumber": "Introduce un número entero.",
     "wholeNumber": "Introduce un número entero.",
     "invalid": "Este valor no es válido.",
     "invalid": "Este valor no es válido.",
     "notSaved": "No se ha guardado. Revisa los campos marcados.",
     "notSaved": "No se ha guardado. Revisa los campos marcados.",
-    "withLabel": "{label}: {problem}"
+    "withLabel": "{label}: {problem}",
+    "positive": "Debe ser mayor que 0."
   }
   }
 }
 }

+ 4 - 1
messages/es/service.json

@@ -23,7 +23,10 @@
       "negative": "Las cantidades, horas, precios y costes no pueden ser negativos.",
       "negative": "Las cantidades, horas, precios y costes no pueden ser negativos.",
       "partName": "Toda pieza con precio necesita un nombre.",
       "partName": "Toda pieza con precio necesita un nombre.",
       "laborDescription": "Toda línea de mano de obra con horas o tarifa necesita una descripción.",
       "laborDescription": "Toda línea de mano de obra con horas o tarifa necesita una descripción.",
-      "concernCondition": "Un motivo con causa, corrección o confirmación necesita que se rellene su condición."
+      "concernCondition": "Un motivo con causa, corrección o confirmación necesita que se rellene su condición.",
+      "negativeReading": "La lectura no puede ser negativa.",
+      "tooLarge": "Una cifra es demasiado grande. Una cantidad puede ser como máximo {quantity}, un precio {price}, un total de línea {total} y una lectura {reading}.",
+      "zeroQuantity": "Una pieza con precio necesita una cantidad mayor que cero."
     }
     }
   },
   },
   "header": {
   "header": {

+ 2 - 1
messages/fr/common.json

@@ -341,6 +341,7 @@
     "wholeNumber": "Saisissez un nombre entier.",
     "wholeNumber": "Saisissez un nombre entier.",
     "invalid": "Cette valeur n'est pas valide.",
     "invalid": "Cette valeur n'est pas valide.",
     "notSaved": "Non enregistré. Vérifiez les champs signalés.",
     "notSaved": "Non enregistré. Vérifiez les champs signalés.",
-    "withLabel": "{label} : {problem}"
+    "withLabel": "{label} : {problem}",
+    "positive": "Doit être supérieur à 0."
   }
   }
 }
 }

+ 4 - 1
messages/fr/service.json

@@ -23,7 +23,10 @@
       "negative": "Les quantités, heures, prix et coûts ne peuvent pas être négatifs.",
       "negative": "Les quantités, heures, prix et coûts ne peuvent pas être négatifs.",
       "partName": "Chaque pièce avec un prix doit avoir un nom.",
       "partName": "Chaque pièce avec un prix doit avoir un nom.",
       "laborDescription": "Chaque ligne de main-d'œuvre avec des heures ou un taux doit avoir une description.",
       "laborDescription": "Chaque ligne de main-d'œuvre avec des heures ou un taux doit avoir une description.",
-      "concernCondition": "Un point avec une cause, une correction ou un contrôle doit avoir son symptôme renseigné."
+      "concernCondition": "Un point avec une cause, une correction ou un contrôle doit avoir son symptôme renseigné.",
+      "negativeReading": "Le relevé ne peut pas être négatif.",
+      "tooLarge": "Un montant est trop élevé. Une quantité peut être au plus {quantity}, un prix {price}, un total de ligne {total} et un relevé {reading}.",
+      "zeroQuantity": "Une pièce avec un prix doit avoir une quantité supérieure à zéro."
     }
     }
   },
   },
   "header": {
   "header": {

+ 2 - 1
messages/it/common.json

@@ -341,6 +341,7 @@
     "wholeNumber": "Inserisci un numero intero.",
     "wholeNumber": "Inserisci un numero intero.",
     "invalid": "Questo valore non è valido.",
     "invalid": "Questo valore non è valido.",
     "notSaved": "Non salvato. Controlla i campi evidenziati.",
     "notSaved": "Non salvato. Controlla i campi evidenziati.",
-    "withLabel": "{label}: {problem}"
+    "withLabel": "{label}: {problem}",
+    "positive": "Deve essere maggiore di 0."
   }
   }
 }
 }

+ 4 - 1
messages/it/service.json

@@ -23,7 +23,10 @@
       "negative": "Quantità, ore, prezzi e costi non possono essere negativi.",
       "negative": "Quantità, ore, prezzi e costi non possono essere negativi.",
       "partName": "Ogni ricambio con un prezzo deve avere un nome.",
       "partName": "Ogni ricambio con un prezzo deve avere un nome.",
       "laborDescription": "Ogni riga di manodopera con ore o tariffa deve avere una descrizione.",
       "laborDescription": "Ogni riga di manodopera con ore o tariffa deve avere una descrizione.",
-      "concernCondition": "Una segnalazione con causa, intervento o verifica deve avere il sintomo compilato."
+      "concernCondition": "Una segnalazione con causa, intervento o verifica deve avere il sintomo compilato.",
+      "negativeReading": "La lettura non può essere negativa.",
+      "tooLarge": "Un valore è troppo grande. Una quantità può essere al massimo {quantity}, un prezzo {price}, un totale di riga {total} e una lettura {reading}.",
+      "zeroQuantity": "Un ricambio con prezzo deve avere una quantità maggiore di zero."
     }
     }
   },
   },
   "header": {
   "header": {

+ 2 - 1
messages/lt/common.json

@@ -341,6 +341,7 @@
     "wholeNumber": "Įveskite sveikąjį skaičių.",
     "wholeNumber": "Įveskite sveikąjį skaičių.",
     "invalid": "Ši reikšmė netinkama.",
     "invalid": "Ši reikšmė netinkama.",
     "notSaved": "Neišsaugota. Patikrinkite pažymėtus laukus.",
     "notSaved": "Neišsaugota. Patikrinkite pažymėtus laukus.",
-    "withLabel": "{label}: {problem}"
+    "withLabel": "{label}: {problem}",
+    "positive": "Turi būti daugiau nei 0."
   }
   }
 }
 }

+ 4 - 1
messages/lt/service.json

@@ -23,7 +23,10 @@
       "negative": "Kiekiai, valandos, kainos ir sąnaudos negali būti neigiami.",
       "negative": "Kiekiai, valandos, kainos ir sąnaudos negali būti neigiami.",
       "partName": "Kiekviena dalis su kaina turi turėti pavadinimą.",
       "partName": "Kiekviena dalis su kaina turi turėti pavadinimą.",
       "laborDescription": "Kiekviena darbo eilutė su valandomis ar įkainiu turi turėti aprašymą.",
       "laborDescription": "Kiekviena darbo eilutė su valandomis ar įkainiu turi turėti aprašymą.",
-      "concernCondition": "Punktui su priežastimi, pataisymu ar patikrinimu reikia užpildyti būklę."
+      "concernCondition": "Punktui su priežastimi, pataisymu ar patikrinimu reikia užpildyti būklę.",
+      "negativeReading": "Rodmuo negali būti neigiamas.",
+      "tooLarge": "Skaičius per didelis. Kiekis gali būti ne didesnis kaip {quantity}, kaina {price}, eilutės suma {total}, o rodmuo {reading}.",
+      "zeroQuantity": "Detalei su kaina reikia kiekio, didesnio už nulį."
     }
     }
   },
   },
   "header": {
   "header": {

+ 2 - 1
messages/nb/common.json

@@ -341,6 +341,7 @@
     "wholeNumber": "Skriv inn et heltall.",
     "wholeNumber": "Skriv inn et heltall.",
     "invalid": "Denne verdien er ikke gyldig.",
     "invalid": "Denne verdien er ikke gyldig.",
     "notSaved": "Ikke lagret. Sjekk de merkede feltene.",
     "notSaved": "Ikke lagret. Sjekk de merkede feltene.",
-    "withLabel": "{label}: {problem}"
+    "withLabel": "{label}: {problem}",
+    "positive": "Må være mer enn 0."
   }
   }
 }
 }

+ 4 - 1
messages/nb/service.json

@@ -23,7 +23,10 @@
       "negative": "Antall, timer, priser og kostnader kan ikke være negative.",
       "negative": "Antall, timer, priser og kostnader kan ikke være negative.",
       "partName": "Alle deler med pris må ha et navn.",
       "partName": "Alle deler med pris må ha et navn.",
       "laborDescription": "Alle arbeidslinjer med timer eller sats må ha en beskrivelse.",
       "laborDescription": "Alle arbeidslinjer med timer eller sats må ha en beskrivelse.",
-      "concernCondition": "Et punkt med årsak, utbedring eller kontroll må ha tilstanden fylt ut."
+      "concernCondition": "Et punkt med årsak, utbedring eller kontroll må ha tilstanden fylt ut.",
+      "negativeReading": "Avlesningen kan ikke være negativ.",
+      "tooLarge": "Et tall er for stort. Et antall kan være høyst {quantity}, en pris {price}, en linjesum {total} og en avlesning {reading}.",
+      "zeroQuantity": "En del med pris må ha et antall over null."
     }
     }
   },
   },
   "header": {
   "header": {

+ 2 - 1
messages/nl/common.json

@@ -341,6 +341,7 @@
     "wholeNumber": "Vul een heel getal in.",
     "wholeNumber": "Vul een heel getal in.",
     "invalid": "Deze waarde is niet geldig.",
     "invalid": "Deze waarde is niet geldig.",
     "notSaved": "Niet opgeslagen. Controleer de gemarkeerde velden.",
     "notSaved": "Niet opgeslagen. Controleer de gemarkeerde velden.",
-    "withLabel": "{label}: {problem}"
+    "withLabel": "{label}: {problem}",
+    "positive": "Moet meer dan 0 zijn."
   }
   }
 }
 }

+ 4 - 1
messages/nl/service.json

@@ -23,7 +23,10 @@
       "negative": "Aantallen, uren, prijzen en kosten kunnen niet negatief zijn.",
       "negative": "Aantallen, uren, prijzen en kosten kunnen niet negatief zijn.",
       "partName": "Elk onderdeel met een prijs heeft een naam nodig.",
       "partName": "Elk onderdeel met een prijs heeft een naam nodig.",
       "laborDescription": "Elke arbeidsregel met uren of tarief heeft een omschrijving nodig.",
       "laborDescription": "Elke arbeidsregel met uren of tarief heeft een omschrijving nodig.",
-      "concernCondition": "Een melding met een oorzaak, oplossing of controle moet een ingevulde klacht hebben."
+      "concernCondition": "Een melding met een oorzaak, oplossing of controle moet een ingevulde klacht hebben.",
+      "negativeReading": "De stand kan niet negatief zijn.",
+      "tooLarge": "Een getal is te groot. Een aantal mag hoogstens {quantity} zijn, een prijs {price}, een regeltotaal {total} en een stand {reading}.",
+      "zeroQuantity": "Een onderdeel met een prijs heeft een aantal boven nul nodig."
     }
     }
   },
   },
   "header": {
   "header": {

+ 2 - 1
messages/pl/common.json

@@ -341,6 +341,7 @@
     "wholeNumber": "Wpisz liczbę całkowitą.",
     "wholeNumber": "Wpisz liczbę całkowitą.",
     "invalid": "Ta wartość jest nieprawidłowa.",
     "invalid": "Ta wartość jest nieprawidłowa.",
     "notSaved": "Nie zapisano. Sprawdź zaznaczone pola.",
     "notSaved": "Nie zapisano. Sprawdź zaznaczone pola.",
-    "withLabel": "{label}: {problem}"
+    "withLabel": "{label}: {problem}",
+    "positive": "Musi być większe niż 0."
   }
   }
 }
 }

+ 4 - 1
messages/pl/service.json

@@ -23,7 +23,10 @@
       "negative": "Ilości, godziny, ceny i koszty nie mogą być ujemne.",
       "negative": "Ilości, godziny, ceny i koszty nie mogą być ujemne.",
       "partName": "Każda część z ceną musi mieć nazwę.",
       "partName": "Każda część z ceną musi mieć nazwę.",
       "laborDescription": "Każda pozycja robocizny z godzinami lub stawką musi mieć opis.",
       "laborDescription": "Każda pozycja robocizny z godzinami lub stawką musi mieć opis.",
-      "concernCondition": "Zgłoszenie z przyczyną, naprawą lub weryfikacją musi mieć wypełniony objaw."
+      "concernCondition": "Zgłoszenie z przyczyną, naprawą lub weryfikacją musi mieć wypełniony objaw.",
+      "negativeReading": "Odczyt nie może być ujemny.",
+      "tooLarge": "Liczba jest za duża. Ilość może wynosić najwyżej {quantity}, cena {price}, suma pozycji {total}, a odczyt {reading}.",
+      "zeroQuantity": "Część z ceną musi mieć ilość większą od zera."
     }
     }
   },
   },
   "header": {
   "header": {

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

@@ -341,6 +341,7 @@
     "wholeNumber": "Digite um número inteiro.",
     "wholeNumber": "Digite um número inteiro.",
     "invalid": "Este valor não é válido.",
     "invalid": "Este valor não é válido.",
     "notSaved": "Não salvo. Verifique os campos marcados.",
     "notSaved": "Não salvo. Verifique os campos marcados.",
-    "withLabel": "{label}: {problem}"
+    "withLabel": "{label}: {problem}",
+    "positive": "Deve ser maior que 0."
   }
   }
 }
 }

+ 4 - 1
messages/pt-BR/service.json

@@ -23,7 +23,10 @@
       "negative": "Quantidades, horas, preços e custos não podem ser negativos.",
       "negative": "Quantidades, horas, preços e custos não podem ser negativos.",
       "partName": "Toda peça com preço precisa de um nome.",
       "partName": "Toda peça com preço precisa de um nome.",
       "laborDescription": "Toda linha de mão de obra com horas ou taxa precisa de uma descrição.",
       "laborDescription": "Toda linha de mão de obra com horas ou taxa precisa de uma descrição.",
-      "concernCondition": "Um relato com causa, correção ou confirmação precisa ter a condição preenchida."
+      "concernCondition": "Um relato com causa, correção ou confirmação precisa ter a condição preenchida.",
+      "negativeReading": "A leitura não pode ser negativa.",
+      "tooLarge": "Um valor é grande demais. Uma quantidade pode ser no máximo {quantity}, um preço {price}, um total de linha {total} e uma leitura {reading}.",
+      "zeroQuantity": "Uma peça com preço precisa de uma quantidade acima de zero."
     }
     }
   },
   },
   "header": {
   "header": {

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

@@ -341,6 +341,7 @@
     "wholeNumber": "Introduza um número inteiro.",
     "wholeNumber": "Introduza um número inteiro.",
     "invalid": "Este valor não é válido.",
     "invalid": "Este valor não é válido.",
     "notSaved": "Não guardado. Verifique os campos assinalados.",
     "notSaved": "Não guardado. Verifique os campos assinalados.",
-    "withLabel": "{label}: {problem}"
+    "withLabel": "{label}: {problem}",
+    "positive": "Tem de ser maior que 0."
   }
   }
 }
 }

+ 4 - 1
messages/pt-PT/service.json

@@ -23,7 +23,10 @@
       "negative": "Quantidades, horas, preços e custos não podem ser negativos.",
       "negative": "Quantidades, horas, preços e custos não podem ser negativos.",
       "partName": "Todas as peças com preço precisam de um nome.",
       "partName": "Todas as peças com preço precisam de um nome.",
       "laborDescription": "Todas as linhas de mão de obra com horas ou taxa precisam de uma descrição.",
       "laborDescription": "Todas as linhas de mão de obra com horas ou taxa precisam de uma descrição.",
-      "concernCondition": "Uma queixa com causa, correção ou confirmação tem de ter a condição preenchida."
+      "concernCondition": "Uma queixa com causa, correção ou confirmação tem de ter a condição preenchida.",
+      "negativeReading": "A leitura não pode ser negativa.",
+      "tooLarge": "Um valor é demasiado grande. Uma quantidade pode ser no máximo {quantity}, um preço {price}, um total de linha {total} e uma leitura {reading}.",
+      "zeroQuantity": "Uma peça com preço precisa de uma quantidade acima de zero."
     }
     }
   },
   },
   "header": {
   "header": {

+ 2 - 1
messages/ru/common.json

@@ -341,6 +341,7 @@
     "wholeNumber": "Введите целое число.",
     "wholeNumber": "Введите целое число.",
     "invalid": "Недопустимое значение.",
     "invalid": "Недопустимое значение.",
     "notSaved": "Не сохранено. Проверьте отмеченные поля.",
     "notSaved": "Не сохранено. Проверьте отмеченные поля.",
-    "withLabel": "{label}: {problem}"
+    "withLabel": "{label}: {problem}",
+    "positive": "Должно быть больше 0."
   }
   }
 }
 }

+ 4 - 1
messages/ru/service.json

@@ -23,7 +23,10 @@
       "negative": "Количество, часы, цены и затраты не могут быть отрицательными.",
       "negative": "Количество, часы, цены и затраты не могут быть отрицательными.",
       "partName": "У каждой детали с ценой должно быть название.",
       "partName": "У каждой детали с ценой должно быть название.",
       "laborDescription": "У каждой строки работ с часами или ставкой должно быть описание.",
       "laborDescription": "У каждой строки работ с часами или ставкой должно быть описание.",
-      "concernCondition": "Если у пункта указаны причина, устранение или проверка, заполните и симптом."
+      "concernCondition": "Если у пункта указаны причина, устранение или проверка, заполните и симптом.",
+      "negativeReading": "Показание не может быть отрицательным.",
+      "tooLarge": "Слишком большое значение. Количество не больше {quantity}, цена не больше {price}, сумма строки не больше {total}, показание не больше {reading}.",
+      "zeroQuantity": "Для запчасти с ценой количество должно быть больше нуля."
     }
     }
   },
   },
   "header": {
   "header": {

+ 2 - 1
messages/tr/common.json

@@ -341,6 +341,7 @@
     "wholeNumber": "Tam sayı girin.",
     "wholeNumber": "Tam sayı girin.",
     "invalid": "Bu değer geçerli değil.",
     "invalid": "Bu değer geçerli değil.",
     "notSaved": "Kaydedilmedi. İşaretli alanları kontrol edin.",
     "notSaved": "Kaydedilmedi. İşaretli alanları kontrol edin.",
-    "withLabel": "{label}: {problem}"
+    "withLabel": "{label}: {problem}",
+    "positive": "0'dan büyük olmalı."
   }
   }
 }
 }

+ 4 - 1
messages/tr/service.json

@@ -23,7 +23,10 @@
       "negative": "Miktarlar, saatler, fiyatlar ve maliyetler negatif olamaz.",
       "negative": "Miktarlar, saatler, fiyatlar ve maliyetler negatif olamaz.",
       "partName": "Fiyatı olan her parçanın bir adı olmalı.",
       "partName": "Fiyatı olan her parçanın bir adı olmalı.",
       "laborDescription": "Saati veya ücreti olan her işçilik satırının bir açıklaması olmalı.",
       "laborDescription": "Saati veya ücreti olan her işçilik satırının bir açıklaması olmalı.",
-      "concernCondition": "Nedeni, onarımı veya doğrulaması olan bir maddenin belirtisi doldurulmalı."
+      "concernCondition": "Nedeni, onarımı veya doğrulaması olan bir maddenin belirtisi doldurulmalı.",
+      "negativeReading": "Okuma değeri negatif olamaz.",
+      "tooLarge": "Bir değer çok büyük. Miktar en fazla {quantity}, fiyat {price}, satır toplamı {total} ve okuma {reading} olabilir.",
+      "zeroQuantity": "Fiyatı olan bir parçanın miktarı sıfırdan büyük olmalı."
     }
     }
   },
   },
   "header": {
   "header": {

+ 23 - 0
src/__tests__/features/tax/taxable-lines-retotal.test.ts

@@ -312,6 +312,29 @@ describe('a part booked onto a job', () => {
     })
     })
   })
   })
 
 
+  it('is refused like a line saved with the work order, and moves no stock', async () => {
+    for (const bad of [
+      { quantity: 0 },
+      { quantity: -1 },
+      { quantity: 1_000_000_000, unitPrice: 99_999_999, total: 1 },
+      { unitPrice: 10_000_001 },
+    ]) {
+      await expect(
+        addPart({ organizationId: 'org-1', userId: 'user-1', input: { ...input, ...bad } })
+      ).rejects.toThrow()
+    }
+    expect(store.parts).toHaveLength(0)
+  })
+
+  it('stores the line total to the cent', async () => {
+    await addPart({
+      organizationId: 'org-1',
+      userId: 'user-1',
+      input: { ...input, quantity: 3, unitPrice: 0.1, total: 0.30000000000000004 },
+    })
+    expect(store.parts[0]).toMatchObject({ total: 0.3 })
+  })
+
   it('takes the caller at its word when it says', async () => {
   it('takes the caller at its word when it says', async () => {
     store.settings = PARTS_ONLY
     store.settings = PARTS_ONLY
     await addPart({
     await addPart({

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

@@ -369,6 +369,31 @@ describe('saving an existing work order', () => {
     })
     })
   })
   })
 
 
+  it('adds the lines up as stored, to the cent, and restates the tax and total from them', async () => {
+    // Two lines of 2.5 h at 19.99: each is stored as 49.98, so the job is
+    // 99.96, not the 99.95 the page summed from 49.975 twice.
+    const line = { ...LABOR, hours: 2.5, rate: 19.99, total: 49.975 }
+    const tx = transaction()
+    const result = await updateServiceRecord({
+      id: 'sr-1',
+      partItems: [],
+      laborItems: [line, line],
+      subtotal: 99.95,
+      taxRate: 8,
+      taxAmount: 8,
+      totalAmount: 107.95,
+      cost: 107.95,
+    })
+    expect(result.success).toBe(true)
+    expect(tx.labor().map((l) => (l as { total?: number }).total)).toEqual([49.98, 49.98])
+    expect(tx.data()).toMatchObject({
+      subtotal: 99.96,
+      taxAmount: 8,
+      totalAmount: 107.96,
+      cost: 107.96,
+    })
+  })
+
   it('keeps a choice made on a line through a save', async () => {
   it('keeps a choice made on a line through a save', async () => {
     settings(PARTS_ONLY)
     settings(PARTS_ONLY)
     const tx = transaction()
     const tx = transaction()

+ 121 - 0
src/__tests__/features/workorders/impossible-values.test.ts

@@ -0,0 +1,121 @@
+/**
+ * What the server refuses whatever the page sends: a reading below zero, a
+ * priced part billed none of, quantities, prices and texts past anything a
+ * workshop writes. A tab opened before this change, or a script, gets an
+ * error and nothing is written. And a line total is held to the cent.
+ */
+import { describe, expect, it } from 'vitest'
+import { createCustomerSchema } from '@/features/customers/Schema/customerSchema'
+import { createLaborPresetSchema } from '@/features/labor-presets/Schema/laborPresetSchema'
+import { createVehicleSchema, updateVehicleSchema } from '@/features/vehicles/Schema/vehicleSchema'
+import {
+  serviceLaborSchema,
+  servicePartSchema,
+  updateServiceSchema,
+} from '@/features/vehicles/Schema/serviceSchema'
+
+const part = { name: 'Brake pads', quantity: 1, unitPrice: 100, total: 100 }
+
+describe('a work order', () => {
+  it('refuses a negative reading and takes an empty one', () => {
+    expect(updateServiceSchema.safeParse({ id: 'j1', mileage: -5 }).success).toBe(false)
+    expect(updateServiceSchema.safeParse({ id: 'j1', mileage: null }).success).toBe(true)
+    expect(updateServiceSchema.safeParse({ id: 'j1', mileage: 120_500 }).success).toBe(true)
+    expect(updateServiceSchema.safeParse({ id: 'j1', mileage: 10_000_001 }).success).toBe(false)
+  })
+
+  it('refuses a priced part with no quantity, and keeps a free one', () => {
+    const zero = servicePartSchema.safeParse({ ...part, quantity: 0, total: 0 })
+    expect(zero.success).toBe(false)
+    expect(zero.error?.issues[0].path).toEqual(['quantity'])
+    expect(
+      servicePartSchema.safeParse({ ...part, quantity: 0, unitPrice: 0, total: 0 }).success
+    ).toBe(true)
+  })
+
+  it('refuses a billion parts at a hundred million each', () => {
+    expect(
+      servicePartSchema.safeParse({
+        ...part,
+        quantity: 1_000_000_000,
+        unitPrice: 99_999_999,
+        total: 119_999_998_800_000_000,
+      }).success
+    ).toBe(false)
+    expect(servicePartSchema.safeParse({ ...part, quantity: 100_001 }).success).toBe(false)
+    expect(servicePartSchema.safeParse({ ...part, unitPrice: 10_000_001 }).success).toBe(false)
+    expect(
+      servicePartSchema.safeParse({ ...part, quantity: 100_000, unitPrice: 10, total: 1_000_000 })
+        .success
+    ).toBe(true)
+  })
+
+  it('holds a line total to the cent', () => {
+    expect(
+      servicePartSchema.parse({ ...part, quantity: 3, unitPrice: 0.1, total: 0.30000000000000004 })
+        .total
+    ).toBe(0.3)
+    expect(
+      serviceLaborSchema.parse({
+        description: 'Fit',
+        hours: 2.5,
+        rate: 19.99,
+        total: 49.974999999999994,
+      }).total
+    ).toBe(49.98)
+  })
+
+  it('keeps a labour line with no hours yet, and refuses absurd ones', () => {
+    expect(serviceLaborSchema.safeParse({ description: 'Diagnose', hours: 0 }).success).toBe(true)
+    expect(serviceLaborSchema.safeParse({ description: 'Diagnose', hours: 100_001 }).success).toBe(
+      false
+    )
+    expect(
+      serviceLaborSchema.safeParse({ description: 'Diagnose', rate: 10_000_001 }).success
+    ).toBe(false)
+  })
+})
+
+describe('a vehicle', () => {
+  const vehicle = { make: 'Volkswagen', model: 'Golf', year: 2018 }
+  it('refuses a negative or absurd reading, on create and on edit', () => {
+    expect(createVehicleSchema.safeParse({ ...vehicle, mileage: -5 }).success).toBe(false)
+    expect(createVehicleSchema.safeParse({ ...vehicle, mileage: 10_000_001 }).success).toBe(false)
+    expect(updateVehicleSchema.safeParse({ id: 'v1', mileage: -5 }).success).toBe(false)
+  })
+
+  it('refuses a make longer than a name gets', () => {
+    expect(createVehicleSchema.safeParse({ ...vehicle, make: 'x'.repeat(201) }).success).toBe(false)
+  })
+})
+
+describe('a customer', () => {
+  it('refuses a name past 200 characters and an address past 500', () => {
+    expect(createCustomerSchema.safeParse({ name: 'x'.repeat(480) }).success).toBe(false)
+    expect(
+      createCustomerSchema.safeParse({ name: 'ZZ Long', address: 'x'.repeat(3000) }).success
+    ).toBe(false)
+    expect(
+      createCustomerSchema.safeParse({ name: 'x'.repeat(200), address: 'x'.repeat(500) }).success
+    ).toBe(true)
+  })
+
+  it('leaves room for long notes', () => {
+    expect(createCustomerSchema.safeParse({ name: 'ZZ', notes: 'x'.repeat(5000) }).success).toBe(
+      true
+    )
+  })
+})
+
+describe('a labour preset', () => {
+  it('refuses absurd hours and rates', () => {
+    const item = { description: 'Oil change', hours: 1, rate: 100 }
+    expect(createLaborPresetSchema.safeParse({ items: [item] }).success).toBe(true)
+    expect(
+      createLaborPresetSchema.safeParse({ items: [{ ...item, hours: 100_001 }] }).success
+    ).toBe(false)
+    expect(
+      createLaborPresetSchema.safeParse({ items: [{ ...item, rate: 10_000_001 }] }).success
+    ).toBe(false)
+  })
+})

+ 118 - 0
src/__tests__/features/workorders/rounded-lines.test.ts

@@ -0,0 +1,118 @@
+/**
+ * Line totals are stored to the cent. Everything that compares or adds up
+ * lines has to see them the same way, or the page and the server disagree:
+ *
+ * - The page tells "a line somebody else added" from "a line I just saved"
+ *   by content, total included. A save that held a reading back recorded the
+ *   page's unrounded total; the refresh brought the server's rounded one; the
+ *   line looked new and was saved again (and its stock taken twice).
+ * - The subtotal a save stores is what the stored lines add up to.
+ */
+import { describe, expect, it } from 'vitest'
+import { addedLaborLines, savedLaborShape } from '@/features/vehicles/Lib/laborLines'
+import { addedPartLines, savedPartShape } from '@/features/vehicles/Lib/partLines'
+import { restatedSubtotal, subtotalFromLines } from '@/features/vehicles/Lib/subtotalFromLines'
+import type { ServiceLaborInput, ServicePartInput } from '@/features/vehicles/Schema/serviceSchema'
+import { createLaborPresetSchema } from '@/features/labor-presets/Schema/laborPresetSchema'
+import { servicePartSchema } from '@/features/vehicles/Schema/serviceSchema'
+import { fieldErrorsFromZod } from '@/lib/field-errors'
+
+const labor = (total: number): ServiceLaborInput =>
+  ({
+    description: 'Fit pads',
+    hours: 2.5,
+    rate: 19.99,
+    total,
+    pricingType: 'hourly',
+  }) as ServiceLaborInput
+
+const part = (total: number): ServicePartInput =>
+  ({ name: 'Bolts', partNumber: '', quantity: 3, unitPrice: 0.1, total }) as ServicePartInput
+
+describe('a line the page saved, as the refresh brings it back', () => {
+  it('is the same labour line, rounded or not', () => {
+    expect(savedLaborShape(labor(49.975)).total).toBe(49.98)
+    // What the page acknowledged (unrounded) against what the server stored.
+    expect(addedLaborLines([labor(49.975)], [labor(49.98)])).toEqual([])
+  })
+
+  it('is the same part line, rounded or not', () => {
+    expect(savedPartShape(part(0.30000000000000004)).total).toBe(0.3)
+    expect(addedPartLines([part(0.30000000000000004)], [part(0.3)])).toEqual([])
+  })
+
+  it('still tells a second line apart', () => {
+    expect(addedLaborLines([labor(49.975)], [labor(49.98), labor(49.98)])).toHaveLength(1)
+  })
+})
+
+describe('what the lines add up to', () => {
+  it('adds each line to the cent first', () => {
+    expect(subtotalFromLines([], [{ total: 49.975 }, { total: 49.975 }])).toBe(99.96)
+    expect(subtotalFromLines([{ total: 0.30000000000000004 }], [{ total: 10 }])).toBe(10.3)
+  })
+
+  it('restates the page’s subtotal and its discount only when they disagree', () => {
+    expect(
+      restatedSubtotal({
+        sentSubtotal: 99.96,
+        linesSubtotal: 99.96,
+        discountType: 'none',
+        discountValue: 0,
+      })
+    ).toBeNull()
+    expect(
+      restatedSubtotal({
+        sentSubtotal: 99.95,
+        linesSubtotal: 99.96,
+        discountType: 'percentage',
+        discountValue: 10,
+      })
+    ).toEqual({ subtotal: 99.96, discountAmount: 10 })
+    expect(
+      restatedSubtotal({
+        sentSubtotal: 99.95,
+        linesSubtotal: 99.96,
+        discountType: undefined,
+        discountValue: undefined,
+      })
+    ).toEqual({ subtotal: 99.96, discountAmount: undefined })
+  })
+})
+
+describe('a line past what any line comes to', () => {
+  it('is refused on a work order whatever total was sent', () => {
+    const result = servicePartSchema.safeParse({
+      name: 'Bolts',
+      quantity: 100_000,
+      unitPrice: 10_001,
+      total: 1,
+    })
+    expect(result.success).toBe(false)
+    expect(fieldErrorsFromZod(result.error!)).toEqual([
+      { field: 'total', issue: 'tooLarge', limit: 1_000_000_000 },
+    ])
+  })
+
+  it('says a priced part needs a quantity above zero, under the quantity', () => {
+    const result = servicePartSchema.safeParse({ name: 'Bolts', quantity: 0, unitPrice: 5 })
+    expect(fieldErrorsFromZod(result.error!)).toEqual([{ field: 'quantity', issue: 'positive' }])
+  })
+
+  it('is refused on a labour preset, for an item and for a part', () => {
+    const item = { description: 'Fit', hours: 100_000, rate: 10_001 }
+    expect(createLaborPresetSchema.safeParse({ items: [item] }).success).toBe(false)
+    expect(
+      createLaborPresetSchema.safeParse({
+        items: [{ description: 'Fit', hours: 1, rate: 100 }],
+        parts: [{ name: 'Bolts', quantity: 100_000, unitPrice: 10_001 }],
+      }).success
+    ).toBe(false)
+    expect(
+      createLaborPresetSchema.safeParse({
+        items: [{ description: 'Fit', hours: 1000, rate: 1000 }],
+        parts: [{ name: 'Bolts', quantity: 1000, unitPrice: 1000 }],
+      }).success
+    ).toBe(true)
+  })
+})

+ 40 - 0
src/__tests__/features/workorders/validate-service-form.test.ts

@@ -153,3 +153,43 @@ describe('what a work order must have before it saves', () => {
     ).toBe('title')
     ).toBe('title')
   })
   })
 })
 })
+
+describe('figures no job has', () => {
+  it('refuses a reading below zero, and leaves an empty one alone', () => {
+    expect(findServiceFormProblem({ ...empty, mileage: '-5' })).toBe('negativeReading')
+    expect(findServiceFormProblem({ ...empty, mileage: '' })).toBeNull()
+    expect(findServiceFormProblem({ ...empty, mileage: null })).toBeNull()
+    expect(findServiceFormProblem({ ...empty, mileage: '120500' })).toBeNull()
+  })
+
+  it('refuses a priced part with a quantity of zero, but not a free one', () => {
+    expect(findServiceFormProblem({ ...empty, partItems: [part({ quantity: 0 })] })).toBe(
+      'zeroQuantity'
+    )
+    expect(
+      findServiceFormProblem({ ...empty, partItems: [part({ quantity: 0, unitPrice: 0 })] })
+    ).toBeNull()
+  })
+
+  it('keeps a labour line with no hours yet', () => {
+    // A line a technician started on the phone arrives at zero hours.
+    expect(findServiceFormProblem({ ...empty, laborItems: [labor({ hours: 0 })] })).toBeNull()
+  })
+
+  it('refuses a quantity, a price or a line total past any job', () => {
+    const tooLarge = [
+      { partItems: [part({ quantity: 1_000_000_000, unitPrice: 99_999_999 })] },
+      { partItems: [part({ quantity: 100_001 })] },
+      { partItems: [part({ unitPrice: 10_000_001 })] },
+      { partItems: [part({ quantity: 1000, unitPrice: 2_000_000 })] },
+      { laborItems: [labor({ hours: 100_001 })] },
+      { mileage: 10_000_001 },
+    ]
+    for (const over of tooLarge) {
+      expect(findServiceFormProblem({ ...empty, ...over })).toBe('tooLarge')
+    }
+    expect(
+      findServiceFormProblem({ ...empty, partItems: [part({ quantity: 100_000, unitPrice: 10 })] })
+    ).toBeNull()
+  })
+})

+ 14 - 10
src/app/(authenticated)/customers/[id]/customer-detail-client.tsx

@@ -351,12 +351,14 @@ export function CustomerDetailClient({
         </Link>
         </Link>
 
 
         <div className="flex items-start gap-4">
         <div className="flex items-start gap-4">
-          <div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/10">
+          <div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-primary/10">
             <Users className="h-7 w-7 text-primary" />
             <Users className="h-7 w-7 text-primary" />
           </div>
           </div>
-          <div className="flex-1">
-            <h1 className="flex items-baseline gap-2 text-2xl font-bold">
-              {customer.name}
+          {/* min-w-0, so a long name or address wraps inside the header
+              instead of widening the page past the screen. */}
+          <div className="min-w-0 flex-1">
+            <h1 className="flex flex-wrap items-baseline gap-x-2 text-2xl font-bold [overflow-wrap:anywhere]">
+              <span className="min-w-0">{customer.name}</span>
               {customer.customerNumber && (
               {customer.customerNumber && (
                 <span className="font-mono text-sm font-normal text-muted-foreground">
                 <span className="font-mono text-sm font-normal text-muted-foreground">
                   #{customer.customerNumber}
                   #{customer.customerNumber}
@@ -366,9 +368,9 @@ export function CustomerDetailClient({
             {hasContactInfo && (
             {hasContactInfo && (
               <div className="mt-1.5 flex flex-wrap gap-x-5 gap-y-1.5 text-sm">
               <div className="mt-1.5 flex flex-wrap gap-x-5 gap-y-1.5 text-sm">
                 {customer.company && (
                 {customer.company && (
-                  <div className="flex items-center gap-1.5 text-muted-foreground">
-                    <Building2 className="h-3.5 w-3.5" />
-                    <span>{customer.company}</span>
+                  <div className="flex min-w-0 items-center gap-1.5 text-muted-foreground">
+                    <Building2 className="h-3.5 w-3.5 shrink-0" />
+                    <span className="[overflow-wrap:anywhere]">{customer.company}</span>
                   </div>
                   </div>
                 )}
                 )}
                 {customer.email && (
                 {customer.email && (
@@ -398,13 +400,15 @@ export function CustomerDetailClient({
                   </button>
                   </button>
                 )}
                 )}
                 {customer.address && (
                 {customer.address && (
-                  <div className="flex items-center gap-1.5 text-muted-foreground">
+                  <div className="flex min-w-0 max-w-full items-center gap-1.5 text-muted-foreground">
                     <MapPin className="h-3.5 w-3.5 shrink-0" />
                     <MapPin className="h-3.5 w-3.5 shrink-0" />
                     {/* One line here, whatever it was typed as. This row is a
                     {/* One line here, whatever it was typed as. This row is a
                         summary sitting beside the email and the phone, and a
                         summary sitting beside the email and the phone, and a
                         three-line address makes the whole header ragged. The
                         three-line address makes the whole header ragged. The
                         invoice prints it as written. */}
                         invoice prints it as written. */}
-                    <span title={customer.address}>{oneLine(customer.address)}</span>
+                    <span title={customer.address} className="min-w-0 truncate">
+                      {oneLine(customer.address)}
+                    </span>
                   </div>
                   </div>
                 )}
                 )}
                 {customer.taxId && (
                 {customer.taxId && (
@@ -441,7 +445,7 @@ export function CustomerDetailClient({
               </div>
               </div>
             )}
             )}
             {customer.notes && (
             {customer.notes && (
-              <p className="mt-2 text-sm text-muted-foreground whitespace-pre-wrap">
+              <p className="mt-2 text-sm text-muted-foreground whitespace-pre-wrap [overflow-wrap:anywhere]">
                 {customer.notes}
                 {customer.notes}
               </p>
               </p>
             )}
             )}

+ 14 - 0
src/features/customers/Components/CustomerForm.tsx

@@ -4,6 +4,13 @@ import { track } from '@/lib/analytics'
 import { useEffect, useRef, useState } from 'react'
 import { useEffect, useRef, useState } from 'react'
 import { useRouter } from 'next/navigation'
 import { useRouter } from 'next/navigation'
 import { useTranslations } from 'next-intl'
 import { useTranslations } from 'next-intl'
+import {
+  ADDRESS_MAX_LENGTH,
+  EMAIL_MAX_LENGTH,
+  NAME_MAX_LENGTH,
+  NOTES_MAX_LENGTH,
+  SHORT_TEXT_MAX_LENGTH,
+} from '@/lib/input-limits'
 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 { Label } from '@/components/ui/label'
 import { Label } from '@/components/ui/label'
@@ -334,6 +341,7 @@ export function CustomerForm({
                   <Input
                   <Input
                     id="name"
                     id="name"
                     name="name"
                     name="name"
+                    maxLength={NAME_MAX_LENGTH}
                     {...fieldErrors.invalidProps('name')}
                     {...fieldErrors.invalidProps('name')}
                     placeholder={t('namePlaceholder')}
                     placeholder={t('namePlaceholder')}
                     defaultValue={customer?.name ?? defaults?.name ?? ''}
                     defaultValue={customer?.name ?? defaults?.name ?? ''}
@@ -361,6 +369,7 @@ export function CustomerForm({
                   <Input
                   <Input
                     id="email"
                     id="email"
                     name="email"
                     name="email"
+                    maxLength={EMAIL_MAX_LENGTH}
                     {...fieldErrors.invalidProps('email')}
                     {...fieldErrors.invalidProps('email')}
                     type="email"
                     type="email"
                     placeholder={t('emailPlaceholder')}
                     placeholder={t('emailPlaceholder')}
@@ -373,6 +382,7 @@ export function CustomerForm({
                   <Input
                   <Input
                     id="phone"
                     id="phone"
                     name="phone"
                     name="phone"
+                    maxLength={SHORT_TEXT_MAX_LENGTH}
                     {...fieldErrors.invalidProps('phone')}
                     {...fieldErrors.invalidProps('phone')}
                     placeholder={t('phonePlaceholder')}
                     placeholder={t('phonePlaceholder')}
                     defaultValue={customer?.phone ?? ''}
                     defaultValue={customer?.phone ?? ''}
@@ -389,6 +399,7 @@ export function CustomerForm({
                 <Textarea
                 <Textarea
                   id="address"
                   id="address"
                   name="address"
                   name="address"
+                  maxLength={ADDRESS_MAX_LENGTH}
                   {...fieldErrors.invalidProps('address')}
                   {...fieldErrors.invalidProps('address')}
                   placeholder={t('addressPlaceholder')}
                   placeholder={t('addressPlaceholder')}
                   rows={2}
                   rows={2}
@@ -410,6 +421,7 @@ export function CustomerForm({
                 <Input
                 <Input
                   id="company"
                   id="company"
                   name="company"
                   name="company"
+                  maxLength={NAME_MAX_LENGTH}
                   {...fieldErrors.invalidProps('company')}
                   {...fieldErrors.invalidProps('company')}
                   placeholder={t('companyPlaceholder')}
                   placeholder={t('companyPlaceholder')}
                   defaultValue={customer?.company ?? ''}
                   defaultValue={customer?.company ?? ''}
@@ -422,6 +434,7 @@ export function CustomerForm({
                 <Input
                 <Input
                   id="taxId"
                   id="taxId"
                   name="taxId"
                   name="taxId"
+                  maxLength={SHORT_TEXT_MAX_LENGTH}
                   {...fieldErrors.invalidProps('taxId')}
                   {...fieldErrors.invalidProps('taxId')}
                   placeholder={t('taxIdPlaceholder')}
                   placeholder={t('taxIdPlaceholder')}
                   defaultValue={customer?.taxId ?? ''}
                   defaultValue={customer?.taxId ?? ''}
@@ -477,6 +490,7 @@ export function CustomerForm({
               <Textarea
               <Textarea
                 id="notes"
                 id="notes"
                 name="notes"
                 name="notes"
+                maxLength={NOTES_MAX_LENGTH}
                 {...fieldErrors.invalidProps('notes')}
                 {...fieldErrors.invalidProps('notes')}
                 placeholder={t('notesPlaceholder')}
                 placeholder={t('notesPlaceholder')}
                 rows={3}
                 rows={3}

+ 14 - 7
src/features/customers/Schema/customerSchema.ts

@@ -1,18 +1,25 @@
 import { z } from 'zod'
 import { z } from 'zod'
+import {
+  ADDRESS_MAX_LENGTH,
+  EMAIL_MAX_LENGTH,
+  NAME_MAX_LENGTH,
+  NOTES_MAX_LENGTH,
+  SHORT_TEXT_MAX_LENGTH,
+} from '@/lib/input-limits'
 
 
 export const createCustomerSchema = z.object({
 export const createCustomerSchema = z.object({
   customerNumber: z.string().max(20).optional(),
   customerNumber: z.string().max(20).optional(),
-  name: z.string().min(1, 'Name is required'),
-  email: z.string().email('Invalid email').optional().or(z.literal('')),
-  phone: z.string().optional(),
-  address: z.string().optional(),
-  company: z.string().optional(),
-  taxId: z.string().optional(),
+  name: z.string().min(1, 'Name is required').max(NAME_MAX_LENGTH),
+  email: z.string().max(EMAIL_MAX_LENGTH).email('Invalid email').optional().or(z.literal('')),
+  phone: z.string().max(SHORT_TEXT_MAX_LENGTH).optional(),
+  address: z.string().max(ADDRESS_MAX_LENGTH).optional(),
+  company: z.string().max(NAME_MAX_LENGTH).optional(),
+  taxId: z.string().max(SHORT_TEXT_MAX_LENGTH).optional(),
   taxExempt: z.boolean().optional(),
   taxExempt: z.boolean().optional(),
   reminderOptOut: z.boolean().optional(),
   reminderOptOut: z.boolean().optional(),
   /** Invoices wait for a reference / PO. Kept only by a workshop that uses the field. */
   /** Invoices wait for a reference / PO. Kept only by a workshop that uses the field. */
   poRequired: z.boolean().optional(),
   poRequired: z.boolean().optional(),
-  notes: z.string().optional(),
+  notes: z.string().max(NOTES_MAX_LENGTH).optional(),
   /** An invoice design for this customer's invoices; null follows the default. */
   /** An invoice design for this customer's invoices; null follows the default. */
   invoiceDesignId: z.string().nullable().optional(),
   invoiceDesignId: z.string().nullable().optional(),
   /**
   /**

+ 3 - 2
src/features/inspections/Schema/inspectionSchema.ts

@@ -1,9 +1,10 @@
 import { z } from 'zod'
 import { z } from 'zod'
+import { READING_MAX } from '@/lib/input-limits'
 
 
 export const createInspectionSchema = z.object({
 export const createInspectionSchema = z.object({
   vehicleId: z.string().min(1, 'Vehicle is required'),
   vehicleId: z.string().min(1, 'Vehicle is required'),
   templateId: z.string().min(1, 'Template is required'),
   templateId: z.string().min(1, 'Template is required'),
-  mileage: z.coerce.number().int().min(0).optional(),
+  mileage: z.coerce.number().int().min(0).max(READING_MAX).optional(),
   /** The booked job this inspection is the work of, when started from one. */
   /** The booked job this inspection is the work of, when started from one. */
   serviceRecordId: z.string().min(1).optional(),
   serviceRecordId: z.string().min(1).optional(),
 })
 })
@@ -22,7 +23,7 @@ export const updateInspectionItemSchema = z.object({
 
 
 /** Roadworthiness certificate fields — Directive 2014/45/EU Annex IV. */
 /** Roadworthiness certificate fields — Directive 2014/45/EU Annex IV. */
 export const updateInspectionDetailsSchema = z.object({
 export const updateInspectionDetailsSchema = z.object({
-  mileage: z.coerce.number().int().min(0).nullable().optional(),
+  mileage: z.coerce.number().int().min(0).max(READING_MAX).nullable().optional(),
   vehicleCategory: z.string().max(10).nullable().optional(),
   vehicleCategory: z.string().max(10).nullable().optional(),
   certificateNumber: z.string().max(64).nullable().optional(),
   certificateNumber: z.string().max(64).nullable().optional(),
   // The inspector is picked from the workshop's technicians; the name is
   // The inspector is picked from the workshop's technicians; the name is

+ 5 - 0
src/features/labor-presets/Components/LaborPresetForm.tsx

@@ -2,6 +2,7 @@
 
 
 import { useState } from 'react'
 import { useState } from 'react'
 import { useTranslations } from 'next-intl'
 import { useTranslations } from 'next-intl'
+import { LABOR_HOURS_MAX, UNIT_PRICE_MAX } from '@/lib/input-limits'
 import { useRouter } from 'next/navigation'
 import { useRouter } from 'next/navigation'
 import { Button } from '@/components/ui/button'
 import { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import { Input } from '@/components/ui/input'
@@ -486,6 +487,7 @@ export function LaborPresetForm({
                       <Input
                       <Input
                         type="number"
                         type="number"
                         min="0"
                         min="0"
+                        max={LABOR_HOURS_MAX}
                         step={item.pricingType === 'service' ? '1' : 'any'}
                         step={item.pricingType === 'service' ? '1' : 'any'}
                         placeholder={
                         placeholder={
                           item.pricingType === 'service' ? t('form.itemQty') : t('form.itemHours')
                           item.pricingType === 'service' ? t('form.itemQty') : t('form.itemHours')
@@ -496,6 +498,7 @@ export function LaborPresetForm({
                       <Input
                       <Input
                         type="number"
                         type="number"
                         min="0"
                         min="0"
+                        max={UNIT_PRICE_MAX}
                         step="0.01"
                         step="0.01"
                         value={item.rate}
                         value={item.rate}
                         onChange={(e) => updateSingleItem(i, 'rate', e.target.value)}
                         onChange={(e) => updateSingleItem(i, 'rate', e.target.value)}
@@ -599,6 +602,7 @@ export function LaborPresetForm({
                       <Input
                       <Input
                         type="number"
                         type="number"
                         min="0"
                         min="0"
+                        max={LABOR_HOURS_MAX}
                         step={item.pricingType === 'service' ? '1' : 'any'}
                         step={item.pricingType === 'service' ? '1' : 'any'}
                         placeholder={
                         placeholder={
                           item.pricingType === 'service' ? t('form.itemQty') : t('form.itemHours')
                           item.pricingType === 'service' ? t('form.itemQty') : t('form.itemHours')
@@ -609,6 +613,7 @@ export function LaborPresetForm({
                       <Input
                       <Input
                         type="number"
                         type="number"
                         min="0"
                         min="0"
+                        max={UNIT_PRICE_MAX}
                         step="0.01"
                         step="0.01"
                         value={item.rate}
                         value={item.rate}
                         onChange={(e) => updateItem(i, 'rate', e.target.value)}
                         onChange={(e) => updateItem(i, 'rate', e.target.value)}

+ 35 - 18
src/features/labor-presets/Schema/laborPresetSchema.ts

@@ -1,24 +1,41 @@
 import { z } from 'zod'
 import { z } from 'zod'
+import { checkLineAmounts, LABOR_HOURS_MAX, QUANTITY_MAX, UNIT_PRICE_MAX } from '@/lib/input-limits'
 
 
-export const laborPresetItemSchema = z.object({
-  description: z.string().min(1, 'Description is required'),
-  hours: z.coerce.number().min(0, 'Hours must be 0 or more').default(0),
-  rate: z.coerce.number().min(0, 'Rate must be 0 or more').default(0),
-  pricingType: z.enum(['hourly', 'service']).default('hourly'),
-  sortOrder: z.coerce.number().int().min(0).default(0),
-})
+export const laborPresetItemSchema = z
+  .object({
+    description: z.string().min(1, 'Description is required'),
+    hours: z.coerce.number().min(0, 'Hours must be 0 or more').max(LABOR_HOURS_MAX).default(0),
+    rate: z.coerce.number().min(0, 'Rate must be 0 or more').max(UNIT_PRICE_MAX).default(0),
+    pricingType: z.enum(['hourly', 'service']).default('hourly'),
+    sortOrder: z.coerce.number().int().min(0).default(0),
+  })
+  // Hours times rate no more than a line may come to (lib/input-limits.ts).
+  .superRefine((item, ctx) =>
+    checkLineAmounts({ count: item.hours, price: item.rate }, ctx, {
+      count: 'hours',
+      total: 'rate',
+    })
+  )
 
 
-export const laborPresetPartSchema = z.object({
-  name: z.string().min(1, 'Part name is required'),
-  partNumber: z.string().optional(),
-  quantity: z.coerce.number().min(0, 'Quantity must be 0 or more').default(1),
-  /** Unit of measure snapshotted from the picked inventory part. */
-  unit: z.string().nullish(),
-  category: z.string().nullish(),
-  unitPrice: z.coerce.number().min(0, 'Price must be 0 or more').default(0),
-  inventoryPartId: z.string().optional(),
-  sortOrder: z.coerce.number().int().min(0).default(0),
-})
+export const laborPresetPartSchema = z
+  .object({
+    name: z.string().min(1, 'Part name is required'),
+    partNumber: z.string().optional(),
+    quantity: z.coerce.number().min(0, 'Quantity must be 0 or more').max(QUANTITY_MAX).default(1),
+    /** Unit of measure snapshotted from the picked inventory part. */
+    unit: z.string().nullish(),
+    category: z.string().nullish(),
+    unitPrice: z.coerce.number().min(0, 'Price must be 0 or more').max(UNIT_PRICE_MAX).default(0),
+    inventoryPartId: z.string().optional(),
+    sortOrder: z.coerce.number().int().min(0).default(0),
+  })
+  // Quantity times price no more than a line may come to (lib/input-limits.ts).
+  .superRefine((part, ctx) =>
+    checkLineAmounts({ count: part.quantity, price: part.unitPrice }, ctx, {
+      count: 'quantity',
+      total: 'unitPrice',
+    })
+  )
 
 
 export type LaborPresetPartInput = z.infer<typeof laborPresetPartSchema>
 export type LaborPresetPartInput = z.infer<typeof laborPresetPartSchema>
 
 

+ 78 - 0
src/features/vehicles/Actions/serviceActions.ts

@@ -34,6 +34,8 @@ import {
 } from '@/features/settings/Lib/warrantyDefaults'
 } from '@/features/settings/Lib/warrantyDefaults'
 import { EMPTY_WARRANTY, normalizeWarranty } from '@/lib/warranty'
 import { EMPTY_WARRANTY, normalizeWarranty } from '@/lib/warranty'
 import { parseTaxComponentDefinitions } from '@/lib/tax-components'
 import { parseTaxComponentDefinitions } from '@/lib/tax-components'
+import { restatedSubtotal, subtotalFromLines } from '@/features/vehicles/Lib/subtotalFromLines'
+import { documentTotals } from '@/features/settings/Lib/workshopTax'
 import { issueInvoice } from '@/features/invoices/Lib/issueInvoice'
 import { issueInvoice } from '@/features/invoices/Lib/issueInvoice'
 import { withAuth } from '@/lib/with-auth'
 import { withAuth } from '@/lib/with-auth'
 import { parseSentFields, sentId } from '@/lib/parse-sent-fields'
 import { parseSentFields, sentId } from '@/lib/parse-sent-fields'
@@ -494,6 +496,34 @@ export async function createServiceRecord(input: unknown) {
       // server's to state whenever the lines decide it (see savedDocumentTax).
       // server's to state whenever the lines decide it (see savedDocumentTax).
       const taxedParts = withTaxableParts(data.partItems ?? [], workshopTax.applies)
       const taxedParts = withTaxableParts(data.partItems ?? [], workshopTax.applies)
       const taxedLabor = withTaxableLabor(data.laborItems ?? [], workshopTax.applies)
       const taxedLabor = withTaxableLabor(data.laborItems ?? [], workshopTax.applies)
+      // The lines are stored to the cent, so the subtotal is what they add up
+      // to as stored, not the page's own sum (see subtotalFromLines).
+      const createdFromLines =
+        (data.partItems?.length ?? 0) + (data.laborItems?.length ?? 0) > 0
+          ? restatedSubtotal({
+              sentSubtotal: data.subtotal,
+              linesSubtotal: subtotalFromLines(data.partItems ?? [], data.laborItems ?? []),
+              discountType: data.discountType,
+              discountValue: data.discountValue,
+            })
+          : null
+      if (createdFromLines) {
+        data.subtotal = createdFromLines.subtotal
+        if (createdFromLines.discountAmount !== undefined) {
+          data.discountAmount = createdFromLines.discountAmount
+        }
+        const totals = documentTotals({
+          subtotal: data.subtotal,
+          discountAmount: data.discountAmount,
+          taxRate: data.taxRate,
+          taxInclusive,
+          taxComponents: null,
+          taxableSubtotal: null,
+        })
+        data.taxAmount = totals.taxAmount
+        data.totalAmount = totals.totalAmount
+        data.cost = totals.totalAmount
+      }
       const savedTax = savedDocumentTax({
       const savedTax = savedDocumentTax({
         subtotal: data.subtotal,
         subtotal: data.subtotal,
         discountAmount: data.discountAmount,
         discountAmount: data.discountAmount,
@@ -804,6 +834,37 @@ export async function updateServiceRecord(input: unknown) {
         laborItems !== undefined && taxApplies
         laborItems !== undefined && taxApplies
           ? withTaxableLabor(laborItems, taxApplies)
           ? withTaxableLabor(laborItems, taxApplies)
           : undefined
           : undefined
+      // Lines are stored to the cent (serviceSchema). The subtotal the page
+      // sent was added up from its own figures, so it is restated from the
+      // lines as stored, and the discount and tax with it, or the invoice's
+      // lines would not add up to its subtotal.
+      let fromLines: ReturnType<typeof restatedSubtotal> = null
+      if (linesSent && recordData.subtotal !== undefined) {
+        const linesSubtotal = subtotalFromLines(
+          partItems ??
+            (await db.servicePart.findMany({
+              where: { serviceRecordId: id },
+              select: { total: true },
+            })),
+          laborItems ??
+            (await db.serviceLabor.findMany({
+              where: { serviceRecordId: id },
+              select: { total: true },
+            }))
+        )
+        fromLines = restatedSubtotal({
+          sentSubtotal: recordData.subtotal,
+          linesSubtotal,
+          discountType: recordData.discountType ?? existing.discountType,
+          discountValue: recordData.discountValue ?? existing.discountValue,
+        })
+        if (fromLines) {
+          recordData.subtotal = fromLines.subtotal
+          if (fromLines.discountAmount !== undefined) {
+            recordData.discountAmount = fromLines.discountAmount
+          }
+        }
+      }
       const moneyTouched =
       const moneyTouched =
         linesSent ||
         linesSent ||
         recordData.subtotal !== undefined ||
         recordData.subtotal !== undefined ||
@@ -844,6 +905,23 @@ export async function updateServiceRecord(input: unknown) {
         if (restated.taxComponents) recordData.taxRate = existing.taxRate
         if (restated.taxComponents) recordData.taxRate = existing.taxRate
         recordData.taxAmount = restated.taxAmount
         recordData.taxAmount = restated.taxAmount
         recordData.totalAmount = restated.totalAmount
         recordData.totalAmount = restated.totalAmount
+      } else if (fromLines) {
+        // A plain job, every line taxed at one rate: its tax and total follow
+        // the restated subtotal too.
+        const totals = documentTotals({
+          subtotal: fromLines.subtotal,
+          discountAmount: recordData.discountAmount ?? existing.discountAmount,
+          taxRate: recordData.taxRate ?? existing.taxRate,
+          taxInclusive: recordData.taxInclusive ?? existing.taxInclusive,
+          taxComponents: existing.taxComponents,
+          taxableSubtotal: null,
+        })
+        recordData.taxAmount = totals.taxAmount
+        recordData.totalAmount = totals.totalAmount
+      }
+      if (fromLines && recordData.cost !== undefined && recordData.totalAmount !== undefined) {
+        // The page sends the job's cost as its total.
+        recordData.cost = recordData.totalAmount
       }
       }
 
 
       // A null vehicleId from the client means "no vehicle" (counter sale) —
       // A null vehicleId from the client means "no vehicle" (counter sale) —

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

@@ -43,6 +43,7 @@ import {
 } from '@/features/customers/Actions/customerActions'
 } from '@/features/customers/Actions/customerActions'
 import { CustomerCombobox } from '@/features/quotes/Components/CustomerCombobox'
 import { CustomerCombobox } from '@/features/quotes/Components/CustomerCombobox'
 import { useFormatter, useTranslations } from 'next-intl'
 import { useFormatter, useTranslations } from 'next-intl'
+import { NAME_MAX_LENGTH, READING_MAX, SHORT_TEXT_MAX_LENGTH } from '@/lib/input-limits'
 import { useFormatDate } from '@/lib/use-format-date'
 import { useFormatDate } from '@/lib/use-format-date'
 import { useServiceType } from '@/components/service-type-context'
 import { useServiceType } from '@/components/service-type-context'
 import type { CreateVehicleInput } from '../Schema/vehicleSchema'
 import type { CreateVehicleInput } from '../Schema/vehicleSchema'
@@ -1156,6 +1157,7 @@ export function VehicleForm({
                       <Input
                       <Input
                         id="licensePlate"
                         id="licensePlate"
                         name="licensePlate"
                         name="licensePlate"
+                        maxLength={SHORT_TEXT_MAX_LENGTH}
                         {...fieldErrors.invalidProps('licensePlate')}
                         {...fieldErrors.invalidProps('licensePlate')}
                         placeholder="ABC-1234"
                         placeholder="ABC-1234"
                         defaultValue={vehicle?.licensePlate ?? ''}
                         defaultValue={vehicle?.licensePlate ?? ''}
@@ -1220,6 +1222,7 @@ export function VehicleForm({
                       <Input
                       <Input
                         id="vin"
                         id="vin"
                         name="vin"
                         name="vin"
+                        maxLength={SHORT_TEXT_MAX_LENGTH}
                         {...fieldErrors.invalidProps('vin')}
                         {...fieldErrors.invalidProps('vin')}
                         placeholder="1HGCM82633A004352"
                         placeholder="1HGCM82633A004352"
                         defaultValue={vehicle?.vin ?? ''}
                         defaultValue={vehicle?.vin ?? ''}
@@ -1334,6 +1337,7 @@ export function VehicleForm({
                       <Input
                       <Input
                         id="make"
                         id="make"
                         name="make"
                         name="make"
+                        maxLength={NAME_MAX_LENGTH}
                         {...fieldErrors.invalidProps('make')}
                         {...fieldErrors.invalidProps('make')}
                         placeholder={isMarine ? 'Boston Whaler' : 'Toyota'}
                         placeholder={isMarine ? 'Boston Whaler' : 'Toyota'}
                         defaultValue={vehicle?.make}
                         defaultValue={vehicle?.make}
@@ -1346,6 +1350,7 @@ export function VehicleForm({
                       <Input
                       <Input
                         id="model"
                         id="model"
                         name="model"
                         name="model"
+                        maxLength={NAME_MAX_LENGTH}
                         {...fieldErrors.invalidProps('model')}
                         {...fieldErrors.invalidProps('model')}
                         placeholder={isMarine ? 'Montauk 170' : 'Camry'}
                         placeholder={isMarine ? 'Montauk 170' : 'Camry'}
                         defaultValue={vehicle?.model}
                         defaultValue={vehicle?.model}
@@ -1412,6 +1417,7 @@ export function VehicleForm({
                       <Input
                       <Input
                         id="engineCode"
                         id="engineCode"
                         name="engineCode"
                         name="engineCode"
+                        maxLength={SHORT_TEXT_MAX_LENGTH}
                         {...fieldErrors.invalidProps('engineCode')}
                         {...fieldErrors.invalidProps('engineCode')}
                         placeholder="2AR-FE"
                         placeholder="2AR-FE"
                         defaultValue={vehicle?.engineCode ?? ''}
                         defaultValue={vehicle?.engineCode ?? ''}
@@ -1439,6 +1445,7 @@ export function VehicleForm({
                         <Input
                         <Input
                           id="color"
                           id="color"
                           name="color"
                           name="color"
+                          maxLength={SHORT_TEXT_MAX_LENGTH}
                           {...fieldErrors.invalidProps('color')}
                           {...fieldErrors.invalidProps('color')}
                           placeholder="Silver"
                           placeholder="Silver"
                           defaultValue={vehicle?.color ?? ''}
                           defaultValue={vehicle?.color ?? ''}
@@ -1456,6 +1463,7 @@ export function VehicleForm({
                           name="mileage"
                           name="mileage"
                           type="number"
                           type="number"
                           min={0}
                           min={0}
+                          max={READING_MAX}
                           placeholder="0"
                           placeholder="0"
                           value={mileageDraft}
                           value={mileageDraft}
                           onChange={(e) => setMileageDraft(e.target.value)}
                           onChange={(e) => setMileageDraft(e.target.value)}

+ 3 - 0
src/features/vehicles/Components/service-page/modern/JobFactsCard.tsx

@@ -5,6 +5,7 @@ import { WorkOnPicker } from '@/features/equipment/Components/WorkOnPicker'
 import { useEffect, useRef, useState } from 'react'
 import { useEffect, useRef, useState } from 'react'
 import Link from 'next/link'
 import Link from 'next/link'
 import { useTranslations } from 'next-intl'
 import { useTranslations } from 'next-intl'
+import { READING_MAX } from '@/lib/input-limits'
 import { Check, ChevronDown } from 'lucide-react'
 import { Check, ChevronDown } from 'lucide-react'
 import { CopyValue, useCopy } from '@/components/copy-value'
 import { CopyValue, useCopy } from '@/components/copy-value'
 import { useFormatCurrency } from '@/components/currency-settings-context'
 import { useFormatCurrency } from '@/components/currency-settings-context'
@@ -444,6 +445,8 @@ export function JobFactsCard({
                     id="mileage"
                     id="mileage"
                     name="mileage"
                     name="mileage"
                     type="number"
                     type="number"
+                    min={0}
+                    max={READING_MAX}
                     placeholder="50000"
                     placeholder="50000"
                     className="h-8 w-32"
                     className="h-8 w-32"
                     defaultValue={initialData.mileage ?? ''}
                     defaultValue={initialData.mileage ?? ''}

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

@@ -4,7 +4,7 @@ import { useRouter } from 'next/navigation'
 import { toast } from 'sonner'
 import { toast } from 'sonner'
 import { useGlassModal } from '@/components/glass-modal'
 import { useGlassModal } from '@/components/glass-modal'
 import { useConfirm } from '@/components/confirm-dialog'
 import { useConfirm } from '@/components/confirm-dialog'
-import { useTranslations } from 'next-intl'
+import { useFormatter, useTranslations } from 'next-intl'
 import {
 import {
   updateServiceRecord,
   updateServiceRecord,
   deleteServiceRecord,
   deleteServiceRecord,
@@ -17,6 +17,7 @@ import { SETTING_KEYS } from '@/features/settings/Schema/settingsSchema'
 import { SMS_TEMPLATE_DEFAULTS, interpolateSmsTemplate } from '@/lib/sms-templates'
 import { SMS_TEMPLATE_DEFAULTS, interpolateSmsTemplate } from '@/lib/sms-templates'
 import { formatCurrency } from '@/lib/format'
 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 { WARRANTY_NONE } from '@/lib/warranty'
 import { WARRANTY_NONE } from '@/lib/warranty'
 import { useServiceType } from '@/components/service-type-context'
 import { useServiceType } from '@/components/service-type-context'
 import { useFieldErrorText } from '@/components/field-errors'
 import { useFieldErrorText } from '@/components/field-errors'
@@ -46,6 +47,7 @@ export function useServiceActions({
   const tc = useTranslations('common')
   const tc = useTranslations('common')
   const tv = useTranslations('vehicles.form')
   const tv = useTranslations('vehicles.form')
   const readingKind = useServiceType() === 'marine' ? 'hours' : 'distance'
   const readingKind = useServiceType() === 'marine' ? 'hours' : 'distance'
+  const { number: formatNumber } = useFormatter()
   const fieldErrorText = useFieldErrorText()
   const fieldErrorText = useFieldErrorText()
 
 
   /**
   /**
@@ -201,13 +203,23 @@ export function useServiceActions({
     // with no name — are not things a `required` attribute can express.
     // with no name — are not things a `required` attribute can express.
     const problem = findServiceFormProblem({
     const problem = findServiceFormProblem({
       title: getVisible('title') ?? '',
       title: getVisible('title') ?? '',
+      mileage: getVisible('mileage'),
       partItems,
       partItems,
       laborItems,
       laborItems,
       concerns,
       concerns,
     })
     })
     if (problem) {
     if (problem) {
       isSavingRef.current = false
       isSavingRef.current = false
-      refuse(t(`page.problems.${problem}`))
+      refuse(
+        t(`page.problems.${problem}`, {
+          quantity: formatNumber(QUANTITY_MAX),
+          price: formatNumber(UNIT_PRICE_MAX),
+          total: formatNumber(LINE_TOTAL_MAX),
+          reading: formatNumber(READING_MAX),
+        })
+      )
+      if (problem === 'negativeReading')
+        form.querySelector<HTMLInputElement>('input[name="mileage"]')?.focus()
       return
       return
     }
     }
 
 

+ 14 - 6
src/features/vehicles/Components/service-page/useServiceFormState.ts

@@ -1,4 +1,5 @@
 import { useState, useCallback, useRef, useEffect } from 'react'
 import { useState, useCallback, useRef, useEffect } from 'react'
+import { roundMoney } from '@/lib/money'
 import { calculateTotals, discountAmountFor, storedTaxableSubtotal } from '@/lib/tax'
 import { calculateTotals, discountAmountFor, storedTaxableSubtotal } from '@/lib/tax'
 import {
 import {
   TAX_APPLIES_TO_ALL,
   TAX_APPLIES_TO_ALL,
@@ -394,7 +395,14 @@ export function useServiceFormState({
   // Computed totals. They count the lines waiting behind the banner too: those
   // Computed totals. They count the lines waiting behind the banner too: those
   // are on the job already, and a save sends them, so the money it sends has
   // are on the job already, and a save sends them, so the money it sends has
   // to include them or the invoice is saved short.
   // to include them or the invoice is saved short.
-  const partsSubtotal = partItemsForSave.reduce((sum, p) => sum + p.total, 0)
+  //
+  // Each line to the cent first, as the save stores it (serviceSchema): the
+  // page's own sum of unrounded lines (2 x 2.5 h at 19.99 is 99.95) is not
+  // what the stored lines add up to (2 x 49.98), and the invoice would not
+  // add up.
+  const partLinesForTotals = partItemsForSave.map((p) => ({ ...p, total: roundMoney(p.total) }))
+  const laborLinesForTotals = laborItemsForSave.map((l) => ({ ...l, total: roundMoney(l.total) }))
+  const partsSubtotal = roundMoney(partLinesForTotals.reduce((sum, p) => sum + p.total, 0))
 
 
   // A percentage shop fee follows the lines it is a percentage of. Returns the
   // A percentage shop fee follows the lines it is a percentage of. Returns the
   // same array when the fee is already right, so this settles after one pass.
   // same array when the fee is already right, so this settles after one pass.
@@ -415,14 +423,14 @@ export function useServiceFormState({
     (sum, p) => sum + (Number(p.unitCost) || 0) * (Number(p.quantity) || 0),
     (sum, p) => sum + (Number(p.unitCost) || 0) * (Number(p.quantity) || 0),
     0
     0
   )
   )
-  const laborSubtotal = laborItemsForSave.reduce((sum, l) => sum + l.total, 0)
-  const subtotal = partsSubtotal + laborSubtotal
+  const laborSubtotal = roundMoney(laborLinesForTotals.reduce((sum, l) => sum + l.total, 0))
+  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 alone. A line says whether it
   // The tax is charged on the taxable lines alone. A line says whether it
   // is taxed, and one that has not been asked follows the workshop's rule
   // is taxed, and one that has not been asked follows the workshop's rule
   // for its kind; the server settles it the same way when the job is saved.
   // for its kind; the server settles it the same way when the job is saved.
-  const taxableParts = taxablePartsTotal(partItemsForSave, taxApplies)
-  const taxableLabor = taxableLaborTotal(laborItemsForSave, taxApplies)
+  const taxableParts = taxablePartsTotal(partLinesForTotals, taxApplies)
+  const taxableLabor = taxableLaborTotal(laborLinesForTotals, taxApplies)
   const taxableSubtotal = storedTaxableSubtotal(subtotal, taxableParts + taxableLabor)
   const taxableSubtotal = storedTaxableSubtotal(subtotal, taxableParts + taxableLabor)
   const {
   const {
     taxAmount,
     taxAmount,
@@ -524,7 +532,7 @@ export function useServiceFormState({
         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

+ 26 - 1
src/features/vehicles/Lib/addPart.ts

@@ -6,6 +6,7 @@ import { loadTaxApplies } from '@/features/settings/Lib/loadTaxApplies'
 import { documentTotals } from '@/features/settings/Lib/workshopTax'
 import { documentTotals } from '@/features/settings/Lib/workshopTax'
 import { reconcileInventoryForParts } from '@/features/inventory/Lib/reconcileStock'
 import { reconcileInventoryForParts } from '@/features/inventory/Lib/reconcileStock'
 import { assertInvoiceEditable } from '@/lib/document-lock.server'
 import { assertInvoiceEditable } from '@/lib/document-lock.server'
+import { servicePartSchema } from '../Schema/serviceSchema'
 import { markupFromCostAndPrice } from '@/features/inventory/Lib/partPricing'
 import { markupFromCostAndPrice } from '@/features/inventory/Lib/partPricing'
 
 
 /**
 /**
@@ -49,7 +50,31 @@ export async function addPart(args: {
   userId: string
   userId: string
   input: AddPartInput
   input: AddPartInput
 }) {
 }) {
-  const { organizationId, userId, input } = args
+  const { organizationId, userId, input: sent } = args
+
+  // The same rules as a line saved with the whole work order: no negatives,
+  // no priced part at a quantity of zero, nothing past the limits in
+  // lib/input-limits.ts, and the total held to the cent. Checked before
+  // anything is read, so a refused line moves no stock.
+  const line = servicePartSchema.parse({
+    partNumber: sent.partNumber ?? undefined,
+    name: sent.name,
+    quantity: sent.quantity,
+    unit: sent.unit,
+    category: sent.category,
+    unitPrice: sent.unitPrice,
+    total: sent.total,
+    unitCost: sent.unitCost,
+    inventoryPartId: sent.inventoryPartId ?? undefined,
+    taxable: sent.taxable,
+  })
+  const input: AddPartInput = {
+    ...sent,
+    quantity: line.quantity,
+    unitPrice: line.unitPrice,
+    total: line.total,
+    unitCost: line.unitCost,
+  }
 
 
   // Guarded here rather than at each caller: the server action and the
   // Guarded here rather than at each caller: the server action and the
   // technician API both come through this function, and a lock enforced in
   // technician API both come through this function, and a lock enforced in

+ 4 - 1
src/features/vehicles/Lib/laborLines.ts

@@ -1,3 +1,4 @@
+import { roundMoney } from '@/lib/money'
 import type { ServiceLaborInput } from '@/features/vehicles/Schema/serviceSchema'
 import type { ServiceLaborInput } from '@/features/vehicles/Schema/serviceSchema'
 import { isShopFeeLine } from '@/features/settings/Lib/shopFee'
 import { isShopFeeLine } from '@/features/settings/Lib/shopFee'
 
 
@@ -22,7 +23,9 @@ export function savedLaborShape(line: ServiceLaborInput): ServiceLaborInput {
     ...line,
     ...line,
     hours: Number(line.hours) || 0,
     hours: Number(line.hours) || 0,
     rate: Number(line.rate) || 0,
     rate: Number(line.rate) || 0,
-    total: Number(line.total) || 0,
+    // Held to the cent, as the save stores it (serviceSchema), so a total the
+    // page worked out with float noise matches the one the refresh brings back.
+    total: roundMoney(line.total),
     pricingType: line.pricingType || 'hourly',
     pricingType: line.pricingType || 'hourly',
   }
   }
 }
 }

+ 4 - 1
src/features/vehicles/Lib/partLines.ts

@@ -1,3 +1,4 @@
+import { roundMoney } from '@/lib/money'
 import { isPriceOverridden } from '@/features/inventory/Lib/partPricing'
 import { isPriceOverridden } from '@/features/inventory/Lib/partPricing'
 import type { ServicePartInput } from '@/features/vehicles/Schema/serviceSchema'
 import type { ServicePartInput } from '@/features/vehicles/Schema/serviceSchema'
 
 
@@ -71,7 +72,9 @@ export function savedPartShape(part: ServicePartInput): ServicePartInput {
     partNumber: part.partNumber || '',
     partNumber: part.partNumber || '',
     quantity: Number(part.quantity) || 0,
     quantity: Number(part.quantity) || 0,
     unitPrice: Number(part.unitPrice) || 0,
     unitPrice: Number(part.unitPrice) || 0,
-    total: Number(part.total) || 0,
+    // Held to the cent, as the save stores it (serviceSchema), so a total the
+    // page worked out with float noise matches the one the refresh brings back.
+    total: roundMoney(part.total),
     inventoryPartId: part.inventoryPartId || undefined,
     inventoryPartId: part.inventoryPartId || undefined,
   }
   }
 }
 }

+ 43 - 0
src/features/vehicles/Lib/subtotalFromLines.ts

@@ -0,0 +1,43 @@
+import { roundMoney } from '@/lib/money'
+import { discountAmountFor } from '@/lib/tax'
+
+/**
+ * What a job's lines add up to, each line held to the cent first, the way
+ * the save stores it (serviceSchema rounds every line total).
+ *
+ * The editor adds up its own figures, and before the lines were rounded on
+ * save those were the stored ones. Now a page that sums 2 x 2.5 h at 19.99
+ * as 99.95 saves two lines of 49.98, and a subtotal taken from the page
+ * would not be what the lines on the invoice add up to. A save that sends
+ * its lines therefore has its subtotal restated from them.
+ */
+export function subtotalFromLines(
+  parts: readonly { total: number | string | null | undefined }[],
+  labor: readonly { total: number | string | null | undefined }[]
+): number {
+  const sum = (lines: readonly { total: number | string | null | undefined }[]) =>
+    lines.reduce((total, line) => total + roundMoney(line.total), 0)
+  return roundMoney(sum(parts) + sum(labor))
+}
+
+/**
+ * The subtotal and the discount a save stores, restated from its lines when
+ * they disagree with what the page sent. A percentage discount follows the
+ * subtotal and a fixed one is capped by it; with no discount type the sent
+ * amount is left alone (undefined). Null when the page was right.
+ */
+export function restatedSubtotal(args: {
+  sentSubtotal: number
+  linesSubtotal: number
+  discountType: string | null | undefined
+  discountValue: number | null | undefined
+}): { subtotal: number; discountAmount: number | undefined } | null {
+  if (roundMoney(args.sentSubtotal) === args.linesSubtotal) return null
+  return {
+    subtotal: args.linesSubtotal,
+    discountAmount:
+      args.discountType === 'percentage' || args.discountType === 'fixed'
+        ? discountAmountFor(args.linesSubtotal, args.discountType, args.discountValue)
+        : undefined,
+  }
+}

+ 44 - 0
src/features/vehicles/Lib/validateServiceForm.ts

@@ -13,10 +13,23 @@
  */
  */
 
 
 import { concernHasStory } from './concernStory'
 import { concernHasStory } from './concernStory'
+import {
+  LABOR_HOURS_MAX,
+  LINE_TOTAL_MAX,
+  QUANTITY_MAX,
+  READING_MAX,
+  UNIT_PRICE_MAX,
+} from '@/lib/input-limits'
 
 
 export type ServiceFormProblem =
 export type ServiceFormProblem =
   | 'title'
   | 'title'
   | 'negative'
   | 'negative'
+  /** The odometer or hour meter typed below zero. */
+  | 'negativeReading'
+  /** A reading, quantity, price or line total past what any job has (lib/input-limits.ts). */
+  | 'tooLarge'
+  /** A part with a price and a quantity of zero: priced, and billed nothing. */
+  | 'zeroQuantity'
   /** A part priced or numbered but never named. */
   /** A part priced or numbered but never named. */
   | 'partName'
   | 'partName'
   /** Labour with hours, or a priced service, but nothing said about it. */
   /** Labour with hours, or a priced service, but nothing said about it. */
@@ -51,6 +64,8 @@ export interface ServiceFormConcern {
 
 
 export interface ServiceFormInput {
 export interface ServiceFormInput {
   title: string
   title: string
+  /** The reading as typed; empty or absent is no reading. */
+  mileage?: number | string | null
   partItems: ServiceFormPart[]
   partItems: ServiceFormPart[]
   laborItems: ServiceFormLabor[]
   laborItems: ServiceFormLabor[]
   concerns?: ServiceFormConcern[]
   concerns?: ServiceFormConcern[]
@@ -88,6 +103,10 @@ export function laborRowHasContent(labor: ServiceFormLabor): boolean {
 export function findServiceFormProblem(input: ServiceFormInput): ServiceFormProblem | null {
 export function findServiceFormProblem(input: ServiceFormInput): ServiceFormProblem | null {
   if (!input.title.trim()) return 'title'
   if (!input.title.trim()) return 'title'
 
 
+  const reading =
+    input.mileage == null || String(input.mileage).trim() === '' ? null : num(input.mileage)
+  if (reading !== null && reading < 0) return 'negativeReading'
+
   // Money and time only run one way. A negative here is a typo or a minus
   // Money and time only run one way. A negative here is a typo or a minus
   // sign left in the field, and it reaches the totals before it reaches the
   // sign left in the field, and it reaches the totals before it reaches the
   // save, so the editor can already be showing a negative invoice.
   // save, so the editor can already be showing a negative invoice.
@@ -102,6 +121,31 @@ export function findServiceFormProblem(input: ServiceFormInput): ServiceFormProb
   const negativeLabor = input.laborItems.some((l) => num(l.hours) < 0 || num(l.rate) < 0)
   const negativeLabor = input.laborItems.some((l) => num(l.hours) < 0 || num(l.rate) < 0)
   if (negativePart || negativeLabor) return 'negative'
   if (negativePart || negativeLabor) return 'negative'
 
 
+  // Past anything a job has: a slip of the finger that would put a total of
+  // trillions on the invoice and push it off the page.
+  const tooLarge =
+    (reading !== null && reading > READING_MAX) ||
+    input.partItems.some(
+      (p) =>
+        num(p.quantity) > QUANTITY_MAX ||
+        num(p.unitPrice) > UNIT_PRICE_MAX ||
+        num(p.unitCost) > UNIT_PRICE_MAX ||
+        num(p.quantity) * num(p.unitPrice) > LINE_TOTAL_MAX
+    ) ||
+    input.laborItems.some(
+      (l) =>
+        num(l.hours) > LABOR_HOURS_MAX ||
+        num(l.rate) > UNIT_PRICE_MAX ||
+        num(l.hours) * num(l.rate) > LINE_TOTAL_MAX
+    )
+  if (tooLarge) return 'tooLarge'
+
+  // Priced and billed nothing. A free part may sit at zero as a note of what
+  // was used; a priced one is a quantity somebody forgot.
+  if (input.partItems.some((p) => p.name.trim() && num(p.unitPrice) > 0 && num(p.quantity) <= 0)) {
+    return 'zeroQuantity'
+  }
+
   // A row with a price and no name used to be dropped on save without a word,
   // A row with a price and no name used to be dropped on save without a word,
   // taking its money off the invoice. The workshop finds out when the
   // taking its money off the invoice. The workshop finds out when the
   // customer's total is short.
   // customer's total is short.

+ 2 - 1
src/features/vehicles/Schema/fuelSchema.ts

@@ -1,9 +1,10 @@
 import { z } from 'zod'
 import { z } from 'zod'
+import { READING_MAX } from '@/lib/input-limits'
 
 
 export const createFuelLogSchema = z.object({
 export const createFuelLogSchema = z.object({
   vehicleId: z.string(),
   vehicleId: z.string(),
   date: z.string().default(() => new Date().toISOString()),
   date: z.string().default(() => new Date().toISOString()),
-  mileage: z.coerce.number().min(0, 'Mileage is required'),
+  mileage: z.coerce.number().min(0, 'Mileage is required').max(READING_MAX),
   gallons: z.coerce.number().min(0, 'Gallons is required'),
   gallons: z.coerce.number().min(0, 'Gallons is required'),
   pricePerGallon: z.coerce.number().min(0, 'Price is required'),
   pricePerGallon: z.coerce.number().min(0, 'Price is required'),
   totalCost: z.coerce.number().min(0),
   totalCost: z.coerce.number().min(0),

+ 76 - 39
src/features/vehicles/Schema/serviceSchema.ts

@@ -1,45 +1,81 @@
 import { z } from 'zod'
 import { z } from 'zod'
+import { roundMoney } from '@/lib/money'
+import {
+  checkLineAmounts,
+  LABOR_HOURS_MAX,
+  LINE_TOTAL_MAX,
+  QUANTITY_MAX,
+  READING_MAX,
+  UNIT_PRICE_MAX,
+} from '@/lib/input-limits'
 import { uploadUrlSchema } from '@/lib/upload-url'
 import { uploadUrlSchema } from '@/lib/upload-url'
 
 
-export const servicePartSchema = 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(),
-  unitPrice: z.coerce.number().min(0).default(0),
-  total: z.coerce.number().min(0).default(0),
-  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),
-  inventoryPartId: z.string().optional(),
-  /**
-   * 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(),
-})
+export const servicePartSchema = 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(),
+    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),
+    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),
+    inventoryPartId: z.string().optional(),
+    /**
+     * 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 priced part billed none of: a quantity of zero puts a price on the
+  // line and nothing on the invoice. A free part (no price) may still be
+  // listed at zero, as a note of what was used.
+  // Its quantity times its price is checked too, whatever total was sent.
+  .superRefine((part, ctx) =>
+    checkLineAmounts(
+      { count: part.quantity, price: part.unitPrice },
+      ctx,
+      { count: 'quantity', total: 'total' },
+      { pricedNeedsCount: true }
+    )
+  )
 
 
-export const serviceLaborSchema = 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'),
-  /**
-   * 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: a line a technician has started and not yet clocked
+ * time on (live labour from the phone), or work done for nothing, is a real
+ * line. Only negatives and absurd figures are refused.
+ */
+export const serviceLaborSchema = 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'),
+    /**
+     * 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 serviceAttachmentSchema = z.object({
 export const serviceAttachmentSchema = z.object({
   fileName: z.string(),
   fileName: z.string(),
@@ -94,7 +130,8 @@ export const createServiceSchema = z.object({
     .enum(['scheduled', 'pending', 'in-progress', 'waiting-parts', 'completed'])
     .enum(['scheduled', 'pending', 'in-progress', 'waiting-parts', 'completed'])
     .default('pending'),
     .default('pending'),
   cost: z.coerce.number().min(0).default(0),
   cost: z.coerce.number().min(0).default(0),
-  mileage: z.coerce.number().nullable().optional(),
+  /** Never below zero, and an odometer's worth at most, as the technician app takes it. */
+  mileage: z.coerce.number().int().min(0).max(READING_MAX).nullable().optional(),
   serviceDate: z.string().default(() => new Date().toISOString()),
   serviceDate: z.string().default(() => new Date().toISOString()),
   shopName: z.string().optional(),
   shopName: z.string().optional(),
   techName: z.string().optional(),
   techName: z.string().optional(),

+ 12 - 11
src/features/vehicles/Schema/vehicleSchema.ts

@@ -1,4 +1,5 @@
 import { z } from 'zod'
 import { z } from 'zod'
+import { NAME_MAX_LENGTH, READING_MAX, SHORT_TEXT_MAX_LENGTH } from '@/lib/input-limits'
 import { FLEET_NUMBER_MAX_LENGTH } from '../Lib/fleetNumber'
 import { FLEET_NUMBER_MAX_LENGTH } from '../Lib/fleetNumber'
 import { optionalUploadUrlSchema } from '@/lib/upload-url'
 import { optionalUploadUrlSchema } from '@/lib/upload-url'
 import { registryLookupSchema } from '../Lib/registryLookup'
 import { registryLookupSchema } from '../Lib/registryLookup'
@@ -16,20 +17,20 @@ const tsnSchema = z
   .refine((v) => v === '' || TSN_PATTERN.test(v), 'TSN is three letters or digits, from field 2.2')
   .refine((v) => v === '' || TSN_PATTERN.test(v), 'TSN is three letters or digits, from field 2.2')
 
 
 export const createVehicleSchema = z.object({
 export const createVehicleSchema = z.object({
-  make: z.string().min(1, 'Make is required'),
-  model: z.string().min(1, 'Model is required'),
+  make: z.string().min(1, 'Make is required').max(NAME_MAX_LENGTH),
+  model: z.string().min(1, 'Model is required').max(NAME_MAX_LENGTH),
   year: z.coerce
   year: z.coerce
     .number()
     .number()
     .min(VEHICLE_YEAR_MIN, 'Year must be after 1900')
     .min(VEHICLE_YEAR_MIN, 'Year must be after 1900')
     .max(vehicleYearMax(), 'Year is too far in the future'),
     .max(vehicleYearMax(), 'Year is too far in the future'),
-  vin: z.string().optional(),
-  licensePlate: z.string().optional(),
-  color: z.string().optional(),
-  mileage: z.coerce.number().min(0).default(0),
-  fuelType: z.string().optional(),
-  transmission: z.string().optional(),
-  engineSize: z.string().optional(),
-  engineCode: z.string().optional(),
+  vin: z.string().max(SHORT_TEXT_MAX_LENGTH).optional(),
+  licensePlate: z.string().max(SHORT_TEXT_MAX_LENGTH).optional(),
+  color: z.string().max(SHORT_TEXT_MAX_LENGTH).optional(),
+  mileage: z.coerce.number().min(0).max(READING_MAX).default(0),
+  fuelType: z.string().max(SHORT_TEXT_MAX_LENGTH).optional(),
+  transmission: z.string().max(SHORT_TEXT_MAX_LENGTH).optional(),
+  engineSize: z.string().max(NAME_MAX_LENGTH).optional(),
+  engineCode: z.string().max(SHORT_TEXT_MAX_LENGTH).optional(),
   hsn: hsnSchema.optional(),
   hsn: hsnSchema.optional(),
   tsn: tsnSchema.optional(),
   tsn: tsnSchema.optional(),
   /** The owner's own number for the vehicle. Kept only by a workshop that uses the field. */
   /** The owner's own number for the vehicle. Kept only by a workshop that uses the field. */
@@ -70,7 +71,7 @@ export const updateVehicleSchema = createVehicleSchema.partial().extend({
   // Without the new vehicle's default: zod fills a default in even on an
   // Without the new vehicle's default: zod fills a default in even on an
   // optional field, so an update that did not send the reading (adding a
   // optional field, so an update that did not send the reading (adding a
   // customer from the work order) came out with `mileage: 0` and wiped it.
   // customer from the work order) came out with `mileage: 0` and wiped it.
-  mileage: z.coerce.number().min(0).optional(),
+  mileage: z.coerce.number().min(0).max(READING_MAX).optional(),
 })
 })
 
 
 export type CreateVehicleInput = z.infer<typeof createVehicleSchema>
 export type CreateVehicleInput = z.infer<typeof createVehicleSchema>

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

@@ -16,6 +16,8 @@ export type FieldIssue =
   | 'tooShort'
   | 'tooShort'
   | 'tooLong'
   | 'tooLong'
   | 'negative'
   | 'negative'
+  /** Above zero: a priced part's quantity. */
+  | 'positive'
   | 'tooSmall'
   | 'tooSmall'
   | 'tooLarge'
   | 'tooLarge'
   | 'notNumber'
   | 'notNumber'
@@ -41,6 +43,7 @@ function issueOf(issue: Issue): Pick<FieldError, 'issue' | 'limit'> {
       }
       }
       if (issue.origin === 'array' || issue.origin === 'set') return { issue: 'required' }
       if (issue.origin === 'array' || issue.origin === 'set') return { issue: 'required' }
       if (minimum === 0 && issue.inclusive !== false) return { issue: 'negative' }
       if (minimum === 0 && issue.inclusive !== false) return { issue: 'negative' }
+      if (minimum === 0) return { issue: 'positive' }
       return { issue: 'tooSmall', limit: minimum }
       return { issue: 'tooSmall', limit: minimum }
     }
     }
     case 'too_big': {
     case 'too_big': {

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

@@ -0,0 +1,76 @@
+import type { z } from 'zod'
+
+/**
+ * The largest figures and the longest texts the forms take.
+ *
+ * Well past anything a workshop writes, and short of what breaks a page or a
+ * document: a quantity of a billion at a hundred million each once saved,
+ * printed a total of 119,999,998,800,000,000 with float noise in it and
+ * pushed the invoice off the page, and a 3,000-character address made a
+ * customer's header 21,545 px wide. The schemas refuse past these, and the
+ * forms carry the same numbers so the browser can say so first.
+ */
+
+/** Of one part on a line. */
+export const QUANTITY_MAX = 100_000
+/** A unit price, a unit cost or an hourly rate. */
+export const UNIT_PRICE_MAX = 10_000_000
+/** Hours on one labour line, or the count of a line priced per service. */
+export const LABOR_HOURS_MAX = 100_000
+/**
+ * One line's total. Money is rounded to the cent on twelve significant
+ * digits (src/lib/money.ts), so a total has to stay below ten billion for
+ * the cents to survive; this keeps it well inside.
+ */
+export const LINE_TOTAL_MAX = 1_000_000_000
+/** An odometer or an hour meter, as the technician app already takes it. */
+export const READING_MAX = 10_000_000
+
+/**
+ * A priced line's own rules, for every schema that takes one (work orders,
+ * labour presets): its count times its price no more than LINE_TOTAL_MAX,
+ * whatever total the caller sent, and, with `pricedNeedsCount`, a priced line
+ * at a count of zero refused. Reported as zod's own size issues, so a form
+ * says them in words (src/lib/field-errors.ts).
+ */
+export function checkLineAmounts(
+  line: { count: number; price: number },
+  ctx: z.RefinementCtx,
+  /** Where each problem is reported: the count field, and the field the line total is said under. */
+  fields: { count: string; total: string },
+  options: { pricedNeedsCount?: boolean } = {}
+): void {
+  if (options.pricedNeedsCount && line.price > 0 && line.count <= 0) {
+    ctx.addIssue({
+      code: 'too_small',
+      origin: 'number',
+      minimum: 0,
+      inclusive: false,
+      path: [fields.count],
+      message: 'A priced line needs a quantity above zero',
+      input: line.count,
+    })
+  }
+  if (line.count * line.price > LINE_TOTAL_MAX) {
+    ctx.addIssue({
+      code: 'too_big',
+      origin: 'number',
+      maximum: LINE_TOTAL_MAX,
+      inclusive: true,
+      path: [fields.total],
+      message: `A line can come to at most ${LINE_TOTAL_MAX}`,
+      input: line.price,
+    })
+  }
+}
+
+/** A person's or a company's name, a make, a model. */
+export const NAME_MAX_LENGTH = 200
+/** A postal address, street to country. */
+export const ADDRESS_MAX_LENGTH = 500
+/** Free notes. */
+export const NOTES_MAX_LENGTH = 10_000
+/** An email address, as long as the standard allows. */
+export const EMAIL_MAX_LENGTH = 254
+/** A phone number, a tax id, a plate, a code. */
+export const SHORT_TEXT_MAX_LENGTH = 50