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

Reorder quote items by dragging (#623)

* Reorder quote items by dragging

Quote parts and labor lines get the drag handle the work order uses, with keyboard support. The order is stored in a new sortOrder column on quote lines, and the quote page, PDF, email, share page, portal and conversion to a work order all follow it. Resolves #619.

* Keep the shop fee last when reordering quote labor

The shop fee line has no drag handle and lines cannot be moved past it, since saving puts it last again.

* List the quote line position column for the workshop chat
Bernt Christian Egeland 23 часов назад
Родитель
Сommit
85f533f48d
35 измененных файлов с 778 добавлено и 81 удалено
  1. 2 0
      messages/de/quotes.json
  2. 2 0
      messages/en/quotes.json
  3. 2 0
      messages/es/quotes.json
  4. 2 0
      messages/fr/quotes.json
  5. 2 0
      messages/it/quotes.json
  6. 2 0
      messages/lt/quotes.json
  7. 2 0
      messages/nb/quotes.json
  8. 2 0
      messages/nl/quotes.json
  9. 2 0
      messages/pl/quotes.json
  10. 2 0
      messages/pt-BR/quotes.json
  11. 2 0
      messages/pt-PT/quotes.json
  12. 2 0
      messages/ru/quotes.json
  13. 2 0
      messages/tr/quotes.json
  14. 27 0
      prisma/migrations/20261117144953_quote_line_sort_order/migration.sql
  15. 6 0
      prisma/schema/quotes.prisma
  16. 2 0
      src/__tests__/features/quotes/multiline-line-items.test.tsx
  17. 172 0
      src/__tests__/features/quotes/quote-line-order-editor.test.tsx
  18. 219 0
      src/__tests__/features/quotes/quote-line-order.test.ts
  19. 2 1
      src/app/(public)/share/quote/[orgId]/[token]/page.tsx
  20. 28 0
      src/components/line-drag-handle.tsx
  21. 2 0
      src/features/ai/tools/workshop-columns.ts
  22. 2 2
      src/features/email/Actions/emailActions.ts
  23. 2 1
      src/features/portal/Actions/getPortalQuote.ts
  24. 17 6
      src/features/quotes/Actions/quoteActions.ts
  25. 32 20
      src/features/quotes/Components/QuoteLaborEditor.tsx
  26. 2 0
      src/features/quotes/Components/QuotePageClient.tsx
  27. 30 19
      src/features/quotes/Components/QuotePartsEditor.tsx
  28. 168 0
      src/features/quotes/Components/SortableQuoteLines.tsx
  29. 21 0
      src/features/quotes/Components/useQuoteFormState.ts
  30. 2 2
      src/features/quotes/Lib/createQuoteRecord.ts
  31. 3 2
      src/features/quotes/Pdf/buildQuotePdfBuffer.ts
  32. 3 1
      src/features/tire-hotel/Actions/tireJobActions.ts
  33. 3 17
      src/features/vehicles/Components/service-edit/LaborEditor.tsx
  34. 3 8
      src/features/vehicles/Components/service-edit/PartsEditor.tsx
  35. 6 2
      src/lib/backup/import.ts

+ 2 - 0
messages/de/quotes.json

@@ -115,6 +115,7 @@
     "total": "Gesamt",
     "total": "Gesamt",
     "subtotal": "Teile Zwischensumme: {amount}",
     "subtotal": "Teile Zwischensumme: {amount}",
     "deleteRow": "Zeile löschen",
     "deleteRow": "Zeile löschen",
+    "reorderRow": "Ziehen zum Neuordnen",
     "excludeFromTotal": "Von der Summe ausnehmen",
     "excludeFromTotal": "Von der Summe ausnehmen",
     "addFromInventory": "Aus Lager",
     "addFromInventory": "Aus Lager",
     "unitCost": "Kosten",
     "unitCost": "Kosten",
@@ -139,6 +140,7 @@
     "hourlyHint": "Stundenbasiert: nach geleisteten Stunden berechnet (Stunden × Satz/Std.). Zum Wechseln klicken.",
     "hourlyHint": "Stundenbasiert: nach geleisteten Stunden berechnet (Stunden × Satz/Std.). Zum Wechseln klicken.",
     "serviceHint": "Pauschale: als Festpreis pro Einheit berechnet. Zum Wechseln klicken.",
     "serviceHint": "Pauschale: als Festpreis pro Einheit berechnet. Zum Wechseln klicken.",
     "deleteRow": "Zeile löschen",
     "deleteRow": "Zeile löschen",
+    "reorderRow": "Ziehen zum Neuordnen",
     "excludeFromTotal": "Von der Summe ausnehmen"
     "excludeFromTotal": "Von der Summe ausnehmen"
   },
   },
   "notes": {
   "notes": {

+ 2 - 0
messages/en/quotes.json

@@ -115,6 +115,7 @@
     "total": "Total",
     "total": "Total",
     "subtotal": "Parts Subtotal: {amount}",
     "subtotal": "Parts Subtotal: {amount}",
     "deleteRow": "Delete row",
     "deleteRow": "Delete row",
+    "reorderRow": "Drag to reorder",
     "excludeFromTotal": "Exclude from total",
     "excludeFromTotal": "Exclude from total",
     "addFromInventory": "From stock",
     "addFromInventory": "From stock",
     "unitCost": "Cost",
     "unitCost": "Cost",
@@ -139,6 +140,7 @@
     "hourlyHint": "Hourly: priced by hours worked (hours × rate/hr). Click to switch.",
     "hourlyHint": "Hourly: priced by hours worked (hours × rate/hr). Click to switch.",
     "serviceHint": "Service: priced as a flat fee per unit. Click to switch.",
     "serviceHint": "Service: priced as a flat fee per unit. Click to switch.",
     "deleteRow": "Delete row",
     "deleteRow": "Delete row",
+    "reorderRow": "Drag to reorder",
     "excludeFromTotal": "Exclude from total"
     "excludeFromTotal": "Exclude from total"
   },
   },
   "notes": {
   "notes": {

+ 2 - 0
messages/es/quotes.json

@@ -115,6 +115,7 @@
     "total": "Total",
     "total": "Total",
     "subtotal": "Subtotal de repuestos: {amount}",
     "subtotal": "Subtotal de repuestos: {amount}",
     "deleteRow": "Eliminar fila",
     "deleteRow": "Eliminar fila",
+    "reorderRow": "Arrastrar para reordenar",
     "excludeFromTotal": "Excluir del total",
     "excludeFromTotal": "Excluir del total",
     "addFromInventory": "Del inventario",
     "addFromInventory": "Del inventario",
     "unitCost": "Costo",
     "unitCost": "Costo",
@@ -139,6 +140,7 @@
     "hourlyHint": "Por horas: se calcula por las horas trabajadas (horas × tarifa/h). Haz clic para cambiar.",
     "hourlyHint": "Por horas: se calcula por las horas trabajadas (horas × tarifa/h). Haz clic para cambiar.",
     "serviceHint": "Servicio: se cobra como tarifa fija por unidad. Haz clic para cambiar.",
     "serviceHint": "Servicio: se cobra como tarifa fija por unidad. Haz clic para cambiar.",
     "deleteRow": "Eliminar fila",
     "deleteRow": "Eliminar fila",
+    "reorderRow": "Arrastrar para reordenar",
     "excludeFromTotal": "Excluir del total"
     "excludeFromTotal": "Excluir del total"
   },
   },
   "notes": {
   "notes": {

+ 2 - 0
messages/fr/quotes.json

@@ -115,6 +115,7 @@
     "total": "Total",
     "total": "Total",
     "subtotal": "Sous-total pièces : {amount}",
     "subtotal": "Sous-total pièces : {amount}",
     "deleteRow": "Supprimer la ligne",
     "deleteRow": "Supprimer la ligne",
+    "reorderRow": "Faire glisser pour réorganiser",
     "excludeFromTotal": "Exclure du total",
     "excludeFromTotal": "Exclure du total",
     "addFromInventory": "Du stock",
     "addFromInventory": "Du stock",
     "unitCost": "Coût",
     "unitCost": "Coût",
@@ -139,6 +140,7 @@
     "hourlyHint": "À l'heure : facturé selon les heures travaillées (heures × taux/h). Cliquez pour changer.",
     "hourlyHint": "À l'heure : facturé selon les heures travaillées (heures × taux/h). Cliquez pour changer.",
     "serviceHint": "Forfait : facturé au prix fixe par unité. Cliquez pour changer.",
     "serviceHint": "Forfait : facturé au prix fixe par unité. Cliquez pour changer.",
     "deleteRow": "Supprimer la ligne",
     "deleteRow": "Supprimer la ligne",
+    "reorderRow": "Faire glisser pour réorganiser",
     "excludeFromTotal": "Exclure du total"
     "excludeFromTotal": "Exclure du total"
   },
   },
   "notes": {
   "notes": {

+ 2 - 0
messages/it/quotes.json

@@ -115,6 +115,7 @@
     "total": "Totale",
     "total": "Totale",
     "subtotal": "Subtotale ricambi: {amount}",
     "subtotal": "Subtotale ricambi: {amount}",
     "deleteRow": "Elimina riga",
     "deleteRow": "Elimina riga",
+    "reorderRow": "Trascina per riordinare",
     "excludeFromTotal": "Escludi dal totale",
     "excludeFromTotal": "Escludi dal totale",
     "addFromInventory": "Dal magazzino",
     "addFromInventory": "Dal magazzino",
     "unitCost": "Costo",
     "unitCost": "Costo",
@@ -139,6 +140,7 @@
     "hourlyHint": "A ore: calcolato sulle ore lavorate (ore × tariffa/h). Clicca per cambiare.",
     "hourlyHint": "A ore: calcolato sulle ore lavorate (ore × tariffa/h). Clicca per cambiare.",
     "serviceHint": "Servizio: addebitato come importo fisso per unità. Clicca per cambiare.",
     "serviceHint": "Servizio: addebitato come importo fisso per unità. Clicca per cambiare.",
     "deleteRow": "Elimina riga",
     "deleteRow": "Elimina riga",
+    "reorderRow": "Trascina per riordinare",
     "excludeFromTotal": "Escludi dal totale"
     "excludeFromTotal": "Escludi dal totale"
   },
   },
   "notes": {
   "notes": {

+ 2 - 0
messages/lt/quotes.json

@@ -115,6 +115,7 @@
     "total": "Suma",
     "total": "Suma",
     "subtotal": "Dalių tarpinė suma: {amount}",
     "subtotal": "Dalių tarpinė suma: {amount}",
     "deleteRow": "Ištrinti eilutę",
     "deleteRow": "Ištrinti eilutę",
+    "reorderRow": "Vilkite, kad pakeistumėte tvarką",
     "excludeFromTotal": "Neįskaičiuoti į sumą",
     "excludeFromTotal": "Neįskaičiuoti į sumą",
     "addFromInventory": "Iš sandėlio",
     "addFromInventory": "Iš sandėlio",
     "unitCost": "Savikaina",
     "unitCost": "Savikaina",
@@ -139,6 +140,7 @@
     "hourlyHint": "Valandinis: skaičiuojama pagal darbo valandas (valandos × įkainis/val.). Spustelėkite, kad pakeistumėte.",
     "hourlyHint": "Valandinis: skaičiuojama pagal darbo valandas (valandos × įkainis/val.). Spustelėkite, kad pakeistumėte.",
     "serviceHint": "Paslauga: apmokestinama fiksuota suma už vienetą. Spustelėkite, kad pakeistumėte.",
     "serviceHint": "Paslauga: apmokestinama fiksuota suma už vienetą. Spustelėkite, kad pakeistumėte.",
     "deleteRow": "Ištrinti eilutę",
     "deleteRow": "Ištrinti eilutę",
+    "reorderRow": "Vilkite, kad pakeistumėte tvarką",
     "excludeFromTotal": "Neįskaičiuoti į sumą"
     "excludeFromTotal": "Neįskaičiuoti į sumą"
   },
   },
   "notes": {
   "notes": {

+ 2 - 0
messages/nb/quotes.json

@@ -115,6 +115,7 @@
     "total": "Totalt",
     "total": "Totalt",
     "subtotal": "Deler delsum: {amount}",
     "subtotal": "Deler delsum: {amount}",
     "deleteRow": "Slett rad",
     "deleteRow": "Slett rad",
+    "reorderRow": "Dra for å endre rekkefølge",
     "excludeFromTotal": "Hold utenfor summen",
     "excludeFromTotal": "Hold utenfor summen",
     "addFromInventory": "Fra lager",
     "addFromInventory": "Fra lager",
     "unitCost": "Kostnad",
     "unitCost": "Kostnad",
@@ -139,6 +140,7 @@
     "hourlyHint": "Timepris: beregnes etter arbeidede timer (timer × sats/t). Klikk for å bytte.",
     "hourlyHint": "Timepris: beregnes etter arbeidede timer (timer × sats/t). Klikk for å bytte.",
     "serviceHint": "Fastpris: beregnes som en fast sum per enhet. Klikk for å bytte.",
     "serviceHint": "Fastpris: beregnes som en fast sum per enhet. Klikk for å bytte.",
     "deleteRow": "Slett rad",
     "deleteRow": "Slett rad",
+    "reorderRow": "Dra for å endre rekkefølge",
     "excludeFromTotal": "Hold utenfor summen"
     "excludeFromTotal": "Hold utenfor summen"
   },
   },
   "notes": {
   "notes": {

+ 2 - 0
messages/nl/quotes.json

@@ -115,6 +115,7 @@
     "total": "Totaal",
     "total": "Totaal",
     "subtotal": "Subtotaal onderdelen: {amount}",
     "subtotal": "Subtotaal onderdelen: {amount}",
     "deleteRow": "Rij verwijderen",
     "deleteRow": "Rij verwijderen",
+    "reorderRow": "Sleep om te herschikken",
     "excludeFromTotal": "Buiten het totaal houden",
     "excludeFromTotal": "Buiten het totaal houden",
     "addFromInventory": "Uit voorraad",
     "addFromInventory": "Uit voorraad",
     "unitCost": "Inkoop",
     "unitCost": "Inkoop",
@@ -139,6 +140,7 @@
     "hourlyHint": "Per uur: berekend op gewerkte uren (uren × tarief/uur). Klik om te wisselen.",
     "hourlyHint": "Per uur: berekend op gewerkte uren (uren × tarief/uur). Klik om te wisselen.",
     "serviceHint": "Service: berekend als vast bedrag per eenheid. Klik om te wisselen.",
     "serviceHint": "Service: berekend als vast bedrag per eenheid. Klik om te wisselen.",
     "deleteRow": "Rij verwijderen",
     "deleteRow": "Rij verwijderen",
+    "reorderRow": "Sleep om te herschikken",
     "excludeFromTotal": "Buiten het totaal houden"
     "excludeFromTotal": "Buiten het totaal houden"
   },
   },
   "notes": {
   "notes": {

+ 2 - 0
messages/pl/quotes.json

@@ -115,6 +115,7 @@
     "total": "Suma",
     "total": "Suma",
     "subtotal": "Części suma częściowa: {amount}",
     "subtotal": "Części suma częściowa: {amount}",
     "deleteRow": "Usuń wiersz",
     "deleteRow": "Usuń wiersz",
+    "reorderRow": "Przeciągnij, aby zmienić kolejność",
     "excludeFromTotal": "Wyłącz z sumy",
     "excludeFromTotal": "Wyłącz z sumy",
     "addFromInventory": "Z magazynu",
     "addFromInventory": "Z magazynu",
     "unitCost": "Koszt",
     "unitCost": "Koszt",
@@ -139,6 +140,7 @@
     "hourlyHint": "Godzinowo: liczone według przepracowanych godzin (godziny × stawka/godz.). Kliknij, aby zmienić.",
     "hourlyHint": "Godzinowo: liczone według przepracowanych godzin (godziny × stawka/godz.). Kliknij, aby zmienić.",
     "serviceHint": "Usługa: rozliczana jako stała opłata za jednostkę. Kliknij, aby zmienić.",
     "serviceHint": "Usługa: rozliczana jako stała opłata za jednostkę. Kliknij, aby zmienić.",
     "deleteRow": "Usuń wiersz",
     "deleteRow": "Usuń wiersz",
+    "reorderRow": "Przeciągnij, aby zmienić kolejność",
     "excludeFromTotal": "Wyłącz z sumy"
     "excludeFromTotal": "Wyłącz z sumy"
   },
   },
   "notes": {
   "notes": {

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

@@ -115,6 +115,7 @@
     "total": "Total",
     "total": "Total",
     "subtotal": "Subtotal de peças: {amount}",
     "subtotal": "Subtotal de peças: {amount}",
     "deleteRow": "Excluir linha",
     "deleteRow": "Excluir linha",
+    "reorderRow": "Arraste para reordenar",
     "excludeFromTotal": "Não somar ao total",
     "excludeFromTotal": "Não somar ao total",
     "addFromInventory": "Do estoque",
     "addFromInventory": "Do estoque",
     "unitCost": "Custo",
     "unitCost": "Custo",
@@ -139,6 +140,7 @@
     "hourlyHint": "Por hora: calculado pelas horas trabalhadas (horas × taxa/h). Clique para alterar.",
     "hourlyHint": "Por hora: calculado pelas horas trabalhadas (horas × taxa/h). Clique para alterar.",
     "serviceHint": "Serviço: cobrado como valor fixo por unidade. Clique para alterar.",
     "serviceHint": "Serviço: cobrado como valor fixo por unidade. Clique para alterar.",
     "deleteRow": "Excluir linha",
     "deleteRow": "Excluir linha",
+    "reorderRow": "Arraste para reordenar",
     "excludeFromTotal": "Não somar ao total"
     "excludeFromTotal": "Não somar ao total"
   },
   },
   "notes": {
   "notes": {

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

@@ -115,6 +115,7 @@
     "total": "Total",
     "total": "Total",
     "subtotal": "Subtotal de peças: {amount}",
     "subtotal": "Subtotal de peças: {amount}",
     "deleteRow": "Eliminar linha",
     "deleteRow": "Eliminar linha",
+    "reorderRow": "Arraste para reordenar",
     "excludeFromTotal": "Não somar ao total",
     "excludeFromTotal": "Não somar ao total",
     "addFromInventory": "Do stock",
     "addFromInventory": "Do stock",
     "unitCost": "Custo",
     "unitCost": "Custo",
@@ -139,6 +140,7 @@
     "hourlyHint": "À hora: calculado pelas horas trabalhadas (horas × preço/hora). Clique para alterar.",
     "hourlyHint": "À hora: calculado pelas horas trabalhadas (horas × preço/hora). Clique para alterar.",
     "serviceHint": "Serviço: cobrado como valor fixo por unidade. Clique para alterar.",
     "serviceHint": "Serviço: cobrado como valor fixo por unidade. Clique para alterar.",
     "deleteRow": "Eliminar linha",
     "deleteRow": "Eliminar linha",
+    "reorderRow": "Arraste para reordenar",
     "excludeFromTotal": "Não somar ao total"
     "excludeFromTotal": "Não somar ao total"
   },
   },
   "notes": {
   "notes": {

+ 2 - 0
messages/ru/quotes.json

@@ -115,6 +115,7 @@
     "total": "Итого",
     "total": "Итого",
     "subtotal": "Подитог запчастей: {amount}",
     "subtotal": "Подитог запчастей: {amount}",
     "deleteRow": "Удалить строку",
     "deleteRow": "Удалить строку",
+    "reorderRow": "Перетащите, чтобы изменить порядок",
     "excludeFromTotal": "Не включать в итог",
     "excludeFromTotal": "Не включать в итог",
     "addFromInventory": "Со склада",
     "addFromInventory": "Со склада",
     "unitCost": "Себестоимость",
     "unitCost": "Себестоимость",
@@ -139,6 +140,7 @@
     "hourlyHint": "Почасовая: оценка по нормо-часам (часы × ставка/час). Нажмите для изменения.",
     "hourlyHint": "Почасовая: оценка по нормо-часам (часы × ставка/час). Нажмите для изменения.",
     "serviceHint": "Услуга: фиксированная цена за единицу. Нажмите для изменения.",
     "serviceHint": "Услуга: фиксированная цена за единицу. Нажмите для изменения.",
     "deleteRow": "Удалить строку",
     "deleteRow": "Удалить строку",
+    "reorderRow": "Перетащите, чтобы изменить порядок",
     "excludeFromTotal": "Не включать в итог"
     "excludeFromTotal": "Не включать в итог"
   },
   },
   "notes": {
   "notes": {

+ 2 - 0
messages/tr/quotes.json

@@ -115,6 +115,7 @@
     "total": "Toplam",
     "total": "Toplam",
     "subtotal": "Parçalar Ara Toplam: {amount}",
     "subtotal": "Parçalar Ara Toplam: {amount}",
     "deleteRow": "Satırı sil",
     "deleteRow": "Satırı sil",
+    "reorderRow": "Sıralamak için sürükleyin",
     "excludeFromTotal": "Toplama dahil etme",
     "excludeFromTotal": "Toplama dahil etme",
     "addFromInventory": "Stoktan",
     "addFromInventory": "Stoktan",
     "unitCost": "Maliyet",
     "unitCost": "Maliyet",
@@ -139,6 +140,7 @@
     "hourlyHint": "Saatlik: çalışılan saate göre hesaplanır (saat × ücret/saat). Değiştirmek için tıklayın.",
     "hourlyHint": "Saatlik: çalışılan saate göre hesaplanır (saat × ücret/saat). Değiştirmek için tıklayın.",
     "serviceHint": "Hizmet: birim başına sabit ücret olarak hesaplanır. Değiştirmek için tıklayın.",
     "serviceHint": "Hizmet: birim başına sabit ücret olarak hesaplanır. Değiştirmek için tıklayın.",
     "deleteRow": "Satırı sil",
     "deleteRow": "Satırı sil",
+    "reorderRow": "Sıralamak için sürükleyin",
     "excludeFromTotal": "Toplama dahil etme"
     "excludeFromTotal": "Toplama dahil etme"
   },
   },
   "notes": {
   "notes": {

+ 27 - 0
prisma/migrations/20261117144953_quote_line_sort_order/migration.sql

@@ -0,0 +1,27 @@
+BEGIN;
+
+-- AlterTable
+ALTER TABLE "quote_labor" ADD COLUMN     "sortOrder" INTEGER NOT NULL DEFAULT 0;
+
+-- AlterTable
+ALTER TABLE "quote_parts" ADD COLUMN     "sortOrder" INTEGER NOT NULL DEFAULT 0;
+
+-- Existing quotes keep the order they show in today. Lines were read without
+-- an ORDER BY, which returns them in physical row order, so number them by it.
+UPDATE "quote_parts" AS p
+SET "sortOrder" = o.position
+FROM (
+  SELECT id, ROW_NUMBER() OVER (PARTITION BY "quoteId" ORDER BY ctid) - 1 AS position
+  FROM "quote_parts"
+) AS o
+WHERE p.id = o.id;
+
+UPDATE "quote_labor" AS l
+SET "sortOrder" = o.position
+FROM (
+  SELECT id, ROW_NUMBER() OVER (PARTITION BY "quoteId" ORDER BY ctid) - 1 AS position
+  FROM "quote_labor"
+) AS o
+WHERE l.id = o.id;
+
+COMMIT;

+ 6 - 0
prisma/schema/quotes.prisma

@@ -128,6 +128,10 @@ model QuotePart {
   /// ServicePart on conversion so the job deducts the right inventory item.
   /// ServicePart on conversion so the job deducts the right inventory item.
   inventoryPartId String?
   inventoryPartId String?
 
 
+  /// Where the line sits on the quote, as the workshop dragged it. Rows are
+  /// rewritten on every save, so this is the array index they were sent in.
+  sortOrder Int @default(0)
+
   quoteId String
   quoteId String
   quote   Quote  @relation(fields: [quoteId], references: [id], onDelete: Cascade)
   quote   Quote  @relation(fields: [quoteId], references: [id], onDelete: Cascade)
 
 
@@ -145,6 +149,8 @@ model QuoteLabor {
   excluded    Boolean @default(false)
   excluded    Boolean @default(false)
   /// Carried into ServiceLabor on conversion. See there.
   /// Carried into ServiceLabor on conversion. See there.
   taxable     Boolean @default(true)
   taxable     Boolean @default(true)
+  /// Where the line sits on the quote. See QuotePart.sortOrder.
+  sortOrder   Int     @default(0)
 
 
   quoteId String
   quoteId String
   quote   Quote  @relation(fields: [quoteId], references: [id], onDelete: Cascade)
   quote   Quote  @relation(fields: [quoteId], references: [id], onDelete: Cascade)

+ 2 - 0
src/__tests__/features/quotes/multiline-line-items.test.tsx

@@ -38,6 +38,7 @@ describe('quote line items take more than one line', () => {
         partsSubtotal={100}
         partsSubtotal={100}
         onUpdate={vi.fn()}
         onUpdate={vi.fn()}
         onDelete={vi.fn()}
         onDelete={vi.fn()}
+        onMove={vi.fn()}
         onAdd={vi.fn()}
         onAdd={vi.fn()}
         t={t}
         t={t}
       />
       />
@@ -59,6 +60,7 @@ describe('quote line items take more than one line', () => {
         laborSubtotal={1600}
         laborSubtotal={1600}
         onUpdate={vi.fn()}
         onUpdate={vi.fn()}
         onDelete={vi.fn()}
         onDelete={vi.fn()}
+        onMove={vi.fn()}
         onAdd={vi.fn()}
         onAdd={vi.fn()}
         t={t}
         t={t}
       />
       />

+ 172 - 0
src/__tests__/features/quotes/quote-line-order-editor.test.tsx

@@ -0,0 +1,172 @@
+/**
+ * Lines on a quote move by their grip, as they do on the work order (issue
+ * #619). The grip is a keyboard control too: focus it, pick the line up with
+ * Space, move it with the arrows and drop it with Space.
+ */
+import { act, fireEvent, render, screen } from '@testing-library/react'
+import { useState } from 'react'
+import { arrayMove } from '@dnd-kit/sortable'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { QuoteLaborEditor } from '@/features/quotes/Components/QuoteLaborEditor'
+import { QuotePartsEditor } from '@/features/quotes/Components/QuotePartsEditor'
+import type { QuoteLaborInput, QuotePartInput } from '@/features/quotes/Components/quote-page-types'
+
+const t = (key: string) => key
+
+const part = (name: string): QuotePartInput => ({
+  name,
+  partNumber: '',
+  quantity: 1,
+  unitCost: 0,
+  markupPercent: 0,
+  unitPrice: 100,
+  total: 100,
+  excluded: false,
+})
+
+const labor = (description: string): QuoteLaborInput => ({
+  description,
+  hours: 1,
+  rate: 800,
+  total: 800,
+  pricingType: 'hourly',
+  excluded: false,
+})
+
+function PartsHarness({ initial }: { initial: QuotePartInput[] }) {
+  const [items, setItems] = useState(initial)
+  return (
+    <QuotePartsEditor
+      partItems={items}
+      currencyCode="NOK"
+      partsSubtotal={0}
+      onUpdate={vi.fn()}
+      onDelete={(index) => setItems((prev) => prev.filter((_, j) => j !== index))}
+      onMove={(from, to) => setItems((prev) => arrayMove(prev, from, to))}
+      onAdd={vi.fn()}
+      t={t}
+    />
+  )
+}
+
+function LaborHarness({ initial }: { initial: QuoteLaborInput[] }) {
+  const [items, setItems] = useState(initial)
+  return (
+    <QuoteLaborEditor
+      laborItems={items}
+      currencyCode="NOK"
+      cs="kr"
+      laborSubtotal={0}
+      onUpdate={vi.fn()}
+      onDelete={(index) => setItems((prev) => prev.filter((_, j) => j !== index))}
+      onMove={(from, to) => setItems((prev) => arrayMove(prev, from, to))}
+      onAdd={vi.fn()}
+      t={t}
+    />
+  )
+}
+
+/**
+ * jsdom lays nothing out, and dnd-kit finds the line above or below by where
+ * it is on screen. Each draggable line is given a 50px slot by its position.
+ */
+const realRect = HTMLElement.prototype.getBoundingClientRect
+beforeEach(() => {
+  HTMLElement.prototype.getBoundingClientRect = function (this: HTMLElement) {
+    const line = this.closest('[data-testid="sortable-line"]') ?? this
+    const siblings = line.parentElement
+      ? Array.from(line.parentElement.children).filter(
+          (el) => el.getAttribute('data-testid') === 'sortable-line'
+        )
+      : []
+    const top = Math.max(siblings.indexOf(line), 0) * 50
+    return {
+      x: 0,
+      y: top,
+      top,
+      left: 0,
+      right: 600,
+      bottom: top + 40,
+      width: 600,
+      height: 40,
+      toJSON: () => ({}),
+    } as DOMRect
+  }
+})
+afterEach(() => {
+  HTMLElement.prototype.getBoundingClientRect = realRect
+})
+
+async function key(target: Element, code: string) {
+  await act(async () => {
+    fireEvent.keyDown(target, { code, key: code === 'Space' ? ' ' : code })
+    await new Promise((resolve) => setTimeout(resolve, 0))
+  })
+}
+
+/** Picks line `index` up by its grip, moves it with `arrow` and drops it. */
+async function moveWithKeyboard(label: string, index: number, arrow: 'ArrowUp' | 'ArrowDown') {
+  const grip = screen.getAllByRole('button', { name: label })[index]
+  grip.focus()
+  await key(grip, 'Space')
+  await key(document.activeElement ?? grip, arrow)
+  await key(document.activeElement ?? grip, 'Space')
+}
+
+const partNames = () =>
+  (screen.getAllByPlaceholderText('parts.namePlaceholder') as HTMLTextAreaElement[]).map(
+    (field) => field.value
+  )
+
+const laborDescriptions = () =>
+  (screen.getAllByPlaceholderText('labor.descriptionPlaceholder') as HTMLTextAreaElement[]).map(
+    (field) => field.value
+  )
+
+describe('reordering quote lines', () => {
+  it('gives every part line a grip named for what it does', () => {
+    render(<PartsHarness initial={[part('Oil filter'), part('Brake pads')]} />)
+    expect(screen.getAllByRole('button', { name: 'parts.reorderRow' })).toHaveLength(2)
+  })
+
+  it('moves a part line up with the keyboard', async () => {
+    render(
+      <PartsHarness initial={[part('Oil filter'), part('Brake pads'), part('Wiper blades')]} />
+    )
+    await moveWithKeyboard('parts.reorderRow', 1, 'ArrowUp')
+    expect(partNames()).toEqual(['Brake pads', 'Oil filter', 'Wiper blades'])
+  })
+
+  it('moves a labour line down with the keyboard', async () => {
+    render(<LaborHarness initial={[labor('Diagnose'), labor('Replace pads')]} />)
+    await moveWithKeyboard('labor.reorderRow', 0, 'ArrowDown')
+    expect(laborDescriptions()).toEqual(['Replace pads', 'Diagnose'])
+  })
+
+  it('deletes the line that was clicked after lines have moved', async () => {
+    render(
+      <PartsHarness initial={[part('Oil filter'), part('Brake pads'), part('Wiper blades')]} />
+    )
+    await moveWithKeyboard('parts.reorderRow', 2, 'ArrowUp')
+    expect(partNames()).toEqual(['Oil filter', 'Wiper blades', 'Brake pads'])
+    fireEvent.click(screen.getAllByRole('button', { name: 'parts.deleteRow' })[1])
+    expect(partNames()).toEqual(['Oil filter', 'Brake pads'])
+  })
+
+  // Every save puts the shop fee last, so the editor keeps it there rather
+  // than show an order that a reload would undo.
+  const shopFee: QuoteLaborInput = { ...labor('Shop fee'), pricingType: 'shopFee' }
+
+  it('gives the shop fee no grip', () => {
+    render(<LaborHarness initial={[labor('Diagnose'), labor('Replace pads'), shopFee]} />)
+    expect(screen.getAllByRole('button', { name: 'labor.reorderRow' })).toHaveLength(2)
+  })
+
+  it('does not move a line below the shop fee', async () => {
+    render(<LaborHarness initial={[labor('Diagnose'), labor('Replace pads'), shopFee]} />)
+    await moveWithKeyboard('labor.reorderRow', 1, 'ArrowDown')
+    expect(laborDescriptions()).toEqual(['Diagnose', 'Replace pads', 'Shop fee'])
+    await moveWithKeyboard('labor.reorderRow', 1, 'ArrowUp')
+    expect(laborDescriptions()).toEqual(['Replace pads', 'Diagnose', 'Shop fee'])
+  })
+})

+ 219 - 0
src/__tests__/features/quotes/quote-line-order.test.ts

@@ -0,0 +1,219 @@
+/**
+ * The order a workshop drags a quote's lines into is the order they come
+ * back in, on the quote and on the work order it becomes (issue #619).
+ *
+ * The database is played by a small store that hands rows back in the
+ * reverse of how they were written unless the read asks for them by
+ * position, as Postgres makes no promise about the order of an unordered
+ * read.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: vi.fn(),
+  getCachedMembership: vi.fn(),
+}))
+vi.mock('next/cache', () => ({ revalidatePath: vi.fn() }))
+vi.mock('server-only', () => ({}))
+vi.mock('@/lib/workshop-timezone', async (importOriginal) => ({
+  ...(await importOriginal<typeof import('@/lib/workshop-timezone')>()),
+  workshopTimeZone: async () => 'UTC',
+}))
+vi.mock('@/lib/document-lock.server', () => ({
+  assertQuoteEditable: vi.fn().mockResolvedValue(undefined),
+  assertInvoiceEditable: vi.fn().mockResolvedValue(undefined),
+  getDocumentLockSettings: vi.fn().mockResolvedValue({}),
+}))
+vi.mock('@/features/inventory/Lib/reconcileStock', () => ({
+  reconcileInventoryForParts: vi.fn().mockResolvedValue(undefined),
+}))
+vi.mock('@/features/inventory/Lib/onInventoryChanged', () => ({
+  onInventoryChanged: vi.fn().mockResolvedValue(undefined),
+}))
+vi.mock('@/lib/invoice-utils', async (importOriginal) => ({
+  ...(await importOriginal<typeof import('@/lib/invoice-utils')>()),
+  resolveInvoicePrefix: vi.fn((p: string) => p),
+}))
+
+vi.mock('@/lib/db', () => ({
+  db: {
+    $queryRaw: async () => [],
+    user: { findUnique: vi.fn() },
+    appSetting: { findMany: vi.fn() },
+    organization: { findUnique: vi.fn() },
+    vehicle: { findFirst: vi.fn() },
+    inspection: { findFirst: vi.fn() },
+    serviceRecord: { findFirst: vi.fn() },
+    quote: { findFirst: vi.fn() },
+    quotePart: { findMany: vi.fn() },
+    quoteLabor: { findMany: vi.fn() },
+    $transaction: vi.fn(),
+  },
+}))
+
+import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
+import { db } from '@/lib/db'
+import {
+  convertQuoteToServiceRecord,
+  getQuote,
+  updateQuote,
+} from '@/features/quotes/Actions/quoteActions'
+
+const ORG = 'org-1'
+
+type Row = Record<string, unknown> & { sortOrder?: number }
+
+/** The quote's lines as the database holds them, in no particular order. */
+const table = { parts: [] as Row[], labor: [] as Row[] }
+
+function read(rows: Row[], relation: unknown): Row[] {
+  const orderBy = (relation as { orderBy?: { sortOrder?: string } } | undefined)?.orderBy
+  if (orderBy?.sortOrder === 'asc') {
+    return [...rows].sort((a, b) => (a.sortOrder ?? 0) - (b.sortOrder ?? 0))
+  }
+  return [...rows].reverse()
+}
+
+const quoteRow = {
+  id: 'q-1',
+  organizationId: ORG,
+  quoteNumber: 'Q-1',
+  title: 'Brakes',
+  description: null,
+  status: 'draft',
+  subtotal: 0,
+  discountType: null,
+  discountValue: 0,
+  discountAmount: 0,
+  taxRate: 0,
+  taxAmount: 0,
+  taxInclusive: false,
+  taxComponents: null,
+  taxableSubtotal: null,
+  totalAmount: 0,
+  warrantyStatus: null,
+  warrantyMonths: null,
+  warrantyMileage: null,
+  warrantyNotes: null,
+  tireSetId: null,
+  inspectionId: null,
+  vehicle: null,
+  attachments: [],
+}
+
+const written = {
+  serviceParts: vi.fn(),
+  serviceLabor: vi.fn(),
+}
+
+beforeEach(() => {
+  vi.resetAllMocks()
+  table.parts = []
+  table.labor = []
+  vi.mocked(getCachedSession).mockResolvedValue({
+    user: { id: 'user-1', email: 'a@example.com' },
+  } as never)
+  vi.mocked(getCachedMembership).mockResolvedValue({
+    organizationId: ORG,
+    role: 'owner',
+    roleId: null,
+    customRole: null,
+  } as never)
+  vi.mocked(db.user.findUnique).mockResolvedValue({ isSuperAdmin: false } as never)
+  vi.mocked(db.appSetting.findMany).mockResolvedValue([] as never)
+  vi.mocked(db.organization.findUnique).mockResolvedValue({ name: 'Shop' } as never)
+  vi.mocked(db.vehicle.findFirst).mockResolvedValue({ id: 'veh-1' } as never)
+  vi.mocked(db.serviceRecord.findFirst).mockResolvedValue(null as never)
+  vi.mocked(db.quote.findFirst).mockImplementation((async (args: {
+    include?: { partItems?: unknown; laborItems?: unknown }
+  }) => ({
+    ...quoteRow,
+    partItems: read(table.parts, args?.include?.partItems),
+    laborItems: read(table.labor, args?.include?.laborItems),
+  })) as never)
+
+  written.serviceParts.mockResolvedValue({ count: 0 })
+  written.serviceLabor.mockResolvedValue({ count: 0 })
+  const tx = {
+    quote: {
+      update: vi.fn(async () => quoteRow),
+      updateMany: vi.fn().mockResolvedValue({ count: 1 }),
+    },
+    quotePart: {
+      deleteMany: vi.fn(async () => {
+        table.parts = []
+      }),
+      createMany: vi.fn(async ({ data }: { data: Row[] }) => {
+        table.parts.push(...data)
+      }),
+    },
+    quoteLabor: {
+      deleteMany: vi.fn(async () => {
+        table.labor = []
+      }),
+      createMany: vi.fn(async ({ data }: { data: Row[] }) => {
+        table.labor.push(...data)
+      }),
+    },
+    serviceRecord: {
+      create: vi.fn().mockResolvedValue({ id: 'sr-1', title: 'Brakes', invoiceNumber: '1001' }),
+    },
+    servicePart: { createMany: written.serviceParts },
+    serviceLabor: { createMany: written.serviceLabor },
+    serviceAttachment: { createMany: vi.fn() },
+  }
+  vi.mocked(db.$transaction).mockImplementation((async (fn: (client: typeof tx) => unknown) =>
+    fn(tx)) as never)
+})
+
+const part = (name: string) => ({ name, quantity: 1, unitPrice: 100, total: 100 })
+const labor = (description: string) => ({ description, hours: 1, rate: 500, total: 500 })
+
+/** Saves the quote with its lines in the order the editor holds them. */
+async function saveInOrder(parts: string[], laborLines: string[]) {
+  const result = await updateQuote({
+    id: 'q-1',
+    title: 'Brakes',
+    partItems: parts.map(part),
+    laborItems: laborLines.map(labor),
+  })
+  expect(result.success).toBe(true)
+}
+
+describe('the order of a quote’s lines', () => {
+  it('comes back as it was saved when the quote is opened again', async () => {
+    await saveInOrder(['Rotors', 'Brake pads', 'Brake fluid'], ['Bleed brakes', 'Replace pads'])
+
+    const result = await getQuote('q-1')
+    expect(result.success).toBe(true)
+    expect(result.data?.partItems.map((p) => p.name)).toEqual([
+      'Rotors',
+      'Brake pads',
+      'Brake fluid',
+    ])
+    expect(result.data?.laborItems.map((l) => l.description)).toEqual([
+      'Bleed brakes',
+      'Replace pads',
+    ])
+  })
+
+  it('follows a later move on the next save', async () => {
+    await saveInOrder(['Rotors', 'Brake pads'], [])
+    await saveInOrder(['Brake pads', 'Rotors'], [])
+
+    const result = await getQuote('q-1')
+    expect(result.data?.partItems.map((p) => p.name)).toEqual(['Brake pads', 'Rotors'])
+  })
+
+  it('is the order the lines arrive in on the work order it becomes', async () => {
+    await saveInOrder(['Rotors', 'Brake pads', 'Brake fluid'], ['Bleed brakes', 'Replace pads'])
+
+    const result = await convertQuoteToServiceRecord('q-1', 'veh-1')
+    expect(result.success).toBe(true)
+
+    const jobParts = written.serviceParts.mock.calls[0][0].data as { name: string }[]
+    expect(jobParts.map((p) => p.name)).toEqual(['Rotors', 'Brake pads', 'Brake fluid'])
+    const jobLabor = written.serviceLabor.mock.calls[0][0].data as { description: string }[]
+    expect(jobLabor.map((l) => l.description)).toEqual(['Bleed brakes', 'Replace pads'])
+  })
+})

+ 2 - 1
src/app/(public)/share/quote/[orgId]/[token]/page.tsx

@@ -80,8 +80,9 @@ export default async function PublicQuotePage({
           // whether it is taxed; left out here, every line would be.
           // whether it is taxed; left out here, every line would be.
           taxable: true,
           taxable: true,
         },
         },
+        orderBy: { sortOrder: 'asc' },
       },
       },
-      laborItems: true,
+      laborItems: { orderBy: { sortOrder: 'asc' } },
       attachments: true,
       attachments: true,
       customer: {
       customer: {
         select: {
         select: {

+ 28 - 0
src/components/line-drag-handle.tsx

@@ -0,0 +1,28 @@
+'use client'
+
+import type { ButtonHTMLAttributes } from 'react'
+import { GripVertical } from 'lucide-react'
+import { cn } from '@/lib/utils'
+
+/**
+ * The grip a document line is dragged by, on the work order and the quote
+ * alike. Pass it dnd-kit's `attributes` and `listeners`, which also make it
+ * move with the arrow keys once focused and picked up with Space.
+ *
+ * `touch-none` keeps a finger on the grip dragging the line instead of
+ * scrolling the page; the rest of the row still scrolls as usual.
+ */
+export function LineDragHandle({ className, ...props }: ButtonHTMLAttributes<HTMLButtonElement>) {
+  return (
+    <button
+      type="button"
+      className={cn(
+        'flex h-9 w-6 shrink-0 cursor-grab touch-none items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing',
+        className
+      )}
+      {...props}
+    >
+      <GripVertical className="h-4 w-4" />
+    </button>
+  )
+}

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

@@ -266,6 +266,7 @@ export const TABLE_COLUMNS: Readonly<Record<string, readonly string[]>> = {
     'excluded',
     'excluded',
     'taxable',
     'taxable',
     'inventoryPartId',
     'inventoryPartId',
+    'sortOrder',
     'quoteId',
     'quoteId',
   ],
   ],
   quote_labor: [
   quote_labor: [
@@ -277,6 +278,7 @@ export const TABLE_COLUMNS: Readonly<Record<string, readonly string[]>> = {
     'pricingType',
     'pricingType',
     'excluded',
     'excluded',
     'taxable',
     'taxable',
+    'sortOrder',
     'quoteId',
     'quoteId',
   ],
   ],
   quote_attachments: [
   quote_attachments: [

+ 2 - 2
src/features/email/Actions/emailActions.ts

@@ -105,8 +105,8 @@ export async function sendQuoteEmail(input: {
       const quote = await db.quote.findFirst({
       const quote = await db.quote.findFirst({
         where: { id: quoteId, organizationId },
         where: { id: quoteId, organizationId },
         include: {
         include: {
-          partItems: true,
-          laborItems: true,
+          partItems: { orderBy: { sortOrder: 'asc' } },
+          laborItems: { orderBy: { sortOrder: 'asc' } },
           customer: {
           customer: {
             select: { name: true, email: true, phone: true, address: true, company: true },
             select: { name: true, email: true, phone: true, address: true, company: true },
           },
           },

+ 2 - 1
src/features/portal/Actions/getPortalQuote.ts

@@ -71,8 +71,9 @@ export async function getPortalQuote(quoteId: string) {
             excluded: true,
             excluded: true,
             taxable: true,
             taxable: true,
           },
           },
+          orderBy: { sortOrder: 'asc' },
         },
         },
-        laborItems: true,
+        laborItems: { orderBy: { sortOrder: 'asc' } },
         customer: {
         customer: {
           select: {
           select: {
             name: true,
             name: true,

+ 17 - 6
src/features/quotes/Actions/quoteActions.ts

@@ -186,8 +186,8 @@ export async function getQuote(quoteId: string) {
       const quote = await db.quote.findFirst({
       const quote = await db.quote.findFirst({
         where: { id: quoteId, organizationId },
         where: { id: quoteId, organizationId },
         include: {
         include: {
-          partItems: true,
-          laborItems: true,
+          partItems: { orderBy: { sortOrder: 'asc' } },
+          laborItems: { orderBy: { sortOrder: 'asc' } },
           attachments: true,
           attachments: true,
           customer: {
           customer: {
             select: {
             select: {
@@ -372,7 +372,8 @@ export async function updateQuote(input: unknown) {
           await tx.quotePart.deleteMany({ where: { quoteId: id } })
           await tx.quotePart.deleteMany({ where: { quoteId: id } })
           if (taxedParts && taxedParts.length > 0) {
           if (taxedParts && taxedParts.length > 0) {
             await tx.quotePart.createMany({
             await tx.quotePart.createMany({
-              data: taxedParts.map((p) => ({ ...p, quoteId: id })),
+              // The array order is the order the workshop arranged the lines in.
+              data: taxedParts.map((p, index) => ({ ...p, sortOrder: index, quoteId: id })),
             })
             })
           }
           }
         }
         }
@@ -381,7 +382,7 @@ export async function updateQuote(input: unknown) {
           await tx.quoteLabor.deleteMany({ where: { quoteId: id } })
           await tx.quoteLabor.deleteMany({ where: { quoteId: id } })
           if (taxedLabor && taxedLabor.length > 0) {
           if (taxedLabor && taxedLabor.length > 0) {
             await tx.quoteLabor.createMany({
             await tx.quoteLabor.createMany({
-              data: taxedLabor.map((l) => ({ ...l, quoteId: id })),
+              data: taxedLabor.map((l, index) => ({ ...l, sortOrder: index, quoteId: id })),
             })
             })
           }
           }
         }
         }
@@ -481,7 +482,12 @@ export async function convertQuoteToServiceRecord(quoteId: string, vehicleId: st
     async ({ userId, organizationId }) => {
     async ({ userId, organizationId }) => {
       const quote = await db.quote.findFirst({
       const quote = await db.quote.findFirst({
         where: { id: quoteId, organizationId },
         where: { id: quoteId, organizationId },
-        include: { partItems: true, laborItems: true, attachments: true },
+        include: {
+          // Lines reach the job in the order the quote shows them.
+          partItems: { orderBy: { sortOrder: 'asc' } },
+          laborItems: { orderBy: { sortOrder: 'asc' } },
+          attachments: true,
+        },
       })
       })
       if (!quote) throw new Error('Quote not found')
       if (!quote) throw new Error('Quote not found')
       // A second pass would raise a second job and take the parts out of
       // A second pass would raise a second job and take the parts out of
@@ -777,7 +783,12 @@ export async function addQuoteToServiceRecord(
     async ({ userId, organizationId }) => {
     async ({ userId, organizationId }) => {
       const quote = await db.quote.findFirst({
       const quote = await db.quote.findFirst({
         where: { id: quoteId, organizationId },
         where: { id: quoteId, organizationId },
-        include: { partItems: true, laborItems: true, attachments: true },
+        include: {
+          // Lines reach the job in the order the quote shows them.
+          partItems: { orderBy: { sortOrder: 'asc' } },
+          laborItems: { orderBy: { sortOrder: 'asc' } },
+          attachments: true,
+        },
       })
       })
       if (!quote) throw new Error('Quote not found')
       if (!quote) throw new Error('Quote not found')
       // A second pass would put the same lines on the job twice.
       // A second pass would put the same lines on the job twice.

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

@@ -8,6 +8,7 @@ import { Layers, Plus, Trash2, Wrench } from 'lucide-react'
 import { useFormatCurrency } from '@/components/currency-settings-context'
 import { useFormatCurrency } from '@/components/currency-settings-context'
 import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
 import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'
 import type { QuoteLaborInput } from './quote-page-types'
 import type { QuoteLaborInput } from './quote-page-types'
+import { SortableQuoteLines } from './SortableQuoteLines'
 import { isShopFeeLine } from '@/features/settings/Lib/shopFee'
 import { isShopFeeLine } from '@/features/settings/Lib/shopFee'
 import { ShopFeeTag, useShopFeeLocked } from '@/features/settings/Components/ShopFeeTag'
 import { ShopFeeTag, useShopFeeLocked } from '@/features/settings/Components/ShopFeeTag'
 import { LineTaxToggle } from '@/features/settings/Components/LineTaxToggle'
 import { LineTaxToggle } from '@/features/settings/Components/LineTaxToggle'
@@ -145,6 +146,8 @@ interface QuoteLaborEditorProps {
   laborSubtotal: number
   laborSubtotal: number
   onUpdate: (index: number, field: keyof QuoteLaborInput, value: string | number | boolean) => void
   onUpdate: (index: number, field: keyof QuoteLaborInput, value: string | number | boolean) => void
   onDelete: (index: number) => void
   onDelete: (index: number) => void
+  /** Moves the line at `from` to `to`, as the workshop dragged it. */
+  onMove: (from: number, to: number) => void
   onAdd: () => void
   onAdd: () => void
   onAddService?: () => void
   onAddService?: () => void
   hasPresets?: boolean
   hasPresets?: boolean
@@ -167,6 +170,7 @@ export const QuoteLaborEditor = memo(function QuoteLaborEditor({
   laborSubtotal,
   laborSubtotal,
   onUpdate,
   onUpdate,
   onDelete,
   onDelete,
+  onMove,
   onAdd,
   onAdd,
   onAddService,
   onAddService,
   hasPresets,
   hasPresets,
@@ -211,32 +215,40 @@ export const QuoteLaborEditor = memo(function QuoteLaborEditor({
         </div>
         </div>
         {laborItems.length > 0 && (
         {laborItems.length > 0 && (
           <>
           <>
-            <div className="hidden grid-cols-[2fr_1fr_1fr_1fr_auto] gap-2 text-xs font-medium text-muted-foreground sm:grid">
+            {/* Indented past the drag grip each line starts with. */}
+            <div className="hidden grid-cols-[2fr_1fr_1fr_1fr_auto] gap-2 pl-7 text-xs font-medium text-muted-foreground sm:grid">
               <span>{t('labor.description')}</span>
               <span>{t('labor.description')}</span>
               <span>{t('labor.qtyOrHours')}</span>
               <span>{t('labor.qtyOrHours')}</span>
               <span>{t('labor.rate', { currency: cs })}</span>
               <span>{t('labor.rate', { currency: cs })}</span>
               <span>{t('labor.total')}</span>
               <span>{t('labor.total')}</span>
               <span />
               <span />
             </div>
             </div>
-            {laborItems.map((labor, i) => (
-              <QuoteLaborRow
-                key={i}
-                labor={labor}
-                index={i}
-                currencyCode={currencyCode}
-                onUpdate={onUpdate}
-                onDelete={onDelete}
-                tDescriptionPlaceholder={t('labor.descriptionPlaceholder')}
-                tHourlyTag={t('labor.hourlyTag')}
-                tServiceTag={t('labor.serviceTag')}
-                tHourlyHint={t('labor.hourlyHint')}
-                tServiceHint={t('labor.serviceHint')}
-                tQty={t('labor.qty')}
-                tHours={t('labor.hours')}
-                tDeleteRow={t('labor.deleteRow')}
-                tExcludeFromTotal={t('labor.excludeFromTotal')}
-              />
-            ))}
+            <SortableQuoteLines
+              count={laborItems.length}
+              keyPrefix="labor"
+              handleLabel={t('labor.reorderRow')}
+              onMove={onMove}
+              onDelete={onDelete}
+              isPinned={(i) => isShopFeeLine(laborItems[i])}
+              renderLine={(i, deleteLine) => (
+                <QuoteLaborRow
+                  labor={laborItems[i]}
+                  index={i}
+                  currencyCode={currencyCode}
+                  onUpdate={onUpdate}
+                  onDelete={deleteLine}
+                  tDescriptionPlaceholder={t('labor.descriptionPlaceholder')}
+                  tHourlyTag={t('labor.hourlyTag')}
+                  tServiceTag={t('labor.serviceTag')}
+                  tHourlyHint={t('labor.hourlyHint')}
+                  tServiceHint={t('labor.serviceHint')}
+                  tQty={t('labor.qty')}
+                  tHours={t('labor.hours')}
+                  tDeleteRow={t('labor.deleteRow')}
+                  tExcludeFromTotal={t('labor.excludeFromTotal')}
+                />
+              )}
+            />
             <button
             <button
               type="button"
               type="button"
               className="flex w-full items-center justify-center rounded-md border border-dashed border-muted-foreground/25 py-1.5 text-muted-foreground transition-colors hover:border-muted-foreground/50 hover:text-foreground"
               className="flex w-full items-center justify-center rounded-md border border-dashed border-muted-foreground/25 py-1.5 text-muted-foreground transition-colors hover:border-muted-foreground/50 hover:text-foreground"

+ 2 - 0
src/features/quotes/Components/QuotePageClient.tsx

@@ -268,6 +268,7 @@ export function QuotePageClient({
         partsSubtotal={state.partsSubtotal}
         partsSubtotal={state.partsSubtotal}
         onUpdate={state.updatePart}
         onUpdate={state.updatePart}
         onDelete={state.deletePart}
         onDelete={state.deletePart}
+        onMove={state.movePart}
         onAdd={state.addPart}
         onAdd={state.addPart}
         onAddBulk={state.addPartBulk}
         onAddBulk={state.addPartBulk}
         inventoryParts={inventoryParts}
         inventoryParts={inventoryParts}
@@ -281,6 +282,7 @@ export function QuotePageClient({
         laborSubtotal={state.laborSubtotal}
         laborSubtotal={state.laborSubtotal}
         onUpdate={state.updateLabor}
         onUpdate={state.updateLabor}
         onDelete={state.deleteLabor}
         onDelete={state.deleteLabor}
+        onMove={state.moveLabor}
         onAdd={state.addLabor}
         onAdd={state.addLabor}
         onAddService={state.addService}
         onAddService={state.addService}
         hasPresets={laborPresets.length > 0}
         hasPresets={laborPresets.length > 0}

+ 30 - 19
src/features/quotes/Components/QuotePartsEditor.tsx

@@ -14,6 +14,7 @@ import { InventoryPickerDialog } from '@/features/vehicles/Components/service-ed
 import type { InventoryPartOption } from '@/features/vehicles/Components/service-edit/form-types'
 import type { InventoryPartOption } from '@/features/vehicles/Components/service-edit/form-types'
 import type { FitVehicle } from '@/features/inventory/Lib/partTags'
 import type { FitVehicle } from '@/features/inventory/Lib/partTags'
 import type { QuotePartInput } from './quote-page-types'
 import type { QuotePartInput } from './quote-page-types'
+import { SortableQuoteLines } from './SortableQuoteLines'
 import {
 import {
   PartNameSuggestions,
   PartNameSuggestions,
   type PartSuggestion,
   type PartSuggestion,
@@ -199,6 +200,8 @@ interface QuotePartsEditorProps {
     options?: { commit?: boolean }
     options?: { commit?: boolean }
   ) => void
   ) => void
   onDelete: (index: number) => void
   onDelete: (index: number) => void
+  /** Moves the line at `from` to `to`, as the workshop dragged it. */
+  onMove: (from: number, to: number) => void
   onAdd: () => void
   onAdd: () => void
   onAddBulk?: (items: QuotePartInput[]) => void
   onAddBulk?: (items: QuotePartInput[]) => void
   inventoryParts?: InventoryPartOption[]
   inventoryParts?: InventoryPartOption[]
@@ -214,6 +217,7 @@ export const QuotePartsEditor = memo(function QuotePartsEditor({
   partsSubtotal,
   partsSubtotal,
   onUpdate,
   onUpdate,
   onDelete,
   onDelete,
+  onMove,
   onAdd,
   onAdd,
   onAddBulk,
   onAddBulk,
   inventoryParts = [],
   inventoryParts = [],
@@ -281,7 +285,8 @@ export const QuotePartsEditor = memo(function QuotePartsEditor({
               <option key={category} value={category} />
               <option key={category} value={category} />
             ))}
             ))}
           </datalist>
           </datalist>
-          <div className="hidden grid-cols-[1fr_2fr_0.6fr_0.9fr_0.7fr_0.9fr_0.9fr_auto] gap-2 text-xs font-medium text-muted-foreground sm:grid">
+          {/* Indented past the drag grip each line starts with. */}
+          <div className="hidden grid-cols-[1fr_2fr_0.6fr_0.9fr_0.7fr_0.9fr_0.9fr_auto] gap-2 pl-7 text-xs font-medium text-muted-foreground sm:grid">
             <span>{t('parts.partNumber')}</span>
             <span>{t('parts.partNumber')}</span>
             <span>{t('parts.name')}</span>
             <span>{t('parts.name')}</span>
             <span>{t('parts.qty')}</span>
             <span>{t('parts.qty')}</span>
@@ -291,24 +296,30 @@ export const QuotePartsEditor = memo(function QuotePartsEditor({
             <span>{t('parts.total')}</span>
             <span>{t('parts.total')}</span>
             <span />
             <span />
           </div>
           </div>
-          {partItems.map((part, i) => (
-            <QuotePartRow
-              key={i}
-              part={part}
-              index={i}
-              currencyCode={currencyCode}
-              onUpdate={onUpdate}
-              onDelete={onDelete}
-              inventoryParts={inventoryParts}
-              onSelectSuggestion={handleSelectSuggestion}
-              tPartNumber={t('parts.partNumber')}
-              tCategory={t('parts.category')}
-              categoryListId={categoryListId}
-              tNamePlaceholder={t('parts.namePlaceholder')}
-              tDeleteRow={t('parts.deleteRow')}
-              tExcludeFromTotal={t('parts.excludeFromTotal')}
-            />
-          ))}
+          <SortableQuoteLines
+            count={partItems.length}
+            keyPrefix="part"
+            handleLabel={t('parts.reorderRow')}
+            onMove={onMove}
+            onDelete={onDelete}
+            renderLine={(i, deleteLine) => (
+              <QuotePartRow
+                part={partItems[i]}
+                index={i}
+                currencyCode={currencyCode}
+                onUpdate={onUpdate}
+                onDelete={deleteLine}
+                inventoryParts={inventoryParts}
+                onSelectSuggestion={handleSelectSuggestion}
+                tPartNumber={t('parts.partNumber')}
+                tCategory={t('parts.category')}
+                categoryListId={categoryListId}
+                tNamePlaceholder={t('parts.namePlaceholder')}
+                tDeleteRow={t('parts.deleteRow')}
+                tExcludeFromTotal={t('parts.excludeFromTotal')}
+              />
+            )}
+          />
           <button
           <button
             type="button"
             type="button"
             className="flex w-full items-center justify-center rounded-md border border-dashed border-muted-foreground/25 py-1.5 text-muted-foreground transition-colors hover:border-muted-foreground/50 hover:text-foreground"
             className="flex w-full items-center justify-center rounded-md border border-dashed border-muted-foreground/25 py-1.5 text-muted-foreground transition-colors hover:border-muted-foreground/50 hover:text-foreground"

+ 168 - 0
src/features/quotes/Components/SortableQuoteLines.tsx

@@ -0,0 +1,168 @@
+'use client'
+
+import { type ReactNode, useCallback, useEffect, useRef, useState } from 'react'
+import {
+  closestCenter,
+  DndContext,
+  type DragEndEvent,
+  KeyboardSensor,
+  PointerSensor,
+  useSensor,
+  useSensors,
+} from '@dnd-kit/core'
+import {
+  arrayMove,
+  SortableContext,
+  sortableKeyboardCoordinates,
+  useSortable,
+  verticalListSortingStrategy,
+} from '@dnd-kit/sortable'
+import { CSS } from '@dnd-kit/utilities'
+import { LineDragHandle } from '@/components/line-drag-handle'
+import { cn } from '@/lib/utils'
+
+/**
+ * Lines on a quote, each with a grip to drag it up or down, the way lines
+ * move on the work order. The list itself lives in the quote's form state;
+ * this only says which line went where.
+ *
+ * dnd-kit needs an id per line that stays with the line while it moves. The
+ * lines have none until they are saved, so each gets a key here that follows
+ * it through moves and deletes, as the work order's editors do.
+ */
+export function SortableQuoteLines({
+  count,
+  keyPrefix,
+  handleLabel,
+  onMove,
+  onDelete,
+  renderLine,
+  isPinned,
+}: {
+  count: number
+  keyPrefix: string
+  /** What a screen reader calls the grip. */
+  handleLabel: string
+  onMove: (from: number, to: number) => void
+  onDelete: (index: number) => void
+  /** Draws line `index`; its delete must call the `onDelete` handed to it. */
+  renderLine: (index: number, onDelete: (index: number) => void) => ReactNode
+  /**
+   * A line that stays where it is: it has no grip and nothing moves past it.
+   * The shop fee is one, because every save puts it last again.
+   */
+  isPinned?: (index: number) => boolean
+}) {
+  // Rendering the drag context only once mounted, as the work order does, so
+  // the server and the browser agree on the ids dnd-kit generates.
+  const [mounted, setMounted] = useState(false)
+  useEffect(() => setMounted(true), [])
+
+  const counterRef = useRef(0)
+  const keysRef = useRef<string[]>([])
+  // Lines are added at the end, so new keys go there too.
+  while (keysRef.current.length < count) {
+    keysRef.current.push(`${keyPrefix}-${counterRef.current++}`)
+  }
+  if (keysRef.current.length > count) {
+    keysRef.current = keysRef.current.slice(0, count)
+  }
+
+  const sensors = useSensors(
+    useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
+    useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
+  )
+
+  const handleDragEnd = useCallback(
+    (event: DragEndEvent) => {
+      const { active, over } = event
+      if (!over || active.id === over.id) return
+      const from = keysRef.current.indexOf(active.id as string)
+      const to = keysRef.current.indexOf(over.id as string)
+      if (from === -1 || to === -1) return
+      // A move that would carry a line across a pinned one is refused, so the
+      // editor never shows an order the save would not keep.
+      if (isPinned) {
+        for (let i = Math.min(from, to); i <= Math.max(from, to); i++) {
+          if (isPinned(i)) return
+        }
+      }
+      keysRef.current = arrayMove(keysRef.current, from, to)
+      onMove(from, to)
+    },
+    [onMove, isPinned]
+  )
+
+  // A deleted line takes its key with it, so the lines below keep theirs.
+  const deleteLine = useCallback(
+    (index: number) => {
+      keysRef.current = keysRef.current.filter((_, j) => j !== index)
+      onDelete(index)
+    },
+    [onDelete]
+  )
+
+  const lines = keysRef.current.map((key, index) =>
+    isPinned?.(index) ? (
+      <PinnedQuoteLine key={key}>{renderLine(index, deleteLine)}</PinnedQuoteLine>
+    ) : (
+      <SortableQuoteLine key={key} id={key} dragEnabled={mounted} handleLabel={handleLabel}>
+        {renderLine(index, deleteLine)}
+      </SortableQuoteLine>
+    )
+  )
+  const sortableKeys = keysRef.current.filter((_, index) => !isPinned?.(index))
+
+  if (!mounted) return <>{lines}</>
+  return (
+    <DndContext sensors={sensors} collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
+      <SortableContext items={sortableKeys} strategy={verticalListSortingStrategy}>
+        {lines}
+      </SortableContext>
+    </DndContext>
+  )
+}
+
+function SortableQuoteLine({
+  id,
+  dragEnabled,
+  handleLabel,
+  children,
+}: {
+  id: string
+  dragEnabled: boolean
+  handleLabel: string
+  children: ReactNode
+}) {
+  const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
+    id,
+  })
+  return (
+    <div
+      ref={dragEnabled ? setNodeRef : undefined}
+      data-testid="sortable-line"
+      style={dragEnabled ? { transform: CSS.Transform.toString(transform), transition } : undefined}
+      className={cn(
+        'flex items-start gap-1',
+        isDragging && dragEnabled && 'relative z-10 opacity-75'
+      )}
+    >
+      <LineDragHandle
+        aria-label={handleLabel}
+        title={handleLabel}
+        {...(dragEnabled ? { ...attributes, ...listeners } : {})}
+      />
+      <div className="min-w-0 flex-1">{children}</div>
+    </div>
+  )
+}
+
+/** A line without a grip, lined up with the ones that have one. */
+function PinnedQuoteLine({ children }: { children: ReactNode }) {
+  return (
+    <div data-testid="sortable-line" className="flex items-start gap-1">
+      <span aria-hidden className="w-6 shrink-0" />
+      <div className="min-w-0 flex-1">{children}</div>
+    </div>
+  )
+}

+ 21 - 0
src/features/quotes/Components/useQuoteFormState.ts

@@ -3,6 +3,7 @@
 import { Trash2 } from 'lucide-react'
 import { Trash2 } from 'lucide-react'
 import { useState, useCallback, useEffect, useRef, useMemo } from 'react'
 import { useState, useCallback, useEffect, useRef, useMemo } from 'react'
 import { useRouter } from 'next/navigation'
 import { useRouter } from 'next/navigation'
+import { arrayMove } from '@dnd-kit/sortable'
 import { toast } from 'sonner'
 import { toast } from 'sonner'
 import { useSaveBeforeLeaving } from '@/hooks/use-save-before-leaving'
 import { useSaveBeforeLeaving } from '@/hooks/use-save-before-leaving'
 import { useGlassModal } from '@/components/glass-modal'
 import { useGlassModal } from '@/components/glass-modal'
@@ -465,6 +466,24 @@ export function useQuoteFormState({
     [markDirty]
     [markDirty]
   )
   )
 
 
+  // A dragged line is an edit like any other: it is saved, and the quote's
+  // documents list the lines in this order.
+  const movePart = useCallback(
+    (from: number, to: number) => {
+      setPartItems((prev) => arrayMove(prev, from, to))
+      markDirty()
+    },
+    [markDirty]
+  )
+
+  const moveLabor = useCallback(
+    (from: number, to: number) => {
+      setLaborItems((prev) => arrayMove(prev, from, to))
+      markDirty()
+    },
+    [markDirty]
+  )
+
   const deletePart = useCallback(
   const deletePart = useCallback(
     (index: number) => {
     (index: number) => {
       setPartItems((prev) => prev.filter((_, j) => j !== index))
       setPartItems((prev) => prev.filter((_, j) => j !== index))
@@ -828,6 +847,8 @@ export function useQuoteFormState({
     addLaborBulk,
     addLaborBulk,
     deletePart,
     deletePart,
     deleteLabor,
     deleteLabor,
+    movePart,
+    moveLabor,
     handleSubmit,
     handleSubmit,
     handleDelete,
     handleDelete,
     handleDownloadPDF,
     handleDownloadPDF,

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

@@ -227,13 +227,13 @@ export async function createQuoteRecord(
 
 
     if (partItems && partItems.length > 0) {
     if (partItems && partItems.length > 0) {
       await tx.quotePart.createMany({
       await tx.quotePart.createMany({
-        data: taxedParts.map((p) => ({ ...p, quoteId: created.id })),
+        data: taxedParts.map((p, index) => ({ ...p, sortOrder: index, quoteId: created.id })),
       })
       })
     }
     }
 
 
     if (laborItems && laborItems.length > 0) {
     if (laborItems && laborItems.length > 0) {
       await tx.quoteLabor.createMany({
       await tx.quoteLabor.createMany({
-        data: taxedLabor.map((l) => ({ ...l, quoteId: created.id })),
+        data: taxedLabor.map((l, index) => ({ ...l, sortOrder: index, quoteId: created.id })),
       })
       })
     }
     }
 
 

+ 3 - 2
src/features/quotes/Pdf/buildQuotePdfBuffer.ts

@@ -41,8 +41,9 @@ export function quoteNumberOf(quote: { id: string; quoteNumber?: string | null }
 }
 }
 
 
 const QUOTE_INCLUDE = {
 const QUOTE_INCLUDE = {
-  partItems: true,
-  laborItems: true,
+  // The sheet lists the lines in the order the workshop arranged them.
+  partItems: { orderBy: { sortOrder: 'asc' as const } },
+  laborItems: { orderBy: { sortOrder: 'asc' as const } },
   attachments: true,
   attachments: true,
   customer: {
   customer: {
     select: { name: true, email: true, phone: true, address: true, company: true, taxId: true },
     select: { name: true, email: true, phone: true, address: true, company: true, taxId: true },

+ 3 - 1
src/features/tire-hotel/Actions/tireJobActions.ts

@@ -394,7 +394,9 @@ export async function createQuoteFromTireSet(input: unknown) {
                 },
                 },
               }
               }
             : {}),
             : {}),
-          ...(labor.length > 0 ? { laborItems: { create: labor } } : {}),
+          ...(labor.length > 0
+            ? { laborItems: { create: labor.map((l, i) => ({ ...l, sortOrder: i })) } }
+            : {}),
         },
         },
       })
       })
 
 

+ 3 - 17
src/features/vehicles/Components/service-edit/LaborEditor.tsx

@@ -9,19 +9,11 @@ import { useRef, useCallback, useState, useEffect } from 'react'
 import { Button } from '@/components/ui/button'
 import { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import { Input } from '@/components/ui/input'
 import { Textarea } from '@/components/ui/textarea'
 import { Textarea } from '@/components/ui/textarea'
-import {
-  AlertTriangle,
-  Eye,
-  GripVertical,
-  Layers,
-  Plus,
-  ScanLine,
-  Trash2,
-  Wrench,
-} from 'lucide-react'
+import { AlertTriangle, Eye, Layers, Plus, ScanLine, Trash2, Wrench } from 'lucide-react'
 import { IconActionButton } from '@/components/icon-action-button'
 import { IconActionButton } from '@/components/icon-action-button'
 import { FieldRow } from '@/components/line-item-field'
 import { FieldRow } from '@/components/line-item-field'
 import { cn } from '@/lib/utils'
 import { cn } from '@/lib/utils'
+import { LineDragHandle } from '@/components/line-drag-handle'
 import { AppCard } from '@/components/app-card'
 import { AppCard } from '@/components/app-card'
 import { useModernWorkOrder } from '@/components/work-order-layout-context'
 import { useModernWorkOrder } from '@/components/work-order-layout-context'
 import {
 import {
@@ -139,13 +131,7 @@ function SortableLaborRow({
         isDragging && dragEnabled && 'z-10 opacity-75'
         isDragging && dragEnabled && 'z-10 opacity-75'
       )}
       )}
     >
     >
-      <button
-        type="button"
-        className="flex h-9 w-6 cursor-grab items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing"
-        {...(dragEnabled ? { ...attributes, ...listeners } : {})}
-      >
-        <GripVertical className="h-4 w-4" />
-      </button>
+      <LineDragHandle {...(dragEnabled ? { ...attributes, ...listeners } : {})} />
       <div className="flex min-w-0 flex-col gap-2 @2xl:contents">
       <div className="flex min-w-0 flex-col gap-2 @2xl:contents">
         <div className="flex gap-2">
         <div className="flex gap-2">
           <Textarea
           <Textarea

+ 3 - 8
src/features/vehicles/Components/service-edit/PartsEditor.tsx

@@ -4,10 +4,11 @@ import { useRef, useCallback, useState, useEffect, useId, useMemo } from 'react'
 import { Button } from '@/components/ui/button'
 import { Button } from '@/components/ui/button'
 import { Input } from '@/components/ui/input'
 import { Input } from '@/components/ui/input'
 import { Textarea } from '@/components/ui/textarea'
 import { Textarea } from '@/components/ui/textarea'
-import { GripVertical, Package, Percent, Plus, ScanBarcode, Trash2 } from 'lucide-react'
+import { Package, Percent, Plus, ScanBarcode, Trash2 } from 'lucide-react'
 import { IconActionButton } from '@/components/icon-action-button'
 import { IconActionButton } from '@/components/icon-action-button'
 import { FieldRow } from '@/components/line-item-field'
 import { FieldRow } from '@/components/line-item-field'
 import { cn } from '@/lib/utils'
 import { cn } from '@/lib/utils'
+import { LineDragHandle } from '@/components/line-drag-handle'
 import { AppCard } from '@/components/app-card'
 import { AppCard } from '@/components/app-card'
 import { useModernWorkOrder } from '@/components/work-order-layout-context'
 import { useModernWorkOrder } from '@/components/work-order-layout-context'
 import { useFormatCurrency } from '@/components/currency-settings-context'
 import { useFormatCurrency } from '@/components/currency-settings-context'
@@ -135,13 +136,7 @@ function SortablePartRow({
         isDragging && dragEnabled && 'z-10 opacity-75'
         isDragging && dragEnabled && 'z-10 opacity-75'
       )}
       )}
     >
     >
-      <button
-        type="button"
-        className="flex h-9 w-6 cursor-grab items-center justify-center text-muted-foreground hover:text-foreground active:cursor-grabbing"
-        {...(dragEnabled ? { ...attributes, ...listeners } : {})}
-      >
-        <GripVertical className="h-4 w-4" />
-      </button>
+      <LineDragHandle {...(dragEnabled ? { ...attributes, ...listeners } : {})} />
       <div className="flex min-w-0 flex-col gap-2 @2xl:contents">
       <div className="flex min-w-0 flex-col gap-2 @2xl:contents">
         <FieldRow label={t('partNumber')}>
         <FieldRow label={t('partNumber')}>
           <div className="flex w-full flex-col gap-1">
           <div className="flex w-full flex-col gap-1">

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

@@ -1462,7 +1462,7 @@ export async function restoreBackup(
             const partItems = q.partItems as Record<string, unknown>[] | undefined
             const partItems = q.partItems as Record<string, unknown>[] | undefined
             if (partItems?.length) {
             if (partItems?.length) {
               await tx.quotePart.createMany({
               await tx.quotePart.createMany({
-                data: partItems.map((p) => ({
+                data: partItems.map((p, index) => ({
                   id: p.id as string,
                   id: p.id as string,
                   partNumber: (p.partNumber as string) || null,
                   partNumber: (p.partNumber as string) || null,
                   name: p.name as string,
                   name: p.name as string,
@@ -1478,6 +1478,9 @@ export async function restoreBackup(
                   // carried into ServicePart on conversion stays intact.
                   // carried into ServicePart on conversion stays intact.
                   inventoryPartId: (p.inventoryPartId as string) || null,
                   inventoryPartId: (p.inventoryPartId as string) || null,
                   taxable: p.taxable !== false,
                   taxable: p.taxable !== false,
+                  // A backup from before lines had an order keeps the order
+                  // it was written in.
+                  sortOrder: numberOr(p.sortOrder, index),
                   quoteId: q.id as string,
                   quoteId: q.id as string,
                 })),
                 })),
               })
               })
@@ -1487,7 +1490,7 @@ export async function restoreBackup(
             const laborItems = q.laborItems as Record<string, unknown>[] | undefined
             const laborItems = q.laborItems as Record<string, unknown>[] | undefined
             if (laborItems?.length) {
             if (laborItems?.length) {
               await tx.quoteLabor.createMany({
               await tx.quoteLabor.createMany({
-                data: laborItems.map((l) => ({
+                data: laborItems.map((l, index) => ({
                   id: l.id as string,
                   id: l.id as string,
                   description: l.description as string,
                   description: l.description as string,
                   hours: (l.hours as number) || 0,
                   hours: (l.hours as number) || 0,
@@ -1498,6 +1501,7 @@ export async function restoreBackup(
                   // came back counted in a total that never included it.
                   // came back counted in a total that never included it.
                   excluded: (l.excluded as boolean) || false,
                   excluded: (l.excluded as boolean) || false,
                   taxable: l.taxable !== false,
                   taxable: l.taxable !== false,
+                  sortOrder: numberOr(l.sortOrder, index),
                   quoteId: q.id as string,
                   quoteId: q.id as string,
                 })),
                 })),
               })
               })