4
0
Эх сурвалжийг харах

Load table rows as you scroll instead of by page (#692)

* Load table rows as you scroll instead of by page

* Keep loading past required relations, long sort values and count sorts; clear selection on list change

* Tell share links of different kinds apart, count-sort in one query, re-read loaded rows after a refresh

* Remove share links in batches of 200, sort admin users by a stable default, drop ticks for rows that left, and pin the booking spec to the start field
Bernt Christian Egeland 1 өдөр өмнө
parent
commit
e275ab9c2d
100 өөрчлөгдсөн 3909 нэмэгдсэн , 143 устгасан
  1. 19 7
      e2e/specs/calendar/booking.spec.ts
  2. 7 0
      messages/bg/common.json
  3. 2 1
      messages/bg/customers.json
  4. 2 1
      messages/bg/inventory.json
  5. 3 2
      messages/bg/settings.json
  6. 1 0
      messages/bg/vehicles.json
  7. 7 0
      messages/de/common.json
  8. 2 1
      messages/de/customers.json
  9. 2 1
      messages/de/inventory.json
  10. 3 2
      messages/de/settings.json
  11. 1 0
      messages/de/vehicles.json
  12. 7 0
      messages/en/common.json
  13. 2 1
      messages/en/customers.json
  14. 2 1
      messages/en/inventory.json
  15. 3 2
      messages/en/settings.json
  16. 1 0
      messages/en/vehicles.json
  17. 7 0
      messages/es/common.json
  18. 2 1
      messages/es/customers.json
  19. 2 1
      messages/es/inventory.json
  20. 3 2
      messages/es/settings.json
  21. 1 0
      messages/es/vehicles.json
  22. 7 0
      messages/fr/common.json
  23. 2 1
      messages/fr/customers.json
  24. 2 1
      messages/fr/inventory.json
  25. 3 2
      messages/fr/settings.json
  26. 1 0
      messages/fr/vehicles.json
  27. 7 0
      messages/it/common.json
  28. 2 1
      messages/it/customers.json
  29. 2 1
      messages/it/inventory.json
  30. 3 2
      messages/it/settings.json
  31. 1 0
      messages/it/vehicles.json
  32. 7 0
      messages/lt/common.json
  33. 2 1
      messages/lt/customers.json
  34. 2 1
      messages/lt/inventory.json
  35. 3 2
      messages/lt/settings.json
  36. 1 0
      messages/lt/vehicles.json
  37. 7 0
      messages/nb/common.json
  38. 2 1
      messages/nb/customers.json
  39. 2 1
      messages/nb/inventory.json
  40. 3 2
      messages/nb/settings.json
  41. 1 0
      messages/nb/vehicles.json
  42. 7 0
      messages/nl/common.json
  43. 2 1
      messages/nl/customers.json
  44. 2 1
      messages/nl/inventory.json
  45. 3 2
      messages/nl/settings.json
  46. 1 0
      messages/nl/vehicles.json
  47. 7 0
      messages/pl/common.json
  48. 2 1
      messages/pl/customers.json
  49. 2 1
      messages/pl/inventory.json
  50. 3 2
      messages/pl/settings.json
  51. 1 0
      messages/pl/vehicles.json
  52. 7 0
      messages/pt-BR/common.json
  53. 2 1
      messages/pt-BR/customers.json
  54. 2 1
      messages/pt-BR/inventory.json
  55. 3 2
      messages/pt-BR/settings.json
  56. 1 0
      messages/pt-BR/vehicles.json
  57. 7 0
      messages/pt-PT/common.json
  58. 2 1
      messages/pt-PT/customers.json
  59. 2 1
      messages/pt-PT/inventory.json
  60. 3 2
      messages/pt-PT/settings.json
  61. 1 0
      messages/pt-PT/vehicles.json
  62. 7 0
      messages/ru/common.json
  63. 2 1
      messages/ru/customers.json
  64. 2 1
      messages/ru/inventory.json
  65. 3 2
      messages/ru/settings.json
  66. 1 0
      messages/ru/vehicles.json
  67. 7 0
      messages/tr/common.json
  68. 2 1
      messages/tr/customers.json
  69. 2 1
      messages/tr/inventory.json
  70. 3 2
      messages/tr/settings.json
  71. 1 0
      messages/tr/vehicles.json
  72. 14 32
      src/__tests__/app/customers/customers-client-delete.test.tsx
  73. 169 0
      src/__tests__/app/customers/customers-selection.test.tsx
  74. 17 9
      src/__tests__/app/labor-presets/labor-presets-client.test.tsx
  75. 74 0
      src/__tests__/app/observations/observations-client.test.tsx
  76. 314 0
      src/__tests__/app/settings/share-links-bulk-revoke.test.tsx
  77. 3 2
      src/__tests__/app/vehicles/vehicle-detail-delete.test.tsx
  78. 9 8
      src/__tests__/app/vehicles/vehicle-detail-dropped-connection.test.tsx
  79. 3 2
      src/__tests__/app/vehicles/vehicle-detail-edit-from-details.test.tsx
  80. 3 2
      src/__tests__/app/vehicles/vehicle-detail-new-work-order.test.tsx
  81. 5 4
      src/__tests__/auth/permission-enforcement.test.ts
  82. 471 0
      src/__tests__/components/infinite-list.test.tsx
  83. 267 0
      src/__tests__/db/count-sort.db.test.ts
  84. 14 8
      src/__tests__/features/admin/account-actions.test.tsx
  85. 215 0
      src/__tests__/features/admin/admin-list-rows.test.ts
  86. 137 0
      src/__tests__/features/audit/get-audit-log-rows.test.ts
  87. 247 0
      src/__tests__/features/billing/billing-rows.test.ts
  88. 85 0
      src/__tests__/features/customers/customer-count-sql.test.ts
  89. 214 0
      src/__tests__/features/customers/get-customer-rows.test.ts
  90. 168 0
      src/__tests__/features/inspections/get-inspection-rows.test.ts
  91. 171 0
      src/__tests__/features/inventory/get-inventory-rows.test.ts
  92. 129 0
      src/__tests__/features/inventory/get-stock-movement-rows.test.ts
  93. 9 2
      src/__tests__/features/inventory/inventory-list-markup.test.tsx
  94. 167 0
      src/__tests__/features/inventory/inventory-selection.test.tsx
  95. 13 8
      src/__tests__/features/inventory/untracked-parts-list.test.tsx
  96. 135 0
      src/__tests__/features/labor-presets/get-labor-preset-rows.test.ts
  97. 179 0
      src/__tests__/features/quotes/get-quote-rows.test.ts
  98. 4 3
      src/__tests__/features/search/equipment-serial-search.test.ts
  99. 247 0
      src/__tests__/features/share-links/get-share-link-rows.test.ts
  100. 197 0
      src/__tests__/features/tire-hotel/get-tire-set-rows.test.ts

+ 19 - 7
e2e/specs/calendar/booking.spec.ts

@@ -32,6 +32,16 @@ const FAR_AWAY = 'Pacific/Auckland'
 let offered = ''
 let jobUrl = ''
 
+/** The work order's start-time field, the one place its start is printed. */
+function startField(page: Page) {
+  return page.getByTestId('schedule-start')
+}
+
+/** The offered time as a pattern, whether the locale writes 10:30 or 10.30. */
+function offeredClock() {
+  return new RegExp(offered.replace('.', '[:.]'))
+}
+
 /** The day column for a date the grid is showing, in day or week view. */
 async function dayColumn(page: Page) {
   const columns = page.locator('[data-testid^="timegrid-day-"]')
@@ -131,10 +141,10 @@ test.describe('booking a job from the calendar', () => {
     jobUrl = page.url()
 
     // The schedule card prints the start as a date and a 24-hour clock, and
-    // the clock has to be the one the calendar offered.
-    await expect(page.getByText(new RegExp(offered.replace('.', '[:.]')))).toBeVisible({
-      timeout: 30_000,
-    })
+    // the clock has to be the one the calendar offered. Read from the start
+    // field itself: the hero's "Opened <date> <time>" is when the job was
+    // created, and a run at that hour of the Auckland day prints the same clock.
+    await expect(startField(page)).toContainText(offeredClock(), { timeout: 30_000 })
 
     await setTitle(page, `E2E booking ${stamp}`)
     await saveWorkOrder(page)
@@ -145,7 +155,7 @@ test.describe('booking a job from the calendar', () => {
     await settle(page)
     // The round trip through the database and back out again, which is where a
     // wall clock gets converted twice and comes back wrong.
-    await expect(page.getByText(new RegExp(offered.replace('.', '[:.]')))).toBeVisible()
+    await expect(startField(page)).toContainText(offeredClock())
   })
 
   test('and the calendar shows it where it put it', async ({ page }) => {
@@ -171,7 +181,9 @@ test.describe('booking a job from the calendar', () => {
 
     await page.goto(jobUrl)
     await settle(page)
-    const shown = await page.locator('body').innerText()
+    const start = startField(page)
+    await expect(start).toContainText(/\d{1,2}[:.]\d{2}/)
+    const shown = await start.innerText()
     expect(
       shown.includes(offered),
       `the start reads differently in another timezone (was ${offered})`
@@ -181,6 +193,6 @@ test.describe('booking a job from the calendar', () => {
     await page.goto(jobUrl)
     await settle(page)
     // And back again: the stored instant never moved.
-    await expect(page.getByText(new RegExp(offered.replace('.', '[:.]')))).toBeVisible()
+    await expect(startField(page)).toContainText(offeredClock())
   })
 })

+ 7 - 0
messages/bg/common.json

@@ -93,6 +93,13 @@
     "next": "Следваща страница",
     "last": "Последна страница"
   },
+  "infiniteList": {
+    "count": "{shown, number} от {total, number}",
+    "countAll": "{total, plural, one {# резултат} other {# резултата}}",
+    "allShown": "Показани са всички {total, number}",
+    "loadFailed": "Не можа да се зареди още",
+    "retry": "Опитай отново"
+  },
   "shared": {
     "close": "Затвори",
     "viewPlans": "Преглед на плановете",

+ 2 - 1
messages/bg/customers.json

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Изтриване на клиенти",
     "batchDeleteDescription": "Да се изтрият ли {count} клиента? Връзката с превозните им средства ще бъде премахната.",
     "batchDeleteSuccess": "Изтрити клиенти: {count}",
-    "openMenu": "Отвори менюто"
+    "openMenu": "Отвори менюто",
+    "selectLoaded": "Избери всички {count, number} показани"
   },
   "detail": {
     "backToCustomers": "Обратно към клиентите",

+ 2 - 1
messages/bg/inventory.json

@@ -41,7 +41,8 @@
     "selected": "Избрани: {count, plural, one {# резервна част} other {# резервни части}}",
     "clearSelection": "Изчисти",
     "deleteSelected": "Изтрий ({count})",
-    "success": "Изтрити: {count, plural, one {# резервна част} other {# резервни части}}"
+    "success": "Изтрити: {count, plural, one {# резервна част} other {# резервни части}}",
+    "selectLoaded": "Избери всички {count, number} показани"
   },
   "markup": {
     "title": "Прилагане на надценка към всички резервни части",

+ 3 - 2
messages/bg/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "Няма връзки, които да отговарят на търсенето.",
       "loadFailed": "Връзките не можаха да бъдат заредени. Презаредете страницата и опитайте отново.",
-      "selectAll": "Избиране на всички връзки на тази страница",
+      "selectAll": "Избиране на всички показани връзки",
       "selectRow": "Избиране на връзката към {document}",
       "selectedCount": "{count, plural, one {Избрана е # връзка} other {Избрани са # връзки}}",
       "clearSelection": "Изчистване на избора",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "Премахване на {count, plural, one {# връзка} other {# връзки}}?",
       "bulkRevokeDescription": "Тези връзки ще престанат да работят за всички, които ги имат. Можете отново да споделите документ, за да създадете нова връзка.",
       "bulkRevoked": "Премахнати са {count, plural, one {# връзка} other {# връзки}}",
-      "bulkRevokeFailed": "Връзките не можаха да бъдат премахнати. Опитайте отново."
+      "bulkRevokeFailed": "Връзките не можаха да бъдат премахнати. Опитайте отново.",
+      "bulkRevokePartial": "Премахнати са {removed} от {total} връзки. Опитайте отново, за да премахнете останалите."
     }
   },
   "meters": {

+ 1 - 0
messages/bg/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Установено в",
     "resolvedIn": "Отстранено в",
     "createWorkOrder": "Създай работна поръчка ({count})",
+    "selectAll": "Избери всички показани",
     "vehicleHasObservations": "Това превозно средство има {count} отворени наблюдения",
     "addToWorkOrder": "Добави към работната поръчка ({count})",
     "dismiss": "Отхвърли",

+ 7 - 0
messages/de/common.json

@@ -100,6 +100,13 @@
     "next": "Nächste Seite",
     "last": "Letzte Seite"
   },
+  "infiniteList": {
+    "count": "{shown, number} von {total, number}",
+    "countAll": "{total, plural, one {# Ergebnis} other {# Ergebnisse}}",
+    "allShown": "Alle {total, number} angezeigt",
+    "loadFailed": "Weitere konnten nicht geladen werden",
+    "retry": "Erneut versuchen"
+  },
   "shared": {
     "close": "Schließen",
     "viewPlans": "Tarife ansehen",

+ 2 - 1
messages/de/customers.json

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Kunden löschen",
     "batchDeleteDescription": "{count} Kunde(n) löschen? Die zugehörigen Fahrzeuge werden dabei entknüpft.",
     "batchDeleteSuccess": "{count} Kunde(n) gelöscht",
-    "openMenu": "Menü öffnen"
+    "openMenu": "Menü öffnen",
+    "selectLoaded": "Alle {count, number} angezeigten auswählen"
   },
   "detail": {
     "backToCustomers": "Zurück zur Kundenliste",

+ 2 - 1
messages/de/inventory.json

@@ -41,7 +41,8 @@
     "selected": "{count, plural, one {# Teil} other {# Teile}} ausgewählt",
     "clearSelection": "Auswahl aufheben",
     "deleteSelected": "Löschen ({count})",
-    "success": "{count, plural, one {# Teil} other {# Teile}} gelöscht"
+    "success": "{count, plural, one {# Teil} other {# Teile}} gelöscht",
+    "selectLoaded": "Alle {count, number} angezeigten auswählen"
   },
   "markup": {
     "title": "Aufschlag auf alle Teile anwenden",

+ 3 - 2
messages/de/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "Keine Links passen zu Ihrer Suche.",
       "loadFailed": "Die Links konnten nicht geladen werden. Laden Sie die Seite neu, um es erneut zu versuchen.",
-      "selectAll": "Alle Links auf dieser Seite auswählen",
+      "selectAll": "Alle angezeigten Links auswählen",
       "selectRow": "Link zu {document} auswählen",
       "selectedCount": "{count, plural, one {# Link ausgewählt} other {# Links ausgewählt}}",
       "clearSelection": "Auswahl aufheben",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "{count, plural, one {# Link entfernen} other {# Links entfernen}}?",
       "bulkRevokeDescription": "Diese Links funktionieren für niemanden mehr, der sie hat. Sie können ein Dokument erneut teilen, um einen neuen Link zu erstellen.",
       "bulkRevoked": "{count, plural, one {# Link entfernt} other {# Links entfernt}}",
-      "bulkRevokeFailed": "Die Links konnten nicht entfernt werden. Versuchen Sie es erneut."
+      "bulkRevokeFailed": "Die Links konnten nicht entfernt werden. Versuchen Sie es erneut.",
+      "bulkRevokePartial": "{removed} von {total} Links entfernt. Versuchen Sie es erneut, um die übrigen zu entfernen."
     }
   },
   "meters": {

+ 1 - 0
messages/de/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Entdeckt in",
     "resolvedIn": "Behoben in",
     "createWorkOrder": "Arbeitsauftrag erstellen ({count})",
+    "selectAll": "Alle angezeigten auswählen",
     "vehicleHasObservations": "Dieses Fahrzeug hat {count} offene Beobachtungen",
     "addToWorkOrder": "Zum Auftrag hinzufügen ({count})",
     "dismiss": "Ausblenden",

+ 7 - 0
messages/en/common.json

@@ -100,6 +100,13 @@
     "next": "Next page",
     "last": "Last page"
   },
+  "infiniteList": {
+    "count": "{shown, number} of {total, number}",
+    "countAll": "{total, plural, one {# result} other {# results}}",
+    "allShown": "All {total, number} shown",
+    "loadFailed": "Couldn't load more",
+    "retry": "Retry"
+  },
   "shared": {
     "close": "Close",
     "viewPlans": "View Plans",

+ 2 - 1
messages/en/customers.json

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Delete Customers",
     "batchDeleteDescription": "Delete {count} customer(s)? This will unlink their vehicles.",
     "batchDeleteSuccess": "{count} customer(s) deleted",
-    "openMenu": "Open menu"
+    "openMenu": "Open menu",
+    "selectLoaded": "Select all {count, number} shown"
   },
   "detail": {
     "backToCustomers": "Back to customers",

+ 2 - 1
messages/en/inventory.json

@@ -41,7 +41,8 @@
     "selected": "{count, plural, one {# part} other {# parts}} selected",
     "clearSelection": "Clear",
     "deleteSelected": "Delete ({count})",
-    "success": "Deleted {count, plural, one {# part} other {# parts}}"
+    "success": "Deleted {count, plural, one {# part} other {# parts}}",
+    "selectLoaded": "Select all {count, number} shown"
   },
   "markup": {
     "title": "Apply Markup to All Parts",

+ 3 - 2
messages/en/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "No links match your search.",
       "loadFailed": "Couldn't load the links. Reload the page to try again.",
-      "selectAll": "Select all links on this page",
+      "selectAll": "Select all links shown",
       "selectRow": "Select the link to {document}",
       "selectedCount": "{count, plural, one {# link selected} other {# links selected}}",
       "clearSelection": "Clear selection",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "Remove {count, plural, one {# link} other {# links}}?",
       "bulkRevokeDescription": "These links stop working for everyone who has them. You can share a document again to make a new link.",
       "bulkRevoked": "{count, plural, one {# link removed} other {# links removed}}",
-      "bulkRevokeFailed": "Couldn't remove the links. Try again."
+      "bulkRevokeFailed": "Couldn't remove the links. Try again.",
+      "bulkRevokePartial": "Removed {removed} of {total} links. Try again to remove the rest."
     }
   },
   "meters": {

+ 1 - 0
messages/en/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Discovered in",
     "resolvedIn": "Resolved in",
     "createWorkOrder": "Create Work Order ({count})",
+    "selectAll": "Select all shown",
     "vehicleHasObservations": "This vehicle has {count} open observations",
     "addToWorkOrder": "Add to Work Order ({count})",
     "dismiss": "Dismiss",

+ 7 - 0
messages/es/common.json

@@ -100,6 +100,13 @@
     "next": "Página siguiente",
     "last": "Última página"
   },
+  "infiniteList": {
+    "count": "{shown, number} de {total, number}",
+    "countAll": "{total, plural, one {# resultado} other {# resultados}}",
+    "allShown": "Se muestran los {total, number}",
+    "loadFailed": "No se pudieron cargar más",
+    "retry": "Reintentar"
+  },
   "shared": {
     "close": "Cerrar",
     "viewPlans": "Ver planes",

+ 2 - 1
messages/es/customers.json

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Eliminar Clientes",
     "batchDeleteDescription": "¿Eliminar {count} cliente(s)? Esto desvinculará sus vehículos.",
     "batchDeleteSuccess": "{count} cliente(s) eliminado(s)",
-    "openMenu": "Abrir menú"
+    "openMenu": "Abrir menú",
+    "selectLoaded": "Seleccionar los {count, number} mostrados"
   },
   "detail": {
     "backToCustomers": "Volver a clientes",

+ 2 - 1
messages/es/inventory.json

@@ -41,7 +41,8 @@
     "selected": "{count, plural, one {# pieza seleccionada} other {# piezas seleccionadas}}",
     "clearSelection": "Limpiar",
     "deleteSelected": "Eliminar ({count})",
-    "success": "{count, plural, one {# pieza eliminada} other {# piezas eliminadas}}"
+    "success": "{count, plural, one {# pieza eliminada} other {# piezas eliminadas}}",
+    "selectLoaded": "Seleccionar los {count, number} mostrados"
   },
   "markup": {
     "title": "Aplicar margen a todas las piezas",

+ 3 - 2
messages/es/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "Ningún enlace coincide con tu búsqueda.",
       "loadFailed": "No se pudieron cargar los enlaces. Recarga la página para volver a intentarlo.",
-      "selectAll": "Seleccionar todos los enlaces de esta página",
+      "selectAll": "Seleccionar todos los enlaces mostrados",
       "selectRow": "Seleccionar el enlace a {document}",
       "selectedCount": "{count, plural, one {# enlace seleccionado} other {# enlaces seleccionados}}",
       "clearSelection": "Borrar selección",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "¿Eliminar {count, plural, one {# enlace} other {# enlaces}}?",
       "bulkRevokeDescription": "Estos enlaces dejan de funcionar para todos los que los tienen. Puedes volver a compartir un documento para crear un enlace nuevo.",
       "bulkRevoked": "{count, plural, one {# enlace eliminado} other {# enlaces eliminados}}",
-      "bulkRevokeFailed": "No se pudieron eliminar los enlaces. Inténtalo de nuevo."
+      "bulkRevokeFailed": "No se pudieron eliminar los enlaces. Inténtalo de nuevo.",
+      "bulkRevokePartial": "Se eliminaron {removed} de {total} enlaces. Inténtalo de nuevo para eliminar el resto."
     }
   },
   "meters": {

+ 1 - 0
messages/es/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Descubierto en",
     "resolvedIn": "Resuelto en",
     "createWorkOrder": "Crear orden de trabajo ({count})",
+    "selectAll": "Seleccionar todas las mostradas",
     "vehicleHasObservations": "Este vehículo tiene {count} observaciones abiertas",
     "addToWorkOrder": "Agregar a la orden ({count})",
     "dismiss": "Descartar",

+ 7 - 0
messages/fr/common.json

@@ -100,6 +100,13 @@
     "next": "Page suivante",
     "last": "Dernière page"
   },
+  "infiniteList": {
+    "count": "{shown, number} sur {total, number}",
+    "countAll": "{total, plural, one {# résultat} other {# résultats}}",
+    "allShown": "Les {total, number} sont affichés",
+    "loadFailed": "Impossible de charger la suite",
+    "retry": "Réessayer"
+  },
   "shared": {
     "close": "Fermer",
     "viewPlans": "Voir les formules",

+ 2 - 1
messages/fr/customers.json

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Supprimer les clients",
     "batchDeleteDescription": "Supprimer {count} client(s) ? Cela dissociera leurs véhicules.",
     "batchDeleteSuccess": "{count} client(s) supprimé(s)",
-    "openMenu": "Ouvrir le menu"
+    "openMenu": "Ouvrir le menu",
+    "selectLoaded": "Sélectionner les {count, number} affichés"
   },
   "detail": {
     "backToCustomers": "Retour aux clients",

+ 2 - 1
messages/fr/inventory.json

@@ -41,7 +41,8 @@
     "selected": "{count, plural, one {# pièce sélectionnée} other {# pièces sélectionnées}}",
     "clearSelection": "Effacer",
     "deleteSelected": "Supprimer ({count})",
-    "success": "{count, plural, one {# pièce supprimée} other {# pièces supprimées}}"
+    "success": "{count, plural, one {# pièce supprimée} other {# pièces supprimées}}",
+    "selectLoaded": "Sélectionner les {count, number} affichés"
   },
   "markup": {
     "title": "Appliquer la marge à toutes les pièces",

+ 3 - 2
messages/fr/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "Aucun lien ne correspond à votre recherche.",
       "loadFailed": "Impossible de charger les liens. Rechargez la page pour réessayer.",
-      "selectAll": "Sélectionner tous les liens de cette page",
+      "selectAll": "Sélectionner tous les liens affichés",
       "selectRow": "Sélectionner le lien vers {document}",
       "selectedCount": "{count, plural, one {# lien sélectionné} other {# liens sélectionnés}}",
       "clearSelection": "Effacer la sélection",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "Supprimer {count, plural, one {# lien} other {# liens}} ?",
       "bulkRevokeDescription": "Ces liens cessent de fonctionner pour toutes les personnes qui les ont. Vous pouvez partager de nouveau un document pour créer un nouveau lien.",
       "bulkRevoked": "{count, plural, one {# lien supprimé} other {# liens supprimés}}",
-      "bulkRevokeFailed": "Impossible de supprimer les liens. Réessayez."
+      "bulkRevokeFailed": "Impossible de supprimer les liens. Réessayez.",
+      "bulkRevokePartial": "{removed} liens sur {total} supprimés. Réessayez pour supprimer les autres."
     }
   },
   "meters": {

+ 1 - 0
messages/fr/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Découvert dans",
     "resolvedIn": "Résolu dans",
     "createWorkOrder": "Créer un ordre de travail ({count})",
+    "selectAll": "Sélectionner toutes celles affichées",
     "vehicleHasObservations": "Ce véhicule a {count} observations en cours",
     "addToWorkOrder": "Ajouter à l'ordre de travail ({count})",
     "dismiss": "Ignorer",

+ 7 - 0
messages/it/common.json

@@ -100,6 +100,13 @@
     "next": "Pagina successiva",
     "last": "Ultima pagina"
   },
+  "infiniteList": {
+    "count": "{shown, number} di {total, number}",
+    "countAll": "{total, plural, one {# risultato} other {# risultati}}",
+    "allShown": "Tutti i {total, number} mostrati",
+    "loadFailed": "Impossibile caricarne altri",
+    "retry": "Riprova"
+  },
   "shared": {
     "close": "Chiudi",
     "viewPlans": "Vedi i piani",

+ 2 - 1
messages/it/customers.json

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Elimina clienti",
     "batchDeleteDescription": "Eliminare {count} cliente/i? I veicoli verranno scollegati.",
     "batchDeleteSuccess": "{count} cliente/i eliminato/i",
-    "openMenu": "Apri menu"
+    "openMenu": "Apri menu",
+    "selectLoaded": "Seleziona tutti i {count, number} visualizzati"
   },
   "detail": {
     "backToCustomers": "Torna ai clienti",

+ 2 - 1
messages/it/inventory.json

@@ -41,7 +41,8 @@
     "selected": "{count, plural, one {# ricambio selezionato} other {# ricambi selezionati}}",
     "clearSelection": "Annulla selezione",
     "deleteSelected": "Elimina ({count})",
-    "success": "{count, plural, one {# ricambio eliminato} other {# ricambi eliminati}}"
+    "success": "{count, plural, one {# ricambio eliminato} other {# ricambi eliminati}}",
+    "selectLoaded": "Seleziona tutti i {count, number} visualizzati"
   },
   "markup": {
     "title": "Applica ricarico a tutti i ricambi",

+ 3 - 2
messages/it/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "Nessun link corrisponde alla ricerca.",
       "loadFailed": "Impossibile caricare i link. Ricarica la pagina per riprovare.",
-      "selectAll": "Seleziona tutti i link di questa pagina",
+      "selectAll": "Seleziona tutti i link mostrati",
       "selectRow": "Seleziona il link a {document}",
       "selectedCount": "{count, plural, one {# link selezionato} other {# link selezionati}}",
       "clearSelection": "Annulla selezione",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "Rimuovere {count, plural, one {# link} other {# link}}?",
       "bulkRevokeDescription": "Questi link smettono di funzionare per chiunque li abbia. Puoi condividere di nuovo un documento per creare un nuovo link.",
       "bulkRevoked": "{count, plural, one {# link rimosso} other {# link rimossi}}",
-      "bulkRevokeFailed": "Impossibile rimuovere i link. Riprova."
+      "bulkRevokeFailed": "Impossibile rimuovere i link. Riprova.",
+      "bulkRevokePartial": "Rimossi {removed} link su {total}. Riprova per rimuovere gli altri."
     }
   },
   "meters": {

+ 1 - 0
messages/it/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Scoperto in",
     "resolvedIn": "Risolto in",
     "createWorkOrder": "Crea ordine di lavoro ({count})",
+    "selectAll": "Seleziona tutte quelle mostrate",
     "vehicleHasObservations": "Questo veicolo ha {count} osservazioni aperte",
     "addToWorkOrder": "Aggiungi all'ordine di lavoro ({count})",
     "dismiss": "Ignora",

+ 7 - 0
messages/lt/common.json

@@ -100,6 +100,13 @@
     "next": "Kitas puslapis",
     "last": "Paskutinis puslapis"
   },
+  "infiniteList": {
+    "count": "{shown, number} iš {total, number}",
+    "countAll": "{total, plural, one {# rezultatas} few {# rezultatai} many {# rezultato} other {# rezultatų}}",
+    "allShown": "Rodomi visi {total, number}",
+    "loadFailed": "Nepavyko įkelti daugiau",
+    "retry": "Bandyti dar kartą"
+  },
   "shared": {
     "close": "Uždaryti",
     "viewPlans": "Peržiūrėti planus",

+ 2 - 1
messages/lt/customers.json

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Ištrinti klientus",
     "batchDeleteDescription": "Ištrinti {count} klientą(-ų)? Bus atsiejamos jų transporto priemonės.",
     "batchDeleteSuccess": "{count} klientas(-ų) ištrintas",
-    "openMenu": "Atidaryti meniu"
+    "openMenu": "Atidaryti meniu",
+    "selectLoaded": "Pažymėti visus {count, number} rodomus"
   },
   "detail": {
     "backToCustomers": "Grįžti prie klientų",

+ 2 - 1
messages/lt/inventory.json

@@ -41,7 +41,8 @@
     "selected": "{count, plural, one {# dalis} other {# dalys}} pasirinkta",
     "clearSelection": "Valyti",
     "deleteSelected": "Ištrinti ({count})",
-    "success": "Ištrinta {count, plural, one {# dalis} other {# dalys}}"
+    "success": "Ištrinta {count, plural, one {# dalis} other {# dalys}}",
+    "selectLoaded": "Pažymėti visus {count, number} rodomus"
   },
   "markup": {
     "title": "Taikyti antkainį visoms dalims",

+ 3 - 2
messages/lt/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "Paieškos atitinkančių nuorodų nėra.",
       "loadFailed": "Nepavyko įkelti nuorodų. Įkelkite puslapį iš naujo ir bandykite dar kartą.",
-      "selectAll": "Pasirinkti visas šio puslapio nuorodas",
+      "selectAll": "Pasirinkti visas rodomas nuorodas",
       "selectRow": "Pasirinkti nuorodą į {document}",
       "selectedCount": "{count, plural, one {Pasirinkta # nuoroda} few {Pasirinktos # nuorodos} many {Pasirinkta # nuorodos} other {Pasirinkta # nuorodų}}",
       "clearSelection": "Išvalyti pasirinkimą",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "Pašalinti {count, plural, one {# nuorodą} few {# nuorodas} many {# nuorodos} other {# nuorodų}}?",
       "bulkRevokeDescription": "Šios nuorodos nustos veikti visiems, kurie jas turi. Norėdami sukurti naują nuorodą, galite dokumentą bendrinti dar kartą.",
       "bulkRevoked": "{count, plural, one {Pašalinta # nuoroda} few {Pašalintos # nuorodos} many {Pašalinta # nuorodos} other {Pašalinta # nuorodų}}",
-      "bulkRevokeFailed": "Nepavyko pašalinti nuorodų. Bandykite dar kartą."
+      "bulkRevokeFailed": "Nepavyko pašalinti nuorodų. Bandykite dar kartą.",
+      "bulkRevokePartial": "Pašalinta nuorodų: {removed} iš {total}. Bandykite dar kartą, kad pašalintumėte likusias."
     }
   },
   "meters": {

+ 1 - 0
messages/lt/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Aptikta",
     "resolvedIn": "Išspręsta",
     "createWorkOrder": "Sukurti darbo užsakymą ({count})",
+    "selectAll": "Pažymėti visus rodomus",
     "vehicleHasObservations": "Ši transporto priemonė turi {count} atvirų pastebėjimų",
     "addToWorkOrder": "Pridėti prie darbo užsakymo ({count})",
     "dismiss": "Atmesti",

+ 7 - 0
messages/nb/common.json

@@ -100,6 +100,13 @@
     "next": "Neste side",
     "last": "Siste side"
   },
+  "infiniteList": {
+    "count": "{shown, number} av {total, number}",
+    "countAll": "{total, plural, one {# treff} other {# treff}}",
+    "allShown": "Alle {total, number} vises",
+    "loadFailed": "Kunne ikke laste flere",
+    "retry": "Prøv igjen"
+  },
   "shared": {
     "close": "Lukk",
     "viewPlans": "Se abonnementer",

+ 2 - 1
messages/nb/customers.json

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Slett kunder",
     "batchDeleteDescription": "Slette {count} kunde(r)? Dette vil koble fra tilknyttede kjøretøy.",
     "batchDeleteSuccess": "{count} kunde(r) slettet",
-    "openMenu": "Åpne meny"
+    "openMenu": "Åpne meny",
+    "selectLoaded": "Velg alle {count, number} som vises"
   },
   "detail": {
     "backToCustomers": "Tilbake til kunder",

+ 2 - 1
messages/nb/inventory.json

@@ -41,7 +41,8 @@
     "selected": "{count, plural, one {# del} other {# deler}} valgt",
     "clearSelection": "Fjern valg",
     "deleteSelected": "Slett ({count})",
-    "success": "{count, plural, one {# del} other {# deler}} slettet"
+    "success": "{count, plural, one {# del} other {# deler}} slettet",
+    "selectLoaded": "Velg alle {count, number} som vises"
   },
   "markup": {
     "title": "Bruk påslag på alle deler",

+ 3 - 2
messages/nb/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "Ingen lenker passer søket ditt.",
       "loadFailed": "Kunne ikke laste lenkene. Last inn siden på nytt for å prøve igjen.",
-      "selectAll": "Velg alle lenkene på denne siden",
+      "selectAll": "Velg alle lenkene som vises",
       "selectRow": "Velg lenken til {document}",
       "selectedCount": "{count, plural, one {# lenke valgt} other {# lenker valgt}}",
       "clearSelection": "Nullstill valg",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "Fjerne {count, plural, one {# lenke} other {# lenker}}?",
       "bulkRevokeDescription": "Disse lenkene slutter å virke for alle som har dem. Du kan dele et dokument på nytt for å lage en ny lenke.",
       "bulkRevoked": "{count, plural, one {# lenke er fjernet} other {# lenker er fjernet}}",
-      "bulkRevokeFailed": "Kunne ikke fjerne lenkene. Prøv igjen."
+      "bulkRevokeFailed": "Kunne ikke fjerne lenkene. Prøv igjen.",
+      "bulkRevokePartial": "Fjernet {removed} av {total} lenker. Prøv igjen for å fjerne resten."
     }
   },
   "meters": {

+ 1 - 0
messages/nb/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Oppdaget i",
     "resolvedIn": "Løst i",
     "createWorkOrder": "Opprett arbeidsordre ({count})",
+    "selectAll": "Velg alle som vises",
     "vehicleHasObservations": "Dette kjøretøyet har {count} åpne observasjoner",
     "addToWorkOrder": "Legg til i arbeidsordre ({count})",
     "dismiss": "Avvis",

+ 7 - 0
messages/nl/common.json

@@ -100,6 +100,13 @@
     "next": "Volgende pagina",
     "last": "Laatste pagina"
   },
+  "infiniteList": {
+    "count": "{shown, number} van {total, number}",
+    "countAll": "{total, plural, one {# resultaat} other {# resultaten}}",
+    "allShown": "Alle {total, number} getoond",
+    "loadFailed": "Kon niet meer laden",
+    "retry": "Opnieuw proberen"
+  },
   "shared": {
     "close": "Sluiten",
     "viewPlans": "Abonnementen bekijken",

+ 2 - 1
messages/nl/customers.json

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Klanten verwijderen",
     "batchDeleteDescription": "{count} klant(en) verwijderen? Hun voertuigen worden ontkoppeld.",
     "batchDeleteSuccess": "{count} klant(en) verwijderd",
-    "openMenu": "Menu openen"
+    "openMenu": "Menu openen",
+    "selectLoaded": "Alle {count, number} getoonde selecteren"
   },
   "detail": {
     "backToCustomers": "Terug naar klanten",

+ 2 - 1
messages/nl/inventory.json

@@ -41,7 +41,8 @@
     "selected": "{count, plural, one {# onderdeel} other {# onderdelen}} geselecteerd",
     "clearSelection": "Wissen",
     "deleteSelected": "Verwijderen ({count})",
-    "success": "{count, plural, one {# onderdeel} other {# onderdelen}} verwijderd"
+    "success": "{count, plural, one {# onderdeel} other {# onderdelen}} verwijderd",
+    "selectLoaded": "Alle {count, number} getoonde selecteren"
   },
   "markup": {
     "title": "Opslag toepassen op alle onderdelen",

+ 3 - 2
messages/nl/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "Geen links gevonden voor je zoekopdracht.",
       "loadFailed": "Kon de links niet laden. Herlaad de pagina om het opnieuw te proberen.",
-      "selectAll": "Alle links op deze pagina selecteren",
+      "selectAll": "Alle getoonde links selecteren",
       "selectRow": "De link naar {document} selecteren",
       "selectedCount": "{count, plural, one {# link geselecteerd} other {# links geselecteerd}}",
       "clearSelection": "Selectie wissen",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "{count, plural, one {# link} other {# links}} verwijderen?",
       "bulkRevokeDescription": "Deze links werken niet meer voor iedereen die ze heeft. Je kunt een document opnieuw delen om een nieuwe link te maken.",
       "bulkRevoked": "{count, plural, one {# link verwijderd} other {# links verwijderd}}",
-      "bulkRevokeFailed": "Kon de links niet verwijderen. Probeer het opnieuw."
+      "bulkRevokeFailed": "Kon de links niet verwijderen. Probeer het opnieuw.",
+      "bulkRevokePartial": "{removed} van {total} links verwijderd. Probeer het opnieuw om de rest te verwijderen."
     }
   },
   "meters": {

+ 1 - 0
messages/nl/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Ontdekt in",
     "resolvedIn": "Opgelost in",
     "createWorkOrder": "Werkorder aanmaken ({count})",
+    "selectAll": "Alle getoonde selecteren",
     "vehicleHasObservations": "Dit voertuig heeft {count} openstaande observaties",
     "addToWorkOrder": "Toevoegen aan werkorder ({count})",
     "dismiss": "Negeren",

+ 7 - 0
messages/pl/common.json

@@ -100,6 +100,13 @@
     "next": "Następna strona",
     "last": "Ostatnia strona"
   },
+  "infiniteList": {
+    "count": "{shown, number} z {total, number}",
+    "countAll": "{total, plural, one {# wynik} few {# wyniki} many {# wyników} other {# wyniku}}",
+    "allShown": "Wyświetlono wszystkie ({total, number})",
+    "loadFailed": "Nie udało się wczytać więcej",
+    "retry": "Spróbuj ponownie"
+  },
   "shared": {
     "close": "Zamknij",
     "viewPlans": "Zobacz plany",

+ 2 - 1
messages/pl/customers.json

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Usuń klientów",
     "batchDeleteDescription": "Usunąć {count} klient(ów)? Spowoduje to odłączenie ich pojazdów.",
     "batchDeleteSuccess": "{count} klient(ów) usunięto",
-    "openMenu": "Otwórz menu"
+    "openMenu": "Otwórz menu",
+    "selectLoaded": "Zaznacz wszystkie wyświetlone ({count, number})"
   },
   "detail": {
     "backToCustomers": "Wróć do klientów",

+ 2 - 1
messages/pl/inventory.json

@@ -41,7 +41,8 @@
     "selected": "{count, plural, one {# część zaznaczona} few {# części zaznaczone} other {# części zaznaczonych}}",
     "clearSelection": "Wyczyść",
     "deleteSelected": "Usuń ({count})",
-    "success": "Usunięto {count, plural, one {# część} few {# części} other {# części}}"
+    "success": "Usunięto {count, plural, one {# część} few {# części} other {# części}}",
+    "selectLoaded": "Zaznacz wszystkie wyświetlone ({count, number})"
   },
   "markup": {
     "title": "Zastosuj marżę do wszystkich części",

+ 3 - 2
messages/pl/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "Żaden link nie pasuje do wyszukiwania.",
       "loadFailed": "Nie udało się wczytać linków. Odśwież stronę, aby spróbować ponownie.",
-      "selectAll": "Zaznacz wszystkie linki na tej stronie",
+      "selectAll": "Zaznacz wszystkie wyświetlone linki",
       "selectRow": "Zaznacz link do {document}",
       "selectedCount": "{count, plural, one {Zaznaczono # link} few {Zaznaczono # linki} many {Zaznaczono # linków} other {Zaznaczono # linku}}",
       "clearSelection": "Wyczyść zaznaczenie",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "Usunąć {count, plural, one {# link} few {# linki} many {# linków} other {# linku}}?",
       "bulkRevokeDescription": "Te linki przestaną działać dla wszystkich, którzy je mają. Możesz udostępnić dokument ponownie, aby utworzyć nowy link.",
       "bulkRevoked": "{count, plural, one {Usunięto # link} few {Usunięto # linki} many {Usunięto # linków} other {Usunięto # linku}}",
-      "bulkRevokeFailed": "Nie udało się usunąć linków. Spróbuj ponownie."
+      "bulkRevokeFailed": "Nie udało się usunąć linków. Spróbuj ponownie.",
+      "bulkRevokePartial": "Usunięto linki: {removed} z {total}. Spróbuj ponownie, aby usunąć pozostałe."
     }
   },
   "meters": {

+ 1 - 0
messages/pl/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Odkryto w",
     "resolvedIn": "Rozwiązano w",
     "createWorkOrder": "Utwórz zlecenie ({count})",
+    "selectAll": "Zaznacz wszystkie widoczne",
     "vehicleHasObservations": "Ten pojazd ma {count} otwartych obserwacji",
     "addToWorkOrder": "Dodaj do zlecenia ({count})",
     "dismiss": "Odrzuć",

+ 7 - 0
messages/pt-BR/common.json

@@ -100,6 +100,13 @@
     "next": "Próxima página",
     "last": "Última página"
   },
+  "infiniteList": {
+    "count": "{shown, number} de {total, number}",
+    "countAll": "{total, plural, one {# resultado} other {# resultados}}",
+    "allShown": "Todos os {total, number} exibidos",
+    "loadFailed": "Não foi possível carregar mais",
+    "retry": "Tentar novamente"
+  },
   "shared": {
     "close": "Fechar",
     "viewPlans": "Ver planos",

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

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Excluir Clientes",
     "batchDeleteDescription": "Excluir {count} cliente(s)? Os veículos vinculados serão desassociados.",
     "batchDeleteSuccess": "{count} cliente(s) excluído(s)",
-    "openMenu": "Abrir menu"
+    "openMenu": "Abrir menu",
+    "selectLoaded": "Selecionar todos os {count, number} exibidos"
   },
   "detail": {
     "backToCustomers": "Voltar para clientes",

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

@@ -41,7 +41,8 @@
     "selected": "{count, plural, one {# peça selecionada} other {# peças selecionadas}}",
     "clearSelection": "Limpar",
     "deleteSelected": "Excluir ({count})",
-    "success": "{count, plural, one {# peça excluída} other {# peças excluídas}}"
+    "success": "{count, plural, one {# peça excluída} other {# peças excluídas}}",
+    "selectLoaded": "Selecionar todos os {count, number} exibidos"
   },
   "markup": {
     "title": "Aplicar margem a todas as peças",

+ 3 - 2
messages/pt-BR/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "Nenhum link corresponde à sua busca.",
       "loadFailed": "Não foi possível carregar os links. Recarregue a página para tentar novamente.",
-      "selectAll": "Selecionar todos os links desta página",
+      "selectAll": "Selecionar todos os links exibidos",
       "selectRow": "Selecionar o link para {document}",
       "selectedCount": "{count, plural, one {# link selecionado} other {# links selecionados}}",
       "clearSelection": "Limpar seleção",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "Remover {count, plural, one {# link} other {# links}}?",
       "bulkRevokeDescription": "Esses links deixam de funcionar para todos que os têm. Você pode compartilhar um documento de novo para criar um novo link.",
       "bulkRevoked": "{count, plural, one {# link removido} other {# links removidos}}",
-      "bulkRevokeFailed": "Não foi possível remover os links. Tente novamente."
+      "bulkRevokeFailed": "Não foi possível remover os links. Tente novamente.",
+      "bulkRevokePartial": "{removed} de {total} links removidos. Tente novamente para remover os restantes."
     }
   },
   "meters": {

+ 1 - 0
messages/pt-BR/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Descoberto em",
     "resolvedIn": "Resolvido em",
     "createWorkOrder": "Criar ordem de serviço ({count})",
+    "selectAll": "Selecionar todas as exibidas",
     "vehicleHasObservations": "Este veículo tem {count} observações em aberto",
     "addToWorkOrder": "Adicionar à ordem de serviço ({count})",
     "dismiss": "Dispensar",

+ 7 - 0
messages/pt-PT/common.json

@@ -100,6 +100,13 @@
     "next": "Página seguinte",
     "last": "Última página"
   },
+  "infiniteList": {
+    "count": "{shown, number} de {total, number}",
+    "countAll": "{total, plural, one {# resultado} other {# resultados}}",
+    "allShown": "Todos os {total, number} apresentados",
+    "loadFailed": "Não foi possível carregar mais",
+    "retry": "Tentar novamente"
+  },
   "shared": {
     "close": "Fechar",
     "viewPlans": "Ver planos",

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

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Eliminar Clientes",
     "batchDeleteDescription": "Eliminar {count} cliente(s)? As viaturas associadas deixarão de estar ligadas a estes clientes.",
     "batchDeleteSuccess": "{count} cliente(s) eliminado(s)",
-    "openMenu": "Abrir menu"
+    "openMenu": "Abrir menu",
+    "selectLoaded": "Selecionar todos os {count, number} apresentados"
   },
   "detail": {
     "backToCustomers": "Voltar aos clientes",

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

@@ -41,7 +41,8 @@
     "selected": "{count, plural, one {# peça selecionada} other {# peças selecionadas}}",
     "clearSelection": "Limpar",
     "deleteSelected": "Eliminar ({count})",
-    "success": "{count, plural, one {# peça eliminada} other {# peças eliminadas}}"
+    "success": "{count, plural, one {# peça eliminada} other {# peças eliminadas}}",
+    "selectLoaded": "Selecionar todos os {count, number} apresentados"
   },
   "markup": {
     "title": "Aplicar margem a todas as peças",

+ 3 - 2
messages/pt-PT/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "Nenhum link corresponde à sua pesquisa.",
       "loadFailed": "Não foi possível carregar os links. Recarregue a página para tentar novamente.",
-      "selectAll": "Selecionar todos os links desta página",
+      "selectAll": "Selecionar todos os links apresentados",
       "selectRow": "Selecionar o link para {document}",
       "selectedCount": "{count, plural, one {# link selecionado} other {# links selecionados}}",
       "clearSelection": "Limpar seleção",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "Remover {count, plural, one {# link} other {# links}}?",
       "bulkRevokeDescription": "Estes links deixam de funcionar para todos os que os têm. Pode voltar a partilhar um documento para criar um novo link.",
       "bulkRevoked": "{count, plural, one {# link removido} other {# links removidos}}",
-      "bulkRevokeFailed": "Não foi possível remover os links. Tente novamente."
+      "bulkRevokeFailed": "Não foi possível remover os links. Tente novamente.",
+      "bulkRevokePartial": "{removed} de {total} links removidos. Tente novamente para remover os restantes."
     }
   },
   "meters": {

+ 1 - 0
messages/pt-PT/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Detetada em",
     "resolvedIn": "Resolvida em",
     "createWorkOrder": "Criar ordem de serviço ({count})",
+    "selectAll": "Selecionar todas as apresentadas",
     "vehicleHasObservations": "Esta viatura tem {count} observações em aberto",
     "addToWorkOrder": "Adicionar à ordem de serviço ({count})",
     "dismiss": "Ignorar",

+ 7 - 0
messages/ru/common.json

@@ -100,6 +100,13 @@
     "next": "Следующая страница",
     "last": "Последняя страница"
   },
+  "infiniteList": {
+    "count": "{shown, number} из {total, number}",
+    "countAll": "{total, plural, one {# результат} few {# результата} many {# результатов} other {# результата}}",
+    "allShown": "Показаны все ({total, number})",
+    "loadFailed": "Не удалось загрузить ещё",
+    "retry": "Повторить"
+  },
   "shared": {
     "close": "Закрыть",
     "viewPlans": "Посмотреть тарифы",

+ 2 - 1
messages/ru/customers.json

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Удалить клиентов",
     "batchDeleteDescription": "Удалить клиентов ({count})? Транспортные средства будут отвязаны.",
     "batchDeleteSuccess": "Удалено клиентов: {count}",
-    "openMenu": "Открыть меню"
+    "openMenu": "Открыть меню",
+    "selectLoaded": "Выбрать все показанные ({count, number})"
   },
   "detail": {
     "backToCustomers": "К списку клиентов",

+ 2 - 1
messages/ru/inventory.json

@@ -41,7 +41,8 @@
     "selected": "{count, plural, one {# деталь выбрана} few {# детали выбраны} other {# деталей выбрано}}",
     "clearSelection": "Сбросить",
     "deleteSelected": "Удалить ({count})",
-    "success": "{count, plural, one {# деталь удалена} few {# детали удалены} other {# деталей удалено}}"
+    "success": "{count, plural, one {# деталь удалена} few {# детали удалены} other {# деталей удалено}}",
+    "selectLoaded": "Выбрать все показанные ({count, number})"
   },
   "markup": {
     "title": "Применить наценку ко всем запчастям",

+ 3 - 2
messages/ru/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "По вашему запросу ссылок не найдено.",
       "loadFailed": "Не удалось загрузить ссылки. Перезагрузите страницу, чтобы попробовать ещё раз.",
-      "selectAll": "Выбрать все ссылки на этой странице",
+      "selectAll": "Выбрать все показанные ссылки",
       "selectRow": "Выбрать ссылку на {document}",
       "selectedCount": "{count, plural, one {Выбрана # ссылка} few {Выбрано # ссылки} many {Выбрано # ссылок} other {Выбрано # ссылки}}",
       "clearSelection": "Снять выбор",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "Удалить {count, plural, one {# ссылку} few {# ссылки} many {# ссылок} other {# ссылки}}?",
       "bulkRevokeDescription": "Эти ссылки перестанут работать для всех, у кого они есть. Чтобы создать новую ссылку, поделитесь документом ещё раз.",
       "bulkRevoked": "{count, plural, one {Удалена # ссылка} few {Удалено # ссылки} many {Удалено # ссылок} other {Удалено # ссылки}}",
-      "bulkRevokeFailed": "Не удалось удалить ссылки. Попробуйте ещё раз."
+      "bulkRevokeFailed": "Не удалось удалить ссылки. Попробуйте ещё раз.",
+      "bulkRevokePartial": "Удалено ссылок: {removed} из {total}. Попробуйте ещё раз, чтобы удалить остальные."
     }
   },
   "meters": {

+ 1 - 0
messages/ru/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Обнаружено в",
     "resolvedIn": "Решено в",
     "createWorkOrder": "Создать заказ-наряд ({count})",
+    "selectAll": "Выбрать все показанные",
     "vehicleHasObservations": "У этого транспортного средства {count} открытых наблюдений",
     "addToWorkOrder": "Добавить в заказ-наряд ({count})",
     "dismiss": "Скрыть",

+ 7 - 0
messages/tr/common.json

@@ -100,6 +100,13 @@
     "next": "Sonraki sayfa",
     "last": "Son sayfa"
   },
+  "infiniteList": {
+    "count": "{shown, number} / {total, number}",
+    "countAll": "{total, plural, one {# sonuç} other {# sonuç}}",
+    "allShown": "{total, number} kaydın tümü gösteriliyor",
+    "loadFailed": "Daha fazlası yüklenemedi",
+    "retry": "Tekrar dene"
+  },
   "shared": {
     "close": "Kapat",
     "viewPlans": "Planlara bak",

+ 2 - 1
messages/tr/customers.json

@@ -27,7 +27,8 @@
     "batchDeleteTitle": "Müşterileri Sil",
     "batchDeleteDescription": "{count} müşteri silinsin mi? Bu işlem araçlarının bağlantısını kaldıracaktır.",
     "batchDeleteSuccess": "{count} müşteri silindi",
-    "openMenu": "Menüyü aç"
+    "openMenu": "Menüyü aç",
+    "selectLoaded": "Gösterilen {count, number} öğenin tümünü seç"
   },
   "detail": {
     "backToCustomers": "Müşterilere dön",

+ 2 - 1
messages/tr/inventory.json

@@ -41,7 +41,8 @@
     "selected": "{count, plural, one {# parça} other {# parça}} seçili",
     "clearSelection": "Temizle",
     "deleteSelected": "Sil ({count})",
-    "success": "{count, plural, one {# parça} other {# parça}} silindi"
+    "success": "{count, plural, one {# parça} other {# parça}} silindi",
+    "selectLoaded": "Gösterilen {count, number} öğenin tümünü seç"
   },
   "markup": {
     "title": "Tüm parçalara kâr marjı uygula",

+ 3 - 2
messages/tr/settings.json

@@ -3354,7 +3354,7 @@
       },
       "emptyFiltered": "Aramanızla eşleşen bağlantı yok.",
       "loadFailed": "Bağlantılar yüklenemedi. Tekrar denemek için sayfayı yenileyin.",
-      "selectAll": "Bu sayfadaki tüm bağlantıları seç",
+      "selectAll": "Gösterilen tüm bağlantıları seç",
       "selectRow": "{document} bağlantısını seç",
       "selectedCount": "{count, plural, one {# bağlantı seçildi} other {# bağlantı seçildi}}",
       "clearSelection": "Seçimi temizle",
@@ -3362,7 +3362,8 @@
       "bulkRevokeTitle": "{count, plural, one {# bağlantı} other {# bağlantı}} kaldırılsın mı?",
       "bulkRevokeDescription": "Bu bağlantılar, onlara sahip olan herkes için çalışmayı bırakır. Yeni bir bağlantı oluşturmak için bir belgeyi yeniden paylaşabilirsiniz.",
       "bulkRevoked": "{count, plural, one {# bağlantı kaldırıldı} other {# bağlantı kaldırıldı}}",
-      "bulkRevokeFailed": "Bağlantılar kaldırılamadı. Tekrar deneyin."
+      "bulkRevokeFailed": "Bağlantılar kaldırılamadı. Tekrar deneyin.",
+      "bulkRevokePartial": "{total} bağlantıdan {removed} tanesi kaldırıldı. Kalanları kaldırmak için tekrar deneyin."
     }
   },
   "meters": {

+ 1 - 0
messages/tr/vehicles.json

@@ -324,6 +324,7 @@
     "discoveredIn": "Keşfedildiği iş emri",
     "resolvedIn": "Çözüldüğü iş emri",
     "createWorkOrder": "İş emri oluştur ({count})",
+    "selectAll": "Gösterilenlerin tümünü seç",
     "vehicleHasObservations": "Bu araçta {count} açık gözlem var",
     "addToWorkOrder": "İş emrine ekle ({count})",
     "dismiss": "Kapat",

+ 14 - 32
src/__tests__/app/customers/customers-client-delete.test.tsx

@@ -29,6 +29,9 @@ vi.mock('@/features/customers/Actions/customerActions', () => ({
 vi.mock('@/features/customers/Components/CustomerForm', () => ({ CustomerForm: () => null }))
 vi.mock('@/features/import/Components/ImportWizard', () => ({ ImportWizard: () => null }))
 
+vi.mock('@/features/customers/Actions/getCustomerRows', () => ({ getCustomerRows: vi.fn() }))
+
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
 import { CustomersClient } from '@/app/(authenticated)/customers/customers-client'
 
 const CUSTOMER = {
@@ -47,15 +50,17 @@ const CUSTOMER = {
 
 function renderList() {
   render(
-    <ConfirmProvider>
-      <CustomersClient
-        data={{ customers: [CUSTOMER], total: 1, page: 1, pageSize: 20, totalPages: 1 }}
-        search=""
-        sortBy="name"
-        sortOrder="asc"
-      />
-      <GlassModal />
-    </ConfirmProvider>
+    <QueryClientProvider client={new QueryClient()}>
+      <ConfirmProvider>
+        <CustomersClient
+          data={{ rows: [CUSTOMER], nextCursor: null, total: 1, renderId: 'render-1' }}
+          search=""
+          sortBy="name"
+          sortOrder="asc"
+        />
+        <GlassModal />
+      </ConfirmProvider>
+    </QueryClientProvider>
   )
 }
 
@@ -102,27 +107,4 @@ describe('customer list deletes', () => {
     // there to try again once the message is closed.
     expect(screen.getByRole('button', { name: 'Delete (1)', hidden: true })).toBeEnabled()
   })
-
-  it('still names a selected customer in the question after moving to another page', async () => {
-    const page = (customers: (typeof CUSTOMER)[], n: number) => (
-      <ConfirmProvider>
-        <CustomersClient
-          data={{ customers, total: 21, page: n, pageSize: 20, totalPages: 2 }}
-          search=""
-          sortBy="name"
-          sortOrder="asc"
-        />
-      </ConfirmProvider>
-    )
-    const { rerender } = render(page([CUSTOMER], 1))
-    fireEvent.click(screen.getAllByRole('checkbox')[0])
-
-    // Page two: Ada is no longer among the rows, but is still selected.
-    rerender(page([{ ...CUSTOMER, id: 'c2', customerNumber: '1002', name: 'Bo Lind' }], 2))
-    fireEvent.click(screen.getByRole('button', { name: 'Delete (1)' }))
-
-    const question = await screen.findByRole('alertdialog')
-    expect(within(question).getByText('Ada Berg')).toBeInTheDocument()
-    expect(within(question).queryByText('Bo Lind')).not.toBeInTheDocument()
-  })
 })

+ 169 - 0
src/__tests__/app/customers/customers-selection.test.tsx

@@ -0,0 +1,169 @@
+/**
+ * Ticking customers in a list that loads more as it scrolls.
+ *
+ * The header box takes the customers loaded so far and says how many, a
+ * bulk delete never reaches one that has not loaded, ticks stay while more
+ * rows arrive, and another search or sort starts with nothing ticked.
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+
+const deleteCustomers = vi.fn()
+const getCustomerRows = vi.fn()
+const router = { push: vi.fn(), refresh: vi.fn() }
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => router,
+  usePathname: () => '/customers',
+  useSearchParams: () => new URLSearchParams(),
+}))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/features/customers/Actions/customerActions', () => ({
+  backfillCustomerNumbers: vi.fn(),
+  deleteCustomer: vi.fn(),
+  deleteCustomers: async (ids: string[]) => deleteCustomers(ids),
+}))
+vi.mock('@/features/customers/Actions/getCustomerRows', () => ({
+  getCustomerRows: (input: unknown) => getCustomerRows(input),
+}))
+vi.mock('@/features/customers/Components/CustomerForm', () => ({ CustomerForm: () => null }))
+vi.mock('@/features/import/Components/ImportWizard', () => ({ ImportWizard: () => null }))
+
+import { CustomersClient } from '@/app/(authenticated)/customers/customers-client'
+
+// The end of the list coming into sight is an IntersectionObserver's call.
+const observers: { callback: IntersectionObserverCallback; observer: IntersectionObserver }[] = []
+class FakeObserver {
+  constructor(public callback: IntersectionObserverCallback) {
+    observers.push({ callback, observer: this as unknown as IntersectionObserver })
+  }
+  observe() {
+    // The test says when the end is in sight.
+  }
+  unobserve() {
+    // As above.
+  }
+  disconnect() {
+    // As above.
+  }
+  takeRecords() {
+    return []
+  }
+}
+function endInSight() {
+  act(() => {
+    for (const { callback, observer } of observers) {
+      callback([{ isIntersecting: true } as IntersectionObserverEntry], observer)
+    }
+  })
+}
+
+function customer(i: number) {
+  return {
+    id: `c${i}`,
+    customerNumber: String(1000 + i),
+    name: `Customer ${i}`,
+    email: null,
+    phone: null,
+    address: null,
+    company: null,
+    taxId: null,
+    taxExempt: false,
+    notes: null,
+    _count: { vehicles: 0 },
+  }
+}
+// Small batches keep the render quick; the list does not care how big they are.
+const all = Array.from({ length: 16 }, (_, i) => customer(i + 1))
+const firstBatch = {
+  rows: all.slice(0, 10),
+  nextCursor: { v: ['x'], id: 'c10' },
+  total: 16,
+  renderId: 'render-1',
+}
+
+let client: QueryClient
+function list(search = '') {
+  return (
+    <QueryClientProvider client={client}>
+      <ConfirmProvider>
+        <CustomersClient
+          data={firstBatch}
+          listScope="org-1"
+          search={search}
+          sortBy="name"
+          sortOrder="asc"
+        />
+      </ConfirmProvider>
+    </QueryClientProvider>
+  )
+}
+
+/** The header box of the table. */
+const headerBox = () => screen.getByRole('checkbox', { name: 'Select all 10 shown' })
+
+beforeEach(() => {
+  observers.length = 0
+  vi.stubGlobal('IntersectionObserver', FakeObserver)
+  client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+  deleteCustomers.mockReset().mockResolvedValue({ success: true, data: { deleted: 0 } })
+  getCustomerRows
+    .mockReset()
+    .mockResolvedValue({ success: true, data: { rows: all.slice(10), nextCursor: null } })
+})
+
+afterEach(() => {
+  vi.unstubAllGlobals()
+  client.clear()
+})
+
+describe('selecting customers in the scrolling list', () => {
+  it('selects only the customers loaded so far, and says how many', async () => {
+    render(list())
+    expect(screen.getByText('10 of 16')).toBeInTheDocument()
+
+    fireEvent.click(headerBox())
+    expect(screen.getByText('10 selected')).toBeInTheDocument()
+
+    fireEvent.click(screen.getByRole('button', { name: 'Delete (10)' }))
+    const question = await screen.findByRole('alertdialog')
+    await act(async () => {
+      fireEvent.click(within(question).getByRole('button', { name: 'Delete' }))
+    })
+    expect(deleteCustomers).toHaveBeenCalledWith(all.slice(0, 10).map((c) => c.id))
+  })
+
+  it('keeps the ticks while more rows load, and leaves the new ones unticked', async () => {
+    render(list())
+    fireEvent.click(headerBox())
+
+    endInSight()
+    // Each customer shows twice in jsdom: the phone card and the table row.
+    await waitFor(() => expect(screen.getAllByText('Customer 16')).not.toHaveLength(0))
+
+    expect(screen.getByText('10 selected')).toBeInTheDocument()
+    const header = screen.getByRole('checkbox', { name: 'Select all 16 shown' })
+    expect(header).toHaveAttribute('data-state', 'indeterminate')
+    const newRow = screen.getAllByRole('checkbox', { name: 'Select Customer 16' })[0]
+    expect(newRow).toHaveAttribute('data-state', 'unchecked')
+
+    // Ticking the header again takes everything now loaded.
+    fireEvent.click(header)
+    expect(screen.getByText('16 selected')).toBeInTheDocument()
+  })
+
+  it('starts another search with nothing selected', () => {
+    const { rerender } = render(list())
+    fireEvent.click(screen.getAllByRole('checkbox', { name: 'Select Customer 3' })[0])
+    expect(screen.getByText('1 selected')).toBeInTheDocument()
+
+    rerender(list('volvo'))
+    expect(screen.queryByText('1 selected')).not.toBeInTheDocument()
+    expect(screen.getAllByRole('checkbox', { name: 'Select Customer 3' })[0]).toHaveAttribute(
+      'data-state',
+      'unchecked'
+    )
+  })
+})

+ 17 - 9
src/__tests__/app/labor-presets/labor-presets-client.test.tsx

@@ -6,6 +6,7 @@
  * The list only read the answer, so on a weak connection Delete did nothing
  * anyone could see and people pressed it again and again.
  */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
 import { act, fireEvent, render, screen, within } from '@testing-library/react'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
 import { ConfirmProvider } from '@/components/confirm-dialog'
@@ -27,6 +28,11 @@ vi.mock('@/features/labor-presets/Actions/laborPresetActions', () => ({
   getLaborPreset: (id: string) => getLaborPreset(id),
 }))
 
+// The list's first batch is all there is here; nothing more is asked for.
+vi.mock('@/features/labor-presets/Actions/getLaborPresetRows', () => ({
+  getLaborPresetRows: vi.fn(),
+}))
+
 // The form is its own screen; here it only has to show that it opened.
 vi.mock('@/features/labor-presets/Components/LaborPresetForm', () => ({
   LaborPresetForm: ({ open, preset }: { open: boolean; preset?: { name: string } }) =>
@@ -51,15 +57,17 @@ const PRESET = {
 
 function renderList() {
   render(
-    <ConfirmProvider>
-      <LaborPresetsClient
-        data={{ presets: [PRESET], total: 1, page: 1, pageSize: 20, totalPages: 1 }}
-        search=""
-        sortBy="name"
-        sortOrder="asc"
-      />
-      <GlassModal />
-    </ConfirmProvider>
+    <QueryClientProvider client={new QueryClient()}>
+      <ConfirmProvider>
+        <LaborPresetsClient
+          data={{ rows: [PRESET], nextCursor: null, total: 1, renderId: 'render-1' }}
+          search=""
+          sortBy="name"
+          sortOrder="asc"
+        />
+        <GlassModal />
+      </ConfirmProvider>
+    </QueryClientProvider>
   )
 }
 

+ 74 - 0
src/__tests__/app/observations/observations-client.test.tsx

@@ -0,0 +1,74 @@
+/**
+ * The observations list shows open observations unless told otherwise, and
+ * its status dropdown says so. Picking "All statuses" has to stay in the
+ * address as ?status=all, or the page would read the missing status as
+ * "Open" again and the choice would not stick.
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { fireEvent, render, screen } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const router = { push: vi.fn(), refresh: vi.fn() }
+let searchParams = new URLSearchParams()
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => router,
+  usePathname: () => '/observations',
+  useSearchParams: () => searchParams,
+}))
+
+// The first batch is all there is here; nothing more is asked for.
+vi.mock('@/features/vehicles/Actions/getObservationRows', () => ({
+  getObservationRows: vi.fn(),
+}))
+
+import { ObservationsClient } from '@/app/(authenticated)/observations/observations-client'
+
+function renderList(statusFilter: string) {
+  render(
+    <QueryClientProvider client={new QueryClient()}>
+      <ObservationsClient
+        data={{ rows: [], nextCursor: null, total: 0, renderId: 'render-1' }}
+        search=""
+        statusFilter={statusFilter}
+        severityFilter="all"
+      />
+    </QueryClientProvider>
+  )
+}
+
+/** The status dropdown is the first of the two. */
+const statusDropdown = () => screen.getAllByRole('combobox')[0]
+
+async function pickStatus(name: string) {
+  fireEvent.keyDown(statusDropdown(), { key: 'Enter' })
+  fireEvent.click(await screen.findByRole('option', { name }))
+}
+
+beforeEach(() => {
+  router.push.mockReset()
+  searchParams = new URLSearchParams()
+  // Radix Select asks for these, which jsdom does not have.
+  Element.prototype.hasPointerCapture ??= () => false
+  Element.prototype.releasePointerCapture ??= vi.fn()
+  Element.prototype.scrollIntoView ??= vi.fn()
+})
+
+describe('the observations status filter', () => {
+  it('keeps "All statuses" in the address, since no status means open', async () => {
+    renderList('open')
+    expect(statusDropdown()).toHaveTextContent('Open')
+
+    await pickStatus('All Statuses')
+    expect(router.push).toHaveBeenCalledWith('/observations?status=all')
+  })
+
+  it('drops the status from the address when going back to open', async () => {
+    searchParams = new URLSearchParams('status=all')
+    renderList('all')
+    expect(statusDropdown()).toHaveTextContent('All Statuses')
+
+    await pickStatus('Open')
+    expect(router.push).toHaveBeenCalledWith('/observations?')
+  })
+})

+ 314 - 0
src/__tests__/app/settings/share-links-bulk-revoke.test.tsx

@@ -0,0 +1,314 @@
+/**
+ * Removing several share links at once, now that the list loads as it
+ * scrolls. The header box ticks the links loaded so far; links that arrive
+ * later come unticked, the ticks already made stay, and Remove selected
+ * removes exactly the ticked ones.
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, fireEvent, render, screen, within } from '@testing-library/react'
+import { toast } from 'sonner'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { ConfirmProvider } from '@/components/confirm-dialog'
+
+const getShareLinkRows = vi.fn()
+const revokeShareLinks = vi.fn()
+const router = { push: vi.fn(), refresh: vi.fn() }
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => router,
+  usePathname: () => '/settings/share-links',
+  useSearchParams: () => new URLSearchParams(),
+}))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/features/share-links/Actions/getShareLinkRows', () => ({
+  getShareLinkRows: (input: unknown) => getShareLinkRows(input),
+}))
+vi.mock('@/features/share-links/Actions/revokeShareLinks', () => ({
+  revokeShareLinks: (input: unknown) => revokeShareLinks(input),
+}))
+vi.mock('@/features/settings/Actions/settingsActions', () => ({ setSettings: vi.fn() }))
+vi.mock('@/features/vehicles/Actions/serviceActions', () => ({ revokePublicLink: vi.fn() }))
+vi.mock('@/features/quotes/Actions/quoteShareActions', () => ({ revokeQuotePublicLink: vi.fn() }))
+vi.mock('@/features/inspections/Actions/inspectionShareActions', () => ({
+  revokeInspectionPublicLink: vi.fn(),
+}))
+// The expiry cell is its own control; here it only has to stay out of the way.
+vi.mock('@/features/share-links/Components/ShareExpiryControl', () => ({
+  ShareExpiryControl: () => null,
+  useShareExpiryText: () => () => '',
+}))
+
+import { ShareLinksSettings } from '@/app/(authenticated)/settings/share-links/share-links-settings'
+
+// The end of the list coming into sight is an IntersectionObserver's call.
+const observers: { callback: IntersectionObserverCallback; observer: IntersectionObserver }[] = []
+class FakeObserver {
+  constructor(public callback: IntersectionObserverCallback) {
+    observers.push({ callback, observer: this as unknown as IntersectionObserver })
+  }
+  observe() {
+    // The test says when the end is in sight.
+  }
+  unobserve() {
+    // As above.
+  }
+  disconnect() {
+    // As above.
+  }
+  takeRecords() {
+    return []
+  }
+}
+
+function endInSight() {
+  act(() => {
+    for (const { callback, observer } of observers) {
+      callback([{ isIntersecting: true } as IntersectionObserverEntry], observer)
+    }
+  })
+}
+
+function link(i: number) {
+  return {
+    kind: 'invoice' as const,
+    id: `inv-${String(i).padStart(3, '0')}`,
+    token: `t${i}`,
+    label: `INV-${i}`,
+    detail: '',
+    customer: 'Kari Nordmann',
+    href: `/sales/inv-${i}`,
+    sharedAt: new Date(Date.UTC(2026, 10, 1, 0, 0, 200 - i)).toISOString(),
+    viewCount: 0,
+    expiry: { expired: false } as never,
+  }
+}
+
+const first = {
+  organizationId: 'org-1',
+  rows: Array.from({ length: 50 }, (_, i) => link(i)),
+  nextCursor: { v: [link(49).sharedAt], id: 'invoice:inv-049' },
+  total: 70,
+  counts: { active: 70, expired: 0 },
+  renderId: 'render-1',
+}
+const second = {
+  organizationId: 'org-1',
+  rows: Array.from({ length: 20 }, (_, i) => link(50 + i)),
+  nextCursor: null,
+}
+
+const RULES = {
+  invoice: { mode: 'never', days: 30 },
+  quote: { mode: 'never', days: 30 },
+  inspection: { mode: 'never', days: 30 },
+} as const
+
+type Filters = { status: string; kind: string; search: string }
+const ALL: Filters = { status: 'active', kind: 'all', search: '' }
+
+function renderPage(firstBatch: typeof first = first) {
+  const client = new QueryClient()
+  const page = (links: typeof first, filters: Filters) => (
+    <QueryClientProvider client={client}>
+      <ConfirmProvider>
+        <ShareLinksSettings
+          rules={RULES}
+          links={links}
+          baseUrl="https://app.example"
+          filters={filters}
+        />
+      </ConfirmProvider>
+    </QueryClientProvider>
+  )
+  const view = render(page(firstBatch, ALL))
+  return {
+    /** The server page again, as a filter, search or sort change renders it. */
+    show: (filters: Filters) => view.rerender(page({ ...first, rows: [...first.rows] }, filters)),
+  }
+}
+
+beforeEach(() => {
+  observers.length = 0
+  vi.stubGlobal('IntersectionObserver', FakeObserver)
+  getShareLinkRows.mockReset()
+  revokeShareLinks.mockReset()
+  router.refresh.mockReset()
+  vi.mocked(toast.success).mockReset()
+  vi.mocked(toast.error).mockReset()
+  getShareLinkRows.mockResolvedValue({ success: true, data: second })
+  revokeShareLinks.mockResolvedValue({ success: true, data: { removed: 50 } })
+})
+
+afterEach(() => {
+  vi.unstubAllGlobals()
+})
+
+// Seventy rows, each a table row and a card, are slow to render under a busy test run.
+describe('bulk revoke on a list that loads as it scrolls', () => {
+  it('ticks the links loaded so far and keeps the ticks when more arrive', async () => {
+    renderPage()
+    expect(screen.getByText('50 of 70')).toBeInTheDocument()
+
+    fireEvent.click(screen.getByRole('checkbox', { name: 'Select all links shown' }))
+    expect(screen.getByText('50 links selected')).toBeInTheDocument()
+
+    endInSight()
+    expect(await screen.findAllByText('INV-69')).not.toHaveLength(0)
+    expect(getShareLinkRows).toHaveBeenCalledWith(
+      expect.objectContaining({ status: 'active', cursor: first.nextCursor })
+    )
+
+    // The new rows come unticked; the old ticks stay.
+    expect(screen.getByText('50 links selected')).toBeInTheDocument()
+    expect(screen.getByRole('checkbox', { name: 'Select all links shown' })).toHaveAttribute(
+      'data-state',
+      'indeterminate'
+    )
+
+    fireEvent.click(screen.getByRole('button', { name: 'Remove selected' }))
+    const question = await screen.findByRole('alertdialog')
+    await act(async () => {
+      fireEvent.click(within(question).getByRole('button', { name: 'Remove selected' }))
+    })
+
+    const sent = revokeShareLinks.mock.calls[0][0].links as { id: string }[]
+    expect(sent).toHaveLength(50)
+    expect(sent.map((l) => l.id)).toEqual(first.rows.map((r) => r.id))
+    expect(router.refresh).toHaveBeenCalled()
+  }, 20_000)
+
+  it('ticks all seventy once they are all loaded', async () => {
+    renderPage()
+    endInSight()
+    expect(await screen.findAllByText('INV-69')).not.toHaveLength(0)
+    fireEvent.click(screen.getByRole('checkbox', { name: 'Select all links shown' }))
+    expect(screen.getByText('70 links selected')).toBeInTheDocument()
+  }, 20_000)
+
+  // The rows below are all invoices, so the invoice filter shows the very
+  // same links: the ticks must still go, as they do on every other list.
+  it.each([
+    ['a filter', { ...ALL, kind: 'invoice' }],
+    ['a status', { ...ALL, status: 'all' }],
+    ['a search', { ...ALL, search: 'INV-1' }],
+  ])(
+    'clears the ticks when %s changes',
+    async (_, filters) => {
+      const page = renderPage()
+      fireEvent.click(screen.getByRole('checkbox', { name: 'Select all links shown' }))
+      expect(screen.getByText('50 links selected')).toBeInTheDocument()
+
+      page.show(filters)
+
+      expect(screen.queryByText(/links? selected/)).not.toBeInTheDocument()
+      expect(screen.getByRole('checkbox', { name: 'Select all links shown' })).toHaveAttribute(
+        'data-state',
+        'unchecked'
+      )
+      for (const box of screen.getAllByRole('checkbox', { name: 'Select the link to INV-3' })) {
+        expect(box).toHaveAttribute('data-state', 'unchecked')
+      }
+    },
+    20_000
+  )
+})
+
+describe('an invoice and a quote with the same id', () => {
+  // Each kind of document numbers its own ids, so two links can carry one.
+  const invoice = { ...link(0), id: 'doc-1', label: 'INV-1', href: '/sales/doc-1' }
+  const quote = {
+    ...link(1),
+    kind: 'quote' as const,
+    id: 'doc-1',
+    token: 'tq',
+    label: 'Q-1',
+    href: '/quotes/doc-1',
+  }
+
+  it('shows both links, the first batch and the next, and removes both', async () => {
+    getShareLinkRows.mockResolvedValue({
+      success: true,
+      data: { organizationId: 'org-1', rows: [quote], nextCursor: null },
+    })
+    renderPage({
+      ...first,
+      rows: [invoice],
+      nextCursor: { v: [invoice.sharedAt], id: 'invoice:doc-1' },
+      total: 2,
+    })
+
+    endInSight()
+    expect(await screen.findAllByText('Q-1')).not.toHaveLength(0)
+    expect(screen.getAllByText('INV-1')).not.toHaveLength(0)
+    expect(screen.getByText('2 results')).toBeInTheDocument()
+
+    fireEvent.click(screen.getByRole('checkbox', { name: 'Select all links shown' }))
+    expect(screen.getByText('2 links selected')).toBeInTheDocument()
+    revokeShareLinks.mockResolvedValue({ success: true, data: { removed: 2 } })
+    fireEvent.click(screen.getByRole('button', { name: 'Remove selected' }))
+    const question = await screen.findByRole('alertdialog')
+    await act(async () => {
+      fireEvent.click(within(question).getByRole('button', { name: 'Remove selected' }))
+    })
+
+    // Each link goes by its own kind and the document's own id.
+    expect(revokeShareLinks).toHaveBeenCalledWith({
+      links: [
+        { kind: 'invoice', id: 'doc-1' },
+        { kind: 'quote', id: 'doc-1' },
+      ],
+    })
+  }, 20_000)
+})
+
+describe('more links ticked than one call takes', () => {
+  // Select all on a long list can tick more than the 200 the action accepts.
+  const many = {
+    ...first,
+    rows: Array.from({ length: 250 }, (_, i) => link(i)),
+    nextCursor: null,
+    total: 250,
+    counts: { active: 250, expired: 0 },
+  }
+
+  async function removeAll() {
+    renderPage(many as unknown as typeof first)
+    fireEvent.click(screen.getByRole('checkbox', { name: 'Select all links shown' }))
+    expect(screen.getByText('250 links selected')).toBeInTheDocument()
+    fireEvent.click(screen.getByRole('button', { name: 'Remove selected' }))
+    const question = await screen.findByRole('alertdialog')
+    await act(async () => {
+      fireEvent.click(within(question).getByRole('button', { name: 'Remove selected' }))
+    })
+  }
+
+  it('removes them all, two hundred at a time', async () => {
+    revokeShareLinks
+      .mockResolvedValueOnce({ success: true, data: { removed: 200 } })
+      .mockResolvedValueOnce({ success: true, data: { removed: 50 } })
+    await removeAll()
+
+    const sent = revokeShareLinks.mock.calls.map(([input]) => (input as { links: unknown[] }).links)
+    expect(sent.map((links) => links.length)).toEqual([200, 50])
+    expect(toast.success).toHaveBeenCalledWith('250 links removed')
+    expect(toast.error).not.toHaveBeenCalled()
+    expect(screen.queryByText(/links? selected/)).not.toBeInTheDocument()
+    expect(router.refresh).toHaveBeenCalled()
+  }, 30_000)
+
+  it('says how many went when a later batch fails, and keeps the rest ticked', async () => {
+    revokeShareLinks
+      .mockResolvedValueOnce({ success: true, data: { removed: 200 } })
+      .mockResolvedValueOnce({ success: false, error: 'nope' })
+    await removeAll()
+
+    expect(revokeShareLinks).toHaveBeenCalledTimes(2)
+    expect(toast.error).toHaveBeenCalledWith(
+      'Removed 200 of 250 links. Try again to remove the rest.'
+    )
+    expect(toast.success).not.toHaveBeenCalled()
+    // The removed ones are unticked; the fifty that still work stay ticked.
+    expect(screen.getByText('50 links selected')).toBeInTheDocument()
+    expect(router.refresh).toHaveBeenCalled()
+  }, 30_000)
+})

+ 3 - 2
src/__tests__/app/vehicles/vehicle-detail-delete.test.tsx

@@ -105,14 +105,15 @@ const VEHICLE = {
 }
 
 const empty = { records: [], total: 0, page: 1, pageSize: 20, totalPages: 0 }
+const noBatch = { rows: [], nextCursor: null, total: 0, renderId: 'render-1' }
 
 function renderPage(vehicle = VEHICLE) {
   render(
     <VehicleDetailClient
       vehicle={vehicle}
       paginatedServices={empty}
-      paginatedNotes={empty}
-      paginatedFindings={empty}
+      noteBatch={noBatch}
+      findingBatch={noBatch}
       serviceSearch=""
       serviceRecordType=""
       unitSystem="metric"

+ 9 - 8
src/__tests__/app/vehicles/vehicle-detail-dropped-connection.test.tsx

@@ -83,16 +83,18 @@ vi.mock('@/app/(authenticated)/vehicles/[id]/vehicle-activity-feed', () => ({
 vi.mock('@/app/(authenticated)/vehicles/[id]/notes-table', () => ({ NotesTable: () => null }))
 vi.mock('@/app/(authenticated)/vehicles/[id]/findings-table', () => ({
   FindingsTable: ({
+    initial,
     onCreateWorkOrder,
     isCreatingWorkOrder,
   }: {
-    onCreateWorkOrder: (ids: string[]) => void
+    initial: { rows: { id: string }[] }
+    onCreateWorkOrder: (findings: { id: string }[]) => void
     isCreatingWorkOrder: boolean
   }) => (
     <button
       type="button"
       disabled={isCreatingWorkOrder}
-      onClick={() => onCreateWorkOrder(['f1', 'f2'])}
+      onClick={() => onCreateWorkOrder(initial.rows)}
     >
       Create Work Order (2)
     </button>
@@ -164,13 +166,12 @@ function renderPage() {
       <VehicleDetailClient
         vehicle={VEHICLE}
         paginatedServices={empty}
-        paginatedNotes={empty}
-        paginatedFindings={{
-          records: [finding('f1', 'Front pads worn'), finding('f2', 'Wiper blades torn')],
+        noteBatch={{ rows: [], nextCursor: null, total: 0, renderId: 'render-1' }}
+        findingBatch={{
+          rows: [finding('f1', 'Front pads worn'), finding('f2', 'Wiper blades torn')],
+          nextCursor: null,
           total: 2,
-          page: 1,
-          pageSize: 20,
-          totalPages: 1,
+          renderId: 'render-1',
         }}
         serviceSearch=""
         serviceRecordType=""

+ 3 - 2
src/__tests__/app/vehicles/vehicle-detail-edit-from-details.test.tsx

@@ -104,14 +104,15 @@ const VEHICLE = {
 }
 
 const empty = { records: [], total: 0, page: 1, pageSize: 20, totalPages: 0 }
+const noBatch = { rows: [], nextCursor: null, total: 0, renderId: 'render-1' }
 
 function renderPage(vehicle: object = {}, fleetNumber = true) {
   render(
     <VehicleDetailClient
       vehicle={{ ...VEHICLE, ...vehicle } as typeof VEHICLE}
       paginatedServices={empty}
-      paginatedNotes={empty}
-      paginatedFindings={empty}
+      noteBatch={noBatch}
+      findingBatch={noBatch}
       serviceSearch=""
       serviceRecordType=""
       unitSystem="metric"

+ 3 - 2
src/__tests__/app/vehicles/vehicle-detail-new-work-order.test.tsx

@@ -98,14 +98,15 @@ const VEHICLE = {
 }
 
 const empty = { records: [], total: 0, page: 1, pageSize: 20, totalPages: 0 }
+const noBatch = { rows: [], nextCursor: null, total: 0, renderId: 'render-1' }
 
 function renderPage(vehicle = VEHICLE) {
   render(
     <VehicleDetailClient
       vehicle={vehicle}
       paginatedServices={empty}
-      paginatedNotes={empty}
-      paginatedFindings={empty}
+      noteBatch={noBatch}
+      findingBatch={noBatch}
       serviceSearch=""
       serviceRecordType=""
       unitSystem="metric"

+ 5 - 4
src/__tests__/auth/permission-enforcement.test.ts

@@ -198,7 +198,8 @@ import {
   updateVehicle,
 } from '@/features/vehicles/Actions/vehicleActions'
 import { getCustomers } from '@/features/customers/Actions/customerActions'
-import { getWorkOrders, getServiceRecords } from '@/features/vehicles/Actions/serviceActions'
+import { getServiceRecords } from '@/features/vehicles/Actions/serviceActions'
+import { getWorkOrderRows } from '@/features/vehicles/Actions/getWorkOrderRows'
 import { getQuotesPaginated } from '@/features/quotes/Actions/quoteActions'
 import { getBillingHistory } from '@/features/billing/Actions/billingActions'
 import { getInventoryPartsPaginated } from '@/features/inventory/Actions/inventoryActions'
@@ -303,7 +304,7 @@ describe('Permission denial — restricted custom role with no permissions', ()
     ['DASHBOARD', 'READ', () => getDashboardStats()],
     ['VEHICLES', 'READ', () => getVehicles()],
     ['CUSTOMERS', 'READ', () => getCustomers()],
-    ['WORK_ORDERS', 'READ', () => getWorkOrders({})],
+    ['WORK_ORDERS', 'READ', () => getWorkOrderRows({})],
     ['QUOTES', 'READ', () => getQuotesPaginated({})],
     ['SERVICES', 'READ', () => getServiceRecords('any-vehicle-id')],
     ['BILLING', 'READ', () => getBillingHistory({})],
@@ -343,7 +344,7 @@ describe('Permission grant — correct permission allows access past the gate',
     ['VEHICLES (UPDATE)', { action: 'update', subject: 'vehicles' }, () => updateVehicle({})],
     ['VEHICLES (DELETE)', { action: 'delete', subject: 'vehicles' }, () => deleteVehicle('any-id')],
     ['CUSTOMERS (READ)', { action: 'read', subject: 'customers' }, () => getCustomers()],
-    ['WORK_ORDERS (READ)', { action: 'read', subject: 'work_orders' }, () => getWorkOrders({})],
+    ['WORK_ORDERS (READ)', { action: 'read', subject: 'work_orders' }, () => getWorkOrderRows({})],
     ['QUOTES (READ)', { action: 'read', subject: 'quotes' }, () => getQuotesPaginated({})],
     ['SERVICES (READ)', { action: 'read', subject: 'services' }, () => getServiceRecords('any-id')],
     ['BILLING (READ)', { action: 'read', subject: 'billing' }, () => getBillingHistory({})],
@@ -580,7 +581,7 @@ describe('Unauthenticated access — all actions require authentication', () =>
     ['getDashboardStats', () => getDashboardStats()],
     ['getVehicles', () => getVehicles()],
     ['getCustomers', () => getCustomers()],
-    ['getWorkOrders', () => getWorkOrders({})],
+    ['getWorkOrderRows', () => getWorkOrderRows({})],
     ['getQuotesPaginated', () => getQuotesPaginated({})],
     ['getServiceRecords', () => getServiceRecords('any-id')],
     ['getBillingHistory', () => getBillingHistory({})],

+ 471 - 0
src/__tests__/components/infinite-list.test.tsx

@@ -0,0 +1,471 @@
+/**
+ * A list that loads more as it scrolls (components/infinite-list).
+ *
+ * What a person notices: rows arrive as the end of the list comes near, the
+ * count says how many are on screen, no row ever shows twice, a batch that
+ * fails says so quietly and comes back on Retry, and another filter starts
+ * over at the top of the new list.
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+  InfiniteListCount,
+  InfiniteListFooter,
+} from '@/components/infinite-list/infinite-list-footer'
+import {
+  type InfinitePage,
+  type ServerBatch,
+  useInfiniteRows,
+} from '@/components/infinite-list/use-infinite-rows'
+import type { ActionResult } from '@/lib/with-auth'
+
+type Row = { id: string; name: string }
+type Page = InfinitePage<Row, number>
+
+// The end of the list coming into sight is an IntersectionObserver's call.
+const observers: { callback: IntersectionObserverCallback; observer: IntersectionObserver }[] = []
+class FakeObserver {
+  constructor(public callback: IntersectionObserverCallback) {
+    observers.push({ callback, observer: this as unknown as IntersectionObserver })
+  }
+  observe() {
+    // Nothing to watch: the test says when the end is in sight.
+  }
+  unobserve() {
+    // As above.
+  }
+  disconnect() {
+    // As above.
+  }
+  takeRecords() {
+    return []
+  }
+}
+
+function endInSight(near: boolean) {
+  act(() => {
+    for (const { callback, observer } of observers) {
+      callback([{ isIntersecting: near } as IntersectionObserverEntry], observer)
+    }
+  })
+}
+
+function rowsOf(prefix: string, count: number): Row[] {
+  return Array.from({ length: count }, (_, i) => ({
+    id: `${prefix}${i + 1}`,
+    name: `${prefix} job ${i + 1}`,
+  }))
+}
+
+/** A list of `all` rows served in batches of 50, the cursor being where the last batch ended. */
+function server(all: Row[]) {
+  return vi.fn(async (cursor: number | null): Promise<ActionResult<Page>> => {
+    const start = cursor ?? 0
+    const rows = all.slice(start, start + 50)
+    const end = start + rows.length
+    return {
+      success: true,
+      data: { rows, nextCursor: end < all.length ? end : null, total: all.length },
+    }
+  })
+}
+
+/** The first batch as one server render of the page hands it over. */
+function firstBatch(all: Row[], renderId = 'render-1'): ServerBatch<Page> {
+  return {
+    rows: all.slice(0, 50),
+    nextCursor: all.length > 50 ? 50 : null,
+    total: all.length,
+    renderId,
+  }
+}
+
+function Harness({
+  filter,
+  initial,
+  fetchPage,
+}: {
+  filter: string
+  initial: ServerBatch<Page>
+  fetchPage: (cursor: number | null) => Promise<ActionResult<Page>>
+}) {
+  const list = useInfiniteRows<Row, number, Page>({
+    queryKey: ['jobs', filter],
+    initial,
+    fetchPage,
+  })
+  return (
+    <>
+      <InfiniteListCount shown={list.rows.length} total={list.total} />
+      <div style={{ overflowY: 'auto' }}>
+        <ul>
+          {list.rows.map((row) => (
+            <li key={row.id}>{row.name}</li>
+          ))}
+        </ul>
+        <InfiniteListFooter state={list} />
+      </div>
+    </>
+  )
+}
+
+let client: QueryClient
+function show(props: Parameters<typeof Harness>[0]) {
+  const view = render(
+    <QueryClientProvider client={client}>
+      <Harness {...props} />
+    </QueryClientProvider>
+  )
+  return {
+    ...view,
+    rerender: (next: Parameters<typeof Harness>[0]) =>
+      view.rerender(
+        <QueryClientProvider client={client}>
+          <Harness {...next} />
+        </QueryClientProvider>
+      ),
+  }
+}
+
+beforeEach(() => {
+  observers.length = 0
+  vi.stubGlobal('IntersectionObserver', FakeObserver)
+  client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+})
+
+afterEach(() => {
+  vi.unstubAllGlobals()
+  client.clear()
+})
+
+describe('loading more as the list scrolls', () => {
+  it('shows the server batch at once and appends the next as the end comes near', async () => {
+    const all = rowsOf('a', 120)
+    const fetchPage = server(all)
+    show({ filter: 'one', initial: firstBatch(all), fetchPage })
+
+    expect(screen.getAllByRole('listitem')).toHaveLength(50)
+    expect(screen.getByText('50 of 120')).toBeInTheDocument()
+    expect(fetchPage).not.toHaveBeenCalled()
+
+    endInSight(true)
+    await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(100))
+    // The end is still in sight after the batch landed, so the last one follows.
+    await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(120))
+    expect(screen.getByText('120 results')).toBeInTheDocument()
+    expect(screen.getByText('All 120 shown')).toBeInTheDocument()
+  })
+
+  it('asks for nothing more once the end is out of sight', async () => {
+    const all = rowsOf('a', 200)
+    const serve = server(all)
+    let open: () => void = () => undefined
+    const gate = new Promise<void>((resolve) => {
+      open = resolve
+    })
+    const fetchPage = vi.fn(async (cursor: number | null) => {
+      await gate
+      return serve(cursor)
+    })
+    show({ filter: 'one', initial: firstBatch(all), fetchPage })
+
+    endInSight(true)
+    await waitFor(() => expect(fetchPage).toHaveBeenCalledTimes(1))
+    // Scrolled back up before the batch arrived.
+    endInSight(false)
+    open()
+    await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(100))
+    await new Promise((resolve) => setTimeout(resolve, 50))
+    expect(fetchPage).toHaveBeenCalledTimes(1)
+    expect(screen.getAllByRole('listitem')).toHaveLength(100)
+  })
+
+  it('never shows a row twice when a batch overlaps the one before it', async () => {
+    const all = rowsOf('a', 80)
+    // A job added at the top while scrolling pushes the last row of the first
+    // batch into the second one.
+    const fetchPage = vi.fn(
+      async (): Promise<ActionResult<Page>> => ({
+        success: true,
+        data: { rows: all.slice(49, 80), nextCursor: null },
+      })
+    )
+    show({ filter: 'one', initial: firstBatch(all), fetchPage })
+
+    endInSight(true)
+    await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(80))
+    expect(screen.getAllByText('a job 50')).toHaveLength(1)
+  })
+
+  it('says quietly when a batch failed, and loads it on Retry', async () => {
+    const all = rowsOf('a', 80)
+    const working = server(all)
+    const fetchPage = vi
+      .fn<(cursor: number | null) => Promise<ActionResult<Page>>>()
+      // The first try and its quiet second try both fail.
+      .mockResolvedValueOnce({ success: false, error: 'offline' })
+      .mockResolvedValueOnce({ success: false, error: 'offline' })
+      .mockImplementation(working)
+    show({ filter: 'one', initial: firstBatch(all), fetchPage })
+
+    endInSight(true)
+    expect(await screen.findByText("Couldn't load more", {}, { timeout: 3000 })).toBeInTheDocument()
+    // The rows already shown stay.
+    expect(screen.getAllByRole('listitem')).toHaveLength(50)
+
+    fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
+    await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(80))
+    expect(screen.queryByText("Couldn't load more")).not.toBeInTheDocument()
+  })
+
+  it('survives an action that cannot reach the server', async () => {
+    const all = rowsOf('a', 80)
+    const fetchPage = vi.fn(async (): Promise<ActionResult<Page>> => {
+      throw new Error('Failed to fetch')
+    })
+    show({ filter: 'one', initial: firstBatch(all), fetchPage })
+
+    endInSight(true)
+    expect(await screen.findByText("Couldn't load more", {}, { timeout: 3000 })).toBeInTheDocument()
+    expect(screen.getAllByRole('listitem')).toHaveLength(50)
+  })
+})
+
+describe('another filter', () => {
+  it('starts over at the first batch of the new list', async () => {
+    const all = rowsOf('a', 120)
+    const view = show({ filter: 'one', initial: firstBatch(all), fetchPage: server(all) })
+    endInSight(true)
+    await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(120))
+
+    const other = rowsOf('b', 70)
+    endInSight(false)
+    view.rerender({ filter: 'two', initial: firstBatch(other), fetchPage: server(other) })
+
+    expect(screen.getAllByRole('listitem')).toHaveLength(50)
+    expect(screen.getByText('b job 1')).toBeInTheDocument()
+    expect(screen.queryByText('a job 1')).not.toBeInTheDocument()
+    expect(screen.getByText('50 of 70')).toBeInTheDocument()
+  })
+
+  it('does not load past the first batch of the new list on its own', async () => {
+    // The old list was scrolled to its end; the new one opens at its top.
+    const all = rowsOf('a', 120)
+    const view = show({ filter: 'one', initial: firstBatch(all), fetchPage: server(all) })
+    endInSight(true)
+    await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(120))
+
+    const other = rowsOf('b', 170)
+    const fetchOther = server(other)
+    view.rerender({ filter: 'two', initial: firstBatch(other), fetchPage: fetchOther })
+    await new Promise((resolve) => setTimeout(resolve, 50))
+    expect(fetchOther).not.toHaveBeenCalled()
+    expect(screen.getAllByRole('listitem')).toHaveLength(50)
+  })
+
+  it('going back to an earlier filter shows its first batch, not where it was left', async () => {
+    const all = rowsOf('a', 120)
+    const other = rowsOf('b', 70)
+    const view = show({ filter: 'one', initial: firstBatch(all), fetchPage: server(all) })
+    endInSight(true)
+    await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(120))
+    endInSight(false)
+    view.rerender({ filter: 'two', initial: firstBatch(other), fetchPage: server(other) })
+    view.rerender({ filter: 'one', initial: firstBatch(all), fetchPage: server(all) })
+
+    expect(screen.getAllByRole('listitem')).toHaveLength(50)
+  })
+})
+
+/**
+ * A page that shows placeholders in the list's box while a search loads (the
+ * vehicles grid): the footer goes away with the rows, the box stays.
+ */
+function PlaceholderHarness({
+  filter,
+  initial,
+  fetchPage,
+  loading,
+}: Parameters<typeof Harness>[0] & { loading: boolean }) {
+  const list = useInfiniteRows<Row, number, Page>({
+    queryKey: ['jobs', filter],
+    initial,
+    fetchPage,
+  })
+  return (
+    <div data-testid="box" style={{ overflowY: 'auto' }}>
+      {loading ? (
+        <p>Loading</p>
+      ) : (
+        <>
+          <ul>
+            {list.rows.map((row) => (
+              <li key={row.id}>{row.name}</li>
+            ))}
+          </ul>
+          <InfiniteListFooter state={list} />
+        </>
+      )}
+    </div>
+  )
+}
+
+describe('a search behind placeholders', () => {
+  function showWithPlaceholders(props: Parameters<typeof PlaceholderHarness>[0]) {
+    const tree = (next: typeof props) => (
+      <QueryClientProvider client={client}>
+        <PlaceholderHarness {...next} />
+      </QueryClientProvider>
+    )
+    const view = render(tree(props))
+    const box = screen.getByTestId('box')
+    // jsdom does not scroll; the box keeps whatever it is told.
+    Object.defineProperty(box, 'scrollTop', { value: 0, writable: true, configurable: true })
+    return { box, rerender: (next: typeof props) => view.rerender(tree(next)) }
+  }
+
+  it('opens the new list at its top, not where the old one was scrolled', () => {
+    const all = rowsOf('a', 120)
+    const other = rowsOf('b', 70)
+    const view = showWithPlaceholders({
+      filter: 'one',
+      initial: firstBatch(all),
+      fetchPage: server(all),
+      loading: false,
+    })
+    view.box.scrollTop = 1000
+
+    view.rerender({
+      filter: 'one',
+      initial: firstBatch(all),
+      fetchPage: server(all),
+      loading: true,
+    })
+    view.rerender({
+      filter: 'two',
+      initial: firstBatch(other),
+      fetchPage: server(other),
+      loading: false,
+    })
+
+    expect(screen.getByText('b job 1')).toBeInTheDocument()
+    expect(view.box.scrollTop).toBe(0)
+  })
+
+  it('leaves the same list where it was', () => {
+    const all = rowsOf('a', 120)
+    const view = showWithPlaceholders({
+      filter: 'one',
+      initial: firstBatch(all),
+      fetchPage: server(all),
+      loading: false,
+    })
+    view.box.scrollTop = 1000
+
+    view.rerender({
+      filter: 'one',
+      initial: firstBatch(all),
+      fetchPage: server(all),
+      loading: true,
+    })
+    view.rerender({
+      filter: 'one',
+      initial: firstBatch(all),
+      fetchPage: server(all),
+      loading: false,
+    })
+
+    expect(view.box.scrollTop).toBe(1000)
+  })
+})
+
+describe('the same list changing', () => {
+  it('shows a changed first batch at once and keeps the rows loaded after it', async () => {
+    const all = rowsOf('a', 120)
+    const fetchPage = server(all)
+    const view = show({ filter: 'one', initial: firstBatch(all), fetchPage })
+    endInSight(true)
+    await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(120))
+    endInSight(false)
+
+    // An edit elsewhere; the server page re-renders with the new first batch.
+    all[0] = { id: 'a1', name: 'a job 1, renamed' }
+    view.rerender({ filter: 'one', initial: firstBatch(all, 'render-2'), fetchPage })
+
+    expect(screen.getByText('a job 1, renamed')).toBeInTheDocument()
+    await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(120))
+  })
+
+  it('re-reads the later batches after a refresh, even when the first batch is the same', async () => {
+    const all = rowsOf('a', 120)
+    const fetchPage = server(all)
+    const view = show({ filter: 'one', initial: firstBatch(all), fetchPage })
+    endInSight(true)
+    await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(120))
+    endInSight(false)
+
+    // A row in the second batch is edited and saved; the form calls
+    // router.refresh() and the page renders again with the same first batch.
+    all[69] = { id: 'a70', name: 'a job 70, edited' }
+    view.rerender({ filter: 'one', initial: firstBatch(all, 'render-2'), fetchPage })
+
+    expect(await screen.findByText('a job 70, edited')).toBeInTheDocument()
+    expect(screen.queryByText('a job 70')).not.toBeInTheDocument()
+    // Nothing went missing while it was re-read.
+    expect(screen.getAllByRole('listitem')).toHaveLength(120)
+  })
+
+  it('reads nothing on a client re-render or Back to a page the router kept', async () => {
+    const all = rowsOf('a', 120)
+    const fetchPage = server(all)
+    const view = show({ filter: 'one', initial: firstBatch(all), fetchPage })
+    endInSight(true)
+    await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(120))
+    endInSight(false)
+    const calls = fetchPage.mock.calls.length
+
+    // A parent re-rendering hands over a copy of the same render.
+    view.rerender({ filter: 'one', initial: firstBatch(all), fetchPage })
+    // Leaving and pressing Back mounts the list again with that render.
+    view.unmount()
+    show({ filter: 'one', initial: firstBatch(all), fetchPage })
+
+    expect(screen.getAllByRole('listitem')).toHaveLength(120)
+    await new Promise((resolve) => setTimeout(resolve, 50))
+    expect(fetchPage).toHaveBeenCalledTimes(calls)
+  })
+})
+
+describe('the wait for a batch', () => {
+  it('shows placeholders only when the batch is slow', async () => {
+    vi.useFakeTimers({ shouldAdvanceTime: true })
+    try {
+      const all = rowsOf('a', 80)
+      let answer: (value: ActionResult<Page>) => void = () => undefined
+      const fetchPage = vi.fn(
+        () =>
+          new Promise<ActionResult<Page>>((resolve) => {
+            answer = resolve
+          })
+      )
+      const { container } = show({ filter: 'one', initial: firstBatch(all), fetchPage })
+      endInSight(true)
+      await waitFor(() => expect(fetchPage).toHaveBeenCalled())
+      expect(container.querySelectorAll('[data-slot="skeleton"]')).toHaveLength(0)
+
+      await act(async () => {
+        vi.advanceTimersByTime(350)
+      })
+      expect(container.querySelectorAll('[data-slot="skeleton"]')).toHaveLength(3)
+
+      await act(async () => {
+        answer({ success: true, data: { rows: all.slice(50), nextCursor: null } })
+      })
+      await waitFor(() => expect(screen.getAllByRole('listitem')).toHaveLength(80))
+      expect(container.querySelectorAll('[data-slot="skeleton"]')).toHaveLength(0)
+    } finally {
+      vi.useRealTimers()
+    }
+  })
+})

+ 267 - 0
src/__tests__/db/count-sort.db.test.ts

@@ -0,0 +1,267 @@
+/**
+ * The count sorts on a real PostgreSQL (`npm run test:db`): the customer list
+ * by vehicle count and the vehicle list by job count.
+ *
+ * Those two sorts read each batch in one SQL query, with the list's filters
+ * written out in SQL beside the Prisma `where` every other sort uses. Walked
+ * batch by batch, the SQL has to give exactly the rows Prisma's own where
+ * finds, in the order Prisma's relation-count orderBy gives them, for every
+ * filter: the search (wildcards in it included), archived, the inspection due
+ * date, and each setting that widens the vehicle search.
+ *
+ * It makes one person and two workshops of its own and removes them again.
+ */
+import { randomUUID } from 'node:crypto'
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import type { CustomerListFilters } from '@/features/customers/Lib/customerList.server'
+import type {
+  VehicleListFilters,
+  VehicleSearchOptions,
+} from '@/features/vehicles/Lib/vehicleList.server'
+import type { Cursor } from '@/lib/keyset'
+
+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.`
+  )
+}
+process.env.DATABASE_URL = url
+
+const stamp = randomUUID().slice(0, 8)
+let db: typeof import('@/lib/db')['db']
+let customers: typeof import('@/features/customers/Lib/customerList.server')
+let vehicles: typeof import('@/features/vehicles/Lib/vehicleList.server')
+let organizationId = ''
+let otherOrganizationId = ''
+let userId = ''
+
+const DAY = 86_400_000
+const NOW = new Date()
+/** Small batches, so every walk crosses several boundaries and plenty of ties. */
+const TAKE = 4
+
+/** Every id the SQL hands out, batch by batch, as the list would ask for them. */
+async function walk(
+  batch: (cursor: Cursor | null, take: number) => Promise<{ id: string; count: number }[]>
+) {
+  const ids: string[] = []
+  let cursor: Cursor | null = null
+  for (let guard = 0; guard < 200; guard++) {
+    const found = await batch(cursor, TAKE + 1)
+    const page = found.slice(0, TAKE)
+    ids.push(...page.map((row) => row.id))
+    const last = page[page.length - 1]
+    if (found.length <= TAKE || !last) return ids
+    cursor = { v: [last.count], id: last.id }
+  }
+  throw new Error('walk did not end')
+}
+
+const NAMES = [
+  'Ada Berg',
+  'Ola Nordmann',
+  'Kari 50% Holm',
+  'Per_Lund',
+  'Back\\slash AS',
+  'Volvo Berg',
+  'Fjord Transport',
+  'Berit Volvosen',
+]
+
+async function makeWorkshop(orgId: string) {
+  const made: string[] = []
+  for (let i = 0; i < NAMES.length * 2; i++) {
+    const customer = await db.customer.create({
+      data: {
+        organizationId: orgId,
+        userId,
+        name: NAMES[i % NAMES.length],
+        email: i % 3 === 0 ? null : `c${i}@example.com`,
+        phone: i % 4 === 0 ? null : `+47 9${i % 5}0 00`,
+        company: i % 2 === 0 ? null : ['Volvo', 'Fjord AS', '50_50 Ltd'][i % 3],
+        customerNumber: i % 5 === 0 ? null : String(1000 + i),
+      },
+    })
+    made.push(customer.id)
+  }
+
+  const makes = ['Volvo', 'Audi', 'Tesla', 'Ford', 'Volkswagen']
+  for (let i = 0; i < 30; i++) {
+    const vehicle = await db.vehicle.create({
+      data: {
+        organizationId: orgId,
+        userId,
+        // Every fourth customer has none; the rest have between one and three.
+        customerId: i % 7 === 6 ? null : made[(i * 3) % made.length],
+        make: makes[i % makes.length],
+        model: i % 6 === 0 ? 'V70 50%' : i % 6 === 1 ? 'Golf_GTI' : `Model ${i % 4}`,
+        year: 2008 + (i % 6),
+        licensePlate: i % 5 === 0 ? null : `AB ${10000 + i}`,
+        vin: i % 3 === 0 ? null : `YV1${String(i).padStart(14, '0')}`,
+        hsn: i % 4 === 0 ? '0603' : i % 4 === 1 ? '0005' : null,
+        tsn: i % 3 === 0 ? 'BFQ' : i % 3 === 1 ? 'AAA' : null,
+        fleetNumber: i % 2 === 0 ? `U${12 + (i % 3)}` : null,
+        isArchived: i % 9 === 4,
+      },
+    })
+    if (i % 3 !== 2) {
+      await db.vehicleInspectionStatus.create({
+        data: {
+          organizationId: orgId,
+          vehicleId: vehicle.id,
+          source: 'test',
+          dueAt: i % 5 === 4 ? null : new Date(NOW.getTime() + ((i % 11) - 3) * 10 * DAY),
+        },
+      })
+    }
+    for (let j = 0; j < i % 4; j++) {
+      await db.serviceRecord.create({
+        data: {
+          organizationId: orgId,
+          vehicleId: vehicle.id,
+          title: `Job ${j}`,
+          serviceDate: new Date('2026-11-01'),
+        },
+      })
+    }
+    if (i % 4 === 1) {
+      const type = await db.equipmentType.create({
+        data: { name: `Crane ${stamp} ${orgId.slice(-4)} ${i}`, organizationId: orgId },
+      })
+      await db.equipmentItem.create({
+        data: {
+          organizationId: orgId,
+          vehicleId: vehicle.id,
+          typeId: type.id,
+          serialNumber: `SN-9${i}`,
+          // One item taken off: it no longer finds the vehicle.
+          removedAt: i === 5 ? new Date() : null,
+        },
+      })
+    }
+  }
+}
+
+beforeAll(async () => {
+  ;({ db } = await import('@/lib/db'))
+  customers = await import('@/features/customers/Lib/customerList.server')
+  vehicles = await import('@/features/vehicles/Lib/vehicleList.server')
+  const user = await db.user.create({
+    data: { name: `Count sort ${stamp}`, email: `count-sort-${stamp}@example.com` },
+  })
+  userId = user.id
+  organizationId = (await db.organization.create({ data: { name: `Count sort ${stamp}` } })).id
+  otherOrganizationId = (
+    await db.organization.create({ data: { name: `Count sort other ${stamp}` } })
+  ).id
+  // The other workshop has the same rows: none of them may turn up.
+  await makeWorkshop(organizationId)
+  await makeWorkshop(otherOrganizationId)
+})
+
+afterAll(async () => {
+  if (!db) return
+  for (const orgId of [organizationId, otherOrganizationId]) {
+    if (!orgId) continue
+    await db.equipmentItem.deleteMany({ where: { organizationId: orgId } })
+    await db.equipmentType.deleteMany({ where: { organizationId: orgId } })
+    await db.serviceRecord.deleteMany({ where: { organizationId: orgId } })
+    await db.vehicle.deleteMany({ where: { organizationId: orgId } })
+    await db.customer.deleteMany({ where: { organizationId: orgId } })
+    await db.organization.deleteMany({ where: { id: orgId } })
+  }
+  await db.user.deleteMany({ where: { id: userId } })
+})
+
+const CUSTOMER_FILTERS: CustomerListFilters[] = [
+  {},
+  { search: 'berg' },
+  { search: 'BERG volvo' },
+  { search: '50%' },
+  { search: '_' },
+  { search: 'Back\\' },
+  { search: '+47 91' },
+  { search: 'nobody at all' },
+]
+
+describe('the customer list by vehicle count', () => {
+  for (const filters of CUSTOMER_FILTERS) {
+    for (const dir of ['asc', 'desc'] as const) {
+      it(`finds what Prisma finds, in its order: ${JSON.stringify(filters)} ${dir}`, async () => {
+        const expected = await db.customer.findMany({
+          where: customers.customerListWhere(organizationId, filters),
+          orderBy: [{ vehicles: { _count: dir } }, { id: 'asc' }],
+          select: { id: true },
+        })
+        const ids = await walk((cursor, take) =>
+          customers.customerIdsByVehicleCount(organizationId, filters, dir, cursor, take)
+        )
+        expect(ids).toEqual(expected.map((row) => row.id))
+      })
+    }
+  }
+
+  it('finds something for the searches that should', async () => {
+    const found = await db.customer.count({
+      where: customers.customerListWhere(organizationId, { search: 'BERG volvo' }),
+    })
+    expect(found).toBeGreaterThan(0)
+  })
+})
+
+const OFF: VehicleSearchOptions = { typeKeyOn: false, fleetNumberOn: false, equipmentOn: false }
+const ON: VehicleSearchOptions = { typeKeyOn: true, fleetNumberOn: true, equipmentOn: true }
+
+const VEHICLE_FILTERS: [VehicleListFilters, VehicleSearchOptions][] = [
+  [{}, OFF],
+  [{ archived: true }, OFF],
+  [{ search: 'volvo' }, OFF],
+  [{ search: 'volvo 2010' }, OFF],
+  [{ search: 'ada / berg' }, OFF],
+  [{ search: '50%' }, OFF],
+  [{ search: 'golf_' }, OFF],
+  [{ search: 'yv1' }, OFF],
+  [{ search: '0603' }, { ...OFF, typeKeyOn: true }],
+  [{ search: 'bfq' }, { ...OFF, typeKeyOn: true }],
+  [{ search: '0603/BFQ' }, ON],
+  [{ search: 'u12' }, { ...OFF, fleetNumberOn: true }],
+  [{ search: 'sn-9' }, { ...OFF, equipmentOn: true }],
+  [{ search: 'sn-95' }, { ...OFF, equipmentOn: true }],
+  [{ inspectionDue: 'overdue' }, OFF],
+  [{ inspectionDue: 30 }, OFF],
+  [{ inspectionDue: 90 }, OFF],
+  [{ search: 'u1 volvo', archived: true, inspectionDue: 90 }, ON],
+]
+
+describe('the vehicle list by job count', () => {
+  for (const [filters, options] of VEHICLE_FILTERS) {
+    for (const sortOrder of ['asc', 'desc'] as const) {
+      it(`finds what Prisma finds, in its order: ${JSON.stringify({ ...filters, ...options })} ${sortOrder}`, async () => {
+        const params = { ...filters, sortBy: 'services', sortOrder }
+        const expected = await db.vehicle.findMany({
+          where: vehicles.vehicleListWhereWith(organizationId, params, options, NOW),
+          orderBy: [{ serviceRecords: { _count: sortOrder } }, { id: 'asc' }],
+          select: { id: true },
+        })
+        const ids = await walk((cursor, take) =>
+          vehicles.vehicleIdsByServiceCount(organizationId, params, options, NOW, cursor, take)
+        )
+        expect(ids).toEqual(expected.map((row) => row.id))
+      })
+    }
+  }
+
+  it('finds something for each widening setting', async () => {
+    const count = (filters: VehicleListFilters, options: VehicleSearchOptions) =>
+      db.vehicle.count({
+        where: vehicles.vehicleListWhereWith(organizationId, filters, options, NOW),
+      })
+    for (const [filters, options] of VEHICLE_FILTERS.slice(8, 13)) {
+      expect(await count(filters, options), JSON.stringify(filters)).toBeGreaterThan(0)
+    }
+    // The only item with that serial was taken off its vehicle.
+    expect(await count({ search: 'sn-95' }, { ...OFF, equipmentOn: true })).toBe(0)
+  })
+})

+ 14 - 8
src/__tests__/features/admin/account-actions.test.tsx

@@ -5,6 +5,7 @@
  * email has been typed.
  */
 
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
 import { render, screen, waitFor, within } from '@testing-library/react'
 import userEvent from '@testing-library/user-event'
 import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -22,6 +23,9 @@ vi.mock('@/features/admin/Actions/revokeSuperAdmin', () => ({
   revokeSuperAdmin: (input: unknown) => revokeSuperAdmin(input),
 }))
 
+// The list's first batch is all there is here; nothing more is asked for.
+vi.mock('@/features/admin/Actions/getUserRows', () => ({ getUserRows: vi.fn() }))
+
 const push = vi.fn()
 const refresh = vi.fn()
 vi.mock('next/navigation', () => ({
@@ -97,14 +101,16 @@ describe('the account list', () => {
   it('offers nothing that changes an account, and a tap only opens it', async () => {
     const actor = userEvent.setup({ pointerEventsCheck: 0 })
     render(
-      <ConfirmProvider>
-        <AdminUsers
-          data={{ users: [row], total: 1, page: 1, pageSize: 20, totalPages: 1 }}
-          search=""
-          sortBy="lastSeen"
-          sortOrder="desc"
-        />
-      </ConfirmProvider>
+      <QueryClientProvider client={new QueryClient()}>
+        <ConfirmProvider>
+          <AdminUsers
+            data={{ rows: [row], nextCursor: null, total: 1, renderId: 'render-1' }}
+            search=""
+            sortBy="lastSeen"
+            sortOrder="desc"
+          />
+        </ConfirmProvider>
+      </QueryClientProvider>
     )
 
     expect(screen.queryByRole('button', { name: 'Open menu' })).not.toBeInTheDocument()

+ 215 - 0
src/__tests__/features/admin/admin-list-rows.test.ts

@@ -0,0 +1,215 @@
+/**
+ * @vitest-environment node
+ *
+ * The platform's user and workshop lists load as they scroll (getUserRows,
+ * getOrganizationRows). Every account and workshop turns up once whatever the
+ * sort, the search holds for every batch, the lists cover the whole platform,
+ * and only a super admin may read them.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { ordered, walkBatches } from '@/__tests__/helpers/in-memory-table'
+
+type Account = {
+  id: string
+  name: string
+  email: string
+  isSuperAdmin: boolean
+  emailVerified: boolean
+  createdAt: Date
+  lastSeen: Date | null
+}
+type Workshop = {
+  id: string
+  name: string
+  createdAt: Date
+  _count: { members: number }
+  members: { userId: string }[]
+  subscription: null
+}
+
+const state = vi.hoisted(() => ({
+  users: [] as Account[],
+  organizations: [] as Workshop[],
+  signedIn: 'admin' as string | null,
+}))
+
+vi.mock('@/lib/cached-session', () => ({
+  getCachedSession: async () =>
+    state.signedIn ? { user: { id: state.signedIn, name: 'A', email: 'a@x' }, session: {} } : null,
+}))
+vi.mock('next/headers', () => ({ headers: async () => new Headers() }))
+vi.mock('@/lib/session-scope', () => ({ sessionOrganizationScope: () => null }))
+vi.mock('@/lib/db', async () => {
+  const { inMemoryTable } = await import('@/__tests__/helpers/in-memory-table')
+  const users = inMemoryTable(() => state.users)
+  return {
+    db: {
+      user: {
+        ...users,
+        findUnique: async ({ where }: { where: { id: string } }) =>
+          state.users.find((u) => u.id === where.id) ?? null,
+      },
+      organization: inMemoryTable(() => state.organizations),
+      organizationMember: {
+        groupBy: async ({ where }: { where: { userId: { in: string[] } } }) =>
+          where.userId.in.map((userId) => ({ userId, _count: userId.length % 3 })),
+      },
+    },
+  }
+})
+
+import { getOrganizationRows } from '@/features/admin/Actions/getOrganizationRows'
+import { getUserRows } from '@/features/admin/Actions/getUserRows'
+
+function makeUsers(): Account[] {
+  const users = Array.from({ length: 117 }, (_, i) => ({
+    id: `u-${String((i * 31) % 117).padStart(3, '0')}`,
+    // Plenty of ties, so the id has to break them.
+    name: ['Ann', 'Bo', 'Cy', 'Di'][i % 4],
+    email: `person${i}@example.com`,
+    isSuperAdmin: i % 9 === 0,
+    emailVerified: i % 2 === 0,
+    createdAt: new Date(Date.UTC(2026, 0, 1 + (i % 12))),
+    // Some never signed in.
+    lastSeen: i % 5 === 0 ? null : new Date(Date.UTC(2026, 10, 1, i % 7)),
+  }))
+  users.push({
+    id: 'admin',
+    name: 'Admin',
+    email: 'admin@example.com',
+    isSuperAdmin: true,
+    emailVerified: true,
+    createdAt: new Date(Date.UTC(2025, 0, 1)),
+    lastSeen: null,
+  })
+  return users
+}
+
+function makeOrganizations(): Workshop[] {
+  return Array.from({ length: 108 }, (_, i) => ({
+    id: `o-${String((i * 29) % 108).padStart(3, '0')}`,
+    name: i % 3 === 0 ? `Nordic Motors ${i}` : `Bilverksted ${i}`,
+    createdAt: new Date(Date.UTC(2026, 3, 1 + (i % 10))),
+    _count: { members: 2 },
+    members: [{ userId: 'admin' }],
+    subscription: null,
+  }))
+}
+
+beforeEach(() => {
+  state.users = makeUsers()
+  state.organizations = makeOrganizations()
+  state.signedIn = 'admin'
+})
+
+/** The users in the order the list should show them. */
+function expectedUsers(sortBy: string, dir: 'asc' | 'desc', filter = (_: Account) => true) {
+  const order =
+    sortBy === 'lastSeen'
+      ? [{ lastSeen: { sort: dir, nulls: 'last' } }, { id: 'asc' }]
+      : [{ [sortBy]: dir }, { id: 'asc' }]
+  return ordered(state.users.filter(filter), order).map((u) => u.id)
+}
+
+describe('the platform user list in batches', () => {
+  for (const sortBy of ['name', 'email', 'createdAt', 'lastSeen', 'isSuperAdmin']) {
+    for (const sortOrder of ['asc', 'desc'] as const) {
+      it(`shows every account once, sorted by ${sortBy} ${sortOrder}`, async () => {
+        const { ids: seen } = await walkBatches(getUserRows, (cursor) => ({
+          sortBy,
+          sortOrder,
+          cursor,
+        }))
+        expect(seen).toEqual(expectedUsers(sortBy, sortOrder))
+        expect(new Set(seen).size).toBe(seen.length)
+      })
+    }
+  }
+
+  it('keeps accounts that never signed in at the end, either way round', async () => {
+    for (const sortOrder of ['asc', 'desc'] as const) {
+      const { ids: seen } = await walkBatches(getUserRows, (cursor) => ({
+        sortBy: 'lastSeen',
+        sortOrder,
+        cursor,
+      }))
+      const never = state.users.filter((u) => !u.lastSeen).map((u) => u.id)
+      expect(new Set(seen.slice(-never.length))).toEqual(new Set(never))
+    }
+  })
+
+  it('keeps the search on every batch', async () => {
+    const { ids: seen } = await walkBatches(getUserRows, (cursor) => ({
+      search: 'ann',
+      sortBy: 'name',
+      sortOrder: 'asc',
+      cursor,
+    }))
+    expect(seen).toEqual(expectedUsers('name', 'asc', (u) => u.name === 'Ann'))
+  })
+
+  it('sends the total and the workshop counts with the first batch', async () => {
+    const first = await getUserRows({})
+    expect(first.data?.rows).toHaveLength(50)
+    expect(first.data?.total).toBe(state.users.length)
+    expect(typeof first.data?.rows[0].organizationCount).toBe('number')
+    const second = await getUserRows({ cursor: first.data?.nextCursor })
+    expect(second.data?.total).toBeUndefined()
+  })
+
+  // Newest account first, a column nothing changes on its own; last seen is
+  // bumped by every open tab's ping and would move people past the cursor.
+  it('opens newest account first', async () => {
+    const { ids: seen } = await walkBatches(getUserRows, (cursor) => ({ cursor }))
+    expect(seen).toEqual(expectedUsers('createdAt', 'desc'))
+  })
+
+  it('treats an unknown column as the default sort', async () => {
+    const { ids: seen } = await walkBatches(getUserRows, (cursor) => ({
+      sortBy: 'password',
+      cursor,
+    }))
+    expect(seen).toEqual(expectedUsers('createdAt', 'desc'))
+  })
+
+  it('is refused to anyone but a super admin', async () => {
+    state.signedIn = state.users.find((u) => !u.isSuperAdmin)?.id ?? null
+    expect(await getUserRows({})).toEqual({ success: false, error: 'Forbidden' })
+    state.signedIn = null
+    expect(await getUserRows({})).toEqual({ success: false, error: 'Unauthorized' })
+  })
+})
+
+describe('the platform workshop list in batches', () => {
+  const newestFirst = (filter = (_: Workshop) => true) =>
+    ordered(state.organizations.filter(filter), [{ createdAt: 'desc' }, { id: 'asc' }]).map(
+      (o) => o.id
+    )
+
+  it('shows every workshop once, newest first', async () => {
+    const { ids: seen } = await walkBatches(getOrganizationRows, (cursor) => ({ cursor }))
+    expect(seen).toEqual(newestFirst())
+    expect(new Set(seen).size).toBe(seen.length)
+  })
+
+  it('keeps the search on every batch', async () => {
+    const { ids: seen } = await walkBatches(getOrganizationRows, (cursor) => ({
+      search: 'nordic',
+      cursor,
+    }))
+    expect(seen).toEqual(newestFirst((o) => o.name.startsWith('Nordic')))
+  })
+
+  it('names each workshop owner and sends the total with the first batch only', async () => {
+    const first = await getOrganizationRows({})
+    expect(first.data?.rows[0]).toMatchObject({ ownerEmail: 'admin@example.com', memberCount: 2 })
+    expect(first.data?.total).toBe(state.organizations.length)
+    const second = await getOrganizationRows({ cursor: first.data?.nextCursor })
+    expect(second.data?.total).toBeUndefined()
+  })
+
+  it('is refused to anyone but a super admin', async () => {
+    state.signedIn = state.users.find((u) => !u.isSuperAdmin)?.id ?? null
+    expect(await getOrganizationRows({})).toEqual({ success: false, error: 'Forbidden' })
+  })
+})

+ 137 - 0
src/__tests__/features/audit/get-audit-log-rows.test.ts

@@ -0,0 +1,137 @@
+/**
+ * @vitest-environment node
+ *
+ * The audit log loads as it scrolls (getAuditLogRows). What a person relies
+ * on: every entry turns up once, newest first, however many share a second;
+ * the filters hold for every batch, not just the first; and a workshop only
+ * ever sees its own log.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { walkBatches } from '@/__tests__/helpers/in-memory-table'
+
+type Log = {
+  id: string
+  organizationId: string
+  timestamp: Date
+  action: string
+  entity: string | null
+  entityId: string | null
+  message: string | null
+  userId: string | null
+  user: { id: string; name: string; email: string } | null
+}
+
+const state = vi.hoisted(() => ({ logs: [] as Log[], options: [] as unknown[] }))
+
+vi.mock('@/lib/db', async () => {
+  const { inMemoryTable } = await import('@/__tests__/helpers/in-memory-table')
+  return { db: { auditLog: inMemoryTable(() => state.logs) } }
+})
+vi.mock('@/lib/with-auth', () => ({
+  withAuth: async (
+    run: (ctx: { organizationId: string }) => Promise<unknown>,
+    options?: unknown
+  ) => {
+    state.options.push(options)
+    try {
+      return { success: true, data: await run({ organizationId: 'org-1' }) }
+    } catch (error) {
+      return { success: false, error: String(error) }
+    }
+  },
+}))
+
+import { getAuditLogRows } from '@/features/audit/Actions/getAuditLogRows'
+
+const ann = { id: 'u-ann', name: 'Ann', email: 'ann@example.com' }
+const bo = { id: 'u-bo', name: 'Bo', email: 'bo@example.com' }
+
+function makeLogs(): Log[] {
+  return Array.from({ length: 137 }, (_, i) => {
+    const user = i % 3 === 0 ? bo : ann
+    return {
+      id: `log-${String((i * 37) % 137).padStart(3, '0')}`,
+      organizationId: i % 10 === 9 ? 'org-2' : 'org-1',
+      // Many entries in the same second, so the id has to break the ties.
+      timestamp: new Date(Date.UTC(2026, 10, 1, 9, 0, Math.floor(i / 4))),
+      action: i % 2 === 0 ? 'invoice.sent' : 'customer.update',
+      entity: i % 2 === 0 ? 'invoice' : 'customer',
+      entityId: `e-${i}`,
+      message: i % 5 === 0 ? 'Brake job emailed' : 'Changed phone',
+      userId: user.id,
+      user,
+    }
+  })
+}
+
+/** The ids the list should show, in order: newest first, ties by id. */
+function expected(filter: (log: Log) => boolean) {
+  return state.logs
+    .filter((log) => log.organizationId === 'org-1' && filter(log))
+    .sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime() || (a.id < b.id ? -1 : 1))
+    .map((log) => log.id)
+}
+
+beforeEach(() => {
+  state.logs = makeLogs()
+  state.options = []
+})
+
+describe('the audit log in batches', () => {
+  it('shows every entry of the workshop once, newest first', async () => {
+    const { ids: seen } = await walkBatches(getAuditLogRows, (cursor) => ({ cursor }))
+    expect(seen).toEqual(expected(() => true))
+    expect(new Set(seen).size).toBe(seen.length)
+  })
+
+  it('sends 50 rows, the total and the filter choices with the first batch only', async () => {
+    const first = await getAuditLogRows({})
+    expect(first.data?.rows).toHaveLength(50)
+    expect(first.data?.total).toBe(expected(() => true).length)
+    expect(first.data?.filters?.actions).toEqual(['customer.update', 'invoice.sent'])
+    expect(first.data?.filters?.users.map((u) => u.id).sort()).toEqual(['u-ann', 'u-bo'])
+
+    const second = await getAuditLogRows({ cursor: first.data?.nextCursor })
+    expect(second.data?.total).toBeUndefined()
+    expect(second.data?.filters).toBeUndefined()
+  })
+
+  it('keeps the filters on every batch', async () => {
+    const { ids: seen } = await walkBatches(getAuditLogRows, (cursor) => ({
+      action: 'invoice.sent',
+      userId: 'u-ann',
+      cursor,
+    }))
+    expect(seen).toEqual(expected((log) => log.action === 'invoice.sent' && log.userId === 'u-ann'))
+  })
+
+  it('searches the message and the person on every batch', async () => {
+    const { ids: seen } = await walkBatches(getAuditLogRows, (cursor) => ({
+      search: 'brake',
+      cursor,
+    }))
+    expect(seen).toEqual(expected((log) => log.message === 'Brake job emailed'))
+    const { ids: byName } = await walkBatches(getAuditLogRows, (cursor) => ({
+      search: 'BO@EX',
+      cursor,
+    }))
+    expect(byName).toEqual(expected((log) => log.userId === 'u-bo'))
+  })
+
+  it('never shows another workshop its entries', async () => {
+    const { ids: seen } = await walkBatches(getAuditLogRows, (cursor) => ({ cursor }))
+    const theirs = state.logs.filter((log) => log.organizationId === 'org-2').map((log) => log.id)
+    expect(theirs.length).toBeGreaterThan(0)
+    expect(seen.some((id) => theirs.includes(id))).toBe(false)
+  })
+
+  it('asks for no more than the old list did: any signed-in member of the workshop', async () => {
+    await getAuditLogRows({})
+    expect(state.options[0]).toBeUndefined()
+  })
+
+  it('refuses a cursor that does not fit the list', async () => {
+    const result = await getAuditLogRows({ cursor: { v: [1, 2], id: 'x' } })
+    expect(result.success).toBe(false)
+  })
+})

+ 247 - 0
src/__tests__/features/billing/billing-rows.test.ts

@@ -0,0 +1,247 @@
+/**
+ * @vitest-environment node
+ *
+ * The billing list loads more invoices as it scrolls. Its query is raw SQL
+ * (payment status and the shown date are computed), so it carries its own
+ * keyset: walking it batch by batch has to show every invoice once and in
+ * the list's order, whatever the sort and however many rows have no value in
+ * it, and every batch keeps to the filters and to the workshop.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const queries = vi.hoisted(() => ({ calls: [] as { sql: string; values: unknown[] }[] }))
+const rawRows = vi.hoisted(() => ({ next: [] as Record<string, unknown>[] }))
+const auth = vi.hoisted(() => ({ options: [] as unknown[] }))
+
+vi.mock('@/lib/db', () => ({
+  db: {
+    $queryRaw: vi.fn(async (query: { sql: string; values: unknown[] }) => {
+      queries.calls.push({ sql: query.sql, values: query.values })
+      if (query.sql.includes('COUNT(*) AS cnt')) return [{ cnt: BigInt(421) }]
+      if (query.sql.includes('total_revenue')) return [{}]
+      return rawRows.next
+    }),
+  },
+}))
+vi.mock('@/lib/with-auth', () => ({
+  withAuth: async (
+    run: (ctx: { organizationId: string }) => Promise<unknown>,
+    options: unknown
+  ) => {
+    auth.options.push(options)
+    try {
+      return { success: true, data: await run({ organizationId: 'org-1' }) }
+    } catch (error) {
+      return { success: false, error: (error as Error).message }
+    }
+  },
+}))
+
+import { getBillingRows } from '@/features/billing/Actions/getBillingRows'
+import {
+  type BillingSortPart,
+  billingKeysetAfter,
+  billingListSort,
+  type KeyCondition,
+} from '@/features/billing/Lib/billingList.server'
+import type { Cursor, KeyValue } from '@/lib/keyset'
+
+/** A row of the list by its sort values, the way the query's k0, k1… columns hold them. */
+type KeyRow = { id: string; k: KeyValue[] }
+
+function cmp(kind: BillingSortPart['kind'], a: KeyValue, b: KeyValue) {
+  const x = kind === 'date' ? new Date(a as string).getTime() : a
+  const y = kind === 'date' ? new Date(b as string).getTime() : b
+  return (x as number) < (y as number) ? -1 : (x as number) > (y as number) ? 1 : 0
+}
+
+/** How Postgres would answer the condition for one row. */
+function holds(parts: BillingSortPart[], row: KeyRow, cond: KeyCondition): boolean {
+  if ('or' in cond) return cond.or.some((c) => holds(parts, row, c))
+  if ('and' in cond) return cond.and.every((c) => holds(parts, row, c))
+  if ('idAfter' in cond) return row.id > cond.idAfter
+  const value = row.k[cond.part]
+  if ('isNull' in cond) return cond.isNull ? value === null : value !== null
+  if (value === null) return false
+  const c = cmp(parts[cond.part].kind, value, cond.value)
+  return cond.op === 'gt' ? c > 0 : cond.op === 'lt' ? c < 0 : c === 0
+}
+
+/** The rows in the order the query's ORDER BY gives them. */
+function sorted(rows: KeyRow[], parts: BillingSortPart[]) {
+  return [...rows].sort((a, b) => {
+    for (let i = 0; i < parts.length; i++) {
+      const x = a.k[i]
+      const y = b.k[i]
+      if (x === null && y === null) continue
+      if (x === null) return parts[i].nulls === 'first' ? -1 : 1
+      if (y === null) return parts[i].nulls === 'first' ? 1 : -1
+      const c = cmp(parts[i].kind, x, y)
+      if (c !== 0) return parts[i].dir === 'asc' ? c : -c
+    }
+    return a.id < b.id ? -1 : 1
+  })
+}
+
+function walk(rows: KeyRow[], parts: BillingSortPart[], size: number) {
+  const order = sorted(rows, parts)
+  const seen: string[] = []
+  let cursor: Cursor | null = null
+  for (let guard = 0; guard < 100; guard++) {
+    const after: KeyCondition | null = cursor ? billingKeysetAfter(parts, cursor) : null
+    const batch: KeyRow[] = order.filter((row) => !after || holds(parts, row, after)).slice(0, size)
+    if (batch.length === 0) break
+    seen.push(...batch.map((row) => row.id))
+    const last: KeyRow = batch[batch.length - 1]
+    cursor = { v: last.k, id: last.id }
+  }
+  return { seen, expected: order.map((row) => row.id) }
+}
+
+/** Sort values for a row under each sort, with plenty of ties and empty values. */
+function keysFor(sortBy: string, i: number): KeyValue[] {
+  const date = new Date(Date.UTC(2026, 0, 1 + (i % 9))).toISOString()
+  switch (sortBy) {
+    case 'invoiceNumber':
+      return [i % 5 === 0 ? null : `INV-${i % 13}`]
+    case 'title':
+      return [['Brakes', 'Service', 'Tyres'][i % 3]]
+    case 'vehicle':
+      // A counter sale has no vehicle at all.
+      return i % 6 === 0 ? [null, null, null] : [['Volvo', 'Audi'][i % 2], 'V70', 2010 + (i % 3)]
+    case 'customer':
+      return [i % 7 === 0 ? null : ['Ola', 'Kari', 'Per'][i % 3]]
+    case 'total':
+      return [(i % 6) * 125.5]
+    case 'delivery':
+      return [i % 3, i % 3 === 2 && i % 4 !== 0 ? date : null]
+    default:
+      return [date]
+  }
+}
+
+describe('walking the list batch by batch', () => {
+  const sorts = ['', 'date', 'invoiceNumber', 'title', 'vehicle', 'customer', 'total', 'delivery']
+  for (const sortBy of sorts) {
+    for (const dir of ['asc', 'desc'] as const) {
+      it(`shows every invoice once, sorted by ${sortBy || 'default'} ${dir}`, () => {
+        const parts = billingListSort(sortBy || undefined, dir)
+        const rows = Array.from({ length: 97 }, (_, i) => ({
+          id: `r${String(i).padStart(3, '0')}`,
+          k: keysFor(sortBy, i),
+        }))
+        for (const size of [1, 7, 50]) {
+          const { seen, expected } = walk(rows, parts, size)
+          expect(seen).toEqual(expected)
+        }
+      })
+    }
+  }
+
+  it('refuses a cursor from another sort', () => {
+    const parts = billingListSort('vehicle', 'asc')
+    expect(() => billingKeysetAfter(parts, { v: ['x'], id: 'r1' })).toThrow('Invalid cursor')
+    expect(() =>
+      billingKeysetAfter(billingListSort('total', 'asc'), { v: ['lots'], id: 'r1' })
+    ).toThrow('Invalid cursor')
+  })
+})
+
+/** A row as the batch query returns it. */
+function rawRow(id: string, k0: unknown) {
+  return {
+    id,
+    title: 'Brakes',
+    invoiceNumber: null,
+    serviceDate: new Date('2026-01-01T00:00:00Z'),
+    startDateTime: null,
+    invoiceDate: null,
+    effective_total: 100,
+    paid_amount: 0,
+    manually_paid: false,
+    vehicle_id: null,
+    vehicle_make: null,
+    vehicle_model: null,
+    vehicle_year: null,
+    vehicle_license_plate: null,
+    customer_id: null,
+    customer_name: null,
+    sent_at: null,
+    view_count: 0,
+    last_viewed_at: null,
+    job_status: 'completed',
+    k0,
+  }
+}
+
+describe('the billing batch action', () => {
+  beforeEach(() => {
+    queries.calls = []
+    auth.options = []
+    rawRows.next = []
+  })
+
+  const batchQuery = () => queries.calls.find((q) => q.sql.includes('ORDER BY'))
+
+  it('reads 50 rows, says where the next batch starts, and counts only on the first', async () => {
+    rawRows.next = Array.from({ length: 51 }, (_, i) =>
+      rawRow(`r${String(i).padStart(3, '0')}`, new Date(Date.UTC(2026, 0, 51 - i)))
+    )
+    const first = await getBillingRows({})
+    expect(first.success).toBe(true)
+    expect(first.data?.rows).toHaveLength(50)
+    expect(first.data?.total).toBe(421)
+    expect(first.data?.summary).toBeDefined()
+    expect(first.data?.nextCursor).toEqual({
+      v: [new Date(Date.UTC(2026, 0, 2)).toISOString()],
+      id: 'r049',
+    })
+    expect(batchQuery()?.values).toContain(51)
+
+    queries.calls = []
+    rawRows.next = [rawRow('r050', new Date(Date.UTC(2026, 0, 1)))]
+    const next = await getBillingRows({ cursor: first.data?.nextCursor })
+    expect(next.data?.rows.map((r) => r.id)).toEqual(['r050'])
+    expect(next.data?.nextCursor).toBeNull()
+    expect(next.data?.total).toBeUndefined()
+    expect(next.data?.summary).toBeUndefined()
+    // Only the batch itself is asked for: no count, no summary.
+    expect(queries.calls).toHaveLength(1)
+    // The batch carries on after the cursor.
+    expect(batchQuery()?.values).toEqual(
+      expect.arrayContaining([new Date(Date.UTC(2026, 0, 2)).toISOString(), 'r049'])
+    )
+  })
+
+  it('keeps every batch to the workshop and the filters', async () => {
+    await getBillingRows({
+      search: 'volvo',
+      status: 'unpaid',
+      delivery: 'unviewed',
+      completedOnly: true,
+      cursor: { v: [new Date().toISOString()], id: 'r1' },
+    })
+    const query = batchQuery()
+    expect(query?.values).toContain('org-1')
+    expect(query?.values).toContain('%volvo%')
+    expect(query?.sql).toContain('paid_amount = 0')
+    expect(query?.sql).toContain('view_count = 0')
+    expect(query?.sql).toContain(`sr.status = 'completed'`)
+    expect(query?.sql).toContain('sub.id >')
+  })
+
+  it('counts and sums only this workshop on the first batch', async () => {
+    await getBillingRows({})
+    expect(queries.calls).toHaveLength(3)
+    for (const query of queries.calls) expect(query.values).toContain('org-1')
+  })
+
+  it('asks for the right to read billing and refuses a cursor from another sort', async () => {
+    await getBillingRows({})
+    expect(auth.options[0]).toEqual({
+      requiredPermissions: [{ action: 'read', subject: 'billing' }],
+    })
+    const result = await getBillingRows({ sortBy: 'vehicle', cursor: { v: [null], id: 'r1' } })
+    expect(result.success).toBe(false)
+  })
+})

+ 85 - 0
src/__tests__/features/customers/customer-count-sql.test.ts

@@ -0,0 +1,85 @@
+/**
+ * @vitest-environment node
+ *
+ * The customer list sorted by vehicle count reads its batches in SQL, with
+ * the list's filters written out a second time beside the Prisma `where`
+ * every other sort uses. If the two drift apart, that sort shows a different
+ * list from the rest. These pins hold both side by side for every filter, so
+ * a change to one fails here until the other matches; the database test
+ * (src/__tests__/db/count-sort.db.test.ts) walks both against Postgres.
+ */
+import { describe, expect, it, vi } from 'vitest'
+
+vi.mock('@/lib/db', () => ({ db: {} }))
+
+import {
+  type CustomerListFilters,
+  customerListWhere,
+  customerListWhereSql,
+} from '@/features/customers/Lib/customerList.server'
+
+const FIELDS = ['name', 'email', 'phone', 'company', 'customerNumber']
+
+/** One word in any field, in Prisma. */
+const anyField = (word: string) =>
+  FIELDS.map((field) => ({ [field]: { contains: word, mode: 'insensitive' } }))
+
+/** The same in SQL: Prisma's own ILIKE, the word a parameter (`?`) per field. */
+const anyFieldSql = `(${FIELDS.map((f) => `c."${f}" ILIKE ('%' || ? || '%')`).join(' OR ')})`
+
+function both(params: CustomerListFilters) {
+  const sql = customerListWhereSql('org-1', params)
+  return {
+    prisma: customerListWhere('org-1', params),
+    sql: sql.sql.replace(/\s+/g, ' ').trim(),
+    values: sql.values,
+  }
+}
+
+describe('the customer filters, in Prisma and in SQL', () => {
+  it('no search: the workshop only', () => {
+    expect(both({})).toEqual({
+      prisma: { organizationId: 'org-1' },
+      sql: 'c."organizationId" = ?',
+      values: ['org-1'],
+    })
+    // Spaces alone are no search.
+    expect(both({ search: '   ' })).toEqual(both({}))
+  })
+
+  it('one word: any field', () => {
+    expect(both({ search: ' berg ' })).toEqual({
+      prisma: { organizationId: 'org-1', OR: anyField('berg') },
+      sql: `c."organizationId" = ? AND ${anyFieldSql}`,
+      values: ['org-1', ...FIELDS.map(() => 'berg')],
+    })
+  })
+
+  it('several words: each in some field', () => {
+    expect(both({ search: 'berg  volvo' })).toEqual({
+      prisma: {
+        organizationId: 'org-1',
+        AND: [{ OR: anyField('berg') }, { OR: anyField('volvo') }],
+      },
+      sql: `c."organizationId" = ? AND ${anyFieldSql} AND ${anyFieldSql}`,
+      values: ['org-1', ...FIELDS.map(() => 'berg'), ...FIELDS.map(() => 'volvo')],
+    })
+  })
+
+  it('a word with LIKE wildcards in it goes as typed, as Prisma sends it', () => {
+    // Prisma 7 puts `contains` in ILIKE ('%' || $n || '%') and escapes
+    // nothing, so `%`, `_` and `\` act as wildcards there; here too.
+    const word = '50%_a\\b'
+    expect(both({ search: word })).toEqual({
+      prisma: { organizationId: 'org-1', OR: anyField(word) },
+      sql: `c."organizationId" = ? AND ${anyFieldSql}`,
+      values: ['org-1', ...FIELDS.map(() => word)],
+    })
+  })
+
+  it('the sort and its direction filter nothing', () => {
+    expect(both({ search: 'berg', sortBy: 'vehicles', sortOrder: 'asc' })).toEqual(
+      both({ search: 'berg' })
+    )
+  })
+})

+ 214 - 0
src/__tests__/features/customers/get-customer-rows.test.ts

@@ -0,0 +1,214 @@
+/**
+ * @vitest-environment node
+ *
+ * The customer list loads in batches as it scrolls (getCustomerRows). Walking
+ * it batch by batch has to show every customer the search finds exactly
+ * once, in the order the column says, whatever it is sorted by, and only the
+ * signed-in workshop's.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+  countKeysetIds,
+  inMemoryTable,
+  ordered,
+  walkBatches,
+} from '@/__tests__/helpers/in-memory-table'
+
+type Customer = {
+  id: string
+  organizationId: string
+  customerNumber: string | null
+  name: string
+  email: string | null
+  phone: string | null
+  company: string | null
+  updatedAt: Date
+  poRequired: boolean
+  vehicles: { id: string }[]
+}
+
+let customers: Customer[] = []
+const table = inMemoryTable(() => customers)
+const findMany = vi.hoisted(() => vi.fn())
+const count = vi.hoisted(() => vi.fn())
+
+vi.mock('@/lib/db', () => ({ db: { customer: { findMany, count } } }))
+vi.mock('@/features/customer-reference/Lib/referenceSetting', async (original) => ({
+  ...(await original<typeof import('@/features/customer-reference/Lib/referenceSetting')>()),
+  isCustomerReferenceEnabled: vi.fn(async () => false),
+}))
+// The vehicle-count sort's SQL, answered from the same rows (the query itself
+// is checked against Postgres). The cursor check is the real one.
+vi.mock('@/features/customers/Lib/customerList.server', async (original) => {
+  const real = await original<typeof import('@/features/customers/Lib/customerList.server')>()
+  const { countCursorValue } = await import('@/lib/keyset-count')
+  return {
+    ...real,
+    customerIdsByVehicleCount: vi.fn(
+      async (
+        organizationId: string,
+        params: { search?: string },
+        dir: 'asc' | 'desc',
+        cursor: { v: (string | number | null)[]; id: string } | null | undefined,
+        take: number
+      ) => {
+        if (cursor) countCursorValue(cursor)
+        // The customers the list's own where finds; the SQL's twin of it is
+        // pinned and walked against Postgres on its own.
+        const { inMemoryTable } = await import('@/__tests__/helpers/in-memory-table')
+        const matching = await inMemoryTable(() => customers).findMany({
+          where: real.customerListWhere(organizationId, params),
+        })
+        const ids = matching.map((c: { id: string }) => c.id)
+        return countKeysetIds(customers, (c) => c.vehicles.length, {
+          organizationId,
+          ids,
+          dir,
+          cursor,
+          take,
+        })
+      }
+    ),
+  }
+})
+const auth = vi.hoisted(() => ({ organizationId: 'org-1', permissions: [] as unknown[] }))
+vi.mock('@/lib/with-auth', () => ({
+  withAuth: async (
+    run: (ctx: { organizationId: string }) => Promise<unknown>,
+    options?: { requiredPermissions?: unknown[] }
+  ) => {
+    auth.permissions = options?.requiredPermissions ?? []
+    try {
+      return { success: true, data: await run({ organizationId: auth.organizationId }) }
+    } catch (error) {
+      return { success: false, error: (error as Error).message }
+    }
+  },
+}))
+
+import { getCustomerRows } from '@/features/customers/Actions/getCustomerRows'
+
+const names = ['Ada Berg', 'Bo Lind', 'Cy Dahl', 'Di Holm']
+function makeCustomers(organizationId: string, howMany: number, prefix: string): Customer[] {
+  return Array.from({ length: howMany }, (_, i) => ({
+    id: `${prefix}${String(i).padStart(3, '0')}`,
+    organizationId,
+    // Plenty of ties and empty values, so the id has to break them.
+    customerNumber: i % 5 === 0 ? null : String(1000 + (i % 40)),
+    name: names[i % names.length],
+    email: i % 3 === 0 ? null : `c${i % 7}@example.com`,
+    phone: i % 4 === 0 ? null : `+47 9${i % 9}`,
+    company: i % 2 === 0 ? null : ['Volvo', 'Fjord AS', 'Holm Transport'][i % 3],
+    updatedAt: new Date(Date.UTC(2026, 9, 1 + (i % 11), 8)),
+    poRequired: i % 6 === 0,
+    vehicles: Array.from({ length: i % 4 }, (_, v) => ({ id: `${prefix}v${i}-${v}` })),
+  }))
+}
+
+beforeEach(() => {
+  auth.organizationId = 'org-1'
+  customers = [...makeCustomers('org-1', 137, 'a'), ...makeCustomers('org-2', 40, 'b')]
+  findMany.mockReset().mockImplementation(table.findMany)
+  count.mockReset().mockImplementation(table.count)
+})
+
+const walk = (params: Parameters<typeof getCustomerRows>[0]) =>
+  walkBatches(getCustomerRows, (cursor) => ({ ...params, cursor }))
+
+const sorts = ['number', 'name', 'company', 'phone', 'email', 'vehicles', undefined]
+
+describe('the customer list, batch by batch', () => {
+  for (const sortBy of sorts) {
+    for (const sortOrder of ['asc', 'desc'] as const) {
+      it(`shows every customer once, in order, sorted by ${sortBy ?? 'last change'} ${sortOrder}`, async () => {
+        const { ids, total } = await walk({ sortBy, sortOrder })
+
+        expect(new Set(ids).size).toBe(ids.length)
+        expect(ids).toHaveLength(137)
+        expect(total).toBe(137)
+        // The order the column promises: the first batch's own orderBy over
+        // every row of the workshop (the vehicle count's is Postgres's).
+        const orderBy =
+          sortBy === 'vehicles'
+            ? [{ vehicles: { _count: sortOrder } }, { id: 'asc' }]
+            : findMany.mock.calls[0][0].orderBy
+        const mine = customers.filter((c) => c.organizationId === 'org-1')
+        expect(ids).toEqual(ordered(mine, orderBy).map((c) => c.id))
+      })
+    }
+  }
+
+  it('sends batches of 50 and only counts the list once', async () => {
+    await walk({ sortBy: 'name', sortOrder: 'asc' })
+    expect(findMany).toHaveBeenCalledTimes(3)
+    for (const [args] of findMany.mock.calls) expect(args.take).toBe(51)
+    expect(count).toHaveBeenCalledTimes(1)
+  })
+
+  it('carries on from the last vehicle count, so a customer deleted above it skips nobody', async () => {
+    for (const sortOrder of ['asc', 'desc'] as const) {
+      customers = [...makeCustomers('org-1', 137, 'a'), ...makeCustomers('org-2', 40, 'b')]
+      const first = await getCustomerRows({ sortBy: 'vehicles', sortOrder })
+      const firstIds = first.data?.rows.map((row) => row.id) ?? []
+      expect(firstIds).toHaveLength(50)
+      // Somebody deletes a customer the first batch already showed.
+      customers = customers.filter((c) => c.id !== firstIds[10])
+
+      const after = await walkBatches(getCustomerRows, (cursor) => ({
+        sortBy: 'vehicles',
+        sortOrder,
+        cursor: cursor ?? first.data?.nextCursor,
+      }))
+      const seen = [...firstIds, ...after.ids]
+      const expected = ordered(
+        customers.filter((c) => c.organizationId === 'org-1'),
+        [{ vehicles: { _count: sortOrder } }, { id: 'asc' }]
+      ).map((c) => c.id)
+      // Every customer still there, once each, and nothing skipped.
+      expect(new Set(seen).size).toBe(seen.length)
+      expect(seen.filter((id) => id !== firstIds[10])).toEqual(expected)
+    }
+  })
+
+  it('keeps to what the search finds, word by word', async () => {
+    const { ids, total } = await walk({ search: 'holm transport', sortBy: 'name' })
+    const expected = customers.filter(
+      (c) =>
+        c.organizationId === 'org-1' &&
+        [c.name, c.company].some((v) => v?.toLowerCase().includes('holm')) &&
+        [c.name, c.company].some((v) => v?.toLowerCase().includes('transport'))
+    )
+    expect(total).toBe(expected.length)
+    expect(ids.sort()).toEqual(expected.map((c) => c.id).sort())
+  })
+
+  it('never shows another workshop’s customers', async () => {
+    auth.organizationId = 'org-2'
+    const { ids } = await walk({ sortBy: 'email', sortOrder: 'desc' })
+    expect(ids).toHaveLength(40)
+    expect(ids.every((id) => id.startsWith('b'))).toBe(true)
+    for (const [args] of findMany.mock.calls) {
+      expect(JSON.stringify(args.where)).toContain('"organizationId":"org-2"')
+    }
+  })
+
+  it('asks for permission to read customers', async () => {
+    await getCustomerRows({})
+    expect(auth.permissions).toEqual([{ action: 'read', subject: 'customers' }])
+  })
+
+  it('refuses a cursor that does not fit the sort', async () => {
+    const result = await getCustomerRows({
+      sortBy: 'vehicles',
+      cursor: { v: ['not a count'], id: 'a001' },
+    })
+    expect(result.success).toBe(false)
+    const keyset = await getCustomerRows({ sortBy: 'name', cursor: { v: [1, 2], id: 'a001' } })
+    expect(keyset.success).toBe(false)
+  })
+
+  it('hides the PO flag while the workshop has the reference field off', async () => {
+    const result = await getCustomerRows({ sortBy: 'name' })
+    expect(result.data?.rows.some((row) => row.poRequired)).toBe(false)
+  })
+})

+ 168 - 0
src/__tests__/features/inspections/get-inspection-rows.test.ts

@@ -0,0 +1,168 @@
+/**
+ * @vitest-environment node
+ *
+ * The inspection list loads more rows as it scrolls (getInspectionRows). Read
+ * batch by batch, every sort has to show each inspection exactly once and in
+ * the same order one long read would, the status tab and the search have to
+ * hold on every batch, and no batch may reach another workshop's inspections.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { inMemoryTable, walkBatches } from '@/__tests__/helpers/in-memory-table'
+
+const state = vi.hoisted(() => ({ org: 'org-1', rows: [] as Record<string, any>[] }))
+
+vi.mock('@/lib/db', async () => {
+  const { inMemoryTable } = await import('@/__tests__/helpers/in-memory-table')
+  return {
+    db: {
+      inspection: {
+        findMany: vi.fn(inMemoryTable(() => state.rows).findMany),
+        count: vi.fn(inMemoryTable(() => state.rows).count),
+        groupBy: vi.fn(async () => [
+          { status: 'in_progress', _count: 5 },
+          { status: 'completed', _count: 7 },
+        ]),
+      },
+    },
+  }
+})
+vi.mock('@/features/vehicles/Lib/typeKeySetting', async (original) => ({
+  ...(await original<typeof import('@/features/vehicles/Lib/typeKeySetting')>()),
+  typeKeySearch: vi.fn(async () => []),
+}))
+vi.mock('@/lib/with-auth', () => ({
+  withAuth: vi.fn(async (run: (ctx: { organizationId: string }) => Promise<unknown>) => {
+    try {
+      return { success: true, data: await run({ organizationId: state.org }) }
+    } catch (error) {
+      return { success: false, error: (error as Error).message }
+    }
+  }),
+}))
+
+import { db } from '@/lib/db'
+import { withAuth } from '@/lib/with-auth'
+import { getInspectionRows } from '@/features/inspections/Actions/getInspectionRows'
+import { INSPECTION_BATCH_SIZE } from '@/features/inspections/Lib/inspectionList.server'
+
+/** 120 inspections here and 15 in another workshop, with plenty of ties. */
+function fixture() {
+  return Array.from({ length: 135 }, (_, i) => ({
+    id: `i${String(i).padStart(3, '0')}`,
+    organizationId: i < 120 ? 'org-1' : 'org-2',
+    status: i % 3 === 0 ? 'completed' : 'in_progress',
+    createdAt: new Date(Date.UTC(2026, 10, 1 + (i % 8))),
+    vehicle: {
+      id: `v${i % 10}`,
+      make: ['Volvo', 'Audi', 'Scania'][i % 3],
+      model: ['V70', 'A4'][i % 2],
+      year: 2012 + (i % 4),
+      licensePlate: i % 4 === 0 ? null : `ZZ${i % 30}`,
+    },
+    template: { id: `t${i % 3}`, name: ['Standard', 'EU control', 'Winter check'][i % 3] },
+    items: [],
+  }))
+}
+
+async function oneLongRead(input: Parameters<typeof getInspectionRows>[0]) {
+  vi.mocked(db.inspection.findMany).mockClear()
+  await getInspectionRows(input)
+  const args = vi.mocked(db.inspection.findMany).mock.calls[0][0] as any
+  const all = await inMemoryTable(() => state.rows).findMany({
+    where: args.where,
+    orderBy: args.orderBy,
+  })
+  return all.map((row) => row.id)
+}
+
+beforeEach(() => {
+  state.org = 'org-1'
+  state.rows = fixture()
+  vi.mocked(db.inspection.findMany).mockClear()
+  vi.mocked(db.inspection.count).mockClear()
+})
+
+const sorts: [string | undefined, 'asc' | 'desc'][] = [
+  [undefined, 'desc'],
+  ['vehicle', 'asc'],
+  ['vehicle', 'desc'],
+  ['template', 'asc'],
+  ['template', 'desc'],
+  ['status', 'asc'],
+  ['createdAt', 'asc'],
+  ['createdAt', 'desc'],
+]
+
+describe('reading the inspection list batch by batch', () => {
+  for (const [sortBy, sortOrder] of sorts) {
+    it(`shows every inspection once, in order, sorted by ${sortBy ?? 'newest'} ${sortOrder}`, async () => {
+      const input = { sortBy, sortOrder }
+      const { ids, batches, total } = await walkBatches(getInspectionRows, (cursor) => ({
+        ...input,
+        cursor,
+      }))
+      const expected = await oneLongRead(input)
+      expect(expected.length).toBe(120)
+      expect(ids).toEqual(expected)
+      expect(new Set(ids).size).toBe(ids.length)
+      expect(batches).toBe(Math.ceil(120 / INSPECTION_BATCH_SIZE))
+      expect(total).toBe(120)
+    })
+  }
+
+  it('keeps the status tab and the search on every batch', async () => {
+    const done = await walkBatches(getInspectionRows, (cursor) => ({
+      status: 'completed',
+      sortBy: 'vehicle',
+      cursor,
+    }))
+    expect(done.ids).toHaveLength(40)
+    for (const id of done.ids) {
+      expect(state.rows.find((row) => row.id === id)?.status).toBe('completed')
+    }
+
+    const winter = await walkBatches(getInspectionRows, (cursor) => ({ search: 'winter', cursor }))
+    expect(winter.ids).toHaveLength(40)
+    for (const id of winter.ids) {
+      expect(state.rows.find((row) => row.id === id)?.template.name).toBe('Winter check')
+    }
+  })
+
+  it('carries the tab counts on the first batch only', async () => {
+    const first = await getInspectionRows({})
+    expect(first.data?.statusCounts).toEqual({ in_progress: 5, completed: 7 })
+    const second = await getInspectionRows({ cursor: first.data?.nextCursor })
+    expect(second.data?.statusCounts).toBeUndefined()
+    expect(second.data?.total).toBeUndefined()
+  })
+})
+
+describe('another workshop', () => {
+  it('never sees this workshop’s inspections, in any batch', async () => {
+    state.org = 'org-2'
+    const { ids } = await walkBatches(getInspectionRows, (cursor) => ({
+      sortBy: 'template',
+      cursor,
+    }))
+    expect(ids).toHaveLength(15)
+    for (const id of ids) {
+      expect(state.rows.find((row) => row.id === id)?.organizationId).toBe('org-2')
+    }
+    for (const [args] of vi.mocked(db.inspection.count).mock.calls) {
+      expect((args as any).where.organizationId).toBe('org-2')
+    }
+  })
+})
+
+describe('the action', () => {
+  it('asks for permission to read inspections', async () => {
+    await getInspectionRows({})
+    expect(vi.mocked(withAuth).mock.calls.at(-1)?.[1]).toEqual({
+      requiredPermissions: [{ action: 'read', subject: 'inspections' }],
+    })
+  })
+
+  it('refuses a cursor that does not fit the sort', async () => {
+    expect((await getInspectionRows({ cursor: { v: ['soon'], id: 'i001' } })).success).toBe(false)
+  })
+})

+ 171 - 0
src/__tests__/features/inventory/get-inventory-rows.test.ts

@@ -0,0 +1,171 @@
+/**
+ * @vitest-environment node
+ *
+ * The inventory list loads in batches as it scrolls (getInventoryRows).
+ * Walking it batch by batch has to show every part the filters find exactly
+ * once, in the order the column says, and only the signed-in workshop's.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { inMemoryTable, ordered, walkBatches } from '@/__tests__/helpers/in-memory-table'
+
+type Part = {
+  id: string
+  organizationId: string
+  isArchived: boolean
+  name: string
+  partNumber: string | null
+  barcode: string | null
+  description: string | null
+  category: string | null
+  quantity: number
+  unitCost: number
+  sellPrice: number
+  supplier: string | null
+  location: string | null
+  updatedAt: Date
+  tags: string[]
+}
+
+let parts: Part[] = []
+const table = inMemoryTable(() => parts)
+const findMany = vi.hoisted(() => vi.fn())
+const count = vi.hoisted(() => vi.fn())
+const lowIds = vi.hoisted(() => ({ ids: [] as string[] }))
+
+vi.mock('@/lib/db', () => ({
+  db: {
+    inventoryPart: { findMany, count },
+    appSetting: { findFirst: vi.fn(async () => null) },
+    $queryRaw: vi.fn(async () => lowIds.ids.map((id) => ({ id }))),
+  },
+}))
+vi.mock('@/features/inventory/Lib/tagSearch.server', () => ({
+  partIdsWithTag: vi.fn(async (organizationId: string, tag: string) =>
+    parts
+      .filter((p) => p.organizationId === organizationId && p.tags.includes(tag))
+      .map((p) => p.id)
+  ),
+  partIdsWithTagContaining: vi.fn(async () => []),
+}))
+const auth = vi.hoisted(() => ({ organizationId: 'org-1', permissions: [] as unknown[] }))
+vi.mock('@/lib/with-auth', () => ({
+  withAuth: async (
+    run: (ctx: { organizationId: string }) => Promise<unknown>,
+    options?: { requiredPermissions?: unknown[] }
+  ) => {
+    auth.permissions = options?.requiredPermissions ?? []
+    try {
+      return { success: true, data: await run({ organizationId: auth.organizationId }) }
+    } catch (error) {
+      return { success: false, error: (error as Error).message }
+    }
+  },
+}))
+
+import { getInventoryRows } from '@/features/inventory/Actions/getInventoryRows'
+
+function makeParts(organizationId: string, howMany: number, prefix: string): Part[] {
+  return Array.from({ length: howMany }, (_, i) => ({
+    id: `${prefix}${String(i).padStart(3, '0')}`,
+    organizationId,
+    isArchived: i % 17 === 0,
+    name: ['Oil filter', 'Brake pad', 'Wiper blade', 'Spark plug'][i % 4],
+    partNumber: i % 5 === 0 ? null : `PN-${i % 23}`,
+    barcode: null,
+    description: null,
+    category: i % 3 === 0 ? null : ['Filters', 'Brakes'][i % 2],
+    quantity: i % 9,
+    unitCost: (i % 6) * 12.5,
+    sellPrice: (i % 8) * 20,
+    supplier: i % 4 === 0 ? null : ['Mekonomen', 'Bilxtra'][i % 2],
+    location: i % 7 === 0 ? null : `Shelf ${i % 5}`,
+    updatedAt: new Date(Date.UTC(2026, 9, 1 + (i % 13), 8)),
+    tags: i % 10 === 0 ? ['Hilux'] : [],
+  }))
+}
+
+beforeEach(() => {
+  auth.organizationId = 'org-1'
+  lowIds.ids = []
+  parts = [...makeParts('org-1', 163, 'a'), ...makeParts('org-2', 30, 'b')]
+  findMany.mockReset().mockImplementation(table.findMany)
+  count.mockReset().mockImplementation(table.count)
+})
+
+const walk = (params: Parameters<typeof getInventoryRows>[0]) =>
+  walkBatches(getInventoryRows, (cursor) => ({ ...params, cursor }))
+
+const live = (organizationId = 'org-1') =>
+  parts.filter((p) => p.organizationId === organizationId && !p.isArchived)
+
+const columns = [
+  'name',
+  'partNumber',
+  'category',
+  'quantity',
+  'unitCost',
+  'sellPrice',
+  'supplier',
+  'location',
+  'updatedAt',
+]
+
+describe('the inventory list, batch by batch', () => {
+  for (const sortBy of columns) {
+    for (const sortOrder of ['asc', 'desc'] as const) {
+      it(`shows every part once, in order, sorted by ${sortBy} ${sortOrder}`, async () => {
+        const { ids, total } = await walk({ sortBy, sortOrder })
+
+        expect(new Set(ids).size).toBe(ids.length)
+        expect(ids).toHaveLength(live().length)
+        expect(total).toBe(live().length)
+        const orderBy = findMany.mock.calls[0][0].orderBy
+        expect(ids).toEqual(ordered(live(), orderBy).map((p) => p.id))
+      })
+    }
+  }
+
+  it('sorts by the last change when asked for a column it does not know', async () => {
+    await getInventoryRows({ sortBy: 'userId' })
+    expect(findMany.mock.calls[0][0].orderBy).toEqual([{ updatedAt: 'desc' }, { id: 'asc' }])
+  })
+
+  it('keeps to the category, tag and low-stock filters', async () => {
+    const filters = await walk({ category: 'Brakes', sortBy: 'name' })
+    expect(filters.ids.sort()).toEqual(
+      live()
+        .filter((p) => p.category === 'Brakes')
+        .map((p) => p.id)
+        .sort()
+    )
+
+    const tagged = await walk({ tag: 'Hilux', sortBy: 'quantity' })
+    expect(tagged.ids.sort()).toEqual(
+      live()
+        .filter((p) => p.tags.includes('Hilux'))
+        .map((p) => p.id)
+        .sort()
+    )
+
+    lowIds.ids = ['a001', 'a002', 'a003']
+    const low = await walk({ lowStock: true })
+    expect(low.ids.sort()).toEqual(['a001', 'a002', 'a003'])
+  })
+
+  it('keeps to what the search finds', async () => {
+    const { ids } = await walk({ search: 'oil', sortBy: 'name' })
+    expect(ids).toHaveLength(live().filter((p) => p.name === 'Oil filter').length)
+  })
+
+  it('never shows another workshop’s parts', async () => {
+    auth.organizationId = 'org-2'
+    const { ids } = await walk({ sortBy: 'location', sortOrder: 'asc' })
+    expect(ids).toHaveLength(live('org-2').length)
+    expect(ids.every((id) => id.startsWith('b'))).toBe(true)
+  })
+
+  it('asks for permission to read the inventory', async () => {
+    await getInventoryRows({})
+    expect(auth.permissions).toEqual([{ action: 'read', subject: 'inventory' }])
+  })
+})

+ 129 - 0
src/__tests__/features/inventory/get-stock-movement-rows.test.ts

@@ -0,0 +1,129 @@
+/**
+ * @vitest-environment node
+ *
+ * A part's stock history loads in batches as it scrolls
+ * (getStockMovementRows). Every movement of that part shows exactly once,
+ * newest first, only the signed-in workshop's, and each with its time written
+ * on the workshop's clock.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { inMemoryTable, walkBatches } from '@/__tests__/helpers/in-memory-table'
+
+type Movement = {
+  id: string
+  organizationId: string
+  inventoryPartId: string
+  delta: number
+  quantityAfter: number
+  reason: string
+  note: string | null
+  createdAt: Date
+  serviceRecordLabel: string | null
+  user: { name: string } | null
+  serviceRecord: null
+}
+
+let movements: Movement[] = []
+const table = inMemoryTable(() => movements)
+const findMany = vi.hoisted(() => vi.fn())
+const count = vi.hoisted(() => vi.fn())
+
+vi.mock('@/lib/db', () => ({ db: { stockMovement: { findMany, count } } }))
+vi.mock('@/lib/workshop-timezone', () => ({
+  workshopDateSettings: vi.fn(async () => ({
+    timeZone: 'Pacific/Auckland',
+    dateFormat: 'yyyy-MM-dd',
+    timeFormat: '24h',
+  })),
+}))
+const auth = vi.hoisted(() => ({ organizationId: 'org-1', permissions: [] as unknown[] }))
+vi.mock('@/lib/with-auth', () => ({
+  withAuth: async (
+    run: (ctx: { organizationId: string }) => Promise<unknown>,
+    options?: { requiredPermissions?: unknown[] }
+  ) => {
+    auth.permissions = options?.requiredPermissions ?? []
+    try {
+      return { success: true, data: await run({ organizationId: auth.organizationId }) }
+    } catch (error) {
+      return { success: false, error: (error as Error).message }
+    }
+  },
+}))
+
+import { getStockMovementRows } from '@/features/inventory/Actions/getStockMovementRows'
+
+const reasons = ['service_record', 'manual_adjustment', 'quote_conversion']
+function makeMovements(organizationId: string, partId: string, howMany: number, prefix: string) {
+  return Array.from({ length: howMany }, (_, i) => ({
+    id: `${prefix}${String(i).padStart(3, '0')}`,
+    organizationId,
+    inventoryPartId: partId,
+    delta: i % 2 ? -1 : 4,
+    quantityAfter: i,
+    reason: reasons[i % 3],
+    note: null,
+    // Several movements in the same instant, as a job saving many lines makes.
+    createdAt: new Date(Date.UTC(2026, 9, 1 + Math.floor(i / 4), 23, 30)),
+    serviceRecordLabel: null,
+    user: { name: 'Kari' },
+    serviceRecord: null,
+  }))
+}
+
+beforeEach(() => {
+  auth.organizationId = 'org-1'
+  movements = [
+    ...makeMovements('org-1', 'part-1', 121, 'a'),
+    ...makeMovements('org-1', 'part-2', 9, 'c'),
+    // Another workshop's movements under the same part id.
+    ...makeMovements('org-2', 'part-1', 12, 'b'),
+  ]
+  findMany.mockReset().mockImplementation(table.findMany)
+  count.mockReset().mockImplementation(table.count)
+})
+
+const walk = (params: Omit<Parameters<typeof getStockMovementRows>[0], 'cursor'>) =>
+  walkBatches(getStockMovementRows, (cursor) => ({ ...params, cursor }))
+
+describe('a part’s stock history, batch by batch', () => {
+  it('shows every movement of the part once, newest first', async () => {
+    const { ids, total } = await walk({ inventoryPartId: 'part-1' })
+
+    expect(total).toBe(121)
+    expect(ids).toHaveLength(121)
+    expect(new Set(ids).size).toBe(121)
+    const expected = movements
+      .filter((m) => m.organizationId === 'org-1' && m.inventoryPartId === 'part-1')
+      .sort((x, y) => y.createdAt.getTime() - x.createdAt.getTime() || (x.id < y.id ? -1 : 1))
+      .map((m) => m.id)
+    expect(ids).toEqual(expected)
+  })
+
+  it('keeps to the reason, and ignores one it does not know', async () => {
+    const used = await walk({ inventoryPartId: 'part-1', reason: 'service_record' })
+    expect(used.ids).toHaveLength(41)
+
+    const unknown = await walk({ inventoryPartId: 'part-1', reason: 'teleported' })
+    expect(unknown.ids).toHaveLength(121)
+  })
+
+  it('never shows another workshop’s movements, even for the same part id', async () => {
+    auth.organizationId = 'org-2'
+    const { ids } = await walk({ inventoryPartId: 'part-1' })
+    expect(ids).toHaveLength(12)
+    expect(ids.every((id) => id.startsWith('b'))).toBe(true)
+  })
+
+  it('writes the time on the workshop’s clock', async () => {
+    const result = await getStockMovementRows({ inventoryPartId: 'part-2' })
+    const first = result.data?.rows.find((row) => row.id === 'c000')
+    // 23:30 UTC on 1 October is 12:30 the next day in Auckland.
+    expect(first?.createdAtLabel).toBe('2026-10-02 12:30')
+  })
+
+  it('asks for permission to read the inventory', async () => {
+    await getStockMovementRows({ inventoryPartId: 'part-1' })
+    expect(auth.permissions).toEqual([{ action: 'read', subject: 'inventory' }])
+  })
+})

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

@@ -69,12 +69,19 @@ vi.mock('@/features/settings/Actions/settingsActions', () => ({
   setSetting: (...args: unknown[]) => setSetting(...args),
 }))
 
+vi.mock('@/features/inventory/Actions/getInventoryRows', () => ({ getInventoryRows: vi.fn() }))
+
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
 import { InventoryClient } from '@/app/(authenticated)/inventory/inventory-client'
 
-const emptyList = { parts: [], total: 0, page: 1, pageSize: 25, totalPages: 0 }
+const emptyList = { rows: [], nextCursor: null, total: 0, renderId: 'render-1' }
 
 function renderList(props: Partial<React.ComponentProps<typeof InventoryClient>> = {}) {
-  render(<InventoryClient data={emptyList} search="" category="" categories={[]} {...props} />)
+  render(
+    <QueryClientProvider client={new QueryClient()}>
+      <InventoryClient data={emptyList} search="" category="" categories={[]} {...props} />
+    </QueryClientProvider>
+  )
 }
 
 /** Opens Apply Markup, types a percentage and presses the named button. */

+ 167 - 0
src/__tests__/features/inventory/inventory-selection.test.tsx

@@ -0,0 +1,167 @@
+/**
+ * Ticking parts in an inventory list that loads more as it scrolls.
+ *
+ * The header box takes the parts loaded so far and says how many, a bulk
+ * delete never reaches one that has not loaded, ticks stay while more rows
+ * arrive, and another filter starts with nothing ticked.
+ */
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const deleteInventoryParts = vi.fn()
+const getInventoryRows = vi.fn()
+const confirm = vi.fn(async () => true)
+
+vi.mock('next/navigation', () => ({
+  useRouter: () => ({ refresh: vi.fn(), push: vi.fn(), replace: vi.fn() }),
+  usePathname: () => '/inventory',
+  useSearchParams: () => new URLSearchParams(),
+}))
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
+vi.mock('@/components/glass-modal', () => ({ useGlassModal: () => ({ open: vi.fn() }) }))
+vi.mock('@/components/confirm-dialog', () => ({ useConfirm: () => confirm }))
+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/Components/InventoryPartForm', () => ({
+  InventoryPartForm: () => null,
+}))
+vi.mock('@/features/inventory/Components/ApplyMarkupDialog', () => ({
+  ApplyMarkupDialog: () => null,
+}))
+vi.mock('@/features/inventory/Actions/lookupPartByBarcode', () => ({
+  lookupPartByBarcode: vi.fn(),
+}))
+vi.mock('@/features/inventory/Actions/inventoryActions', () => ({
+  deleteInventoryPart: vi.fn(),
+  deleteInventoryParts: async (ids: string[]) => deleteInventoryParts(ids),
+}))
+vi.mock('@/features/inventory/Actions/getInventoryRows', () => ({
+  getInventoryRows: (input: unknown) => getInventoryRows(input),
+}))
+
+import { InventoryClient } from '@/app/(authenticated)/inventory/inventory-client'
+
+const observers: { callback: IntersectionObserverCallback; observer: IntersectionObserver }[] = []
+class FakeObserver {
+  constructor(public callback: IntersectionObserverCallback) {
+    observers.push({ callback, observer: this as unknown as IntersectionObserver })
+  }
+  observe() {
+    // The test says when the end is in sight.
+  }
+  unobserve() {
+    // As above.
+  }
+  disconnect() {
+    // As above.
+  }
+  takeRecords() {
+    return []
+  }
+}
+function endInSight() {
+  act(() => {
+    for (const { callback, observer } of observers) {
+      callback([{ isIntersecting: true } as IntersectionObserverEntry], observer)
+    }
+  })
+}
+
+function part(i: number) {
+  return {
+    id: `p${i}`,
+    partNumber: `PN-${i}`,
+    barcode: null,
+    name: `Part ${i}`,
+    description: null,
+    category: null,
+    quantity: 10,
+    minQuantity: 0,
+    trackStock: true,
+    unit: null,
+    unitCost: 1,
+    sellPrice: 2,
+    supplier: null,
+    supplierPhone: null,
+    supplierEmail: null,
+    supplierUrl: null,
+    imageUrl: null,
+    gallery: [],
+    location: null,
+    tags: [],
+  }
+}
+// Small batches keep the render quick; the list does not care how big they are.
+const all = Array.from({ length: 16 }, (_, i) => part(i + 1))
+const firstBatch = {
+  rows: all.slice(0, 10),
+  nextCursor: { v: ['x'], id: 'p10' },
+  total: 16,
+  renderId: 'render-1',
+}
+
+let client: QueryClient
+function list(category = '') {
+  return (
+    <QueryClientProvider client={client}>
+      <InventoryClient
+        data={firstBatch}
+        listScope="org-1"
+        search=""
+        category={category}
+        categories={['Filters']}
+      />
+    </QueryClientProvider>
+  )
+}
+
+beforeEach(() => {
+  observers.length = 0
+  vi.stubGlobal('IntersectionObserver', FakeObserver)
+  client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+  deleteInventoryParts.mockReset().mockResolvedValue({ success: true, data: { deleted: 0 } })
+  getInventoryRows
+    .mockReset()
+    .mockResolvedValue({ success: true, data: { rows: all.slice(10), nextCursor: null } })
+})
+
+afterEach(() => {
+  vi.unstubAllGlobals()
+  client.clear()
+})
+
+describe('selecting parts in the scrolling list', () => {
+  it('deletes only the parts that were loaded and ticked, after more have loaded', async () => {
+    render(list())
+    fireEvent.click(screen.getByRole('checkbox', { name: 'Select all 10 shown' }))
+    expect(screen.getByText('10 parts selected')).toBeInTheDocument()
+
+    endInSight()
+    await waitFor(() => expect(screen.getAllByText('Part 16')).not.toHaveLength(0))
+    // Still the ten; the six that arrived are not ticked.
+    expect(screen.getByText('10 parts selected')).toBeInTheDocument()
+    expect(screen.getByRole('checkbox', { name: 'Select all 16 shown' })).toHaveAttribute(
+      'data-state',
+      'indeterminate'
+    )
+
+    await act(async () => {
+      fireEvent.click(screen.getByRole('button', { name: 'Delete (10)' }))
+    })
+    expect(deleteInventoryParts).toHaveBeenCalledWith(all.slice(0, 10).map((p) => p.id))
+  })
+
+  it('starts another filter with nothing selected', () => {
+    const { rerender } = render(list())
+    fireEvent.click(screen.getAllByRole('checkbox', { name: 'Select Part 2' })[0])
+    expect(screen.getByText('1 part selected')).toBeInTheDocument()
+
+    rerender(list('Filters'))
+    expect(screen.queryByText('1 part selected')).not.toBeInTheDocument()
+  })
+})

+ 13 - 8
src/__tests__/features/inventory/untracked-parts-list.test.tsx

@@ -67,9 +67,12 @@ vi.mock('@/features/settings/Actions/settingsActions', () => ({
   setSetting: vi.fn(),
 }))
 
+vi.mock('@/features/inventory/Actions/getInventoryRows', () => ({ getInventoryRows: vi.fn() }))
+
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
 import { InventoryClient } from '@/app/(authenticated)/inventory/inventory-client'
 
-type Part = React.ComponentProps<typeof InventoryClient>['data']['parts'][number]
+type Part = React.ComponentProps<typeof InventoryClient>['data']['rows'][number]
 
 function part(overrides: Partial<Part>): Part {
   return {
@@ -99,13 +102,15 @@ function part(overrides: Partial<Part>): Part {
 
 function renderList(parts: Part[]) {
   render(
-    <InventoryClient
-      data={{ parts, total: parts.length, page: 1, pageSize: 25, totalPages: 1 }}
-      search=""
-      category=""
-      categories={[]}
-      lowStockDefault={5}
-    />
+    <QueryClientProvider client={new QueryClient()}>
+      <InventoryClient
+        data={{ rows: parts, nextCursor: null, total: parts.length, renderId: 'render-1' }}
+        search=""
+        category=""
+        categories={[]}
+        lowStockDefault={5}
+      />
+    </QueryClientProvider>
   )
 }
 

+ 135 - 0
src/__tests__/features/labor-presets/get-labor-preset-rows.test.ts

@@ -0,0 +1,135 @@
+/**
+ * @vitest-environment node
+ *
+ * The labor packages list loads as it scrolls (getLaborPresetRows). Every
+ * package turns up once whatever column it is sorted by, archived ones and
+ * other workshops' never do, the search holds for every batch, and reading the
+ * list still takes the right to read labor packages.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { PermissionAction, PermissionSubject } from '@/lib/permissions'
+import { ordered, walkBatches } from '@/__tests__/helpers/in-memory-table'
+
+type Preset = {
+  id: string
+  organizationId: string
+  isArchived: boolean
+  name: string
+  description: string | null
+  createdAt: Date
+  updatedAt: Date
+  _count: { items: number; parts: number }
+  items: { hours: number; pricingType: string }[]
+}
+
+const state = vi.hoisted(() => ({ presets: [] as Preset[], options: [] as unknown[] }))
+
+vi.mock('@/lib/db', async () => {
+  const { inMemoryTable } = await import('@/__tests__/helpers/in-memory-table')
+  return { db: { laborPreset: inMemoryTable(() => state.presets) } }
+})
+vi.mock('@/lib/with-auth', () => ({
+  withAuth: async (
+    run: (ctx: { organizationId: string }) => Promise<unknown>,
+    options?: unknown
+  ) => {
+    state.options.push(options)
+    try {
+      return { success: true, data: await run({ organizationId: 'org-1' }) }
+    } catch (error) {
+      return { success: false, error: String(error) }
+    }
+  },
+}))
+
+import { getLaborPresetRows } from '@/features/labor-presets/Actions/getLaborPresetRows'
+
+const names = ['Brake service', 'Oil change', 'Tyre swap', 'Brake service', 'Timing belt']
+
+function makePresets(): Preset[] {
+  return Array.from({ length: 123 }, (_, i) => ({
+    id: `p-${String((i * 37) % 123).padStart(3, '0')}`,
+    organizationId: i % 11 === 10 ? 'org-2' : 'org-1',
+    isArchived: i % 13 === 12,
+    // Plenty of ties, so the id has to break them.
+    name: names[i % names.length],
+    description: i % 4 === 0 ? null : ['Front axle', 'Full synthetic', 'Seasonal'][i % 3],
+    createdAt: new Date(Date.UTC(2026, 0, 1 + (i % 9))),
+    updatedAt: new Date(Date.UTC(2026, 5, 1, i % 6)),
+    _count: { items: 1, parts: 0 },
+    items: [{ hours: 1, pricingType: 'hourly' }],
+  }))
+}
+
+/** What the list should show for this sort, in order, from the same rows. */
+function expected(
+  sortBy: string,
+  dir: 'asc' | 'desc',
+  filter: (preset: Preset) => boolean = () => true
+) {
+  const column = ['name', 'description', 'createdAt'].includes(sortBy) ? sortBy : 'updatedAt'
+  const mine = state.presets.filter(
+    (p) => p.organizationId === 'org-1' && !p.isArchived && filter(p)
+  )
+  return ordered(mine, [{ [column]: dir }, { id: 'asc' }]).map((p) => p.id)
+}
+
+beforeEach(() => {
+  state.presets = makePresets()
+  state.options = []
+})
+
+describe('the labor packages list in batches', () => {
+  for (const sortBy of ['name', 'description', 'createdAt', 'updatedAt']) {
+    for (const sortOrder of ['asc', 'desc'] as const) {
+      it(`shows every package once, sorted by ${sortBy} ${sortOrder}`, async () => {
+        const { ids: seen } = await walkBatches(getLaborPresetRows, (cursor) => ({
+          sortBy,
+          sortOrder,
+          cursor,
+        }))
+        expect(seen).toEqual(expected(sortBy, sortOrder))
+        expect(new Set(seen).size).toBe(seen.length)
+      })
+    }
+  }
+
+  it('starts with 50 and the total, and later batches leave the total out', async () => {
+    const first = await getLaborPresetRows({})
+    expect(first.data?.rows).toHaveLength(50)
+    expect(first.data?.total).toBe(expected('updatedAt', 'desc').length)
+    const second = await getLaborPresetRows({ cursor: first.data?.nextCursor })
+    expect(second.data?.total).toBeUndefined()
+  })
+
+  it('keeps the search on every batch', async () => {
+    const { ids: seen } = await walkBatches(getLaborPresetRows, (cursor) => ({
+      search: 'brake',
+      sortBy: 'name',
+      sortOrder: 'asc',
+      cursor,
+    }))
+    expect(seen).toEqual(expected('name', 'asc', (p) => p.name === 'Brake service'))
+  })
+
+  it('never shows archived packages or another workshop its packages', async () => {
+    const seen = new Set((await walkBatches(getLaborPresetRows, (cursor) => ({ cursor }))).ids)
+    const hidden = state.presets.filter((p) => p.isArchived || p.organizationId === 'org-2')
+    expect(hidden.length).toBeGreaterThan(0)
+    expect(hidden.some((p) => seen.has(p.id))).toBe(false)
+  })
+
+  it('takes the right to read labor packages, as the old list did', async () => {
+    await getLaborPresetRows({})
+    expect(state.options[0]).toEqual({
+      requiredPermissions: [
+        { action: PermissionAction.READ, subject: PermissionSubject.LABOR_PRESETS },
+      ],
+    })
+  })
+
+  it('refuses input that is not a list query', async () => {
+    const result = await getLaborPresetRows({ sortOrder: 'sideways' as 'asc' })
+    expect(result.success).toBe(false)
+  })
+})

+ 179 - 0
src/__tests__/features/quotes/get-quote-rows.test.ts

@@ -0,0 +1,179 @@
+/**
+ * @vitest-environment node
+ *
+ * The quote list loads more rows as it scrolls (getQuoteRows). Read batch by
+ * batch, every sort has to show each quote exactly once and in the same order
+ * one long read would, the status tab and the search have to hold on every
+ * batch, and no batch may ever reach another workshop's quotes.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { inMemoryTable, walkBatches } from '@/__tests__/helpers/in-memory-table'
+
+const state = vi.hoisted(() => ({ org: 'org-1', rows: [] as Record<string, any>[] }))
+
+vi.mock('@/lib/db', async () => {
+  const { inMemoryTable } = await import('@/__tests__/helpers/in-memory-table')
+  return {
+    db: {
+      quote: {
+        findMany: vi.fn(inMemoryTable(() => state.rows).findMany),
+        count: vi.fn(inMemoryTable(() => state.rows).count),
+        groupBy: vi.fn(async () => [
+          { status: 'draft', _count: 4 },
+          { status: 'accepted', _count: 2 },
+          { status: 'changes_requested', _count: 1 },
+        ]),
+      },
+    },
+  }
+})
+vi.mock('@/features/customer-reference/Lib/referenceSetting', async (original) => ({
+  ...(await original<typeof import('@/features/customer-reference/Lib/referenceSetting')>()),
+  isCustomerReferenceEnabled: vi.fn(async () => false),
+}))
+vi.mock('@/lib/with-auth', () => ({
+  withAuth: vi.fn(async (run: (ctx: { organizationId: string }) => Promise<unknown>) => {
+    try {
+      return { success: true, data: await run({ organizationId: state.org }) }
+    } catch (error) {
+      return { success: false, error: (error as Error).message }
+    }
+  }),
+}))
+
+import { db } from '@/lib/db'
+import { withAuth } from '@/lib/with-auth'
+import { getQuoteRows } from '@/features/quotes/Actions/getQuoteRows'
+import { QUOTE_BATCH_SIZE } from '@/features/quotes/Lib/quoteList.server'
+import { ATTENTION_STATUSES } from '@/features/quotes/Lib/quoteStatus'
+
+const statuses = ['draft', 'sent', 'accepted', 'rejected', 'converted', ...ATTENTION_STATUSES]
+
+/** 140 quotes here and 20 in another workshop, with plenty of ties and gaps. */
+function fixture() {
+  return Array.from({ length: 160 }, (_, i) => ({
+    id: `q${String(i).padStart(3, '0')}`,
+    organizationId: i < 140 ? 'org-1' : 'org-2',
+    quoteNumber: i % 6 === 0 ? null : `QT-${1000 + (i % 50)}`,
+    title: ['Brakes', 'Service', 'Tyres', 'Timing belt'][i % 4],
+    status: statuses[i % statuses.length],
+    totalAmount: (i % 5) * 250.5,
+    customerReference: null,
+    createdAt: new Date(Date.UTC(2026, 10, 1 + (i % 12))),
+    customer: i % 7 === 0 ? null : { id: `c${i % 4}`, name: ['Ola', 'Kari', 'Per'][i % 3] },
+    vehicle:
+      i % 5 === 0
+        ? null
+        : { id: `v${i % 9}`, make: ['Volvo', 'Audi'][i % 2], model: 'X', year: 2015 + (i % 3) },
+  }))
+}
+
+async function oneLongRead(input: Parameters<typeof getQuoteRows>[0]) {
+  vi.mocked(db.quote.findMany).mockClear()
+  await getQuoteRows(input)
+  const args = vi.mocked(db.quote.findMany).mock.calls[0][0] as any
+  const all = await inMemoryTable(() => state.rows).findMany({
+    where: args.where,
+    orderBy: args.orderBy,
+  })
+  return all.map((row) => row.id)
+}
+
+beforeEach(() => {
+  state.org = 'org-1'
+  state.rows = fixture()
+  vi.mocked(db.quote.findMany).mockClear()
+  vi.mocked(db.quote.count).mockClear()
+})
+
+const sorts: [string | undefined, 'asc' | 'desc'][] = [
+  [undefined, 'desc'],
+  ['quoteNumber', 'asc'],
+  ['quoteNumber', 'desc'],
+  ['title', 'asc'],
+  ['customer', 'asc'],
+  ['customer', 'desc'],
+  ['vehicle', 'asc'],
+  ['vehicle', 'desc'],
+  ['status', 'asc'],
+  ['totalAmount', 'desc'],
+  ['createdAt', 'asc'],
+]
+
+describe('reading the quote list batch by batch', () => {
+  for (const [sortBy, sortOrder] of sorts) {
+    it(`shows every quote once, in order, sorted by ${sortBy ?? 'newest'} ${sortOrder}`, async () => {
+      const input = { sortBy, sortOrder }
+      const { ids, batches, total } = await walkBatches(getQuoteRows, (cursor) => ({
+        ...input,
+        cursor,
+      }))
+      const expected = await oneLongRead(input)
+      expect(expected.length).toBe(140)
+      expect(ids).toEqual(expected)
+      expect(new Set(ids).size).toBe(ids.length)
+      expect(batches).toBe(Math.ceil(140 / QUOTE_BATCH_SIZE))
+      expect(total).toBe(140)
+    })
+  }
+
+  it('keeps the status tab and the search on every batch', async () => {
+    const attention = await walkBatches(getQuoteRows, (cursor) => ({
+      status: 'attention',
+      sortBy: 'title',
+      cursor,
+    }))
+    expect(attention.ids.length).toBeGreaterThan(0)
+    for (const id of attention.ids) {
+      expect(ATTENTION_STATUSES).toContain(state.rows.find((row) => row.id === id)?.status)
+    }
+
+    const brakes = await walkBatches(getQuoteRows, (cursor) => ({ search: 'brak', cursor }))
+    expect(brakes.ids).toHaveLength(35)
+    for (const id of brakes.ids) {
+      expect(state.rows.find((row) => row.id === id)?.title).toBe('Brakes')
+    }
+  })
+
+  it('carries the tab counts on the first batch only, attention summed', async () => {
+    const first = await getQuoteRows({})
+    expect(first.data?.statusCounts).toMatchObject({ draft: 4, accepted: 2 })
+    expect(first.data?.statusCounts?.attention).toBe(3)
+    const second = await getQuoteRows({ cursor: first.data?.nextCursor })
+    expect(second.data?.statusCounts).toBeUndefined()
+    expect(second.data?.total).toBeUndefined()
+  })
+})
+
+describe('another workshop', () => {
+  it('never sees this workshop’s quotes, in any batch', async () => {
+    state.org = 'org-2'
+    const { ids } = await walkBatches(getQuoteRows, (cursor) => ({ cursor }))
+    expect(ids).toHaveLength(20)
+    for (const id of ids) {
+      expect(state.rows.find((row) => row.id === id)?.organizationId).toBe('org-2')
+    }
+    for (const [args] of vi.mocked(db.quote.count).mock.calls) {
+      expect((args as any).where.organizationId).toBe('org-2')
+    }
+    expect(vi.mocked(db.quote.groupBy).mock.calls.at(-1)?.[0]).toMatchObject({
+      where: { organizationId: 'org-2' },
+    })
+  })
+})
+
+describe('the action', () => {
+  it('asks for permission to read quotes', async () => {
+    await getQuoteRows({})
+    expect(vi.mocked(withAuth).mock.calls.at(-1)?.[1]).toEqual({
+      requiredPermissions: [{ action: 'read', subject: 'quotes' }],
+    })
+  })
+
+  it('refuses a cursor that does not fit the sort', async () => {
+    expect((await getQuoteRows({ cursor: { v: [], id: 'q001' } })).success).toBe(false)
+    expect((await getQuoteRows({ sortBy: 'title', cursor: { v: [4], id: 'q001' } })).success).toBe(
+      false
+    )
+  })
+})

+ 4 - 3
src/__tests__/features/search/equipment-serial-search.test.ts

@@ -56,7 +56,8 @@ import { getCachedMembership, getCachedSession } from '@/lib/cached-session'
 import { db } from '@/lib/db'
 import { equipmentEnabled } from '@/features/equipment/Lib/equipmentGate.server'
 import { globalSearch } from '@/features/search/Actions/searchActions'
-import { getVehiclesPaginated, searchVehicles } from '@/features/vehicles/Actions/vehicleActions'
+import { searchVehicles } from '@/features/vehicles/Actions/vehicleActions'
+import { getVehicleRows } from '@/features/vehicles/Actions/getVehicleRows'
 
 const ORG = 'org-a'
 
@@ -151,7 +152,7 @@ describe('a serial number of equipment', () => {
   })
 
   it('finds its vehicle in the vehicle list', async () => {
-    const { off, on } = await vehicleQueries(() => getVehiclesPaginated({ search: 'SN-4471' }))
+    const { off, on } = await vehicleQueries(() => getVehicleRows({ search: 'SN-4471' }))
     expect(JSON.stringify(off)).not.toContain('equipment')
     const before = (off?.where?.OR ?? []) as unknown[]
     expect(on?.where?.OR).toEqual([...before.slice(0, -1), serialOn('SN-4471'), before.at(-1)])
@@ -166,7 +167,7 @@ describe('a serial number of equipment', () => {
   it('is not searched at all while the workshop records no equipment', async () => {
     vi.mocked(equipmentEnabled).mockResolvedValue(false)
     await globalSearch('HX4471')
-    await getVehiclesPaginated({ search: '4471' })
+    await getVehicleRows({ search: '4471' })
     await searchVehicles('4471')
     for (const [args] of vi.mocked(db.vehicle.findMany).mock.calls) {
       expect(JSON.stringify(args)).not.toContain('equipment')

+ 247 - 0
src/__tests__/features/share-links/get-share-link-rows.test.ts

@@ -0,0 +1,247 @@
+/**
+ * @vitest-environment node
+ *
+ * The share links list in Settings loads as it scrolls (getShareLinkRows).
+ * The links come from four kinds of document and are sorted in memory, so a
+ * batch carries on from the last link's shared date and its kind and id:
+ * every link turns up once, newest first, even when many were shared in the
+ * same second; the status, kind and search filters hold for every batch; a
+ * workshop only sees its own links; and reading them takes the same rights as
+ * before.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { PermissionAction, PermissionSubject } from '@/lib/permissions'
+import { walkBatches } from '@/__tests__/helpers/in-memory-table'
+
+type Doc = Record<string, any>
+
+const state = vi.hoisted(() => ({
+  invoices: [] as Doc[],
+  quotes: [] as Doc[],
+  inspections: [] as Doc[],
+  reports: [] as Doc[],
+  options: [] as unknown[],
+}))
+
+vi.mock('@/lib/db', async () => {
+  const { inMemoryTable } = await import('@/__tests__/helpers/in-memory-table')
+  return {
+    db: {
+      serviceRecord: inMemoryTable(() => state.invoices),
+      quote: inMemoryTable(() => state.quotes),
+      inspection: inMemoryTable(() => state.inspections),
+      statusReport: inMemoryTable(() => state.reports),
+    },
+  }
+})
+// Whether a link is open is the expiry rules' business, tested on their own;
+// here each document says outright whether its link has run out.
+vi.mock('@/lib/share-link.server', () => ({
+  loadShareExpiryContext: async () => ({
+    rules: {
+      invoice: { mode: 'never', days: 0 },
+      quote: { mode: 'never', days: 0 },
+      inspection: { mode: 'never', days: 0 },
+    },
+    timeZone: 'Pacific/Auckland',
+  }),
+  SHARE_FACT_COLUMNS: {},
+  INVOICE_PAYMENT_COLUMNS: {},
+  shareFacts: (row: Doc) => row,
+}))
+vi.mock('@/lib/share-expiry', async (original) => ({
+  ...(await original<typeof import('@/lib/share-expiry')>()),
+  shareExpiry: (facts: Doc) => facts,
+}))
+vi.mock('@/features/share-links/Lib/shareLinkDocument.server', async (original) => ({
+  ...(await original<typeof import('@/features/share-links/Lib/shareLinkDocument.server')>()),
+  toExpiryView: (expiry: Doc) => ({
+    expired: expiry.expired === true || (expiry.kind === 'date' && expiry.at < new Date()),
+  }),
+}))
+vi.mock('@/lib/with-auth', () => ({
+  withAuth: async (
+    run: (ctx: { organizationId: string }) => Promise<unknown>,
+    options?: unknown
+  ) => {
+    state.options.push(options)
+    try {
+      return { success: true, data: await run({ organizationId: 'org-1' }) }
+    } catch (error) {
+      return { success: false, error: String(error) }
+    }
+  },
+}))
+
+import { getShareLinkRows } from '@/features/share-links/Actions/getShareLinkRows'
+
+/** Shared on one of a few days, so plenty of links share a moment. */
+function sharedOn(i: number) {
+  return i % 9 === 0 ? null : new Date(Date.UTC(2026, 10, 1 + (i % 4), 9))
+}
+
+const vehicle = {
+  make: 'Volvo',
+  model: 'V70',
+  year: 2012,
+  licensePlate: 'AB 12345',
+  customer: null,
+}
+
+function makeDocuments() {
+  state.invoices = Array.from({ length: 70 }, (_, i) => ({
+    id: `inv-${String((i * 17) % 70).padStart(2, '0')}`,
+    organizationId: i % 10 === 9 ? 'org-2' : 'org-1',
+    publicToken: `t-inv-${i}`,
+    title: i % 3 === 0 ? 'Brake job' : 'Oil service',
+    invoiceNumber: `INV-${i}`,
+    vehicleId: 'v1',
+    viewCount: i,
+    customer: { name: i % 2 === 0 ? 'Kari' : 'Ola' },
+    vehicle,
+    sharedAt: sharedOn(i),
+    expired: i % 4 === 0,
+  }))
+  state.quotes = Array.from({ length: 45 }, (_, i) => ({
+    id: `quo-${String((i * 13) % 45).padStart(2, '0')}`,
+    organizationId: 'org-1',
+    publicToken: i % 8 === 7 ? null : `t-quo-${i}`,
+    title: 'Brake quote',
+    quoteNumber: `Q-${i}`,
+    viewCount: 0,
+    customer: { name: 'Per' },
+    vehicle,
+    sharedAt: sharedOn(i + 1),
+    expired: i % 5 === 0,
+  }))
+  state.inspections = Array.from({ length: 30 }, (_, i) => ({
+    id: `ins-${String((i * 7) % 30).padStart(2, '0')}`,
+    organizationId: 'org-1',
+    publicToken: `t-ins-${i}`,
+    template: { name: 'Annual check' },
+    vehicle,
+    sharedAt: sharedOn(i + 2),
+    expired: false,
+  }))
+  state.reports = Array.from({ length: 20 }, (_, i) => ({
+    id: `rep-${String(i).padStart(2, '0')}`,
+    organizationId: 'org-1',
+    status: i % 5 === 0 ? 'draft' : 'sent',
+    publicToken: `t-rep-${i}`,
+    title: 'Progress video',
+    sentAt: sharedOn(i + 3),
+    createdAt: new Date(Date.UTC(2026, 9, 1)),
+    expiresAt: i % 3 === 0 ? new Date(Date.UTC(2020, 0, 1)) : null,
+    serviceRecord: { id: 'job-1', title: 'Brake job', vehicleId: 'v1', vehicle },
+    inspection: null,
+  }))
+}
+
+beforeEach(() => {
+  makeDocuments()
+  state.options = []
+})
+
+/** Every row of every batch, in the order the list was handed them. */
+function walk(filters: { status?: string; kind?: string; search?: string }) {
+  return walkBatches(getShareLinkRows, (cursor) => ({ ...filters, cursor }))
+}
+
+describe('the share links list in batches', () => {
+  it('shows every link once, newest first, with unknown days last', async () => {
+    const { rows } = await walk({ status: 'all' })
+    const keys = rows.map((r) => `${r.kind}:${r.id}`)
+    expect(new Set(keys).size).toBe(keys.length)
+
+    // Every shared document of the workshop, and each report out of draft.
+    const expectedCount =
+      state.invoices.filter((d) => d.organizationId === 'org-1').length +
+      state.quotes.filter((d) => d.publicToken).length +
+      state.inspections.length +
+      state.reports.filter((d) => d.status !== 'draft').length
+    expect(rows).toHaveLength(expectedCount)
+
+    const days = rows.map((r) => r.sharedAt)
+    const known = days.filter((d): d is string => d !== null)
+    expect(known).toEqual([...known].sort().reverse())
+    expect(days.slice(known.length).every((d) => d === null)).toBe(true)
+  })
+
+  it('sends 50 rows, the total and the counts with the first batch only', async () => {
+    const first = await getShareLinkRows({ status: 'all' })
+    expect(first.data?.rows).toHaveLength(50)
+    expect(first.data?.organizationId).toBe('org-1')
+    const counts = first.data?.counts
+    expect(counts && counts.active + counts.expired).toBe(first.data?.total)
+
+    const second = await getShareLinkRows({ status: 'all', cursor: first.data?.nextCursor })
+    expect(second.data?.total).toBeUndefined()
+    expect(second.data?.counts).toBeUndefined()
+  })
+
+  it('keeps the status, kind and search filters on every batch', async () => {
+    const expired = await walk({ status: 'expired' })
+    expect(expired.rows.length).toBeGreaterThan(0)
+    expect(expired.rows.every((r) => r.expiry.expired)).toBe(true)
+
+    const active = await walk({})
+    expect(active.rows.every((r) => !r.expiry.expired)).toBe(true)
+
+    const first = await getShareLinkRows({ status: 'all' })
+    expect(expired.rows.length + active.rows.length).toBe(first.data?.total)
+
+    const invoices = await walk({ status: 'all', kind: 'invoice', search: 'kari' })
+    expect(invoices.rows.length).toBeGreaterThan(0)
+    expect(invoices.rows.every((r) => r.kind === 'invoice')).toBe(true)
+    expect(invoices.rows).toHaveLength(
+      state.invoices.filter((d) => d.organizationId === 'org-1' && d.customer.name === 'Kari')
+        .length
+    )
+  })
+
+  it('never shows another workshop its links', async () => {
+    const { ids } = await walk({ status: 'all' })
+    const theirs = state.invoices.filter((d) => d.organizationId === 'org-2').map((d) => d.id)
+    expect(theirs.length).toBeGreaterThan(0)
+    expect(ids.some((id) => theirs.includes(id))).toBe(false)
+  })
+
+  it('takes the right to read settings and every kind of document, as before', async () => {
+    await getShareLinkRows({})
+    expect(state.options[0]).toEqual({
+      requiredPermissions: [
+        { action: PermissionAction.READ, subject: PermissionSubject.SETTINGS },
+        { action: PermissionAction.READ, subject: PermissionSubject.SERVICES },
+        { action: PermissionAction.READ, subject: PermissionSubject.QUOTES },
+        { action: PermissionAction.READ, subject: PermissionSubject.INSPECTIONS },
+      ],
+    })
+  })
+
+  it('keeps an invoice and a quote with the same id apart across a batch boundary', async () => {
+    const at = new Date(Date.UTC(2026, 10, 1, 9))
+    // 49 newer invoices, then an invoice and a quote shared in the same
+    // moment with the same id: the first batch ends on the invoice.
+    state.invoices = Array.from({ length: 50 }, (_, i) => ({
+      ...state.invoices[0],
+      organizationId: 'org-1',
+      id: i === 49 ? 'same' : `inv-n${String(i).padStart(2, '0')}`,
+      sharedAt: i === 49 ? at : new Date(at.getTime() + (50 - i) * 1000),
+    }))
+    state.quotes = [{ ...state.quotes[0], id: 'same', publicToken: 't-same', sharedAt: at }]
+    state.inspections = []
+    state.reports = []
+
+    const first = await getShareLinkRows({ status: 'all' })
+    expect(first.data?.nextCursor?.id).toBe('invoice:same')
+    const { rows } = await walk({ status: 'all' })
+    const same = rows.filter((r) => r.id === 'same').map((r) => r.kind)
+    expect(same).toEqual(['invoice', 'quote'])
+    expect(rows).toHaveLength(first.data?.total ?? -1)
+  })
+
+  it('refuses a cursor that does not fit the list', async () => {
+    const result = await getShareLinkRows({ cursor: { v: [3], id: 'invoice:x' } })
+    expect(result.success).toBe(false)
+  })
+})

+ 197 - 0
src/__tests__/features/tire-hotel/get-tire-set-rows.test.ts

@@ -0,0 +1,197 @@
+/**
+ * @vitest-environment node
+ *
+ * The tire hotel list loads more rows as it scrolls (getTireSetRows). Read
+ * batch by batch, every sort has to show each set exactly once and in the same
+ * order one long read would, the tabs and the search have to hold on every
+ * batch (written-off sets stay out of the default view), and no batch may
+ * reach another workshop's sets.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { inMemoryTable, walkBatches } from '@/__tests__/helpers/in-memory-table'
+
+const state = vi.hoisted(() => ({ org: 'org-1', rows: [] as Record<string, any>[] }))
+
+vi.mock('@/lib/db', async () => {
+  const { inMemoryTable } = await import('@/__tests__/helpers/in-memory-table')
+  return {
+    db: {
+      tireSet: {
+        findMany: vi.fn(inMemoryTable(() => state.rows).findMany),
+        count: vi.fn(inMemoryTable(() => state.rows).count),
+        groupBy: vi.fn(async () => [
+          { status: 'stored', _count: { _all: 9 } },
+          { status: 'released', _count: { _all: 4 } },
+        ]),
+      },
+    },
+  }
+})
+vi.mock('@/features/tire-hotel/Lib/tireHotelSettings', () => ({
+  requireTireHotel: vi.fn(async () => undefined),
+}))
+vi.mock('@/features/vehicles/Lib/typeKeySetting', async (original) => ({
+  ...(await original<typeof import('@/features/vehicles/Lib/typeKeySetting')>()),
+  typeKeySearch: vi.fn(async () => []),
+}))
+vi.mock('@/lib/with-auth', () => ({
+  withAuth: vi.fn(async (run: (ctx: { organizationId: string }) => Promise<unknown>) => {
+    try {
+      return { success: true, data: await run({ organizationId: state.org }) }
+    } catch (error) {
+      return { success: false, error: (error as Error).message }
+    }
+  }),
+}))
+
+import { db } from '@/lib/db'
+import { withAuth } from '@/lib/with-auth'
+import { requireTireHotel } from '@/features/tire-hotel/Lib/tireHotelSettings'
+import { getTireSetRows } from '@/features/tire-hotel/Actions/getTireSetRows'
+import { TIRE_SET_BATCH_SIZE } from '@/features/tire-hotel/Lib/tireSetList.server'
+
+/** 130 sets here and 15 in another workshop, with plenty of ties and gaps. */
+function fixture() {
+  return Array.from({ length: 145 }, (_, i) => ({
+    id: `t${String(i).padStart(3, '0')}`,
+    organizationId: i < 130 ? 'org-1' : 'org-2',
+    reference: i % 5 === 0 ? null : `R-${i % 25}`,
+    season: ['summer', 'winter', 'all_season'][i % 3],
+    status: ['stored', 'released', 'stored', 'disposed'][i % 4],
+    brand: ['Michelin', 'Nokian'][i % 2],
+    model: null,
+    size: '205/55R16',
+    dotCode: null,
+    checkedInAt: i % 6 === 0 ? null : new Date(Date.UTC(2026, 9, 1 + (i % 9))),
+    updatedAt: new Date(Date.UTC(2026, 10, 1 + (i % 7))),
+    location: i % 8 === 0 ? null : { code: `A-${i % 10}`, warehouseId: 'w1' },
+    customer: i % 7 === 0 ? null : { id: `c${i % 3}`, name: ['Ola', 'Kari', 'Per'][i % 3] },
+    vehicle: null,
+    treatments: i % 10 === 0 ? [{ type: 'wash', status: 'pending' }] : [],
+  }))
+}
+
+async function oneLongRead(input: Parameters<typeof getTireSetRows>[0]) {
+  vi.mocked(db.tireSet.findMany).mockClear()
+  await getTireSetRows(input)
+  const args = vi.mocked(db.tireSet.findMany).mock.calls[0][0] as any
+  const all = await inMemoryTable(() => state.rows).findMany({
+    where: args.where,
+    orderBy: args.orderBy,
+  })
+  return all.map((row) => row.id)
+}
+
+const live = (org = 'org-1') =>
+  fixture().filter((row) => row.organizationId === org && row.status !== 'disposed').length
+
+beforeEach(() => {
+  state.org = 'org-1'
+  state.rows = fixture()
+  vi.mocked(db.tireSet.findMany).mockClear()
+  vi.mocked(db.tireSet.count).mockClear()
+})
+
+const sorts: [string | undefined, 'asc' | 'desc'][] = [
+  [undefined, 'desc'],
+  [undefined, 'asc'],
+  ['reference', 'asc'],
+  ['reference', 'desc'],
+  ['season', 'asc'],
+  ['status', 'desc'],
+  ['checkedInAt', 'asc'],
+  ['checkedInAt', 'desc'],
+  ['customer', 'asc'],
+  ['customer', 'desc'],
+]
+
+describe('reading the tire hotel list batch by batch', () => {
+  for (const [sortBy, sortOrder] of sorts) {
+    it(`shows every set once, in order, sorted by ${sortBy ?? 'last saved'} ${sortOrder}`, async () => {
+      const input = { sortBy, sortOrder }
+      const { ids, batches, total } = await walkBatches(getTireSetRows, (cursor) => ({
+        ...input,
+        cursor,
+      }))
+      const expected = await oneLongRead(input)
+      expect(expected.length).toBe(live())
+      expect(expected.length).toBeGreaterThan(TIRE_SET_BATCH_SIZE)
+      expect(ids).toEqual(expected)
+      expect(new Set(ids).size).toBe(ids.length)
+      expect(batches).toBe(Math.ceil(expected.length / TIRE_SET_BATCH_SIZE))
+      expect(total).toBe(expected.length)
+    })
+  }
+
+  it('keeps written-off sets out of the default view, and the tabs on every batch', async () => {
+    const all = await walkBatches(getTireSetRows, (cursor) => ({ cursor }))
+    for (const id of all.ids) {
+      expect(state.rows.find((row) => row.id === id)?.status).not.toBe('disposed')
+    }
+
+    const disposed = await walkBatches(getTireSetRows, (cursor) => ({ status: 'disposed', cursor }))
+    expect(disposed.ids.length).toBeGreaterThan(0)
+    for (const id of disposed.ids) {
+      expect(state.rows.find((row) => row.id === id)?.status).toBe('disposed')
+    }
+
+    const prep = await walkBatches(getTireSetRows, (cursor) => ({ status: 'needs_prep', cursor }))
+    expect(prep.ids.length).toBeGreaterThan(0)
+    for (const id of prep.ids) {
+      const row = state.rows.find((r) => r.id === id)
+      expect(row?.treatments).toEqual([{ type: 'wash', status: 'pending' }])
+      expect(row?.status).not.toBe('disposed')
+    }
+
+    const nokian = await walkBatches(getTireSetRows, (cursor) => ({
+      search: 'nokian',
+      sortBy: 'reference',
+      cursor,
+    }))
+    expect(nokian.ids.length).toBeGreaterThan(0)
+    for (const id of nokian.ids) {
+      expect(state.rows.find((row) => row.id === id)?.brand).toBe('Nokian')
+    }
+  })
+
+  it('carries the tab counts on the first batch only', async () => {
+    const first = await getTireSetRows({})
+    expect(first.data?.statusCounts).toEqual({
+      stored: 9,
+      released: 4,
+      needs_prep: expect.any(Number),
+    })
+    const second = await getTireSetRows({ cursor: first.data?.nextCursor })
+    expect(second.data?.statusCounts).toBeUndefined()
+    expect(second.data?.total).toBeUndefined()
+  })
+})
+
+describe('another workshop', () => {
+  it('never sees this workshop’s sets, in any batch', async () => {
+    state.org = 'org-2'
+    const { ids } = await walkBatches(getTireSetRows, (cursor) => ({ cursor }))
+    expect(ids).toHaveLength(live('org-2'))
+    for (const id of ids) {
+      expect(state.rows.find((row) => row.id === id)?.organizationId).toBe('org-2')
+    }
+    for (const [args] of vi.mocked(db.tireSet.count).mock.calls) {
+      expect((args as any).where.organizationId).toBe('org-2')
+    }
+  })
+})
+
+describe('the action', () => {
+  it('asks for permission to read the tire hotel, and that the module is on', async () => {
+    vi.mocked(requireTireHotel).mockClear()
+    await getTireSetRows({})
+    expect(vi.mocked(withAuth).mock.calls.at(-1)?.[1]).toEqual({
+      requiredPermissions: [{ action: 'read', subject: 'tire_hotel' }],
+    })
+    expect(requireTireHotel).toHaveBeenCalledWith('org-1')
+  })
+
+  it('refuses a cursor that does not fit the sort', async () => {
+    expect((await getTireSetRows({ cursor: { v: [1, 2], id: 't001' } })).success).toBe(false)
+  })
+})

Энэ ялгаанд хэт олон файл өөрчлөгдсөн тул зарим файлыг харуулаагүй болно