Bläddra i källkod

Turn off stock tracking for fees and consumables (#625)

* Turn off stock tracking for fees and consumables

A part can be marked as not tracking stock. Using it on a work order, counter sale, quote conversion or from the technician app leaves its quantity alone and writes no stock history, and taking the line off again adds nothing back. Such parts are never low on stock and are left out of stock value. Turning tracking off sets the quantity to zero with one stock history entry.

* Keep the reorder point and record tracking turned off at zero stock

Turning tracking off no longer resets the reorder point, writes its stock history entry even when the part already stood at zero, and a barcode stock adjustment cannot land on a part whose tracking was switched off in the meantime.
Bernt Christian Egeland 22 timmar sedan
förälder
incheckning
6efac19be9
49 ändrade filer med 993 tillägg och 140 borttagningar
  1. 10 4
      messages/de/inventory.json
  2. 10 4
      messages/en/inventory.json
  3. 10 4
      messages/es/inventory.json
  4. 10 4
      messages/fr/inventory.json
  5. 10 4
      messages/it/inventory.json
  6. 10 4
      messages/lt/inventory.json
  7. 10 4
      messages/nb/inventory.json
  8. 10 4
      messages/nl/inventory.json
  9. 10 4
      messages/pl/inventory.json
  10. 10 4
      messages/pt-BR/inventory.json
  11. 10 4
      messages/pt-PT/inventory.json
  12. 10 4
      messages/ru/inventory.json
  13. 10 4
      messages/tr/inventory.json
  14. 2 0
      prisma/migrations/20261117150353_inventory_part_track_stock/migration.sql
  15. 5 0
      prisma/schema/inventory.prisma
  16. 182 0
      src/__tests__/db/untracked-stock.db.test.ts
  17. 9 0
      src/__tests__/features/inventory/inventory-list-markup.test.tsx
  18. 9 0
      src/__tests__/features/inventory/part-form-sell-price-markup.test.tsx
  19. 9 0
      src/__tests__/features/inventory/part-form-supplier-fetch.test.tsx
  20. 195 0
      src/__tests__/features/inventory/untracked-parts-list.test.tsx
  21. 206 0
      src/__tests__/features/inventory/untracked-parts.test.ts
  22. 8 2
      src/app/(authenticated)/inventory/[id]/part-detail-client.tsx
  23. 9 2
      src/app/(authenticated)/inventory/inventory-client.tsx
  24. 3 0
      src/app/api/v1/tech/parts/lookup/route.ts
  25. 13 3
      src/components/mobile-bottom-nav.tsx
  26. 1 0
      src/features/ai/tools/workshop-columns.ts
  27. 1 1
      src/features/ai/tools/workshop-tools.ts
  28. 2 0
      src/features/integrations/Lib/fluid-stock.ts
  29. 1 0
      src/features/inventory/Actions/getStockMovements.ts
  30. 61 27
      src/features/inventory/Actions/inventoryActions.ts
  31. 1 0
      src/features/inventory/Actions/lookupPartByBarcode.ts
  32. 6 2
      src/features/inventory/Components/BarcodeScanActionDialog.tsx
  33. 59 24
      src/features/inventory/Components/InventoryPartForm.tsx
  34. 3 1
      src/features/inventory/Components/PartNameSuggestions.tsx
  35. 6 1
      src/features/inventory/Lib/lowStockAlerts.ts
  36. 22 5
      src/features/inventory/Lib/reconcileStock.ts
  37. 1 0
      src/features/inventory/Lib/stockMovementReasons.ts
  38. 4 0
      src/features/inventory/Schema/inventorySchema.ts
  39. 3 1
      src/features/reports/Actions/reportActions.ts
  40. 1 0
      src/features/search/Actions/searchActions.ts
  41. 7 1
      src/features/search/Components/SearchCommand.tsx
  42. 1 0
      src/features/vehicles/Actions/dashboardActions.ts
  43. 8 5
      src/features/vehicles/Components/MyActiveJobs.tsx
  44. 11 8
      src/features/vehicles/Components/labor-guide/FluidPartButton.tsx
  45. 1 1
      src/features/vehicles/Components/service-edit/InventoryPickerDialog.tsx
  46. 2 0
      src/features/vehicles/Components/service-edit/form-types.ts
  47. 2 0
      src/lib/backup/import.ts
  48. 7 3
      src/lib/cron/low-stock-alerts.ts
  49. 2 1
      src/lib/cron/report-schedules.ts

+ 10 - 4
messages/de/inventory.json

@@ -14,7 +14,8 @@
     "supplier": "Lieferant",
     "location": "Lagerort",
     "low": "Niedrig",
-    "barcode": "Barcode"
+    "barcode": "Barcode",
+    "notTracked": "Nicht erfasst"
   },
   "empty": {
     "noMatch": "Keine Teile entsprechen Ihrer Suche.",
@@ -74,7 +75,8 @@
     "currentStock": "Aktueller Bestand: {quantity}",
     "addedStock": "{amount} zum Bestand hinzugefügt",
     "customAmount": "Menge...",
-    "scanParts": "Teile scannen"
+    "scanParts": "Teile scannen",
+    "notTracked": "Für dieses Teil wird kein Bestand geführt"
   },
   "form": {
     "editPart": "Teil bearbeiten",
@@ -142,7 +144,10 @@
     "tagsHint": "Nach jedem Tag Enter oder ein Komma drücken. In einem Auftrag stehen Teile mit der Marke oder dem Modell des Fahrzeugs ganz oben.",
     "tagsHintMarine": "Nach jedem Tag Enter oder ein Komma drücken. In einem Auftrag stehen Teile mit der Marke oder dem Modell des Bootes ganz oben.",
     "removeTag": "{tag} entfernen",
-    "tagTooLong": "Ein Tag darf höchstens {max} Zeichen lang sein. Bitte vor dem Speichern kürzen."
+    "tagTooLong": "Ein Tag darf höchstens {max} Zeichen lang sein. Bitte vor dem Speichern kürzen.",
+    "trackStock": "Bestand führen",
+    "trackStockHint": "Ausschalten für Gebühren und Verbrauchsmaterial, das Sie berechnen, aber nie zählen.",
+    "trackStockOffNote": "Beim Speichern wird die Menge auf null gesetzt und im Bestandsverlauf vermerkt. Aufträge ändern sie nicht mehr."
   },
   "openMenu": "Menü öffnen",
   "history": {
@@ -159,7 +164,8 @@
       "service_record_deleted": "Auftrag gelöscht",
       "quote_conversion": "Angebot umgewandelt",
       "manual_adjustment": "Manuelle Anpassung",
-      "bulk_markup": "Massenaufschlag"
+      "bulk_markup": "Massenaufschlag",
+      "stock_tracking_off": "Bestandsführung ausgeschaltet"
     },
     "backToInventory": "Lager",
     "reason": "Grund",

+ 10 - 4
messages/en/inventory.json

@@ -14,7 +14,8 @@
     "supplier": "Supplier",
     "location": "Location",
     "low": "Low",
-    "barcode": "Barcode"
+    "barcode": "Barcode",
+    "notTracked": "Not tracked"
   },
   "empty": {
     "noMatch": "No parts match your search.",
@@ -74,7 +75,8 @@
     "currentStock": "Current stock: {quantity}",
     "addedStock": "Added {amount} to stock",
     "customAmount": "Qty...",
-    "scanParts": "Scan Parts"
+    "scanParts": "Scan Parts",
+    "notTracked": "Stock is not tracked for this part"
   },
   "form": {
     "editPart": "Edit Part",
@@ -142,7 +144,10 @@
     "tagsHint": "Press Enter or a comma after each one. On a job, parts tagged with the vehicle's make or model are listed first.",
     "tagsHintMarine": "Press Enter or a comma after each one. On a job, parts tagged with the vessel's make or model are listed first.",
     "removeTag": "Remove {tag}",
-    "tagTooLong": "A tag can be at most {max} characters. Shorten it before saving."
+    "tagTooLong": "A tag can be at most {max} characters. Shorten it before saving.",
+    "trackStock": "Track stock",
+    "trackStockHint": "Turn off for fees and consumables you charge but never count.",
+    "trackStockOffNote": "Saving sets the quantity to zero and notes it in the stock history. Jobs no longer change it."
   },
   "openMenu": "Open menu",
   "history": {
@@ -159,7 +164,8 @@
       "service_record_deleted": "Work order deleted",
       "quote_conversion": "Quote converted",
       "manual_adjustment": "Manual adjustment",
-      "bulk_markup": "Bulk markup"
+      "bulk_markup": "Bulk markup",
+      "stock_tracking_off": "Stock tracking turned off"
     },
     "backToInventory": "Inventory",
     "reason": "Reason",

+ 10 - 4
messages/es/inventory.json

@@ -14,7 +14,8 @@
     "supplier": "Proveedor",
     "location": "Ubicación",
     "low": "Bajo",
-    "barcode": "Código de barras"
+    "barcode": "Código de barras",
+    "notTracked": "Sin seguimiento"
   },
   "empty": {
     "noMatch": "Ninguna pieza coincide con su búsqueda.",
@@ -74,7 +75,8 @@
     "currentStock": "Stock actual: {quantity}",
     "addedStock": "{amount} agregados al stock",
     "customAmount": "Cant...",
-    "scanParts": "Escanear piezas"
+    "scanParts": "Escanear piezas",
+    "notTracked": "No se lleva el stock de esta pieza"
   },
   "form": {
     "editPart": "Editar pieza",
@@ -142,7 +144,10 @@
     "tagsHint": "Pulsa Intro o una coma después de cada una. En un trabajo, las piezas etiquetadas con la marca o el modelo del vehículo aparecen primero.",
     "tagsHintMarine": "Pulsa Intro o una coma después de cada una. En un trabajo, las piezas etiquetadas con la marca o el modelo de la embarcación aparecen primero.",
     "removeTag": "Quitar {tag}",
-    "tagTooLong": "Una etiqueta puede tener como máximo {max} caracteres. Acórtala antes de guardar."
+    "tagTooLong": "Una etiqueta puede tener como máximo {max} caracteres. Acórtala antes de guardar.",
+    "trackStock": "Controlar stock",
+    "trackStockHint": "Desactívalo para tasas y consumibles que cobras pero nunca cuentas.",
+    "trackStockOffNote": "Al guardar, la cantidad pasa a cero y queda anotado en el historial de stock. Los trabajos ya no la cambian."
   },
   "openMenu": "Abrir menú",
   "history": {
@@ -159,7 +164,8 @@
       "service_record_deleted": "Orden eliminada",
       "quote_conversion": "Presupuesto convertido",
       "manual_adjustment": "Ajuste manual",
-      "bulk_markup": "Margen masivo"
+      "bulk_markup": "Margen masivo",
+      "stock_tracking_off": "Control de stock desactivado"
     },
     "backToInventory": "Inventario",
     "reason": "Motivo",

+ 10 - 4
messages/fr/inventory.json

@@ -14,7 +14,8 @@
     "supplier": "Fournisseur",
     "location": "Emplacement",
     "low": "Bas",
-    "barcode": "Code-barres"
+    "barcode": "Code-barres",
+    "notTracked": "Non suivi"
   },
   "empty": {
     "noMatch": "Aucune pièce ne correspond à votre recherche.",
@@ -74,7 +75,8 @@
     "currentStock": "Stock actuel : {quantity}",
     "addedStock": "{amount} ajoutés au stock",
     "customAmount": "Qté...",
-    "scanParts": "Scanner des pièces"
+    "scanParts": "Scanner des pièces",
+    "notTracked": "Le stock de cette pièce n'est pas suivi"
   },
   "form": {
     "editPart": "Modifier la pièce",
@@ -142,7 +144,10 @@
     "tagsHint": "Appuyez sur Entrée ou une virgule après chaque étiquette. Sur une intervention, les pièces étiquetées avec la marque ou le modèle du véhicule apparaissent en premier.",
     "tagsHintMarine": "Appuyez sur Entrée ou une virgule après chaque étiquette. Sur une intervention, les pièces étiquetées avec la marque ou le modèle du bateau apparaissent en premier.",
     "removeTag": "Retirer {tag}",
-    "tagTooLong": "Une étiquette peut contenir au plus {max} caractères. Raccourcissez-la avant d'enregistrer."
+    "tagTooLong": "Une étiquette peut contenir au plus {max} caractères. Raccourcissez-la avant d'enregistrer.",
+    "trackStock": "Suivre le stock",
+    "trackStockHint": "Désactivez pour les frais et consommables que vous facturez sans jamais les compter.",
+    "trackStockOffNote": "L'enregistrement remet la quantité à zéro et le note dans l'historique du stock. Les travaux ne la modifient plus."
   },
   "openMenu": "Ouvrir le menu",
   "history": {
@@ -159,7 +164,8 @@
       "service_record_deleted": "Ordre supprimé",
       "quote_conversion": "Devis converti",
       "manual_adjustment": "Ajustement manuel",
-      "bulk_markup": "Marge en masse"
+      "bulk_markup": "Marge en masse",
+      "stock_tracking_off": "Suivi du stock désactivé"
     },
     "backToInventory": "Inventaire",
     "reason": "Motif",

+ 10 - 4
messages/it/inventory.json

@@ -14,7 +14,8 @@
     "supplier": "Fornitore",
     "location": "Posizione",
     "low": "Basso",
-    "barcode": "Codice a barre"
+    "barcode": "Codice a barre",
+    "notTracked": "Non tracciato"
   },
   "empty": {
     "noMatch": "Nessun ricambio corrisponde alla ricerca.",
@@ -74,7 +75,8 @@
     "currentStock": "Stock attuale: {quantity}",
     "addedStock": "{amount} aggiunti allo stock",
     "customAmount": "Qtà...",
-    "scanParts": "Scansiona ricambi"
+    "scanParts": "Scansiona ricambi",
+    "notTracked": "La giacenza di questo ricambio non è tracciata"
   },
   "form": {
     "editPart": "Modifica ricambio",
@@ -142,7 +144,10 @@
     "tagsHint": "Premi Invio o una virgola dopo ogni tag. In un lavoro, i ricambi con la marca o il modello del veicolo compaiono per primi.",
     "tagsHintMarine": "Premi Invio o una virgola dopo ogni tag. In un lavoro, i ricambi con la marca o il modello dell'imbarcazione compaiono per primi.",
     "removeTag": "Rimuovi {tag}",
-    "tagTooLong": "Un tag può avere al massimo {max} caratteri. Accorcialo prima di salvare."
+    "tagTooLong": "Un tag può avere al massimo {max} caratteri. Accorcialo prima di salvare.",
+    "trackStock": "Traccia giacenza",
+    "trackStockHint": "Disattiva per contributi e materiali di consumo che addebiti ma non conti mai.",
+    "trackStockOffNote": "Salvando, la quantità va a zero e viene annotato nello storico della giacenza. I lavori non la modificano più."
   },
   "openMenu": "Apri menu",
   "history": {
@@ -159,7 +164,8 @@
       "service_record_deleted": "Ordine eliminato",
       "quote_conversion": "Preventivo convertito",
       "manual_adjustment": "Rettifica manuale",
-      "bulk_markup": "Ricarico massivo"
+      "bulk_markup": "Ricarico massivo",
+      "stock_tracking_off": "Tracciamento giacenza disattivato"
     },
     "backToInventory": "Magazzino",
     "reason": "Motivo",

+ 10 - 4
messages/lt/inventory.json

@@ -14,7 +14,8 @@
     "supplier": "Tiekėjas",
     "location": "Vieta",
     "low": "Mažas",
-    "barcode": "Brūkšninis kodas"
+    "barcode": "Brūkšninis kodas",
+    "notTracked": "Nesekama"
   },
   "empty": {
     "noMatch": "Nėra dalių, atitinkančių paiešką.",
@@ -74,7 +75,8 @@
     "currentStock": "Dabartinės atsargos: {quantity}",
     "addedStock": "Pridėta {amount} prie atsargų",
     "customAmount": "Kiekis...",
-    "scanParts": "Nuskaityti dalis"
+    "scanParts": "Nuskaityti dalis",
+    "notTracked": "Šios dalies atsargos nesekamos"
   },
   "form": {
     "editPart": "Redaguoti dalį",
@@ -142,7 +144,10 @@
     "tagsHint": "Po kiekvienos žymos paspauskite Enter arba kablelį. Darbe pirmiausia rodomos dalys, pažymėtos transporto priemonės marke ar modeliu.",
     "tagsHintMarine": "Po kiekvienos žymos paspauskite Enter arba kablelį. Darbe pirmiausia rodomos dalys, pažymėtos laivo marke ar modeliu.",
     "removeTag": "Pašalinti {tag}",
-    "tagTooLong": "Žyma gali būti ne ilgesnė nei {max} simbolių. Sutrumpinkite ją prieš išsaugodami."
+    "tagTooLong": "Žyma gali būti ne ilgesnė nei {max} simbolių. Sutrumpinkite ją prieš išsaugodami.",
+    "trackStock": "Sekti atsargas",
+    "trackStockHint": "Išjunkite mokesčiams ir eksploatacinėms medžiagoms, kurias apmokestinate, bet niekada neskaičiuojate.",
+    "trackStockOffNote": "Išsaugojus kiekis nustatomas į nulį ir tai įrašoma atsargų istorijoje. Darbai jo nebekeičia."
   },
   "openMenu": "Atidaryti meniu",
   "history": {
@@ -159,7 +164,8 @@
       "service_record_deleted": "Užsakymas ištrintas",
       "quote_conversion": "Pasiūlymas konvertuotas",
       "manual_adjustment": "Rankinis koregavimas",
-      "bulk_markup": "Masinis antkainis"
+      "bulk_markup": "Masinis antkainis",
+      "stock_tracking_off": "Atsargų sekimas išjungtas"
     },
     "backToInventory": "Sandėlis",
     "reason": "Priežastis",

+ 10 - 4
messages/nb/inventory.json

@@ -14,7 +14,8 @@
     "supplier": "Leverandør",
     "location": "Plassering",
     "low": "Lav",
-    "barcode": "Strekkode"
+    "barcode": "Strekkode",
+    "notTracked": "Føres ikke"
   },
   "empty": {
     "noMatch": "Ingen deler samsvarer med søket ditt.",
@@ -74,7 +75,8 @@
     "currentStock": "Nåværende beholdning: {quantity}",
     "addedStock": "{amount} lagt til på lager",
     "customAmount": "Antall...",
-    "scanParts": "Skann deler"
+    "scanParts": "Skann deler",
+    "notTracked": "Lager føres ikke for denne delen"
   },
   "form": {
     "editPart": "Rediger del",
@@ -142,7 +144,10 @@
     "tagsHint": "Trykk Enter eller komma etter hvert stikkord. På en arbeidsordre vises deler med kjøretøyets merke eller modell først.",
     "tagsHintMarine": "Trykk Enter eller komma etter hvert stikkord. På en arbeidsordre vises deler med båtens merke eller modell først.",
     "removeTag": "Fjern {tag}",
-    "tagTooLong": "Et stikkord kan være på høyst {max} tegn. Gjør det kortere før du lagrer."
+    "tagTooLong": "Et stikkord kan være på høyst {max} tegn. Gjør det kortere før du lagrer.",
+    "trackStock": "Før lager",
+    "trackStockHint": "Slå av for gebyrer og forbruksmateriell du tar betalt for, men aldri teller.",
+    "trackStockOffNote": "Når du lagrer, settes antallet til null og det noteres i lagerhistorikken. Jobber endrer det ikke lenger."
   },
   "openMenu": "Åpne meny",
   "history": {
@@ -159,7 +164,8 @@
       "service_record_deleted": "Arbeidsordre slettet",
       "quote_conversion": "Tilbud konvertert",
       "manual_adjustment": "Manuell justering",
-      "bulk_markup": "Masse-påslag"
+      "bulk_markup": "Masse-påslag",
+      "stock_tracking_off": "Lagerføring slått av"
     },
     "backToInventory": "Lager",
     "reason": "Årsak",

+ 10 - 4
messages/nl/inventory.json

@@ -14,7 +14,8 @@
     "supplier": "Leverancier",
     "location": "Locatie",
     "low": "Laag",
-    "barcode": "Barcode"
+    "barcode": "Barcode",
+    "notTracked": "Niet bijgehouden"
   },
   "empty": {
     "noMatch": "Geen onderdelen gevonden voor uw zoekopdracht.",
@@ -74,7 +75,8 @@
     "currentStock": "Huidige voorraad: {quantity}",
     "addedStock": "{amount} toegevoegd aan voorraad",
     "customAmount": "Aantal...",
-    "scanParts": "Onderdelen scannen"
+    "scanParts": "Onderdelen scannen",
+    "notTracked": "Voorraad wordt niet bijgehouden voor dit onderdeel"
   },
   "form": {
     "editPart": "Onderdeel bewerken",
@@ -142,7 +144,10 @@
     "tagsHint": "Druk na elke tag op Enter of een komma. Bij een werkorder staan onderdelen met het merk of model van het voertuig bovenaan.",
     "tagsHintMarine": "Druk na elke tag op Enter of een komma. Bij een werkorder staan onderdelen met het merk of model van het vaartuig bovenaan.",
     "removeTag": "{tag} verwijderen",
-    "tagTooLong": "Een tag mag maximaal {max} tekens lang zijn. Maak hem korter voordat je opslaat."
+    "tagTooLong": "Een tag mag maximaal {max} tekens lang zijn. Maak hem korter voordat je opslaat.",
+    "trackStock": "Voorraad bijhouden",
+    "trackStockHint": "Zet uit voor toeslagen en verbruiksmaterialen die je rekent maar nooit telt.",
+    "trackStockOffNote": "Bij opslaan gaat de hoeveelheid naar nul en wordt dit genoteerd in de voorraadgeschiedenis. Klussen wijzigen deze niet meer."
   },
   "openMenu": "Menu openen",
   "history": {
@@ -159,7 +164,8 @@
       "service_record_deleted": "Werkorder verwijderd",
       "quote_conversion": "Offerte omgezet",
       "manual_adjustment": "Handmatige aanpassing",
-      "bulk_markup": "Bulkopslag"
+      "bulk_markup": "Bulkopslag",
+      "stock_tracking_off": "Voorraad bijhouden uitgezet"
     },
     "backToInventory": "Voorraad",
     "reason": "Reden",

+ 10 - 4
messages/pl/inventory.json

@@ -14,7 +14,8 @@
     "supplier": "Dostawca",
     "location": "Lokalizacja",
     "low": "Niski",
-    "barcode": "Kod kreskowy"
+    "barcode": "Kod kreskowy",
+    "notTracked": "Nieśledzone"
   },
   "empty": {
     "noMatch": "Żadne części nie pasują do wyszukiwania.",
@@ -74,7 +75,8 @@
     "currentStock": "Aktualny stan: {quantity}",
     "addedStock": "Dodano {amount} do stanu",
     "customAmount": "Ilość...",
-    "scanParts": "Skanuj części"
+    "scanParts": "Skanuj części",
+    "notTracked": "Stan tej części nie jest śledzony"
   },
   "form": {
     "editPart": "Edytuj część",
@@ -142,7 +144,10 @@
     "tagsHint": "Po każdym tagu naciśnij Enter lub przecinek. W zleceniu najpierw widać części oznaczone marką lub modelem pojazdu.",
     "tagsHintMarine": "Po każdym tagu naciśnij Enter lub przecinek. W zleceniu najpierw widać części oznaczone marką lub modelem jednostki pływającej.",
     "removeTag": "Usuń {tag}",
-    "tagTooLong": "Tag może mieć najwyżej {max} znaków. Skróć go przed zapisaniem."
+    "tagTooLong": "Tag może mieć najwyżej {max} znaków. Skróć go przed zapisaniem.",
+    "trackStock": "Śledź stan",
+    "trackStockHint": "Wyłącz dla opłat i materiałów eksploatacyjnych, które doliczasz, ale nigdy nie liczysz.",
+    "trackStockOffNote": "Zapisanie ustawia ilość na zero i odnotowuje to w historii stanu. Zlecenia już jej nie zmieniają."
   },
   "openMenu": "Otwórz menu",
   "history": {
@@ -159,7 +164,8 @@
       "service_record_deleted": "Zlecenie usunięte",
       "quote_conversion": "Wycena przekształcona",
       "manual_adjustment": "Korekta ręczna",
-      "bulk_markup": "Marża zbiorcza"
+      "bulk_markup": "Marża zbiorcza",
+      "stock_tracking_off": "Śledzenie stanu wyłączone"
     },
     "backToInventory": "Magazyn",
     "reason": "Powód",

+ 10 - 4
messages/pt-BR/inventory.json

@@ -14,7 +14,8 @@
     "supplier": "Fornecedor",
     "location": "Localização",
     "low": "Baixo",
-    "barcode": "Código de barras"
+    "barcode": "Código de barras",
+    "notTracked": "Não controlado"
   },
   "empty": {
     "noMatch": "Nenhuma peça corresponde à sua busca.",
@@ -74,7 +75,8 @@
     "currentStock": "Estoque atual: {quantity}",
     "addedStock": "{amount} adicionados ao estoque",
     "customAmount": "Qtd...",
-    "scanParts": "Escanear peças"
+    "scanParts": "Escanear peças",
+    "notTracked": "O estoque desta peça não é controlado"
   },
   "form": {
     "editPart": "Editar peça",
@@ -142,7 +144,10 @@
     "tagsHint": "Pressione Enter ou vírgula após cada tag. Em uma ordem de serviço, as peças com a marca ou o modelo do veículo aparecem primeiro.",
     "tagsHintMarine": "Pressione Enter ou vírgula após cada tag. Em uma ordem de serviço, as peças com a marca ou o modelo da embarcação aparecem primeiro.",
     "removeTag": "Remover {tag}",
-    "tagTooLong": "Uma tag pode ter no máximo {max} caracteres. Encurte-a antes de salvar."
+    "tagTooLong": "Uma tag pode ter no máximo {max} caracteres. Encurte-a antes de salvar.",
+    "trackStock": "Controlar estoque",
+    "trackStockHint": "Desative para taxas e consumíveis que você cobra, mas nunca conta.",
+    "trackStockOffNote": "Ao salvar, a quantidade vai para zero e isso fica anotado no histórico de estoque. Os serviços não a alteram mais."
   },
   "openMenu": "Abrir menu",
   "history": {
@@ -159,7 +164,8 @@
       "service_record_deleted": "Ordem excluída",
       "quote_conversion": "Orçamento convertido",
       "manual_adjustment": "Ajuste manual",
-      "bulk_markup": "Margem em massa"
+      "bulk_markup": "Margem em massa",
+      "stock_tracking_off": "Controle de estoque desativado"
     },
     "backToInventory": "Estoque",
     "reason": "Motivo",

+ 10 - 4
messages/pt-PT/inventory.json

@@ -14,7 +14,8 @@
     "supplier": "Fornecedor",
     "location": "Localização",
     "low": "Baixo",
-    "barcode": "Código de barras"
+    "barcode": "Código de barras",
+    "notTracked": "Não controlado"
   },
   "empty": {
     "noMatch": "Nenhuma peça corresponde à pesquisa.",
@@ -74,7 +75,8 @@
     "currentStock": "Stock atual: {quantity}",
     "addedStock": "{amount} adicionado(s) ao stock",
     "customAmount": "Qtd...",
-    "scanParts": "Ler peças"
+    "scanParts": "Ler peças",
+    "notTracked": "O stock desta peça não é controlado"
   },
   "form": {
     "editPart": "Editar peça",
@@ -142,7 +144,10 @@
     "tagsHint": "Prima Enter ou uma vírgula após cada etiqueta. Numa ordem de reparação, as peças com a marca ou o modelo do veículo aparecem primeiro.",
     "tagsHintMarine": "Prima Enter ou uma vírgula após cada etiqueta. Numa ordem de reparação, as peças com a marca ou o modelo da embarcação aparecem primeiro.",
     "removeTag": "Remover {tag}",
-    "tagTooLong": "Uma etiqueta pode ter no máximo {max} caracteres. Encurte-a antes de guardar."
+    "tagTooLong": "Uma etiqueta pode ter no máximo {max} caracteres. Encurte-a antes de guardar.",
+    "trackStock": "Controlar stock",
+    "trackStockHint": "Desative para taxas e consumíveis que cobra, mas nunca conta.",
+    "trackStockOffNote": "Ao guardar, a quantidade passa a zero e isso fica registado no histórico de stock. Os trabalhos deixam de a alterar."
   },
   "openMenu": "Abrir menu",
   "history": {
@@ -159,7 +164,8 @@
       "service_record_deleted": "Ordem de serviço eliminada",
       "quote_conversion": "Orçamento convertido",
       "manual_adjustment": "Ajuste manual",
-      "bulk_markup": "Margem em massa"
+      "bulk_markup": "Margem em massa",
+      "stock_tracking_off": "Controlo de stock desativado"
     },
     "backToInventory": "Stock",
     "reason": "Motivo",

+ 10 - 4
messages/ru/inventory.json

@@ -14,7 +14,8 @@
     "supplier": "Поставщик",
     "location": "Расположение",
     "low": "Мало",
-    "barcode": "Штрихкод"
+    "barcode": "Штрихкод",
+    "notTracked": "Не учитывается"
   },
   "empty": {
     "noMatch": "Нет запчастей, соответствующих поиску.",
@@ -74,7 +75,8 @@
     "currentStock": "Текущий запас: {quantity}",
     "addedStock": "{amount} добавлено на склад",
     "customAmount": "Кол-во...",
-    "scanParts": "Сканировать детали"
+    "scanParts": "Сканировать детали",
+    "notTracked": "Остаток этой запчасти не учитывается"
   },
   "form": {
     "editPart": "Редактировать запчасть",
@@ -142,7 +144,10 @@
     "tagsHint": "Нажимайте Enter или запятую после каждого тега. В заказ-наряде запчасти с маркой или моделью автомобиля показываются первыми.",
     "tagsHintMarine": "Нажимайте Enter или запятую после каждого тега. В заказ-наряде запчасти с маркой или моделью судна показываются первыми.",
     "removeTag": "Удалить {tag}",
-    "tagTooLong": "Тег может содержать не более {max} символов. Сократите его перед сохранением."
+    "tagTooLong": "Тег может содержать не более {max} символов. Сократите его перед сохранением.",
+    "trackStock": "Вести учёт остатка",
+    "trackStockHint": "Отключите для сборов и расходных материалов, которые вы включаете в счёт, но никогда не считаете.",
+    "trackStockOffNote": "При сохранении количество станет нулевым, и это будет отмечено в истории остатков. Заказы больше его не меняют."
   },
   "openMenu": "Открыть меню",
   "history": {
@@ -159,7 +164,8 @@
       "service_record_deleted": "Заказ-наряд удалён",
       "quote_conversion": "Предложение конвертировано",
       "manual_adjustment": "Ручная корректировка",
-      "bulk_markup": "Массовая наценка"
+      "bulk_markup": "Массовая наценка",
+      "stock_tracking_off": "Учёт остатка отключён"
     },
     "backToInventory": "Склад",
     "reason": "Причина",

+ 10 - 4
messages/tr/inventory.json

@@ -14,7 +14,8 @@
     "supplier": "Tedarikçi",
     "location": "Konum",
     "low": "Düşük",
-    "barcode": "Barkod"
+    "barcode": "Barkod",
+    "notTracked": "Takip edilmiyor"
   },
   "empty": {
     "noMatch": "Aramanızla eşleşen parça bulunamadı.",
@@ -74,7 +75,8 @@
     "currentStock": "Mevcut stok: {quantity}",
     "addedStock": "Stoka {amount} eklendi",
     "customAmount": "Adet...",
-    "scanParts": "Parça tara"
+    "scanParts": "Parça tara",
+    "notTracked": "Bu parçanın stoğu takip edilmiyor"
   },
   "form": {
     "editPart": "Parçayı düzenle",
@@ -142,7 +144,10 @@
     "tagsHint": "Her etiketten sonra Enter'a veya virgüle basın. Bir işte, aracın markası veya modeliyle etiketlenmiş parçalar önce listelenir.",
     "tagsHintMarine": "Her etiketten sonra Enter'a veya virgüle basın. Bir işte, teknenin markası veya modeliyle etiketlenmiş parçalar önce listelenir.",
     "removeTag": "{tag} kaldır",
-    "tagTooLong": "Bir etiket en fazla {max} karakter olabilir. Kaydetmeden önce kısaltın."
+    "tagTooLong": "Bir etiket en fazla {max} karakter olabilir. Kaydetmeden önce kısaltın.",
+    "trackStock": "Stok takibi",
+    "trackStockHint": "Ücretlendirdiğiniz ama hiç saymadığınız ücretler ve sarf malzemeleri için kapatın.",
+    "trackStockOffNote": "Kaydedince miktar sıfırlanır ve stok geçmişine not düşülür. İşler artık miktarı değiştirmez."
   },
   "openMenu": "Menüyü aç",
   "history": {
@@ -159,7 +164,8 @@
       "service_record_deleted": "İş emri silindi",
       "quote_conversion": "Teklif dönüştürüldü",
       "manual_adjustment": "Manuel düzeltme",
-      "bulk_markup": "Toplu kâr marjı"
+      "bulk_markup": "Toplu kâr marjı",
+      "stock_tracking_off": "Stok takibi kapatıldı"
     },
     "backToInventory": "Stok",
     "reason": "Neden",

+ 2 - 0
prisma/migrations/20261117150353_inventory_part_track_stock/migration.sql

@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "inventory_parts" ADD COLUMN     "trackStock" BOOLEAN NOT NULL DEFAULT true;

+ 5 - 0
prisma/schema/inventory.prisma

@@ -59,6 +59,11 @@ model InventoryPart {
   category      String?
   quantity      Float    @default(0)
   minQuantity   Float    @default(0)
+  /// False for a charge kept as a part but never counted, such as a
+  /// consumables or environmental fee. Using one on a job moves no stock and
+  /// writes no ledger row, its `quantity` stays 0, and it is left out of
+  /// low-stock alerts and stock value.
+  trackStock    Boolean  @default(true)
   /// Unit of measure for `quantity` (e.g. "pcs", "l", "kg"). Free text,
   /// snapshotted onto part lines at pick time so invoices keep the unit the
   /// part had when it was billed.

+ 182 - 0
src/__tests__/db/untracked-stock.db.test.ts

@@ -0,0 +1,182 @@
+/**
+ * Parts that do not track stock, on a real PostgreSQL (`npm run test:db`
+ * with E2E_DATABASE_URL set).
+ *
+ * A workshop keeps a consumables fee as a part so it can go on every job.
+ * Counted like a filter, it sinks further below zero with each one. The rule
+ * that stops that lives in the SQL of the stock helper, which the unit tests
+ * mock, so this runs it: what the part's quantity and its ledger look like
+ * after a job uses it, hands it back, and after tracking is switched off.
+ *
+ * It makes one person and one workshop of its own and removes them again; it
+ * empties nothing.
+ */
+import { randomUUID } from 'node:crypto'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+
+const url = process.env.E2E_DATABASE_URL ?? ''
+const databaseName = url.split('/').pop()?.split('?')[0]?.toLowerCase() ?? ''
+if (url && !/test|e2e/.test(databaseName)) {
+  throw new Error(
+    `Refusing to use database "${databaseName}": its name must say test or e2e, like the rest of this suite.`
+  )
+}
+
+// Set before the app's modules load, so the client connects to the test database.
+process.env.DATABASE_URL = url
+
+const stamp = randomUUID().slice(0, 8)
+
+let db: typeof import('@/lib/db')['db']
+let stock: typeof import('@/features/inventory/Lib/reconcileStock')
+let organizationId = ''
+let userId = ''
+
+const JOB = { reason: 'service_record' as const, serviceRecordLabel: 'WO-1' }
+
+async function makePart(name: string, data: { quantity?: number; trackStock?: boolean }) {
+  const part = await db.inventoryPart.create({
+    data: { name: `${name} ${stamp}`, userId, organizationId, ...data },
+  })
+  return part.id
+}
+
+async function quantityOf(id: string) {
+  const part = await db.inventoryPart.findUniqueOrThrow({ where: { id } })
+  return part.quantity
+}
+
+function ledgerOf(id: string) {
+  return db.stockMovement.findMany({
+    where: { inventoryPartId: id },
+    orderBy: { createdAt: 'asc' },
+  })
+}
+
+beforeAll(async () => {
+  ;({ db } = await import('@/lib/db'))
+  stock = await import('@/features/inventory/Lib/reconcileStock')
+  const user = await db.user.create({
+    data: { name: `Stock ${stamp}`, email: `stock-${stamp}@example.com` },
+  })
+  userId = user.id
+  const organization = await db.organization.create({ data: { name: `Stock ${stamp}` } })
+  organizationId = organization.id
+})
+
+afterAll(async () => {
+  // The parts and their ledger go with the workshop.
+  if (organizationId) await db.organization.delete({ where: { id: organizationId } })
+  if (userId) await db.user.delete({ where: { id: userId } })
+  await db.$disconnect()
+})
+
+describe('a part that does not track stock', () => {
+  it('keeps its quantity and gets no ledger row when a job uses it', async () => {
+    const fee = await makePart('Consumables', { trackStock: false })
+    const filter = await makePart('Oil filter', { quantity: 10 })
+
+    await db.$transaction((tx) =>
+      stock.reconcileInventoryForParts(
+        tx,
+        organizationId,
+        [],
+        [
+          { inventoryPartId: fee, quantity: 1 },
+          { inventoryPartId: filter, quantity: 2 },
+        ],
+        JOB
+      )
+    )
+
+    expect(await quantityOf(fee)).toBe(0)
+    expect(await ledgerOf(fee)).toEqual([])
+    // The counted part on the same job still moves.
+    expect(await quantityOf(filter)).toBe(8)
+    expect(await ledgerOf(filter)).toHaveLength(1)
+  })
+
+  it('gains nothing when the line is taken off the job again', async () => {
+    const fee = await makePart('Environmental fee', { trackStock: false })
+
+    await db.$transaction((tx) =>
+      stock.reconcileInventoryForParts(
+        tx,
+        organizationId,
+        [{ inventoryPartId: fee, quantity: 3 }],
+        [],
+        { reason: 'service_record_deleted' }
+      )
+    )
+
+    expect(await quantityOf(fee)).toBe(0)
+    expect(await ledgerOf(fee)).toEqual([])
+  })
+})
+
+describe('turning stock tracking off', () => {
+  it('takes a negative quantity to zero with one ledger entry saying why', async () => {
+    const fee = await makePart('Shop supplies', { quantity: 0 })
+    // Forty jobs' worth, back when it was counted.
+    await db.$transaction((tx) =>
+      stock.reconcileInventoryForParts(
+        tx,
+        organizationId,
+        [],
+        [{ inventoryPartId: fee, quantity: 40 }],
+        JOB
+      )
+    )
+    expect(await quantityOf(fee)).toBe(-40)
+
+    await db.$transaction(async (tx) => {
+      await stock.recordAbsoluteStockChange(tx, organizationId, fee, 0, {
+        reason: 'stock_tracking_off',
+        userId,
+      })
+      await tx.inventoryPart.update({ where: { id: fee }, data: { trackStock: false } })
+    })
+
+    expect(await quantityOf(fee)).toBe(0)
+    const ledger = await ledgerOf(fee)
+    expect(ledger).toHaveLength(2)
+    expect(ledger[1]).toMatchObject({
+      reason: 'stock_tracking_off',
+      delta: 40,
+      quantityAfter: 0,
+      userId,
+    })
+
+    // From here on a job leaves it alone.
+    await db.$transaction((tx) =>
+      stock.reconcileInventoryForParts(
+        tx,
+        organizationId,
+        [],
+        [{ inventoryPartId: fee, quantity: 1 }],
+        JOB
+      )
+    )
+    expect(await quantityOf(fee)).toBe(0)
+    expect(await ledgerOf(fee)).toHaveLength(2)
+  })
+
+  it('leaves an entry in the history for a part that already stood at zero', async () => {
+    const fee = await makePart('Disposal fee', { quantity: 0 })
+
+    await db.$transaction((tx) =>
+      stock.recordAbsoluteStockChange(
+        tx,
+        organizationId,
+        fee,
+        0,
+        { reason: 'stock_tracking_off', userId },
+        { recordUnchanged: true }
+      )
+    )
+
+    expect(await ledgerOf(fee)).toMatchObject([
+      { reason: 'stock_tracking_off', delta: 0, quantityAfter: 0 },
+    ])
+  })
+})

+ 9 - 0
src/__tests__/features/inventory/inventory-list-markup.test.tsx

@@ -16,6 +16,15 @@ const applyMarkupToAll = vi.fn()
 const setSetting = vi.fn()
 const refresh = vi.fn()
 
+// The Track stock switch sits in the form, and Radix measures a switch in a
+// form; jsdom has no ResizeObserver.
+class NoResize {
+  observe = vi.fn()
+  unobserve = vi.fn()
+  disconnect = vi.fn()
+}
+vi.stubGlobal('ResizeObserver', NoResize)
+
 vi.mock('next/navigation', () => ({
   useRouter: () => ({ refresh, push: vi.fn(), replace: vi.fn() }),
   usePathname: () => '/inventory',

+ 9 - 0
src/__tests__/features/inventory/part-form-sell-price-markup.test.tsx

@@ -11,6 +11,15 @@
 import { describe, expect, it, vi } from 'vitest'
 import { fireEvent, render, screen } from '@testing-library/react'
 
+// The Track stock switch sits in the form, and Radix measures a switch in a
+// form; jsdom has no ResizeObserver.
+class NoResize {
+  observe = vi.fn()
+  unobserve = vi.fn()
+  disconnect = vi.fn()
+}
+vi.stubGlobal('ResizeObserver', NoResize)
+
 vi.mock('next/navigation', () => ({
   useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }),
 }))

+ 9 - 0
src/__tests__/features/inventory/part-form-supplier-fetch.test.tsx

@@ -22,6 +22,15 @@ vi.stubGlobal('matchMedia', (query: string) => ({
   removeEventListener: noop,
 }))
 
+// The Track stock switch sits in the form, and Radix measures a switch in a
+// form; jsdom has no ResizeObserver.
+class NoResize {
+  observe = vi.fn()
+  unobserve = vi.fn()
+  disconnect = vi.fn()
+}
+vi.stubGlobal('ResizeObserver', NoResize)
+
 vi.mock('next/navigation', () => ({ useRouter: () => ({ refresh: vi.fn(), push: vi.fn() }) }))
 vi.mock('sonner', () => ({
   toast: { success: vi.fn(), error: vi.fn(), loading: vi.fn() },

+ 195 - 0
src/__tests__/features/inventory/untracked-parts-list.test.tsx

@@ -0,0 +1,195 @@
+/**
+ * A part that does not track stock, as the inventory list and the part form
+ * show it.
+ *
+ * A consumables fee kept as a part has no shelf count, so the list says so in
+ * place of a number, never calls it low, and the form puts the stock fields
+ * away once the switch is off.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { render, screen, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+
+const createInventoryPart = vi.fn()
+const updateInventoryPart = vi.fn()
+
+// The Track stock switch sits in the form, and Radix measures a switch in a
+// form; jsdom has no ResizeObserver.
+class NoResize {
+  observe = vi.fn()
+  unobserve = vi.fn()
+  disconnect = vi.fn()
+}
+vi.stubGlobal('ResizeObserver', NoResize)
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ refresh: vi.fn(), push: vi.fn(), replace: vi.fn() }),
+  usePathname: () => '/inventory',
+  useSearchParams: () => new URLSearchParams(),
+}))
+vi.mock('@/components/glass-modal', () => ({
+  useGlassModal: () => ({ open: vi.fn() }),
+}))
+vi.mock('@/components/confirm-dialog', () => ({
+  useConfirm: () => vi.fn(),
+}))
+vi.mock('@/hooks/use-native-camera', () => ({
+  useNativeCamera: () => false,
+}))
+vi.mock('@/hooks/use-hardware-scanner', () => ({
+  useHardwareScanner: vi.fn(),
+}))
+vi.mock('@/hooks/use-remembered-sort', () => ({
+  useRememberedSort: vi.fn(),
+}))
+vi.mock('@/components/barcode-scanner-dialog', () => ({
+  BarcodeScannerDialog: () => null,
+}))
+vi.mock('@/features/inventory/Components/BarcodeScanActionDialog', () => ({
+  BarcodeScanActionDialog: () => null,
+}))
+vi.mock('@/features/inventory/Actions/lookupPartByBarcode', () => ({
+  lookupPartByBarcode: vi.fn(),
+}))
+vi.mock('@/features/inventory/Actions/aiAnalyzePartImage', () => ({
+  aiAnalyzePartImage: vi.fn(),
+}))
+vi.mock('@/features/inventory/Actions/inventoryActions', () => ({
+  applyMarkupToAll: vi.fn(),
+  createInventoryPart: (...args: unknown[]) => createInventoryPart(...args),
+  updateInventoryPart: (...args: unknown[]) => updateInventoryPart(...args),
+  deleteInventoryPart: vi.fn(),
+  deleteInventoryParts: vi.fn(),
+  deleteOrphanedUploads: vi.fn(),
+}))
+vi.mock('@/features/settings/Actions/settingsActions', () => ({
+  setSetting: vi.fn(),
+}))
+
+import { InventoryClient } from '@/app/(authenticated)/inventory/inventory-client'
+
+type Part = React.ComponentProps<typeof InventoryClient>['data']['parts'][number]
+
+function part(overrides: Partial<Part>): Part {
+  return {
+    id: 'p1',
+    partNumber: null,
+    barcode: null,
+    name: 'Part',
+    description: null,
+    category: null,
+    quantity: 0,
+    minQuantity: 0,
+    trackStock: true,
+    unit: null,
+    unitCost: 0,
+    sellPrice: 0,
+    supplier: null,
+    supplierPhone: null,
+    supplierEmail: null,
+    supplierUrl: null,
+    imageUrl: null,
+    gallery: [],
+    location: null,
+    tags: [],
+    ...overrides,
+  }
+}
+
+function renderList(parts: Part[]) {
+  render(
+    <InventoryClient
+      data={{ parts, total: parts.length, page: 1, pageSize: 25, totalPages: 1 }}
+      search=""
+      category=""
+      categories={[]}
+      lowStockDefault={5}
+    />
+  )
+}
+
+/** The table row for a part (the phone cards render beside it in jsdom). */
+function rowOf(name: string) {
+  const row = screen
+    .getAllByRole('row')
+    .find((candidate) => within(candidate).queryByText(name) !== null)
+  if (!row) throw new Error(`No row for ${name}`)
+  return row
+}
+
+beforeEach(() => {
+  createInventoryPart.mockReset().mockResolvedValue({ success: true, data: { id: 'new' } })
+  updateInventoryPart.mockReset().mockResolvedValue({ success: true })
+})
+
+describe('the inventory list', () => {
+  it('says Not tracked in place of a quantity, and never calls the part low', () => {
+    renderList([
+      part({ id: 'fee', name: 'Consumables fee', trackStock: false }),
+      // Counted, and under the workshop's reorder point of 5.
+      part({ id: 'filter', name: 'Oil filter', quantity: 2, unit: 'pcs' }),
+    ])
+
+    const fee = rowOf('Consumables fee')
+    expect(within(fee).getByText('Not tracked')).toBeInTheDocument()
+    expect(within(fee).queryByText('Low')).not.toBeInTheDocument()
+
+    const filter = rowOf('Oil filter')
+    expect(within(filter).getByText('2 pcs')).toBeInTheDocument()
+    expect(within(filter).getByText('Low')).toBeInTheDocument()
+    expect(within(filter).queryByText('Not tracked')).not.toBeInTheDocument()
+  })
+})
+
+describe('the part form', () => {
+  it('hides the stock fields once Track stock is off and saves the part uncounted', async () => {
+    const user = userEvent.setup()
+    renderList([])
+
+    await user.click(screen.getAllByRole('button', { name: /add part/i })[0])
+    const dialog = screen.getByRole('dialog')
+    const tracking = within(dialog).getByRole('switch', { name: 'Track stock' })
+    expect(tracking).toBeChecked()
+    expect(within(dialog).getByLabelText('Quantity')).toBeInTheDocument()
+    expect(within(dialog).getByLabelText('Min Qty')).toBeInTheDocument()
+
+    await user.click(tracking)
+    expect(within(dialog).queryByLabelText('Quantity')).not.toBeInTheDocument()
+    expect(within(dialog).queryByLabelText('Min Qty')).not.toBeInTheDocument()
+    // What it costs the customer is still set here.
+    expect(within(dialog).getByLabelText('Sell Price')).toBeInTheDocument()
+
+    await user.type(within(dialog).getByLabelText('Name *'), 'Consumables fee')
+    await user.click(within(dialog).getByRole('button', { name: 'Add Part' }))
+
+    expect(createInventoryPart).toHaveBeenCalledTimes(1)
+    expect(createInventoryPart.mock.calls[0][0]).toMatchObject({
+      name: 'Consumables fee',
+      trackStock: false,
+      quantity: 0,
+    })
+  })
+
+  it('opens an uncounted part with the switch off and says what turning it off does', async () => {
+    const user = userEvent.setup()
+    renderList([part({ id: 'supplies', name: 'Shop supplies', quantity: -40, minQuantity: 6 })])
+
+    await user.click(rowOf('Shop supplies'))
+    const dialog = screen.getByRole('dialog')
+    const tracking = within(dialog).getByRole('switch', { name: 'Track stock' })
+    expect(tracking).toBeChecked()
+
+    await user.click(tracking)
+    expect(within(dialog).getByText(/sets the quantity to zero/i)).toBeInTheDocument()
+
+    await user.click(within(dialog).getByRole('button', { name: 'Save Changes' }))
+    expect(updateInventoryPart.mock.calls[0][0]).toMatchObject({
+      id: 'supplies',
+      trackStock: false,
+      quantity: 0,
+      // Kept for the day tracking is switched back on.
+      minQuantity: 6,
+    })
+  })
+})

+ 206 - 0
src/__tests__/features/inventory/untracked-parts.test.ts

@@ -0,0 +1,206 @@
+/**
+ * The rules for a part that does not track stock (a fee or consumable that is
+ * charged but never counted): it is never low, it is left out of stock value,
+ * and switching tracking off empties what was counted so far.
+ *
+ * That a job leaves its quantity alone is proved against PostgreSQL in
+ * src/__tests__/db/untracked-stock.db.test.ts, since the rule is in the SQL.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}))
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
+vi.mock('@/lib/files/collect', () => ({
+  inventoryPartFileUrls: vi.fn(async () => []),
+}))
+vi.mock('@/lib/files/manager', () => ({
+  releaseFiles: vi.fn(async () => ({ removed: [], kept: [], skipped: [] })),
+  parseStoredFileUrl: vi.fn(() => null),
+}))
+vi.mock('@/features/inventory/Lib/onInventoryChanged', () => ({
+  onInventoryChanged: vi.fn(async () => undefined),
+}))
+
+vi.mock('@/lib/db', () => {
+  const db = {
+    // The stock helper's one statement: the part goes to the quantity asked
+    // for and reports how far it moved.
+    $queryRaw: vi.fn(),
+    $transaction: vi.fn(async (run: unknown) =>
+      typeof run === 'function' ? run(db) : Promise.all(run as Promise<unknown>[])
+    ),
+    user: { findUnique: vi.fn() },
+    inventoryPart: {
+      findFirst: vi.fn(),
+      findMany: vi.fn(),
+      create: vi.fn(),
+      updateMany: vi.fn(),
+    },
+    stockMovement: { create: vi.fn() },
+    storedImage: { deleteMany: vi.fn(), createMany: vi.fn() },
+    auditLog: { create: vi.fn() },
+  }
+  return { db }
+})
+
+import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
+import { db } from '@/lib/db'
+import {
+  adjustInventoryStock,
+  createInventoryPart,
+  updateInventoryPart,
+} from '@/features/inventory/Actions/inventoryActions'
+import { decideLowStockAlerts, isLow } from '@/features/inventory/Lib/lowStockAlerts'
+import { getInventoryReport } from '@/features/reports/Actions/reportActions'
+
+const ORG = 'org-1'
+
+const m = db as any
+
+beforeEach(() => {
+  vi.clearAllMocks()
+  vi.mocked(getCachedSession).mockResolvedValue({
+    user: { id: 'user-1', email: 'owner@example.com' },
+  } as any)
+  vi.mocked(getCachedMembership).mockResolvedValue({
+    organizationId: ORG,
+    role: 'owner',
+    roleId: null,
+    customRole: null,
+  } as any)
+  m.user.findUnique.mockResolvedValue({ isSuperAdmin: false })
+  m.inventoryPart.updateMany.mockResolvedValue({ count: 1 })
+})
+
+describe('low stock', () => {
+  const fee = {
+    id: 'fee',
+    name: 'Consumables fee',
+    partNumber: null,
+    quantity: 0,
+    minQuantity: 5,
+    unit: null,
+    lowStockAlertedAt: null,
+  }
+
+  it('never counts an untracked part as low, though a counted one at zero is', () => {
+    expect(isLow({ ...fee, trackStock: false })).toBe(false)
+    expect(isLow({ ...fee, trackStock: false }, 10)).toBe(false)
+    expect(isLow({ ...fee, trackStock: true })).toBe(true)
+  })
+
+  it('sends no alert for it', () => {
+    const { newlyLow } = decideLowStockAlerts([{ ...fee, trackStock: false }], 10)
+    expect(newlyLow).toEqual([])
+  })
+})
+
+describe('stock value', () => {
+  it('reads only the parts that are counted', async () => {
+    m.inventoryPart.findMany.mockResolvedValue([])
+    await getInventoryReport()
+    expect(m.inventoryPart.findMany.mock.calls[0][0].where).toMatchObject({
+      organizationId: ORG,
+      trackStock: true,
+    })
+  })
+})
+
+describe('turning stock tracking off', () => {
+  it('takes a negative quantity to zero, notes why in the ledger, and clears the low-stock flag', async () => {
+    m.inventoryPart.findFirst.mockResolvedValue({ id: 'supplies', trackStock: true })
+    // The part stood at -40.
+    m.$queryRaw.mockResolvedValue([{ quantity: 0, delta: 40 }])
+
+    const result = await updateInventoryPart({ id: 'supplies', trackStock: false, quantity: 12 })
+
+    expect(result.success).toBe(true)
+    expect(m.stockMovement.create).toHaveBeenCalledTimes(1)
+    expect(m.stockMovement.create.mock.calls[0][0].data).toMatchObject({
+      inventoryPartId: 'supplies',
+      organizationId: ORG,
+      reason: 'stock_tracking_off',
+      delta: 40,
+      quantityAfter: 0,
+      userId: 'user-1',
+    })
+    expect(m.inventoryPart.updateMany.mock.lastCall[0].data).toMatchObject({
+      trackStock: false,
+      quantity: 0,
+      lowStockAlertedAt: null,
+    })
+  })
+
+  it('notes it in the ledger even when the part already stood at zero', async () => {
+    m.inventoryPart.findFirst.mockResolvedValue({ id: 'fee', trackStock: true })
+    m.$queryRaw.mockResolvedValue([{ quantity: 0, delta: 0 }])
+
+    await updateInventoryPart({ id: 'fee', trackStock: false })
+
+    expect(m.stockMovement.create).toHaveBeenCalledTimes(1)
+    expect(m.stockMovement.create.mock.calls[0][0].data).toMatchObject({
+      reason: 'stock_tracking_off',
+      delta: 0,
+      quantityAfter: 0,
+    })
+  })
+
+  it('writes no ledger entry for a part that was already uncounted, and keeps it at zero', async () => {
+    m.inventoryPart.findFirst.mockResolvedValue({ id: 'fee', trackStock: false })
+
+    // A tab opened before the switch existed still sends a quantity.
+    await updateInventoryPart({ id: 'fee', name: 'Consumables', quantity: 7 })
+
+    expect(m.$queryRaw).not.toHaveBeenCalled()
+    expect(m.stockMovement.create).not.toHaveBeenCalled()
+    expect(m.inventoryPart.updateMany.mock.lastCall[0].data).toMatchObject({ quantity: 0 })
+  })
+
+  it('leaves a counted part alone when the switch is not sent', async () => {
+    m.inventoryPart.findFirst.mockResolvedValue({ id: 'filter', trackStock: true })
+
+    await updateInventoryPart({ id: 'filter', quantity: 7 })
+
+    expect(m.stockMovement.create).not.toHaveBeenCalled()
+    const data = m.inventoryPart.updateMany.mock.lastCall[0].data
+    expect(data.quantity).toBe(7)
+    expect(data).not.toHaveProperty('lowStockAlertedAt')
+  })
+})
+
+describe('an untracked part', () => {
+  it('is created with no stock, whatever quantity came with it', async () => {
+    m.inventoryPart.create.mockResolvedValue({ id: 'fee', name: 'Consumables fee' })
+
+    await createInventoryPart({ name: 'Consumables fee', trackStock: false, quantity: 3 })
+
+    expect(m.inventoryPart.create.mock.calls[0][0].data).toMatchObject({
+      trackStock: false,
+      quantity: 0,
+    })
+  })
+
+  it('refuses stock added from a barcode scan', async () => {
+    m.inventoryPart.findFirst.mockResolvedValue({ id: 'fee', trackStock: false, quantity: 0 })
+
+    const result = await adjustInventoryStock({ id: 'fee', adjustment: 5 })
+
+    expect(result.success).toBe(false)
+    expect(m.inventoryPart.updateMany).not.toHaveBeenCalled()
+  })
+
+  it('refuses the scan when tracking was switched off while it was being added', async () => {
+    // Counted when the scan read it, uncounted by the time it wrote.
+    m.inventoryPart.findFirst.mockResolvedValue({ id: 'fee', trackStock: true, quantity: 0 })
+    m.inventoryPart.updateMany.mockResolvedValue({ count: 0 })
+
+    const result = await adjustInventoryStock({ id: 'fee', adjustment: 5 })
+
+    expect(result.success).toBe(false)
+    expect(m.inventoryPart.updateMany.mock.lastCall[0].where).toMatchObject({ trackStock: true })
+  })
+})

+ 8 - 2
src/app/(authenticated)/inventory/[id]/part-detail-client.tsx

@@ -117,6 +117,8 @@ export function PartDetailClient({
         return t('history.reasons.manual_adjustment')
       case 'bulk_markup':
         return t('history.reasons.bulk_markup')
+      case 'stock_tracking_off':
+        return t('history.reasons.stock_tracking_off')
       default:
         // A row written by a newer build may carry a reason this one has no
         // translation for; show the raw value rather than an empty cell.
@@ -161,7 +163,9 @@ export function PartDetailClient({
         <div className="rounded-lg border bg-card px-3 py-2">
           <p className="text-[11px] text-muted-foreground">{t('table.inStock')}</p>
           <p className={`text-lg font-bold ${isLow ? 'text-destructive' : ''}`}>
-            {formatQuantity(part.quantity, part.unit)}
+            {part.trackStock === false
+              ? t('table.notTracked')
+              : formatQuantity(part.quantity, part.unit)}
             {isLow && (
               <Badge variant="destructive" className="ml-2 px-1.5 py-0 text-[10px]">
                 {t('table.low')}
@@ -171,7 +175,9 @@ export function PartDetailClient({
         </div>
         <div className="rounded-lg border bg-card px-3 py-2">
           <p className="text-[11px] text-muted-foreground">{t('form.minQty')}</p>
-          <p className="text-lg font-bold">{formatQuantity(part.minQuantity, part.unit)}</p>
+          <p className="text-lg font-bold">
+            {part.trackStock === false ? '-' : formatQuantity(part.minQuantity, part.unit)}
+          </p>
         </div>
         <div className="rounded-lg border bg-card px-3 py-2">
           <p className="text-[11px] text-muted-foreground">{t('table.unitCost')}</p>

+ 9 - 2
src/app/(authenticated)/inventory/inventory-client.tsx

@@ -89,6 +89,7 @@ interface InventoryPart {
   category: string | null
   quantity: number
   minQuantity: number
+  trackStock: boolean
   unit: string | null
   unitCost: number
   sellPrice: number
@@ -574,7 +575,9 @@ export function InventoryClient({
                       <span className="inline-flex items-center gap-1.5">
                         {t('table.inStock')}:{' '}
                         <span className="font-medium text-foreground">
-                          {formatQuantity(part.quantity, part.unit)}
+                          {part.trackStock
+                            ? formatQuantity(part.quantity, part.unit)
+                            : t('table.notTracked')}
                         </span>
                         {isLow && (
                           <Badge variant="destructive" className="px-1.5 py-0 text-[10px]">
@@ -828,7 +831,11 @@ export function InventoryClient({
                         </TableCell>
                         <TableCell>
                           <div className="flex items-center gap-2">
-                            <span>{formatQuantity(part.quantity, part.unit)}</span>
+                            {part.trackStock ? (
+                              <span>{formatQuantity(part.quantity, part.unit)}</span>
+                            ) : (
+                              <span className="text-muted-foreground">{t('table.notTracked')}</span>
+                            )}
                             {isLow && (
                               <Badge variant="destructive" className="text-[10px] px-1.5 py-0">
                                 {t('table.low')}

+ 3 - 0
src/app/api/v1/tech/parts/lookup/route.ts

@@ -39,6 +39,9 @@ export async function GET(request: Request) {
           unitCost: true,
           sellPrice: true,
           quantity: true,
+          // False for a fee or consumable that is charged but never counted:
+          // the app shows no stock figure for it.
+          trackStock: true,
           category: true,
         },
       })

+ 13 - 3
src/components/mobile-bottom-nav.tsx

@@ -117,6 +117,7 @@ export function MobileBottomNav({
     partNumber: string | null
     barcode: string | null
     quantity: number
+    trackStock?: boolean
     category: string | null
   } | null>(null)
   const [scannedBarcode, setScannedBarcode] = useState('')
@@ -353,11 +354,19 @@ export function MobileBottomNav({
                   </div>
                 </div>
                 <div className="text-right text-sm text-muted-foreground shrink-0">
-                  {tScan('currentStock', { quantity: scannedPart.quantity })}
+                  {scannedPart.trackStock === false
+                    ? tScan('notTracked')
+                    : tScan('currentStock', { quantity: scannedPart.quantity })}
                 </div>
               </div>
 
-              <div className="flex items-center justify-center gap-4 py-6">
+              <div
+                className={
+                  scannedPart.trackStock === false
+                    ? 'hidden'
+                    : 'flex items-center justify-center gap-4 py-6'
+                }
+              >
                 <Button
                   variant="outline"
                   size="icon"
@@ -396,7 +405,7 @@ export function MobileBottomNav({
               <div className="flex gap-2">
                 <Button
                   size="lg"
-                  className="flex-1"
+                  className={scannedPart.trackStock === false ? 'hidden' : 'flex-1'}
                   onClick={async () => {
                     setAddingStock(true)
                     const result = await adjustInventoryStock({
@@ -422,6 +431,7 @@ export function MobileBottomNav({
                 <Button
                   size="lg"
                   variant="outline"
+                  className={scannedPart.trackStock === false ? 'flex-1' : undefined}
                   onClick={async () => {
                     const result = await getInventoryPart(scannedPart.id)
                     if (result.success && result.data) {

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

@@ -302,6 +302,7 @@ export const TABLE_COLUMNS: Readonly<Record<string, readonly string[]>> = {
     'category',
     'quantity',
     'minQuantity',
+    'trackStock',
     'unit',
     'unitCost',
     'sellPrice',

+ 1 - 1
src/features/ai/tools/workshop-tools.ts

@@ -690,7 +690,7 @@ quote_parts (id, "partNumber", name, quantity, unit, category, "unitPrice", tota
 
 quote_labor (id, description, hours, rate, total, excluded, "quoteId")
 
-inventory_parts (id, "partNumber", name, description, category, quantity, "minQuantity", unit, "unitCost", "sellPrice", supplier, "supplierPhone", "supplierEmail", "supplierUrl", location, "isArchived", tags, "createdAt", "updatedAt") -- tags is text[]: the makes and models a part fits, or any label; match with array_to_string(tags, ',') ILIKE '%hilux%'
+inventory_parts (id, "partNumber", name, description, category, quantity, "minQuantity", "trackStock", unit, "unitCost", "sellPrice", supplier, "supplierPhone", "supplierEmail", "supplierUrl", location, "isArchived", tags, "createdAt", "updatedAt") -- "trackStock" false is a fee or consumable that is charged but never counted: leave it out of stock levels, low stock and stock value; tags is text[]: the makes and models a part fits, or any label; match with array_to_string(tags, ',') ILIKE '%hilux%'
 
 notes (id, title, content, "isPinned", "createdAt", "updatedAt", "vehicleId")
 

+ 2 - 0
src/features/integrations/Lib/fluid-stock.ts

@@ -30,6 +30,8 @@ export interface StockPart {
   sellPrice: number
   /** In stock, in `unit`. */
   quantity: number
+  /** False for a part that is charged but never counted. */
+  trackStock?: boolean
 }
 
 /** A part line the page adds as it would a pick from stock. */

+ 1 - 0
src/features/inventory/Actions/getStockMovements.ts

@@ -132,6 +132,7 @@ export async function getInventoryPart(id: string) {
           category: true,
           quantity: true,
           minQuantity: true,
+          trackStock: true,
           // The edit form saves back every field it is given, so a field left
           // out here would be cleared when the part is saved from this page.
           unit: true,

+ 61 - 27
src/features/inventory/Actions/inventoryActions.ts

@@ -1,6 +1,6 @@
 'use server'
 
-import { db } from '@/lib/db'
+import { db, type TxClient } from '@/lib/db'
 import { assertOwnUploads } from '@/lib/upload-url'
 import { withAuth } from '@/lib/with-auth'
 import {
@@ -9,6 +9,7 @@ import {
   adjustStockSchema,
 } from '../Schema/inventorySchema'
 import { onInventoryChanged } from '../Lib/onInventoryChanged'
+import { recordAbsoluteStockChange } from '../Lib/reconcileStock'
 import { Prisma } from '@/generated/prisma/client'
 import { z } from 'zod'
 import { releaseFiles, parseStoredFileUrl } from '@/lib/files/manager'
@@ -95,6 +96,7 @@ export async function getInventoryPartsPaginated(params: {
         FROM "public"."inventory_parts"
         WHERE "organizationId" = ${organizationId}
           AND "isArchived" = false
+          AND "trackStock" = true
           AND COALESCE(NULLIF("minQuantity", 0), ${lowStockDefault}) > 0
           AND "quantity" <= COALESCE(NULLIF("minQuantity", 0), ${lowStockDefault})
       `
@@ -174,6 +176,8 @@ export async function createInventoryPart(input: unknown) {
         db.inventoryPart.create({
           data: {
             ...rest,
+            // A part that does not track stock has none to start with.
+            quantity: rest.trackStock === false ? 0 : rest.quantity,
             partNumber: rest.partNumber || undefined,
             unit: rest.unit?.trim() || undefined,
             barcode: barcode ?? undefined,
@@ -233,10 +237,15 @@ export async function updateInventoryPart(input: unknown) {
       // gallery rows are keyed by the part alone.
       const owned = await db.inventoryPart.findFirst({
         where: { id, organizationId },
-        select: { id: true },
+        select: { id: true, trackStock: true },
       })
       if (!owned) throw new Error('Part not found')
 
+      // Left out (a page opened before the switch existed), the part keeps
+      // what it has.
+      const tracksStock = updateData.trackStock ?? owned.trackStock
+      const turningTrackingOff = owned.trackStock && !tracksStock
+
       // The images the part had before a change to them, let go at the end
       // once nothing uses them (the new gallery keeps the ones it still has).
       const replacedImages =
@@ -274,29 +283,49 @@ export async function updateInventoryPart(input: unknown) {
 
       const nextBarcode =
         updateData.barcode !== undefined ? normalizeBarcode(updateData.barcode) : undefined
+      const changes: Prisma.InventoryPartUpdateManyMutationInput = {
+        ...updateData,
+        // An untracked part holds no stock and is never low, whatever
+        // the form sent. Turned back on, it starts from what is typed.
+        ...(tracksStock ? {} : { quantity: 0, lowStockAlertedAt: null }),
+        partNumber: updateData.partNumber !== undefined ? updateData.partNumber || null : undefined,
+        unit: updateData.unit !== undefined ? updateData.unit.trim() || null : undefined,
+        barcode: nextBarcode,
+        description:
+          updateData.description !== undefined ? updateData.description || null : undefined,
+        category: updateData.category !== undefined ? updateData.category || null : undefined,
+        supplier: updateData.supplier !== undefined ? updateData.supplier || null : undefined,
+        supplierPhone:
+          updateData.supplierPhone !== undefined ? updateData.supplierPhone || null : undefined,
+        supplierEmail:
+          updateData.supplierEmail !== undefined ? updateData.supplierEmail || null : undefined,
+        supplierUrl:
+          updateData.supplierUrl !== undefined ? updateData.supplierUrl || null : undefined,
+        location: updateData.location !== undefined ? updateData.location || null : undefined,
+        tags: updateData.tags !== undefined ? normalizePartTags(updateData.tags) : undefined,
+      }
+      const writePart = (client: Pick<TxClient, 'inventoryPart'>) =>
+        client.inventoryPart.updateMany({ where: { id, organizationId }, data: changes })
+
       const result = await withBarcodeConflictMessage(organizationId, nextBarcode ?? null, () =>
-        db.inventoryPart.updateMany({
-          where: { id, organizationId },
-          data: {
-            ...updateData,
-            partNumber:
-              updateData.partNumber !== undefined ? updateData.partNumber || null : undefined,
-            unit: updateData.unit !== undefined ? updateData.unit.trim() || null : undefined,
-            barcode: nextBarcode,
-            description:
-              updateData.description !== undefined ? updateData.description || null : undefined,
-            category: updateData.category !== undefined ? updateData.category || null : undefined,
-            supplier: updateData.supplier !== undefined ? updateData.supplier || null : undefined,
-            supplierPhone:
-              updateData.supplierPhone !== undefined ? updateData.supplierPhone || null : undefined,
-            supplierEmail:
-              updateData.supplierEmail !== undefined ? updateData.supplierEmail || null : undefined,
-            supplierUrl:
-              updateData.supplierUrl !== undefined ? updateData.supplierUrl || null : undefined,
-            location: updateData.location !== undefined ? updateData.location || null : undefined,
-            tags: updateData.tags !== undefined ? normalizePartTags(updateData.tags) : undefined,
-          },
-        })
+        turningTrackingOff
+          ? // Turning tracking off empties the shelf in the ledger first, while
+            // the part still counts: one entry takes whatever was there (often
+            // a large negative) to zero, so it stops showing in stock reports.
+            db.$transaction(async (tx) => {
+              await recordAbsoluteStockChange(
+                tx,
+                organizationId,
+                id,
+                0,
+                { reason: 'stock_tracking_off', userId },
+                // A part already at zero still gets the entry: the history
+                // is where the day tracking stopped is read from.
+                { recordUnchanged: true }
+              )
+              return writePart(tx)
+            })
+          : writePart(db)
       )
       if (result.count === 0) throw new Error('Part not found')
       await releaseFiles(replacedImages, { organizationId, reason: 'inventory images replaced' })
@@ -385,14 +414,18 @@ export async function adjustInventoryStock(input: unknown) {
         where: { id, organizationId },
       })
       if (!part) throw new Error('Part not found')
+      if (part.trackStock === false) throw new Error('This part does not track stock')
 
       const newQuantity = part.quantity + adjustment
       if (newQuantity < 0) throw new Error('Insufficient stock')
 
-      await db.inventoryPart.updateMany({
-        where: { id, organizationId },
+      // Tracking is checked again in the write itself: switched off between
+      // the read above and here, the part must stay at zero.
+      const written = await db.inventoryPart.updateMany({
+        where: { id, organizationId, trackStock: true },
         data: { quantity: newQuantity },
       })
+      if (written.count === 0) throw new Error('This part does not track stock')
       await onInventoryChanged(organizationId)
       return { quantity: newQuantity }
     },
@@ -462,6 +495,7 @@ export async function getInventoryPartsList() {
           unitCost: true,
           sellPrice: true,
           quantity: true,
+          trackStock: true,
           category: true,
           tags: true,
           gallery: {
@@ -544,7 +578,7 @@ export async function hasAnyReorderPoint() {
       if ((Number(setting?.value) || 0) > 0) return true
 
       const configured = await db.inventoryPart.count({
-        where: { organizationId, isArchived: false, minQuantity: { gt: 0 } },
+        where: { organizationId, isArchived: false, trackStock: true, minQuantity: { gt: 0 } },
       })
       return configured > 0
     },

+ 1 - 0
src/features/inventory/Actions/lookupPartByBarcode.ts

@@ -31,6 +31,7 @@ export async function lookupPartByBarcode(barcode: string) {
           unitCost: true,
           sellPrice: true,
           quantity: true,
+          trackStock: true,
           category: true,
         },
       })

+ 6 - 2
src/features/inventory/Components/BarcodeScanActionDialog.tsx

@@ -21,6 +21,8 @@ interface BarcodeScanActionDialogProps {
     partNumber: string | null
     barcode: string | null
     quantity: number
+    /** False for a part that is charged but never counted: nothing to add to. */
+    trackStock?: boolean
     unit: string | null
     category: string | null
   } | null
@@ -77,11 +79,13 @@ export function BarcodeScanActionDialog({
                 )}
               </div>
               <p className="mt-1 text-sm">
-                {t('currentStock', { quantity: formatQuantity(part.quantity, part.unit) })}
+                {part.trackStock === false
+                  ? t('notTracked')
+                  : t('currentStock', { quantity: formatQuantity(part.quantity, part.unit) })}
               </p>
             </div>
 
-            <div className="space-y-2">
+            <div className={part.trackStock === false ? 'hidden' : 'space-y-2'}>
               <Label className="text-sm font-medium">{t('addStock')}</Label>
               <div className="flex gap-2">
                 <Button

+ 59 - 24
src/features/inventory/Components/InventoryPartForm.tsx

@@ -9,6 +9,7 @@ import { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import { Label } from '@/components/ui/label'
 import { Textarea } from '@/components/ui/textarea'
+import { Switch } from '@/components/ui/switch'
 import {
   Dialog,
   DialogBody,
@@ -92,6 +93,11 @@ interface InventoryPartFormProps {
     category: string | null
     quantity: number
     minQuantity: number
+    /**
+     * Whether jobs count this part down. A part opened without it keeps what
+     * is stored: the switch is then not sent on Save.
+     */
+    trackStock?: boolean
     unit: string | null
     unitCost: number
     sellPrice: number
@@ -161,6 +167,7 @@ export function InventoryPartForm({
   const shownIssue = fetchIssue?.url === supplierUrl ? fetchIssue.issue : null
   const [category, setCategory] = useState(part?.category ?? '')
   const [unit, setUnit] = useState(part ? (part.unit ?? '') : (defaultUnit ?? ''))
+  const [trackStock, setTrackStock] = useState(part?.trackStock ?? true)
   const [categoryOpen, setCategoryOpen] = useState(false)
   const [categorySearch, setCategorySearch] = useState('')
   const [tags, setTags] = useState<string[]>(part?.tags ?? [])
@@ -195,6 +202,7 @@ export function InventoryPartForm({
       setFetchIssue(null)
       setCategory(part?.category ?? '')
       setUnit(part ? (part.unit ?? '') : (defaultUnit ?? ''))
+      setTrackStock(part?.trackStock ?? true)
       setCategorySearch('')
       setTags(part?.tags ?? [])
       sellPriceManualRef.current = !!(part?.sellPrice && part.sellPrice > 0)
@@ -397,6 +405,9 @@ export function InventoryPartForm({
     }
   }, [gallery, t])
 
+  // Switching tracking off on a part that has a count: Save takes it to zero.
+  const willEmptyStock = Boolean(part?.trackStock) && !trackStock && part?.quantity !== 0
+
   const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
     e.preventDefault()
 
@@ -406,6 +417,7 @@ export function InventoryPartForm({
     // ones rather than being saved with none.
     const typedTags = splitTagInput(String(formData.get('tagDraft') ?? ''))
     const knowsTags = !part || Array.isArray(part.tags)
+    const knowsTrackStock = !part || typeof part.trackStock === 'boolean'
     // The box keeps a tag that is too long, with a note under it; saving it
     // would only come back refused, so it is shortened first.
     if (typedTags.some((tag) => tag.length > MAX_TAG_LENGTH)) {
@@ -431,8 +443,12 @@ export function InventoryPartForm({
       barcode: optional(formData.get('barcode')),
       description: optional(formData.get('description')),
       category: optional(category),
-      quantity: Number(formData.get('quantity')) || 0,
-      minQuantity: Number(formData.get('minQuantity')) || 0,
+      // The stock fields are not on the form while tracking is off. The
+      // reorder point is sent back as stored, for the day tracking comes
+      // back: left out, the action would read it as zero.
+      quantity: trackStock ? Number(formData.get('quantity')) || 0 : 0,
+      minQuantity: trackStock ? Number(formData.get('minQuantity')) || 0 : (part?.minQuantity ?? 0),
+      trackStock: knowsTrackStock ? trackStock : undefined,
       unit: unit.trim(),
       unitCost: Number(formData.get('unitCost')) || 0,
       sellPrice: Number(formData.get('sellPrice')) || 0,
@@ -875,18 +891,35 @@ export function InventoryPartForm({
                   </p>
                 </div>
 
-                <div className="grid grid-cols-2 gap-3 sm:grid-cols-5 sm:gap-4">
-                  <div className="space-y-2">
-                    <Label htmlFor="quantity">{t('form.quantity')}</Label>
-                    <Input
-                      id="quantity"
-                      name="quantity"
-                      type="number"
-                      min="0"
-                      step="any"
-                      defaultValue={part?.quantity ?? 1}
-                    />
+                <div className="flex items-center justify-between gap-4 rounded-lg border p-3">
+                  <div className="space-y-0.5">
+                    <Label htmlFor="trackStock">{t('form.trackStock')}</Label>
+                    <p className="text-xs text-muted-foreground">
+                      {willEmptyStock ? t('form.trackStockOffNote') : t('form.trackStockHint')}
+                    </p>
                   </div>
+                  <Switch id="trackStock" checked={trackStock} onCheckedChange={setTrackStock} />
+                </div>
+
+                <div
+                  className={cn(
+                    'grid grid-cols-2 gap-3 sm:gap-4',
+                    trackStock ? 'sm:grid-cols-5' : 'sm:grid-cols-3'
+                  )}
+                >
+                  {trackStock && (
+                    <div className="space-y-2">
+                      <Label htmlFor="quantity">{t('form.quantity')}</Label>
+                      <Input
+                        id="quantity"
+                        name="quantity"
+                        type="number"
+                        min="0"
+                        step="any"
+                        defaultValue={part ? (part.trackStock === false ? 0 : part.quantity) : 1}
+                      />
+                    </div>
+                  )}
                   <div className="space-y-2">
                     <Label htmlFor="unit">{t('form.unit')}</Label>
                     <UnitCombobox
@@ -896,17 +929,19 @@ export function InventoryPartForm({
                       unitSystem={unitSystem}
                     />
                   </div>
-                  <div className="space-y-2">
-                    <Label htmlFor="minQuantity">{t('form.minQty')}</Label>
-                    <Input
-                      id="minQuantity"
-                      name="minQuantity"
-                      type="number"
-                      min="0"
-                      step="any"
-                      defaultValue={part?.minQuantity ?? 0}
-                    />
-                  </div>
+                  {trackStock && (
+                    <div className="space-y-2">
+                      <Label htmlFor="minQuantity">{t('form.minQty')}</Label>
+                      <Input
+                        id="minQuantity"
+                        name="minQuantity"
+                        type="number"
+                        min="0"
+                        step="any"
+                        defaultValue={part?.minQuantity ?? 0}
+                      />
+                    </div>
+                  )}
                   <div className="space-y-2">
                     <Label htmlFor="unitCost">{t('form.unitCost')}</Label>
                     <Input

+ 3 - 1
src/features/inventory/Components/PartNameSuggestions.tsx

@@ -19,6 +19,8 @@ export interface PartSuggestion {
   unitCost: number
   sellPrice: number
   quantity: number
+  /** False for a fee or consumable that is charged but never counted. */
+  trackStock?: boolean
   tags?: string[]
 }
 
@@ -203,7 +205,7 @@ export function PartNameSuggestions({
             {part.unitCost > 0 && priceOf(part) !== part.unitCost && (
               <span className="line-through">{formatCurrency(part.unitCost, currencyCode)}</span>
             )}
-            {part.quantity > 0 ? (
+            {part.trackStock === false ? null : part.quantity > 0 ? (
               <span>
                 {t('suggestions.inStock', { quantity: formatQuantity(part.quantity, part.unit) })}
               </span>

+ 6 - 1
src/features/inventory/Lib/lowStockAlerts.ts

@@ -22,6 +22,8 @@ export interface LowStockCandidate {
   minQuantity: number
   unit: string | null
   lowStockAlertedAt: Date | null
+  /** Absent means tracked. A part that does not track stock is never low. */
+  trackStock?: boolean
 }
 
 export interface LowStockDecision {
@@ -52,11 +54,14 @@ export function effectiveThreshold(part: { minQuantity: number }, defaultThresho
  * This is the single definition of "low" — the alert engine, the dashboard
  * count, the list badge and the inventory filter all resolve through it (or
  * through SQL mirroring it), so the numbers can never disagree.
+ *
+ * A part that does not track stock (a fee, consumables) is never low.
  */
 export function isLow(
-  part: { quantity: number; minQuantity: number },
+  part: { quantity: number; minQuantity: number; trackStock?: boolean },
   defaultThreshold = 0
 ): boolean {
+  if (part.trackStock === false) return false
   const threshold = effectiveThreshold(part, defaultThreshold)
   return threshold > 0 && part.quantity <= threshold
 }

+ 22 - 5
src/features/inventory/Lib/reconcileStock.ts

@@ -21,6 +21,7 @@ export type StockMovementReason =
   | 'quote_conversion'
   | 'manual_adjustment'
   | 'bulk_markup'
+  | 'stock_tracking_off'
 
 /**
  * Provenance recorded alongside every movement, so the ledger can answer
@@ -75,6 +76,12 @@ function stockUnits(quantity: number): number {
  * `inventoryPartId` simply matches no rows, records no movement, and is
  * skipped — it can never mutate another tenant's inventory.
  *
+ * A part that does not track stock (`trackStock` false: a fee or consumable
+ * charged on jobs but never counted) is skipped the same way: the UPDATE
+ * matches no row, so its quantity stays put and no ledger row is written.
+ * Every path that uses or returns parts comes through here, which is what
+ * makes this the one place the rule lives.
+ *
  * Stock is allowed to go negative: over-consuming is real information
  * ("you used more than you had on hand") and, crucially, keeps the operation
  * reversible. Clamping at zero would corrupt the count as soon as the part is
@@ -114,11 +121,14 @@ export async function reconcileInventoryForParts(
     const updated = await tx.$queryRaw<{ quantity: number }[]>`
       UPDATE "public"."inventory_parts"
       SET "quantity" = "quantity" - ${decrement}, "updatedAt" = NOW()
-      WHERE "id" = ${inventoryPartId} AND "organizationId" = ${organizationId}
+      WHERE "id" = ${inventoryPartId}
+        AND "organizationId" = ${organizationId}
+        AND "trackStock" = true
       RETURNING "quantity"
     `
 
-    // No row matched — unknown part, or one belonging to another organization.
+    // No row matched — unknown part, one belonging to another organization,
+    // or one that does not track stock.
     if (updated.length === 0) continue
 
     ledgerRows.push({
@@ -152,14 +162,20 @@ export async function reconcileInventoryForParts(
  * RETURNING would always yield 0, since RETURNING evaluates against the updated
  * row.)
  *
- * Returns false when no row matched — unknown part, or wrong organization.
+ * A change that leaves the quantity where it was writes no ledger row, unless
+ * `recordUnchanged` asks for one: an event worth keeping in the history even
+ * when the balance did not move, such as stock tracking being turned off.
+ *
+ * Returns false when no row matched — unknown part, wrong organization, or a
+ * part that does not track stock.
  */
 export async function recordAbsoluteStockChange(
   tx: TxClient,
   organizationId: string,
   inventoryPartId: string,
   newQuantity: number,
-  context: StockMovementContext
+  context: StockMovementContext,
+  options: { recordUnchanged?: boolean } = {}
 ): Promise<boolean> {
   const updated = await tx.$queryRaw<{ quantity: number; delta: number }[]>`
     UPDATE "public"."inventory_parts" AS p
@@ -168,13 +184,14 @@ export async function recordAbsoluteStockChange(
     WHERE p."id" = prev."id"
       AND p."id" = ${inventoryPartId}
       AND p."organizationId" = ${organizationId}
+      AND p."trackStock" = true
     RETURNING p."quantity" AS "quantity", (p."quantity" - prev."quantity") AS "delta"
   `
 
   if (updated.length === 0) return false
 
   const delta = Number(updated[0].delta)
-  if (delta === 0) return true
+  if (delta === 0 && !options.recordUnchanged) return true
 
   await tx.stockMovement.create({
     data: {

+ 1 - 0
src/features/inventory/Lib/stockMovementReasons.ts

@@ -12,4 +12,5 @@ export const STOCK_MOVEMENT_REASONS = [
   'quote_conversion',
   'manual_adjustment',
   'bulk_markup',
+  'stock_tracking_off',
 ] as const

+ 4 - 0
src/features/inventory/Schema/inventorySchema.ts

@@ -11,6 +11,10 @@ export const createInventoryPartSchema = z.object({
   category: z.string().optional(),
   quantity: z.coerce.number().min(0, 'Quantity must be 0 or more').default(0),
   minQuantity: z.coerce.number().min(0, 'Min quantity must be 0 or more').default(0),
+  // No default: on an update, leaving it out keeps what the part has, and a
+  // page opened before the switch existed sends none. A new part tracks stock
+  // unless told otherwise (the column default).
+  trackStock: z.boolean().optional(),
   unit: z.string().max(20).optional(),
   unitCost: z.coerce.number().min(0, 'Unit cost must be 0 or more').default(0),
   sellPrice: z.coerce.number().min(0, 'Sell price must be 0 or more').default(0),

+ 3 - 1
src/features/reports/Actions/reportActions.ts

@@ -741,7 +741,9 @@ export async function getInventoryReport() {
   return withAuth(
     async ({ organizationId }) => {
       const parts = await db.inventoryPart.findMany({
-        where: { organizationId, isArchived: false },
+        // Stock on hand: a part that does not track stock (a fee,
+        // consumables) has none, so it is not counted, valued or listed low.
+        where: { organizationId, isArchived: false, trackStock: true },
         select: {
           id: true,
           name: true,

+ 1 - 0
src/features/search/Actions/searchActions.ts

@@ -239,6 +239,7 @@ export async function globalSearch(query: string) {
                 name: true,
                 partNumber: true,
                 quantity: true,
+                trackStock: true,
                 unit: true,
               },
               take: 10,

+ 7 - 1
src/features/search/Components/SearchCommand.tsx

@@ -92,6 +92,8 @@ interface SearchResult {
     name: string
     partNumber: string | null
     quantity: number
+    /** False for a fee or consumable that is charged but never counted. */
+    trackStock?: boolean
     unit: string | null
   }[]
   quotes: {
@@ -1050,7 +1052,11 @@ export function SearchCommand({
                 onSelect={() => pickRecord('/inventory', p.name, p.partNumber ?? undefined)}
                 icon={Package}
                 title={p.name}
-                subtitle={`${formatQuantity(p.quantity, p.unit)} in stock`}
+                subtitle={
+                  p.trackStock === false
+                    ? undefined
+                    : `${formatQuantity(p.quantity, p.unit)} in stock`
+                }
                 trailing={p.partNumber}
               />
             ))}

+ 1 - 0
src/features/vehicles/Actions/dashboardActions.ts

@@ -46,6 +46,7 @@ export async function getDashboardStats() {
         FROM "public"."inventory_parts" p
         WHERE p."organizationId" = ${organizationId}
           AND p."isArchived" = false
+          AND p."trackStock" = true
           AND COALESCE(NULLIF(p."minQuantity", 0), ${lowStockDefault}) > 0
           AND p."quantity" <= COALESCE(NULLIF(p."minQuantity", 0), ${lowStockDefault})
       `,

+ 8 - 5
src/features/vehicles/Components/MyActiveJobs.tsx

@@ -106,6 +106,7 @@ export function MyActiveJobs({
     partNumber: string | null
     barcode: string | null
     quantity: number
+    trackStock?: boolean
     unit: string | null
     category: string | null
     sellPrice: number
@@ -695,11 +696,13 @@ export function MyActiveJobs({
                     )}
                   </div>
                 </div>
-                <div className="text-right text-sm text-muted-foreground shrink-0">
-                  {t('inStock', {
-                    quantity: formatQuantity(scannedPart.quantity, scannedPart.unit),
-                  })}
-                </div>
+                {scannedPart.trackStock !== false && (
+                  <div className="text-right text-sm text-muted-foreground shrink-0">
+                    {t('inStock', {
+                      quantity: formatQuantity(scannedPart.quantity, scannedPart.unit),
+                    })}
+                  </div>
+                )}
               </div>
 
               <div className="flex items-center justify-center gap-4 py-6">

+ 11 - 8
src/features/vehicles/Components/labor-guide/FluidPartButton.tsx

@@ -138,14 +138,17 @@ export function FluidPartButton({ fluid, units, stock, added, onAdd }: FluidPart
                     <span className="block text-xs text-muted-foreground">
                       {formatCurrency(line.unitPrice)}
                       {part.unit ? ` / ${part.unit}` : ''}
-                      {' · '}
-                      {part.quantity > 0
-                        ? tParts('inStock', {
-                            quantity: part.unit
-                              ? `${num(part.quantity)} ${part.unit}`
-                              : num(part.quantity),
-                          })
-                        : tParts('outOfStock')}
+                      {part.trackStock === false
+                        ? null
+                        : ` · ${
+                            part.quantity > 0
+                              ? tParts('inStock', {
+                                  quantity: part.unit
+                                    ? `${num(part.quantity)} ${part.unit}`
+                                    : num(part.quantity),
+                                })
+                              : tParts('outOfStock')
+                          }`}
                     </span>
                   </span>
                   <span className="shrink-0 text-xs font-medium tabular-nums">{qty(line)}</span>

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

@@ -174,7 +174,7 @@ export function InventoryPickerDialog({
                 ) : (
                   <span>{formatCurrency(ip.unitCost, currencyCode)}</span>
                 )}
-                {ip.quantity > 0 ? (
+                {ip.trackStock === false ? null : ip.quantity > 0 ? (
                   <span>{t('inStock', { quantity: formatQuantity(ip.quantity, ip.unit) })}</span>
                 ) : ip.quantity === 0 ? (
                   <span className="font-medium text-amber-600 dark:text-amber-500">

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

@@ -16,6 +16,8 @@ export interface InventoryPartOption {
   unitCost: number
   sellPrice: number
   quantity: number
+  /** False for a fee or consumable that is charged but never counted. */
+  trackStock?: boolean
   category: string | null
   /** The part's tags; makes and models in them rank it for the job's vehicle. */
   tags?: string[]

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

@@ -1051,6 +1051,8 @@ export async function restoreBackup(
                 category: (p.category as string) || null,
                 quantity: (p.quantity as number) || 0,
                 minQuantity: (p.minQuantity as number) || 0,
+                // Backups from before the switch have none: every part counted.
+                trackStock: p.trackStock !== false,
                 unit: (p.unit as string) || null,
                 unitCost: (p.unitCost as number) || 0,
                 sellPrice: (p.sellPrice as number) || 0,

+ 7 - 3
src/lib/cron/low-stock-alerts.ts

@@ -175,7 +175,8 @@ export async function processOrgLowStock(organizationId: string, now = new Date(
   // run on every stock movement, not just on the hourly sweep.
   //
   // The COALESCE mirrors effectiveThreshold(): the part's own reorder point
-  // wins, else the org-wide default.
+  // wins, else the org-wide default. A part that does not track stock is
+  // never low; one still carrying a marker is only re-armed.
   const threshold = settings.defaultThreshold
   const candidates = await db.$queryRaw<
     {
@@ -186,15 +187,18 @@ export async function processOrgLowStock(organizationId: string, now = new Date(
       minQuantity: number
       unit: string | null
       lowStockAlertedAt: Date | null
+      trackStock: boolean
     }[]
   >`
-    SELECT "id", "name", "partNumber", "quantity", "minQuantity", "unit", "lowStockAlertedAt"
+    SELECT "id", "name", "partNumber", "quantity", "minQuantity", "unit", "lowStockAlertedAt",
+      "trackStock"
     FROM "public"."inventory_parts"
     WHERE "organizationId" = ${organizationId}
       AND "isArchived" = false
       AND (
         (
-          COALESCE(NULLIF("minQuantity", 0), ${threshold}) > 0
+          "trackStock" = true
+          AND COALESCE(NULLIF("minQuantity", 0), ${threshold}) > 0
           AND "quantity" <= COALESCE(NULLIF("minQuantity", 0), ${threshold})
         )
         OR "lowStockAlertedAt" IS NOT NULL

+ 2 - 1
src/lib/cron/report-schedules.ts

@@ -504,7 +504,8 @@ async function fetchRetention(orgId: string, start: Date, end: Date) {
 
 async function fetchInventory(orgId: string) {
   const parts = await db.inventoryPart.findMany({
-    where: { organizationId: orgId, isArchived: false },
+    // Stock on hand only: parts that do not track stock are left out.
+    where: { organizationId: orgId, isArchived: false, trackStock: true },
     select: {
       id: true,
       name: true,